diff --git a/tasks/traccar__traccar-5347/tests/test.sh b/tasks/traccar__traccar-5347/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a9d613af66e4e4952b46bad3fab4a18335e25e0 --- /dev/null +++ b/tasks/traccar__traccar-5347/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 bc65eb120807b7c899d3fd95fbb6684934bfa3ef > "$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/traccar__traccar-5347/tests/verifier.py b/tasks/traccar__traccar-5347/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5347/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/traccar__traccar-5348/environment/Dockerfile b/tasks/traccar__traccar-5348/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5c7e363dfad10fdc8db9d528da68d4a94342550d --- /dev/null +++ b/tasks/traccar__traccar-5348/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0436abf3bafbfa3bb7f7b489bdf47302124a6398 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0436abf3bafbfa3bb7f7b489bdf47302124a6398 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0436abf3bafbfa3bb7f7b489bdf47302124a6398 \ + && 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/traccar__traccar-5348/instruction.md b/tasks/traccar__traccar-5348/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..061bf7a57ae7e39da4e7ef71855ce420709429d8 --- /dev/null +++ b/tasks/traccar__traccar-5348/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add maxLifetime for hikariConfig + +## Description + +Fix for + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0436abf3bafb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5348/solution/patch.diff b/tasks/traccar__traccar-5348/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9f24f4fa03223a07365ac765bb93100ad671fee7 --- /dev/null +++ b/tasks/traccar__traccar-5348/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/src/main/java/org/traccar/config/Keys.java b/src/main/java/org/traccar/config/Keys.java +index e51ba07c4..17e230340 100644 +--- a/src/main/java/org/traccar/config/Keys.java ++++ b/src/main/java/org/traccar/config/Keys.java +@@ -542,6 +542,13 @@ public final class Keys { + "database.saveEmpty", + List.of(KeyType.CONFIG)); + ++ /** ++ * This property controls the maximum lifetime in miliseconds of a connection in the pool. ++ */ ++ public static final ConfigKey DATABASE_MAX_LIFETIME = new IntegerConfigKey( ++ "database.maxLifetime", ++ List.of(KeyType.CONFIG)); ++ + /** + * Device limit for self registered users. Default value is -1, which indicates no limit. + */ +diff --git a/src/main/java/org/traccar/storage/DatabaseModule.java b/src/main/java/org/traccar/storage/DatabaseModule.java +index cd66d7298..6a446d659 100644 +--- a/src/main/java/org/traccar/storage/DatabaseModule.java ++++ b/src/main/java/org/traccar/storage/DatabaseModule.java +@@ -71,7 +71,10 @@ public class DatabaseModule extends AbstractModule { + hikariConfig.setPassword(config.getString(Keys.DATABASE_PASSWORD)); + hikariConfig.setConnectionInitSql(config.getString(Keys.DATABASE_CHECK_CONNECTION)); + hikariConfig.setIdleTimeout(600000); +- ++ int maxLifetime = config.getInteger(Keys.DATABASE_MAX_LIFETIME); ++ if (maxLifetime != 0 ) { ++ hikariConfig.setMaxLifetime(maxLifetime); ++ } + int maxPoolSize = config.getInteger(Keys.DATABASE_MAX_POOL_SIZE); + if (maxPoolSize != 0) { + hikariConfig.setMaximumPoolSize(maxPoolSize); diff --git a/tasks/traccar__traccar-5348/solution/solve.sh b/tasks/traccar__traccar-5348/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5348/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/traccar__traccar-5348/task.toml b/tasks/traccar__traccar-5348/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c7f6933a98f46f0fe0ba08eedb41d8356d8349eb --- /dev/null +++ b/tasks/traccar__traccar-5348/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5348" +description = "Add maxLifetime for hikariConfig" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "0436abf3bafbfa3bb7f7b489bdf47302124a6398" +reference = "https://github.com/traccar/traccar/pull/5348" +source_access = "auto" +built_at = "2026-11-16T16:09:42.588350+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a96d61e25dffceedbbd106394105cc8e0693758b6d72fddc86cfc2a02b89c8eb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-09T23:35:36Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/config/Keys.java", + "src/main/java/org/traccar/storage/DatabaseModule.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.435308+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:102ff3c53420174b4b1ce35fedbae40246d8ba4c9acfdb2420aa836b74dba363" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5348/tests/capture.py b/tasks/traccar__traccar-5348/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5348/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/traccar__traccar-5348/tests/instruction.md b/tasks/traccar__traccar-5348/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..061bf7a57ae7e39da4e7ef71855ce420709429d8 --- /dev/null +++ b/tasks/traccar__traccar-5348/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add maxLifetime for hikariConfig + +## Description + +Fix for + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0436abf3bafb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5348/tests/oracle.patch b/tasks/traccar__traccar-5348/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9f24f4fa03223a07365ac765bb93100ad671fee7 --- /dev/null +++ b/tasks/traccar__traccar-5348/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/src/main/java/org/traccar/config/Keys.java b/src/main/java/org/traccar/config/Keys.java +index e51ba07c4..17e230340 100644 +--- a/src/main/java/org/traccar/config/Keys.java ++++ b/src/main/java/org/traccar/config/Keys.java +@@ -542,6 +542,13 @@ public final class Keys { + "database.saveEmpty", + List.of(KeyType.CONFIG)); + ++ /** ++ * This property controls the maximum lifetime in miliseconds of a connection in the pool. ++ */ ++ public static final ConfigKey DATABASE_MAX_LIFETIME = new IntegerConfigKey( ++ "database.maxLifetime", ++ List.of(KeyType.CONFIG)); ++ + /** + * Device limit for self registered users. Default value is -1, which indicates no limit. + */ +diff --git a/src/main/java/org/traccar/storage/DatabaseModule.java b/src/main/java/org/traccar/storage/DatabaseModule.java +index cd66d7298..6a446d659 100644 +--- a/src/main/java/org/traccar/storage/DatabaseModule.java ++++ b/src/main/java/org/traccar/storage/DatabaseModule.java +@@ -71,7 +71,10 @@ public class DatabaseModule extends AbstractModule { + hikariConfig.setPassword(config.getString(Keys.DATABASE_PASSWORD)); + hikariConfig.setConnectionInitSql(config.getString(Keys.DATABASE_CHECK_CONNECTION)); + hikariConfig.setIdleTimeout(600000); +- ++ int maxLifetime = config.getInteger(Keys.DATABASE_MAX_LIFETIME); ++ if (maxLifetime != 0 ) { ++ hikariConfig.setMaxLifetime(maxLifetime); ++ } + int maxPoolSize = config.getInteger(Keys.DATABASE_MAX_POOL_SIZE); + if (maxPoolSize != 0) { + hikariConfig.setMaximumPoolSize(maxPoolSize); diff --git a/tasks/traccar__traccar-5348/tests/test.sh b/tasks/traccar__traccar-5348/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..26e27842d7c250b324c28403dafcea9734e00b33 --- /dev/null +++ b/tasks/traccar__traccar-5348/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 0436abf3bafbfa3bb7f7b489bdf47302124a6398 > "$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/traccar__traccar-5348/tests/verifier.py b/tasks/traccar__traccar-5348/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5348/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/traccar__traccar-5358/environment/Dockerfile b/tasks/traccar__traccar-5358/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9c5ed95fa7df0134ef5c04848e488c4da0391c99 --- /dev/null +++ b/tasks/traccar__traccar-5358/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 90e5c5a7ede05d5d06abda6474d593b5a7843c9e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 90e5c5a7ede05d5d06abda6474d593b5a7843c9e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 90e5c5a7ede05d5d06abda6474d593b5a7843c9e \ + && 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/traccar__traccar-5358/instruction.md b/tasks/traccar__traccar-5358/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..28a9307ed1dc060ce939d116d690de6d683866d1 --- /dev/null +++ b/tasks/traccar__traccar-5358/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Implemented power and battery for aovx v series + +## Description + +Implemented power and battery for aovx v series + +[AOVX_V Series_Cloud Platform Protocol_V2.9.pdf](https://github.com/user-attachments/files/16038325/AOVX_V.Series_Cloud.Platform.Protocol_V2.9.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `90e5c5a7ede0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5358/solution/patch.diff b/tasks/traccar__traccar-5358/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..df70aadf1abe0e712b5db3961be3a17571c998b9 --- /dev/null +++ b/tasks/traccar__traccar-5358/solution/patch.diff @@ -0,0 +1,55 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index d010a8fe0..8afe04d0f 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -710,6 +710,9 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.001); + position.set(Position.KEY_SATELLITES, buf.readUnsignedByte()); + break; ++ case 0xF1: ++ position.set(Position.KEY_POWER, buf.readUnsignedInt() * 0.001); ++ break; + case 0xF3: + while (buf.readerIndex() < endIndex) { + int extendedType = buf.readUnsignedShort(); +@@ -772,6 +775,21 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + } + } + break; ++ case 0xF7: ++ position.set(Position.KEY_BATTERY, buf.readUnsignedInt() * 0.001); ++ if (length >= 5) { ++ short batteryStatus = buf.readUnsignedByte(); ++ switch (batteryStatus) { ++ case 2: ++ case 3: ++ position.set(Position.KEY_CHARGE, true); ++ default: ++ } ++ } ++ if (length >= 6) { ++ position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); ++ } ++ break; + case 0xFE: + if (length == 1) { + position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 2ba37ab09..286ebfed1 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -227,6 +227,14 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + verifyNull(decoder, binary( + "7e0002000004304832546500b7ca7e")); + ++ verifyAttribute(decoder, binary( ++ "7E020000964130564801050048000000001000004F01651E2E02CAEC3802E80000001524062616002101040000000330011F31010EF1040000308CF231414F56585F564C3330302D4C415F48322E315F4547393135554C4141425230334130324D30385F56322E312E305F763130F3011FF400F5080000000000000001F6084008FFFFFFFD0009F70600000E870246F912000F000000010000062A00082406261600184D7E"), ++ Position.KEY_CHARGE, true); ++ ++ verifyAttribute(decoder, binary( ++ "7E020000964130564801050048000000001000004F01651E2E02CAEC3802E80000001524062616002101040000000330011F31010EF1040000308CF231414F56585F564C3330302D4C415F48322E315F4547393135554C4141425230334130324D30385F56322E312E305F763130F3011FF400F5080000000000000001F6084008FFFFFFFD0009F70600000E870246F912000F000000010000062A00082406261600184D7E"), ++ Position.KEY_POWER, 12.428); ++ + } + + } diff --git a/tasks/traccar__traccar-5358/solution/solve.sh b/tasks/traccar__traccar-5358/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5358/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/traccar__traccar-5358/task.toml b/tasks/traccar__traccar-5358/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6322674f6c0c77fcf6c68c2dfcbce1c50f924c06 --- /dev/null +++ b/tasks/traccar__traccar-5358/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5358" +description = "Implemented power and battery for aovx v series" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "90e5c5a7ede05d5d06abda6474d593b5a7843c9e" +reference = "https://github.com/traccar/traccar/pull/5358" +source_access = "auto" +built_at = "2026-11-16T16:09:42.688028+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:bb8968de93f59b2a14b99ba801067b04b7acd53a8eddbf112b15d3b4cd16ee59" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-06-30T14:02:30Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java", + "src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 26 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.435906+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:be014ce94984514f9bea8c00bb4cae209d268ec58d2492ce08f364c78f293dfb" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5358/tests/capture.py b/tasks/traccar__traccar-5358/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5358/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/traccar__traccar-5358/tests/instruction.md b/tasks/traccar__traccar-5358/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..28a9307ed1dc060ce939d116d690de6d683866d1 --- /dev/null +++ b/tasks/traccar__traccar-5358/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Implemented power and battery for aovx v series + +## Description + +Implemented power and battery for aovx v series + +[AOVX_V Series_Cloud Platform Protocol_V2.9.pdf](https://github.com/user-attachments/files/16038325/AOVX_V.Series_Cloud.Platform.Protocol_V2.9.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `90e5c5a7ede0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5358/tests/oracle.patch b/tasks/traccar__traccar-5358/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..df70aadf1abe0e712b5db3961be3a17571c998b9 --- /dev/null +++ b/tasks/traccar__traccar-5358/tests/oracle.patch @@ -0,0 +1,55 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index d010a8fe0..8afe04d0f 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -710,6 +710,9 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.001); + position.set(Position.KEY_SATELLITES, buf.readUnsignedByte()); + break; ++ case 0xF1: ++ position.set(Position.KEY_POWER, buf.readUnsignedInt() * 0.001); ++ break; + case 0xF3: + while (buf.readerIndex() < endIndex) { + int extendedType = buf.readUnsignedShort(); +@@ -772,6 +775,21 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + } + } + break; ++ case 0xF7: ++ position.set(Position.KEY_BATTERY, buf.readUnsignedInt() * 0.001); ++ if (length >= 5) { ++ short batteryStatus = buf.readUnsignedByte(); ++ switch (batteryStatus) { ++ case 2: ++ case 3: ++ position.set(Position.KEY_CHARGE, true); ++ default: ++ } ++ } ++ if (length >= 6) { ++ position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); ++ } ++ break; + case 0xFE: + if (length == 1) { + position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 2ba37ab09..286ebfed1 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -227,6 +227,14 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + verifyNull(decoder, binary( + "7e0002000004304832546500b7ca7e")); + ++ verifyAttribute(decoder, binary( ++ "7E020000964130564801050048000000001000004F01651E2E02CAEC3802E80000001524062616002101040000000330011F31010EF1040000308CF231414F56585F564C3330302D4C415F48322E315F4547393135554C4141425230334130324D30385F56322E312E305F763130F3011FF400F5080000000000000001F6084008FFFFFFFD0009F70600000E870246F912000F000000010000062A00082406261600184D7E"), ++ Position.KEY_CHARGE, true); ++ ++ verifyAttribute(decoder, binary( ++ "7E020000964130564801050048000000001000004F01651E2E02CAEC3802E80000001524062616002101040000000330011F31010EF1040000308CF231414F56585F564C3330302D4C415F48322E315F4547393135554C4141425230334130324D30385F56322E312E305F763130F3011FF400F5080000000000000001F6084008FFFFFFFD0009F70600000E870246F912000F000000010000062A00082406261600184D7E"), ++ Position.KEY_POWER, 12.428); ++ + } + + } diff --git a/tasks/traccar__traccar-5358/tests/test.sh b/tasks/traccar__traccar-5358/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..64c5844bb6d3907cc5dc53b5122d2c2a93fa3f3a --- /dev/null +++ b/tasks/traccar__traccar-5358/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 90e5c5a7ede05d5d06abda6474d593b5a7843c9e > "$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/traccar__traccar-5358/tests/verifier.py b/tasks/traccar__traccar-5358/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5358/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/traccar__traccar-5371/environment/Dockerfile b/tasks/traccar__traccar-5371/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1e82b7c8339bde601d882d9b2a103b1262ab87f --- /dev/null +++ b/tasks/traccar__traccar-5371/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 62f1cb5cd3374ac0012c9c054f3556c5e43a8549 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 62f1cb5cd3374ac0012c9c054f3556c5e43a8549 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 62f1cb5cd3374ac0012c9c054f3556c5e43a8549 \ + && 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/traccar__traccar-5371/instruction.md b/tasks/traccar__traccar-5371/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63d6ce3eb95da3601ec25528e207994d6d070346 --- /dev/null +++ b/tasks/traccar__traccar-5371/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** geocoder: Implement OlaMaps Reverse geocoder + +## Description + +We have integrated Ola Maps geocoder. Kindly review. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `62f1cb5cd337`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5371/solution/patch.diff b/tasks/traccar__traccar-5371/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ac5bd1ef82dc1c7cc16d58504ed86a918597337c --- /dev/null +++ b/tasks/traccar__traccar-5371/solution/patch.diff @@ -0,0 +1,55 @@ +diff --git a/src/main/java/org/traccar/MainModule.java b/src/main/java/org/traccar/MainModule.java +index c7b74d049..945bb8bc2 100644 +--- a/src/main/java/org/traccar/MainModule.java ++++ b/src/main/java/org/traccar/MainModule.java +@@ -226,7 +226,7 @@ public class MainModule extends AbstractModule { + case "maptiler" -> new MapTilerGeocoder(client, key, cacheSize, addressFormat); + case "geoapify" -> new GeoapifyGeocoder(client, key, language, cacheSize, addressFormat); + case "geocodejson" -> new GeocodeJsonGeocoder(client, url, key, language, cacheSize, addressFormat); +- default -> new GoogleGeocoder(client, key, language, cacheSize, addressFormat); ++ default -> new GoogleGeocoder(client, url, key, language, cacheSize, addressFormat); + }; + geocoder.setStatisticsManager(statisticsManager); + return geocoder; +diff --git a/src/main/java/org/traccar/geocoder/GoogleGeocoder.java b/src/main/java/org/traccar/geocoder/GoogleGeocoder.java +index 93f128b46..174ef66c8 100644 +--- a/src/main/java/org/traccar/geocoder/GoogleGeocoder.java ++++ b/src/main/java/org/traccar/geocoder/GoogleGeocoder.java +@@ -22,8 +22,10 @@ import jakarta.ws.rs.client.Client; + + public class GoogleGeocoder extends JsonGeocoder { + +- private static String formatUrl(String key, String language) { +- String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f"; ++ private static String formatUrl(String url, String key, String language) { ++ if (url == null) { ++ url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f"; ++ } + if (key != null) { + url += "&key=" + key; + } +@@ -33,8 +35,9 @@ public class GoogleGeocoder extends JsonGeocoder { + return url; + } + +- public GoogleGeocoder(Client client, String key, String language, int cacheSize, AddressFormat addressFormat) { +- super(client, formatUrl(key, language), cacheSize, addressFormat); ++ public GoogleGeocoder( ++ Client client, String url, String key, String language, int cacheSize, AddressFormat addressFormat) { ++ super(client, formatUrl(url, key, language), cacheSize, addressFormat); + } + + @Override +diff --git a/src/test/java/org/traccar/geocoder/GeocoderTest.java b/src/test/java/org/traccar/geocoder/GeocoderTest.java +index 3e65d20c7..2aa7ab77c 100644 +--- a/src/test/java/org/traccar/geocoder/GeocoderTest.java ++++ b/src/test/java/org/traccar/geocoder/GeocoderTest.java +@@ -20,7 +20,7 @@ public class GeocoderTest { + @Disabled + @Test + public void testGoogle() { +- Geocoder geocoder = new GoogleGeocoder(client, null, null, 0, new AddressFormat()); ++ Geocoder geocoder = new GoogleGeocoder(client, null, null, null, 0, new AddressFormat()); + String address = geocoder.getAddress(31.776797, 35.211489, null); + assertEquals("1 Ibn Shaprut St, Jerusalem, Jerusalem District, IL", address); + } diff --git a/tasks/traccar__traccar-5371/solution/solve.sh b/tasks/traccar__traccar-5371/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5371/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/traccar__traccar-5371/task.toml b/tasks/traccar__traccar-5371/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..884bfa89c04999fd3deaa53899ec50db2f607c91 --- /dev/null +++ b/tasks/traccar__traccar-5371/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5371" +description = "geocoder: Implement OlaMaps Reverse geocoder" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "62f1cb5cd3374ac0012c9c054f3556c5e43a8549" +reference = "https://github.com/traccar/traccar/pull/5371" +source_access = "auto" +built_at = "2026-11-16T16:09:42.686616+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5acba9c1f64cc398d37d636be4481c5523c4076d879e21b4a8a24aa157999ae4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-07-27T02:12:47Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/MainModule.java", + "src/main/java/org/traccar/geocoder/GoogleGeocoder.java", + "src/test/java/org/traccar/geocoder/GeocoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 15 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.436449+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:36ec96466a6260e315492ab6d02bc5d37c9e99990c607e68e0361b016bd2eba1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5371/tests/capture.py b/tasks/traccar__traccar-5371/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5371/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/traccar__traccar-5371/tests/instruction.md b/tasks/traccar__traccar-5371/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63d6ce3eb95da3601ec25528e207994d6d070346 --- /dev/null +++ b/tasks/traccar__traccar-5371/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** geocoder: Implement OlaMaps Reverse geocoder + +## Description + +We have integrated Ola Maps geocoder. Kindly review. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `62f1cb5cd337`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5371/tests/oracle.patch b/tasks/traccar__traccar-5371/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ac5bd1ef82dc1c7cc16d58504ed86a918597337c --- /dev/null +++ b/tasks/traccar__traccar-5371/tests/oracle.patch @@ -0,0 +1,55 @@ +diff --git a/src/main/java/org/traccar/MainModule.java b/src/main/java/org/traccar/MainModule.java +index c7b74d049..945bb8bc2 100644 +--- a/src/main/java/org/traccar/MainModule.java ++++ b/src/main/java/org/traccar/MainModule.java +@@ -226,7 +226,7 @@ public class MainModule extends AbstractModule { + case "maptiler" -> new MapTilerGeocoder(client, key, cacheSize, addressFormat); + case "geoapify" -> new GeoapifyGeocoder(client, key, language, cacheSize, addressFormat); + case "geocodejson" -> new GeocodeJsonGeocoder(client, url, key, language, cacheSize, addressFormat); +- default -> new GoogleGeocoder(client, key, language, cacheSize, addressFormat); ++ default -> new GoogleGeocoder(client, url, key, language, cacheSize, addressFormat); + }; + geocoder.setStatisticsManager(statisticsManager); + return geocoder; +diff --git a/src/main/java/org/traccar/geocoder/GoogleGeocoder.java b/src/main/java/org/traccar/geocoder/GoogleGeocoder.java +index 93f128b46..174ef66c8 100644 +--- a/src/main/java/org/traccar/geocoder/GoogleGeocoder.java ++++ b/src/main/java/org/traccar/geocoder/GoogleGeocoder.java +@@ -22,8 +22,10 @@ import jakarta.ws.rs.client.Client; + + public class GoogleGeocoder extends JsonGeocoder { + +- private static String formatUrl(String key, String language) { +- String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f"; ++ private static String formatUrl(String url, String key, String language) { ++ if (url == null) { ++ url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f"; ++ } + if (key != null) { + url += "&key=" + key; + } +@@ -33,8 +35,9 @@ public class GoogleGeocoder extends JsonGeocoder { + return url; + } + +- public GoogleGeocoder(Client client, String key, String language, int cacheSize, AddressFormat addressFormat) { +- super(client, formatUrl(key, language), cacheSize, addressFormat); ++ public GoogleGeocoder( ++ Client client, String url, String key, String language, int cacheSize, AddressFormat addressFormat) { ++ super(client, formatUrl(url, key, language), cacheSize, addressFormat); + } + + @Override +diff --git a/src/test/java/org/traccar/geocoder/GeocoderTest.java b/src/test/java/org/traccar/geocoder/GeocoderTest.java +index 3e65d20c7..2aa7ab77c 100644 +--- a/src/test/java/org/traccar/geocoder/GeocoderTest.java ++++ b/src/test/java/org/traccar/geocoder/GeocoderTest.java +@@ -20,7 +20,7 @@ public class GeocoderTest { + @Disabled + @Test + public void testGoogle() { +- Geocoder geocoder = new GoogleGeocoder(client, null, null, 0, new AddressFormat()); ++ Geocoder geocoder = new GoogleGeocoder(client, null, null, null, 0, new AddressFormat()); + String address = geocoder.getAddress(31.776797, 35.211489, null); + assertEquals("1 Ibn Shaprut St, Jerusalem, Jerusalem District, IL", address); + } diff --git a/tasks/traccar__traccar-5371/tests/test.sh b/tasks/traccar__traccar-5371/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a2401bf544b9abe61c1f3a54658aec84da94d5bc --- /dev/null +++ b/tasks/traccar__traccar-5371/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 62f1cb5cd3374ac0012c9c054f3556c5e43a8549 > "$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/traccar__traccar-5371/tests/verifier.py b/tasks/traccar__traccar-5371/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5371/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/traccar__traccar-5379/environment/Dockerfile b/tasks/traccar__traccar-5379/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..10da035faf70ffcf59f82b70b9626c88cc1f4c9f --- /dev/null +++ b/tasks/traccar__traccar-5379/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b1791569e71a39936c5d5d6e96996f55cb671ae4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b1791569e71a39936c5d5d6e96996f55cb671ae4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b1791569e71a39936c5d5d6e96996f55cb671ae4 \ + && 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/traccar__traccar-5379/instruction.md b/tasks/traccar__traccar-5379/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..89a238b7f66c6531acea18f0b7fce94b8f45dc52 --- /dev/null +++ b/tasks/traccar__traccar-5379/instruction.md @@ -0,0 +1,99 @@ +# Issue + +**Title:** tlt2h: Fix handling UDP + +## Description + +Currently, the tlt2h decoder used with UDP does not correctly detect the end of the datagram, leading to a second empty position returned in [positions](https://github.com/frederictobiasc/traccar/blob/da82ef8979c23496bbf3507f34fc410e5f86f8ed/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java#L249) (see example contents of `positions` below. This results for instance in networks, battery voltage, ... being never shown in the `details` view of a device. This was initially reported in + +I confirm that this fixes the issue. + +Is it fine to fix this by introducing the CharacterDelimiterFrameDecoder also used by the TCP handler, or should we rather catch this in the frame decoder itself? + +## Further information + +Contents of [messages](https://github.com/frederictobiasc/traccar/blob/da82ef8979c23496bbf3507f34fc410e5f86f8ed/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java#L151) when processing a datagram: + + +``` +messages = [ + "#4065#$WIFI,015036.00,A,-79,66C0E2A3AAAA,-68,E4F75BA2AAAA,-77,ACDB48E6AAAA,-79,388B59DCAAAA,-79,56C0E2A3AAAA,030824*7D", + "##" +]; +``` + +
+ Contents of positions + +See [positions](https://github.com/frederictobiasc/traccar/blob/da82ef8979c23496bbf3507f34fc410e5f86f8ed/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java#L249) + +``` +LinkedList@75 size=2 +0: + accuracy: 0.000000 + address: null + altitude: 0.000000 + attributes: LinkedHashMap@141 size=1 + 0: LinkedHashMap$Entry@172 "battery":"4.065" + key: "battery" + value: "4.065" + course: 0.000000 + deviceId: 1 + deviceTime: Date@142 + fixTime: null + geofenceIds: null + id: 0 + latitude: 0.000000 + longitude: 0.000000 + network: + carrier: null + cellTowers: null + considerIp: Boolean@182 + homeMobileCountryCode: null + homeMobileNetworkCode: null + radioType: "gsm" + wifiAccessPoints: ArrayList@184 size=5 + 0: WifiAccessPoint@190 + channel: null + macAddress: "66:C0:E2:A3:AA:AA" + signalStrength: Integer@211 + 1: WifiAccessPoint@191 + 2: WifiAccessPoint@192 + 3: WifiAccessPoint@193 + 4: WifiAccessPoint@194 + outdated: true + protocol: "tlt2h" + coder: 0 + hash: 110458994 + hashIsZero: false + value: byte[5]@165 + serverTime: Date@145 + speed: 0.000000 + type: null + valid: false +1: + accuracy: 0.000000 + address: null + altitude: 0.000000 + attributes: LinkedHashMap@155 size=0 + course: 0.000000 + deviceId: 1 + deviceTime: null + fixTime: null + geofenceIds: null + id: 0 + latitude: 0.000000 + longitude: 0.000000 + network: null + outdated: true + protocol: "tlt2h" + serverTime: Date@156 + speed: 0.000000 + type: null + valid: false +``` +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b1791569e71a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5379/solution/patch.diff b/tasks/traccar__traccar-5379/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5a2738b10cd14ea4ead182cc108700b7b3732dc3 --- /dev/null +++ b/tasks/traccar__traccar-5379/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java b/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java +index 2d59ffda8..58a10725b 100644 +--- a/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java +@@ -148,7 +148,10 @@ public class Tlt2hProtocolDecoder extends BaseProtocolDecoder { + + String status = parser.next(); + +- String[] messages = sentence.substring(sentence.indexOf('\n') + 1).split("\r\n"); ++ String[] messages = sentence.substring( ++ sentence.indexOf('\n') + 1, ++ sentence.endsWith("##") ? sentence.length() - 4 : sentence.length()) ++ .split("\r\n"); + List positions = new LinkedList<>(); + + for (String message : messages) { diff --git a/tasks/traccar__traccar-5379/solution/solve.sh b/tasks/traccar__traccar-5379/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5379/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/traccar__traccar-5379/task.toml b/tasks/traccar__traccar-5379/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3732b329cc86676e4b89f01c40b7d35e42cce533 --- /dev/null +++ b/tasks/traccar__traccar-5379/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5379" +description = "tlt2h: Fix handling UDP" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "b1791569e71a39936c5d5d6e96996f55cb671ae4" +reference = "https://github.com/traccar/traccar/pull/5379" +source_access = "auto" +built_at = "2026-11-16T16:09:42.683558+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:eb1c6e08b8e999bc03284a1eb5fbe2f0a79baf6d94328a6b11f086d2d1ca4252" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-08-09T18:49:20Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.436960+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:58ed8bd6c9d23a5f8d4d54225415913167191ee37c2664026ab1b194775ac4f5" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5379/tests/capture.py b/tasks/traccar__traccar-5379/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5379/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/traccar__traccar-5379/tests/instruction.md b/tasks/traccar__traccar-5379/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..89a238b7f66c6531acea18f0b7fce94b8f45dc52 --- /dev/null +++ b/tasks/traccar__traccar-5379/tests/instruction.md @@ -0,0 +1,99 @@ +# Issue + +**Title:** tlt2h: Fix handling UDP + +## Description + +Currently, the tlt2h decoder used with UDP does not correctly detect the end of the datagram, leading to a second empty position returned in [positions](https://github.com/frederictobiasc/traccar/blob/da82ef8979c23496bbf3507f34fc410e5f86f8ed/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java#L249) (see example contents of `positions` below. This results for instance in networks, battery voltage, ... being never shown in the `details` view of a device. This was initially reported in + +I confirm that this fixes the issue. + +Is it fine to fix this by introducing the CharacterDelimiterFrameDecoder also used by the TCP handler, or should we rather catch this in the frame decoder itself? + +## Further information + +Contents of [messages](https://github.com/frederictobiasc/traccar/blob/da82ef8979c23496bbf3507f34fc410e5f86f8ed/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java#L151) when processing a datagram: + + +``` +messages = [ + "#4065#$WIFI,015036.00,A,-79,66C0E2A3AAAA,-68,E4F75BA2AAAA,-77,ACDB48E6AAAA,-79,388B59DCAAAA,-79,56C0E2A3AAAA,030824*7D", + "##" +]; +``` + +
+ Contents of positions + +See [positions](https://github.com/frederictobiasc/traccar/blob/da82ef8979c23496bbf3507f34fc410e5f86f8ed/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java#L249) + +``` +LinkedList@75 size=2 +0: + accuracy: 0.000000 + address: null + altitude: 0.000000 + attributes: LinkedHashMap@141 size=1 + 0: LinkedHashMap$Entry@172 "battery":"4.065" + key: "battery" + value: "4.065" + course: 0.000000 + deviceId: 1 + deviceTime: Date@142 + fixTime: null + geofenceIds: null + id: 0 + latitude: 0.000000 + longitude: 0.000000 + network: + carrier: null + cellTowers: null + considerIp: Boolean@182 + homeMobileCountryCode: null + homeMobileNetworkCode: null + radioType: "gsm" + wifiAccessPoints: ArrayList@184 size=5 + 0: WifiAccessPoint@190 + channel: null + macAddress: "66:C0:E2:A3:AA:AA" + signalStrength: Integer@211 + 1: WifiAccessPoint@191 + 2: WifiAccessPoint@192 + 3: WifiAccessPoint@193 + 4: WifiAccessPoint@194 + outdated: true + protocol: "tlt2h" + coder: 0 + hash: 110458994 + hashIsZero: false + value: byte[5]@165 + serverTime: Date@145 + speed: 0.000000 + type: null + valid: false +1: + accuracy: 0.000000 + address: null + altitude: 0.000000 + attributes: LinkedHashMap@155 size=0 + course: 0.000000 + deviceId: 1 + deviceTime: null + fixTime: null + geofenceIds: null + id: 0 + latitude: 0.000000 + longitude: 0.000000 + network: null + outdated: true + protocol: "tlt2h" + serverTime: Date@156 + speed: 0.000000 + type: null + valid: false +``` +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b1791569e71a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5379/tests/oracle.patch b/tasks/traccar__traccar-5379/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5a2738b10cd14ea4ead182cc108700b7b3732dc3 --- /dev/null +++ b/tasks/traccar__traccar-5379/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java b/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java +index 2d59ffda8..58a10725b 100644 +--- a/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java +@@ -148,7 +148,10 @@ public class Tlt2hProtocolDecoder extends BaseProtocolDecoder { + + String status = parser.next(); + +- String[] messages = sentence.substring(sentence.indexOf('\n') + 1).split("\r\n"); ++ String[] messages = sentence.substring( ++ sentence.indexOf('\n') + 1, ++ sentence.endsWith("##") ? sentence.length() - 4 : sentence.length()) ++ .split("\r\n"); + List positions = new LinkedList<>(); + + for (String message : messages) { diff --git a/tasks/traccar__traccar-5379/tests/test.sh b/tasks/traccar__traccar-5379/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..61bcc64fabe0017ce788e7653e08445cf84e0063 --- /dev/null +++ b/tasks/traccar__traccar-5379/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 b1791569e71a39936c5d5d6e96996f55cb671ae4 > "$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/traccar__traccar-5379/tests/verifier.py b/tasks/traccar__traccar-5379/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5379/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/traccar__traccar-5395/environment/Dockerfile b/tasks/traccar__traccar-5395/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..df6b5d3b2e7333d86e3bc9413d60d00ed3ef0eed --- /dev/null +++ b/tasks/traccar__traccar-5395/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fb4d74479f21e99c80df8a6a7775defcf35fce53 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fb4d74479f21e99c80df8a6a7775defcf35fce53 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fb4d74479f21e99c80df8a6a7775defcf35fce53 \ + && 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/traccar__traccar-5395/instruction.md b/tasks/traccar__traccar-5395/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2426ab336f1cbdd995984de2df36f0ff7dd9294c --- /dev/null +++ b/tasks/traccar__traccar-5395/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Implement temperature on aovx + +## Description + +https://github.com/AOVX-Corporation/AOVX_Share/blob/main/Document/en/01_G%20series/AOVX_G%26A_Series%20Cloud%20Platform%20Protocol.pdf + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fb4d74479f21`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5395/solution/patch.diff b/tasks/traccar__traccar-5395/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6685234cb5d312c6566293a5f4e50a21ee862203 --- /dev/null +++ b/tasks/traccar__traccar-5395/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index 4f912edbe..253bf887f 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -699,6 +699,16 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + } + } + break; ++ case 0xF6: ++ buf.readUnsignedByte(); // data type ++ int fieldMask = buf.readUnsignedByte(); ++ if (BitUtil.check(fieldMask, 0)) { ++ buf.readUnsignedShort(); // light ++ } ++ if (BitUtil.check(fieldMask, 1)) { ++ position.set(Position.PREFIX_TEMP + 1, buf.readShort() * 0.1); ++ } ++ break; + case 0xF7: + position.set(Position.KEY_BATTERY, buf.readUnsignedInt() * 0.001); + if (length >= 5) { +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 2d59dd649..5e52414df 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new HuabaoProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "7e020000bd4130571601850419000000001000000e01651ec702caec6402d10000000024082423485001040000000030011f310108f00d02d4000301080509000079c9aff231414f56585f474c3130302d4c415f48322e305f4547393135554c4141425230334130314d30385f56322e302e393a763130f616071eff940261ffe8ff10fdd805dc002800000032000af70600000f620150f81d04086541305716018589553202100062282617474c3130302d4c410000f912000f00000004000000000010240824234954d27e"), ++ Position.PREFIX_TEMP + 1, -10.8); ++ + verifyAttribute(decoder, binary( + "7e0200003a019172511329001300000000000000020158df7206c9607000370000008424051311201801040000000030010d31011d5708000000000000000082020092510201230b7e"), + Position.PREFIX_TEMP + 1, 29.1); diff --git a/tasks/traccar__traccar-5395/solution/solve.sh b/tasks/traccar__traccar-5395/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5395/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/traccar__traccar-5395/task.toml b/tasks/traccar__traccar-5395/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..99655c11e3f95617f98857d15fb11bd9fea30c9d --- /dev/null +++ b/tasks/traccar__traccar-5395/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5395" +description = "Implement temperature on aovx" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "fb4d74479f21e99c80df8a6a7775defcf35fce53" +reference = "https://github.com/traccar/traccar/pull/5395" +source_access = "auto" +built_at = "2026-11-16T16:09:42.679311+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:dc072da492d624745a9b2462f55677bc42776438de6f92a27d18b679d67fddfb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-08-25T00:07:50Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java", + "src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.437528+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9ed0a974914942d3bbc532fd65b30b68cf61029a3beaa1c51b716ea8750ac8ca" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5395/tests/capture.py b/tasks/traccar__traccar-5395/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5395/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/traccar__traccar-5395/tests/instruction.md b/tasks/traccar__traccar-5395/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2426ab336f1cbdd995984de2df36f0ff7dd9294c --- /dev/null +++ b/tasks/traccar__traccar-5395/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Implement temperature on aovx + +## Description + +https://github.com/AOVX-Corporation/AOVX_Share/blob/main/Document/en/01_G%20series/AOVX_G%26A_Series%20Cloud%20Platform%20Protocol.pdf + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fb4d74479f21`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5395/tests/oracle.patch b/tasks/traccar__traccar-5395/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6685234cb5d312c6566293a5f4e50a21ee862203 --- /dev/null +++ b/tasks/traccar__traccar-5395/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index 4f912edbe..253bf887f 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -699,6 +699,16 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + } + } + break; ++ case 0xF6: ++ buf.readUnsignedByte(); // data type ++ int fieldMask = buf.readUnsignedByte(); ++ if (BitUtil.check(fieldMask, 0)) { ++ buf.readUnsignedShort(); // light ++ } ++ if (BitUtil.check(fieldMask, 1)) { ++ position.set(Position.PREFIX_TEMP + 1, buf.readShort() * 0.1); ++ } ++ break; + case 0xF7: + position.set(Position.KEY_BATTERY, buf.readUnsignedInt() * 0.001); + if (length >= 5) { +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 2d59dd649..5e52414df 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new HuabaoProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "7e020000bd4130571601850419000000001000000e01651ec702caec6402d10000000024082423485001040000000030011f310108f00d02d4000301080509000079c9aff231414f56585f474c3130302d4c415f48322e305f4547393135554c4141425230334130314d30385f56322e302e393a763130f616071eff940261ffe8ff10fdd805dc002800000032000af70600000f620150f81d04086541305716018589553202100062282617474c3130302d4c410000f912000f00000004000000000010240824234954d27e"), ++ Position.PREFIX_TEMP + 1, -10.8); ++ + verifyAttribute(decoder, binary( + "7e0200003a019172511329001300000000000000020158df7206c9607000370000008424051311201801040000000030010d31011d5708000000000000000082020092510201230b7e"), + Position.PREFIX_TEMP + 1, 29.1); diff --git a/tasks/traccar__traccar-5395/tests/test.sh b/tasks/traccar__traccar-5395/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41b4d89ab208b7c9cf9c22f1928a0cabe741458d --- /dev/null +++ b/tasks/traccar__traccar-5395/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 fb4d74479f21e99c80df8a6a7775defcf35fce53 > "$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/traccar__traccar-5395/tests/verifier.py b/tasks/traccar__traccar-5395/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5395/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/traccar__traccar-5396/environment/Dockerfile b/tasks/traccar__traccar-5396/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ca13b7c9094669eb7db23ada4d6354d5320a0554 --- /dev/null +++ b/tasks/traccar__traccar-5396/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin cf798db951c4a1988a114be7243210389e7818f9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard cf798db951c4a1988a114be7243210389e7818f9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base cf798db951c4a1988a114be7243210389e7818f9 \ + && 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/traccar__traccar-5396/instruction.md b/tasks/traccar__traccar-5396/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2d00e18d417c1c254c13c0be0da362f04e8d554b --- /dev/null +++ b/tasks/traccar__traccar-5396/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** aovx implement wifi + +## Description + +https://github.com/AOVX-Corporation/AOVX_Share/blob/main/Document/en/01_G%20series/AOVX_G%26A_Series%20Cloud%20Platform%20Protocol.pdf + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cf798db951c4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5396/solution/patch.diff b/tasks/traccar__traccar-5396/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e6f65dfe0d4b9722e188770fb9ed49c699b0fc9b --- /dev/null +++ b/tasks/traccar__traccar-5396/solution/patch.diff @@ -0,0 +1,85 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index 253bf887f..2fa6ddf07 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -20,6 +20,7 @@ import io.netty.buffer.ByteBufUtil; + import io.netty.buffer.Unpooled; + import io.netty.channel.Channel; + import org.traccar.BaseProtocolDecoder; ++import org.traccar.model.WifiAccessPoint; + import org.traccar.session.DeviceSession; + import org.traccar.NetworkMessage; + import org.traccar.Protocol; +@@ -424,6 +425,7 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + return position; + + } ++ Network network = new Network(); + + while (buf.readableBytes() > 2) { + +@@ -611,7 +613,6 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + break; + case 0xEB: + if (buf.getUnsignedShort(buf.readerIndex()) > 200) { +- Network network = new Network(); + int mcc = buf.readUnsignedShort(); + int mnc = buf.readUnsignedByte(); + while (buf.readerIndex() < endIndex) { +@@ -619,7 +620,6 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + mcc, mnc, buf.readUnsignedShort(), buf.readUnsignedShort(), + buf.readUnsignedByte())); + } +- position.setNetwork(network); + } else { + while (buf.readerIndex() < endIndex) { + int extendedLength = buf.readUnsignedShort(); +@@ -641,11 +641,9 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); + break; + case 0x00D8: +- Network network = new Network(); + network.addCellTower(CellTower.from( + buf.readUnsignedShort(), buf.readUnsignedByte(), + buf.readUnsignedShort(), buf.readUnsignedInt())); +- position.setNetwork(network); + break; + case 0x00A8: + case 0x00E1: +@@ -699,6 +697,13 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + } + } + break; ++ case 0xF4: ++ while (buf.readerIndex() < endIndex) { ++ String mac = ByteBufUtil.hexDump(buf.readSlice(6)).replaceAll("(..)", "$1:"); ++ network.addWifiAccessPoint(WifiAccessPoint.from( ++ mac.substring(0, mac.length() - 1), buf.readByte())); ++ } ++ break; + case 0xF6: + buf.readUnsignedByte(); // data type + int fieldMask = buf.readUnsignedByte(); +@@ -763,6 +768,9 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + buf.readerIndex(endIndex); + } + ++ if (network.getCellTowers() != null || network.getWifiAccessPoints() != null) { ++ position.setNetwork(network); ++ } + return position; + } + +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 5e52414df..2779bdd97 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -11,6 +11,8 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new HuabaoProtocolDecoder(null)); + ++ verifyPosition(decoder, binary("7E020000E241305716018504E6000000009020001E01651EAD02CAEC9902DE0000000024082517034401040000000030011D310107F00D02D4000301080509000079C9ACF231414F56585F474C3130302D4C415F48322E305F4547393135554C4141425230334130314D30385F56322E302E393A763130F423C0252F96F022D0C03DD95C5EC8C6E4FAC4EA462EB798B3EF4F74DCB58416F94020E6B4F616001E00D3026B0000FFD0000805DC002800000032000AF70600000F48014EF81D04086541305716018589553202100062282617474C3130302D4C410000F912000F00000001000000000018240825170407E27E")); ++ + verifyAttribute(decoder, binary( + "7e020000bd4130571601850419000000001000000e01651ec702caec6402d10000000024082423485001040000000030011f310108f00d02d4000301080509000079c9aff231414f56585f474c3130302d4c415f48322e305f4547393135554c4141425230334130314d30385f56322e302e393a763130f616071eff940261ffe8ff10fdd805dc002800000032000af70600000f620150f81d04086541305716018589553202100062282617474c3130302d4c410000f912000f00000004000000000010240824234954d27e"), + Position.PREFIX_TEMP + 1, -10.8); diff --git a/tasks/traccar__traccar-5396/solution/solve.sh b/tasks/traccar__traccar-5396/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5396/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/traccar__traccar-5396/task.toml b/tasks/traccar__traccar-5396/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..540a4ab54bd891255cf5fd853838f2a6fe641d15 --- /dev/null +++ b/tasks/traccar__traccar-5396/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5396" +description = "aovx implement wifi" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "cf798db951c4a1988a114be7243210389e7818f9" +reference = "https://github.com/traccar/traccar/pull/5396" +source_access = "auto" +built_at = "2026-11-16T16:09:42.680590+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d67e363fadc0c10cda1bcf9044816169efb81df533aa1690c84e868cfad99882" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-08-25T21:01:45Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java", + "src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.438089+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:dc9859056d5b8ae8732b95db5a381568779df06f8ebe63f0fc0940cf61315a77" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5396/tests/capture.py b/tasks/traccar__traccar-5396/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5396/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/traccar__traccar-5396/tests/instruction.md b/tasks/traccar__traccar-5396/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2d00e18d417c1c254c13c0be0da362f04e8d554b --- /dev/null +++ b/tasks/traccar__traccar-5396/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** aovx implement wifi + +## Description + +https://github.com/AOVX-Corporation/AOVX_Share/blob/main/Document/en/01_G%20series/AOVX_G%26A_Series%20Cloud%20Platform%20Protocol.pdf + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cf798db951c4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5396/tests/oracle.patch b/tasks/traccar__traccar-5396/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e6f65dfe0d4b9722e188770fb9ed49c699b0fc9b --- /dev/null +++ b/tasks/traccar__traccar-5396/tests/oracle.patch @@ -0,0 +1,85 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index 253bf887f..2fa6ddf07 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -20,6 +20,7 @@ import io.netty.buffer.ByteBufUtil; + import io.netty.buffer.Unpooled; + import io.netty.channel.Channel; + import org.traccar.BaseProtocolDecoder; ++import org.traccar.model.WifiAccessPoint; + import org.traccar.session.DeviceSession; + import org.traccar.NetworkMessage; + import org.traccar.Protocol; +@@ -424,6 +425,7 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + return position; + + } ++ Network network = new Network(); + + while (buf.readableBytes() > 2) { + +@@ -611,7 +613,6 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + break; + case 0xEB: + if (buf.getUnsignedShort(buf.readerIndex()) > 200) { +- Network network = new Network(); + int mcc = buf.readUnsignedShort(); + int mnc = buf.readUnsignedByte(); + while (buf.readerIndex() < endIndex) { +@@ -619,7 +620,6 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + mcc, mnc, buf.readUnsignedShort(), buf.readUnsignedShort(), + buf.readUnsignedByte())); + } +- position.setNetwork(network); + } else { + while (buf.readerIndex() < endIndex) { + int extendedLength = buf.readUnsignedShort(); +@@ -641,11 +641,9 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); + break; + case 0x00D8: +- Network network = new Network(); + network.addCellTower(CellTower.from( + buf.readUnsignedShort(), buf.readUnsignedByte(), + buf.readUnsignedShort(), buf.readUnsignedInt())); +- position.setNetwork(network); + break; + case 0x00A8: + case 0x00E1: +@@ -699,6 +697,13 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + } + } + break; ++ case 0xF4: ++ while (buf.readerIndex() < endIndex) { ++ String mac = ByteBufUtil.hexDump(buf.readSlice(6)).replaceAll("(..)", "$1:"); ++ network.addWifiAccessPoint(WifiAccessPoint.from( ++ mac.substring(0, mac.length() - 1), buf.readByte())); ++ } ++ break; + case 0xF6: + buf.readUnsignedByte(); // data type + int fieldMask = buf.readUnsignedByte(); +@@ -763,6 +768,9 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + buf.readerIndex(endIndex); + } + ++ if (network.getCellTowers() != null || network.getWifiAccessPoints() != null) { ++ position.setNetwork(network); ++ } + return position; + } + +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 5e52414df..2779bdd97 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -11,6 +11,8 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new HuabaoProtocolDecoder(null)); + ++ verifyPosition(decoder, binary("7E020000E241305716018504E6000000009020001E01651EAD02CAEC9902DE0000000024082517034401040000000030011D310107F00D02D4000301080509000079C9ACF231414F56585F474C3130302D4C415F48322E305F4547393135554C4141425230334130314D30385F56322E302E393A763130F423C0252F96F022D0C03DD95C5EC8C6E4FAC4EA462EB798B3EF4F74DCB58416F94020E6B4F616001E00D3026B0000FFD0000805DC002800000032000AF70600000F48014EF81D04086541305716018589553202100062282617474C3130302D4C410000F912000F00000001000000000018240825170407E27E")); ++ + verifyAttribute(decoder, binary( + "7e020000bd4130571601850419000000001000000e01651ec702caec6402d10000000024082423485001040000000030011f310108f00d02d4000301080509000079c9aff231414f56585f474c3130302d4c415f48322e305f4547393135554c4141425230334130314d30385f56322e302e393a763130f616071eff940261ffe8ff10fdd805dc002800000032000af70600000f620150f81d04086541305716018589553202100062282617474c3130302d4c410000f912000f00000004000000000010240824234954d27e"), + Position.PREFIX_TEMP + 1, -10.8); diff --git a/tasks/traccar__traccar-5396/tests/test.sh b/tasks/traccar__traccar-5396/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c2d02fca9aa3537fcb511fe04b3d94eceab417c --- /dev/null +++ b/tasks/traccar__traccar-5396/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 cf798db951c4a1988a114be7243210389e7818f9 > "$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/traccar__traccar-5396/tests/verifier.py b/tasks/traccar__traccar-5396/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5396/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/traccar__traccar-5409/environment/Dockerfile b/tasks/traccar__traccar-5409/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e6a71b17828b0d3ef6a3d1c41d689887877d15d1 --- /dev/null +++ b/tasks/traccar__traccar-5409/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b89a69251bded7036488c765ec17499cb5e88346 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b89a69251bded7036488c765ec17499cb5e88346 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b89a69251bded7036488c765ec17499cb5e88346 \ + && 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/traccar__traccar-5409/instruction.md b/tasks/traccar__traccar-5409/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ee0a5da07ea098ec75e355c71650e99528f79b40 --- /dev/null +++ b/tasks/traccar__traccar-5409/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Allow managers to send announcements + +## Description + +Managers should also be allowed to send announcements, since they can have many users bellow them to manage. + +Plus, this would enhance the announcements feature to cover scenarios of Traccar servers where managers want to send information to their managed users. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b89a69251bde`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5409/solution/patch.diff b/tasks/traccar__traccar-5409/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2e1fa8bd8a3a86d99ea02b1b53474e23b863db9c --- /dev/null +++ b/tasks/traccar__traccar-5409/solution/patch.diff @@ -0,0 +1,42 @@ +diff --git a/src/main/java/org/traccar/api/resource/NotificationResource.java b/src/main/java/org/traccar/api/resource/NotificationResource.java +index 8bc81a3a4..5cc3055d1 100644 +--- a/src/main/java/org/traccar/api/resource/NotificationResource.java ++++ b/src/main/java/org/traccar/api/resource/NotificationResource.java +@@ -29,6 +29,7 @@ import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + import org.traccar.api.ExtendedObjectResource; + import org.traccar.model.Event; ++import org.traccar.model.ManagedUser; + import org.traccar.model.Notification; + import org.traccar.model.Typed; + import org.traccar.model.User; +@@ -113,15 +114,26 @@ public class NotificationResource extends ExtendedObjectResource { + public Response sendMessage( + @PathParam("notificator") String notificator, @QueryParam("userId") List userIds, + NotificationMessage message) throws MessageException, StorageException { +- permissionsService.checkAdmin(getUserId()); ++ permissionsService.checkManager(getUserId()); + List users; + if (userIds.isEmpty()) { +- users = storage.getObjects(User.class, new Request(new Columns.All())); ++ if (permissionsService.notAdmin(getUserId())) { ++ users = storage.getObjects(User.class, new Request(new Columns.All(), ++ new Condition.Permission(User.class, getUserId(), ManagedUser.class).excludeGroups())); ++ } else { ++ users = storage.getObjects(User.class, new Request(new Columns.All())); ++ } + } else { + users = new ArrayList<>(); + for (long userId : userIds) { ++ var conditions = new LinkedList(); ++ conditions.add(new Condition.Equals("id", userId)); ++ if (permissionsService.notAdmin(getUserId())) { ++ conditions.add(new Condition.Permission( ++ User.class, getUserId(), ManagedUser.class).excludeGroups()); ++ } + users.add(storage.getObject( +- User.class, new Request(new Columns.All(), new Condition.Equals("id", userId)))); ++ User.class, new Request(new Columns.All(), Condition.merge(conditions)))); + } + } + for (User user : users) { diff --git a/tasks/traccar__traccar-5409/solution/solve.sh b/tasks/traccar__traccar-5409/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5409/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/traccar__traccar-5409/task.toml b/tasks/traccar__traccar-5409/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f4c99faebaa732a0e203792bc74cea5790d002d8 --- /dev/null +++ b/tasks/traccar__traccar-5409/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5409" +description = "Allow managers to send announcements" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "b89a69251bded7036488c765ec17499cb5e88346" +reference = "https://github.com/traccar/traccar/pull/5409" +source_access = "auto" +built_at = "2026-11-16T16:09:42.678065+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:933106f828c43de22efa0724ff0775686b48fc5ede874f796d77dddbc81d16c9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-09-18T16:05:44Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/api/resource/NotificationResource.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.438600+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fc38698a7c8d17a7b951852c19ce5d93c7e985cfd7ff3a2226493f495c29d9f3" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5409/tests/capture.py b/tasks/traccar__traccar-5409/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5409/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/traccar__traccar-5409/tests/instruction.md b/tasks/traccar__traccar-5409/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ee0a5da07ea098ec75e355c71650e99528f79b40 --- /dev/null +++ b/tasks/traccar__traccar-5409/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Allow managers to send announcements + +## Description + +Managers should also be allowed to send announcements, since they can have many users bellow them to manage. + +Plus, this would enhance the announcements feature to cover scenarios of Traccar servers where managers want to send information to their managed users. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b89a69251bde`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5409/tests/oracle.patch b/tasks/traccar__traccar-5409/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2e1fa8bd8a3a86d99ea02b1b53474e23b863db9c --- /dev/null +++ b/tasks/traccar__traccar-5409/tests/oracle.patch @@ -0,0 +1,42 @@ +diff --git a/src/main/java/org/traccar/api/resource/NotificationResource.java b/src/main/java/org/traccar/api/resource/NotificationResource.java +index 8bc81a3a4..5cc3055d1 100644 +--- a/src/main/java/org/traccar/api/resource/NotificationResource.java ++++ b/src/main/java/org/traccar/api/resource/NotificationResource.java +@@ -29,6 +29,7 @@ import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + import org.traccar.api.ExtendedObjectResource; + import org.traccar.model.Event; ++import org.traccar.model.ManagedUser; + import org.traccar.model.Notification; + import org.traccar.model.Typed; + import org.traccar.model.User; +@@ -113,15 +114,26 @@ public class NotificationResource extends ExtendedObjectResource { + public Response sendMessage( + @PathParam("notificator") String notificator, @QueryParam("userId") List userIds, + NotificationMessage message) throws MessageException, StorageException { +- permissionsService.checkAdmin(getUserId()); ++ permissionsService.checkManager(getUserId()); + List users; + if (userIds.isEmpty()) { +- users = storage.getObjects(User.class, new Request(new Columns.All())); ++ if (permissionsService.notAdmin(getUserId())) { ++ users = storage.getObjects(User.class, new Request(new Columns.All(), ++ new Condition.Permission(User.class, getUserId(), ManagedUser.class).excludeGroups())); ++ } else { ++ users = storage.getObjects(User.class, new Request(new Columns.All())); ++ } + } else { + users = new ArrayList<>(); + for (long userId : userIds) { ++ var conditions = new LinkedList(); ++ conditions.add(new Condition.Equals("id", userId)); ++ if (permissionsService.notAdmin(getUserId())) { ++ conditions.add(new Condition.Permission( ++ User.class, getUserId(), ManagedUser.class).excludeGroups()); ++ } + users.add(storage.getObject( +- User.class, new Request(new Columns.All(), new Condition.Equals("id", userId)))); ++ User.class, new Request(new Columns.All(), Condition.merge(conditions)))); + } + } + for (User user : users) { diff --git a/tasks/traccar__traccar-5409/tests/test.sh b/tasks/traccar__traccar-5409/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..cb3f808013d35970e94b655213020816fa484af0 --- /dev/null +++ b/tasks/traccar__traccar-5409/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 b89a69251bded7036488c765ec17499cb5e88346 > "$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/traccar__traccar-5409/tests/verifier.py b/tasks/traccar__traccar-5409/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5409/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/traccar__traccar-5412/environment/Dockerfile b/tasks/traccar__traccar-5412/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..408e56da323c44ae7d78d32054bfe5bbdb22a145 --- /dev/null +++ b/tasks/traccar__traccar-5412/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e6517ddf21234f32f067f89ffeec22b5447bc775 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e6517ddf21234f32f067f89ffeec22b5447bc775 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e6517ddf21234f32f067f89ffeec22b5447bc775 \ + && 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/traccar__traccar-5412/instruction.md b/tasks/traccar__traccar-5412/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..25e78b929a7f5f910dbe4b4afd678cd71495f09a --- /dev/null +++ b/tasks/traccar__traccar-5412/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Allow managers to see device's users + +## Description + +Managers should also be allowed to see wich of their users are linked to devices, since they can have many users bellow them to manage. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e6517ddf2123`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5412/solution/patch.diff b/tasks/traccar__traccar-5412/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9ed52ff424fc5efcd63a1882d6de985a4ecf1a2a --- /dev/null +++ b/tasks/traccar__traccar-5412/solution/patch.diff @@ -0,0 +1,30 @@ +diff --git a/src/main/java/org/traccar/api/resource/UserResource.java b/src/main/java/org/traccar/api/resource/UserResource.java +index 65ca2c883..1dea5a2a0 100644 +--- a/src/main/java/org/traccar/api/resource/UserResource.java ++++ b/src/main/java/org/traccar/api/resource/UserResource.java +@@ -45,6 +45,7 @@ import jakarta.ws.rs.QueryParam; + import jakarta.ws.rs.core.MediaType; + import jakarta.ws.rs.core.Response; + import java.util.Collection; ++import java.util.LinkedList; + + @Path("users") + @Produces(MediaType.APPLICATION_JSON) +@@ -70,10 +71,13 @@ public class UserResource extends BaseObjectResource { + new Columns.All(), + new Condition.Permission(User.class, userId, ManagedUser.class).excludeGroups())); + } else if (deviceId > 0) { +- permissionsService.checkAdmin(getUserId()); +- return storage.getObjects(baseClass, new Request( +- new Columns.All(), +- new Condition.Permission(User.class, Device.class, deviceId).excludeGroups())); ++ permissionsService.checkManager(getUserId()); ++ var conditions = new LinkedList(); ++ conditions.add(new Condition.Permission(User.class, Device.class, deviceId).excludeGroups()); ++ if (permissionsService.notAdmin(getUserId())) { ++ conditions.add(new Condition.Permission(User.class, getUserId(), ManagedUser.class).excludeGroups()); ++ } ++ return storage.getObjects(baseClass, new Request(new Columns.All(), Condition.merge(conditions))); + } else if (permissionsService.notAdmin(getUserId())) { + return storage.getObjects(baseClass, new Request( + new Columns.All(), diff --git a/tasks/traccar__traccar-5412/solution/solve.sh b/tasks/traccar__traccar-5412/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5412/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/traccar__traccar-5412/task.toml b/tasks/traccar__traccar-5412/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4db16a52d8818e285c86ddea13f70111b96c544c --- /dev/null +++ b/tasks/traccar__traccar-5412/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5412" +description = "Allow managers to see device's users" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "e6517ddf21234f32f067f89ffeec22b5447bc775" +reference = "https://github.com/traccar/traccar/pull/5412" +source_access = "auto" +built_at = "2026-11-16T16:09:42.676724+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:34e752dbb252c7952d90c8c4f7d879fd43263cc4440637731b0d1a4f60b94281" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-09-19T22:29:24Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/api/resource/UserResource.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.439131+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a2513c7df6ce7d95550214850e06d0c282c21dd2f59e1c3c677220df4c60b5c8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5412/tests/capture.py b/tasks/traccar__traccar-5412/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5412/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/traccar__traccar-5412/tests/instruction.md b/tasks/traccar__traccar-5412/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..25e78b929a7f5f910dbe4b4afd678cd71495f09a --- /dev/null +++ b/tasks/traccar__traccar-5412/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Allow managers to see device's users + +## Description + +Managers should also be allowed to see wich of their users are linked to devices, since they can have many users bellow them to manage. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e6517ddf2123`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5412/tests/oracle.patch b/tasks/traccar__traccar-5412/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9ed52ff424fc5efcd63a1882d6de985a4ecf1a2a --- /dev/null +++ b/tasks/traccar__traccar-5412/tests/oracle.patch @@ -0,0 +1,30 @@ +diff --git a/src/main/java/org/traccar/api/resource/UserResource.java b/src/main/java/org/traccar/api/resource/UserResource.java +index 65ca2c883..1dea5a2a0 100644 +--- a/src/main/java/org/traccar/api/resource/UserResource.java ++++ b/src/main/java/org/traccar/api/resource/UserResource.java +@@ -45,6 +45,7 @@ import jakarta.ws.rs.QueryParam; + import jakarta.ws.rs.core.MediaType; + import jakarta.ws.rs.core.Response; + import java.util.Collection; ++import java.util.LinkedList; + + @Path("users") + @Produces(MediaType.APPLICATION_JSON) +@@ -70,10 +71,13 @@ public class UserResource extends BaseObjectResource { + new Columns.All(), + new Condition.Permission(User.class, userId, ManagedUser.class).excludeGroups())); + } else if (deviceId > 0) { +- permissionsService.checkAdmin(getUserId()); +- return storage.getObjects(baseClass, new Request( +- new Columns.All(), +- new Condition.Permission(User.class, Device.class, deviceId).excludeGroups())); ++ permissionsService.checkManager(getUserId()); ++ var conditions = new LinkedList(); ++ conditions.add(new Condition.Permission(User.class, Device.class, deviceId).excludeGroups()); ++ if (permissionsService.notAdmin(getUserId())) { ++ conditions.add(new Condition.Permission(User.class, getUserId(), ManagedUser.class).excludeGroups()); ++ } ++ return storage.getObjects(baseClass, new Request(new Columns.All(), Condition.merge(conditions))); + } else if (permissionsService.notAdmin(getUserId())) { + return storage.getObjects(baseClass, new Request( + new Columns.All(), diff --git a/tasks/traccar__traccar-5412/tests/test.sh b/tasks/traccar__traccar-5412/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7fa3eea09d5bb13a2aff26c2dbe9b4b2f9bcb04 --- /dev/null +++ b/tasks/traccar__traccar-5412/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 e6517ddf21234f32f067f89ffeec22b5447bc775 > "$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/traccar__traccar-5412/tests/verifier.py b/tasks/traccar__traccar-5412/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5412/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/traccar__traccar-5426/environment/Dockerfile b/tasks/traccar__traccar-5426/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b134e984f19e9e182553ab18f37cf23419c6bdb5 --- /dev/null +++ b/tasks/traccar__traccar-5426/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin efdd5fdd44afab2c29a2ed2ffce2a755684eb0d9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard efdd5fdd44afab2c29a2ed2ffce2a755684eb0d9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base efdd5fdd44afab2c29a2ed2ffce2a755684eb0d9 \ + && 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/traccar__traccar-5426/instruction.md b/tasks/traccar__traccar-5426/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e9e11d79c857a2e89bc7170d635dd345b3d799ad --- /dev/null +++ b/tasks/traccar__traccar-5426/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** No response for some more IWAP Commands + +## Description + +[Gps Watch protocol_2023.pdf](https://github.com/user-attachments/files/17203195/Gps.Watch.protocol_2023.pdf) +No response for following IWAP Commands: +AP33 +AP34 +AP84 +AP85 + +Attached is the protocol where the changes are visible. On page 20, you can see AP33; on page 21, AP34; and on page 23, AP84/AP85. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efdd5fdd44af`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5426/solution/patch.diff b/tasks/traccar__traccar-5426/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a9c18db86adb4219e0d5f428927e33f504c0b05d --- /dev/null +++ b/tasks/traccar__traccar-5426/solution/patch.diff @@ -0,0 +1,21 @@ +diff --git a/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java b/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java +index a0efdc982..7ce1b510c 100644 +--- a/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java +@@ -33,6 +33,7 @@ import java.net.SocketAddress; + import java.text.SimpleDateFormat; + import java.util.Date; + import java.util.regex.Pattern; ++import java.util.Set; + + public class TrvProtocolDecoder extends BaseProtocolDecoder { + +@@ -180,7 +181,7 @@ public class TrvProtocolDecoder extends BaseProtocolDecoder { + channel.writeAndFlush(new NetworkMessage(responseHeader + "," + time + ",0#", remoteAddress)); + } else if (type.equals("AP14") && !id.equals("IW")) { + channel.writeAndFlush(new NetworkMessage(responseHeader + ",0.000,0.000#", remoteAddress)); +- } else if (!type.equals("AP12") && !type.equals("AP14") ++ } else if (!Set.of("AP12", "AP14", "AP33", "AP34", "AP84", "AP85").contains(type) + && !sentence.substring(responseHeader.length() + 1).matches("^\\d{6}$")) { + channel.writeAndFlush(new NetworkMessage(responseHeader + "#", remoteAddress)); + } diff --git a/tasks/traccar__traccar-5426/solution/solve.sh b/tasks/traccar__traccar-5426/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5426/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/traccar__traccar-5426/task.toml b/tasks/traccar__traccar-5426/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..88f342741bad24e2bef95e8498f404d52c464414 --- /dev/null +++ b/tasks/traccar__traccar-5426/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5426" +description = "No response for some more IWAP Commands" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "efdd5fdd44afab2c29a2ed2ffce2a755684eb0d9" +reference = "https://github.com/traccar/traccar/pull/5426" +source_access = "auto" +built_at = "2026-11-16T16:09:42.673988+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7ac5e7887fdc7e3667bc39a1933d1d2dcea1527c56521acae8d92213cc572720" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-01T13:07:13Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/TrvProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.439748+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8a994bb36c0e343892566b8da40a03261a8a20c0799fa99937b438ff66716f83" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5426/tests/capture.py b/tasks/traccar__traccar-5426/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5426/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/traccar__traccar-5426/tests/instruction.md b/tasks/traccar__traccar-5426/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e9e11d79c857a2e89bc7170d635dd345b3d799ad --- /dev/null +++ b/tasks/traccar__traccar-5426/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** No response for some more IWAP Commands + +## Description + +[Gps Watch protocol_2023.pdf](https://github.com/user-attachments/files/17203195/Gps.Watch.protocol_2023.pdf) +No response for following IWAP Commands: +AP33 +AP34 +AP84 +AP85 + +Attached is the protocol where the changes are visible. On page 20, you can see AP33; on page 21, AP34; and on page 23, AP84/AP85. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efdd5fdd44af`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5426/tests/oracle.patch b/tasks/traccar__traccar-5426/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a9c18db86adb4219e0d5f428927e33f504c0b05d --- /dev/null +++ b/tasks/traccar__traccar-5426/tests/oracle.patch @@ -0,0 +1,21 @@ +diff --git a/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java b/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java +index a0efdc982..7ce1b510c 100644 +--- a/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java +@@ -33,6 +33,7 @@ import java.net.SocketAddress; + import java.text.SimpleDateFormat; + import java.util.Date; + import java.util.regex.Pattern; ++import java.util.Set; + + public class TrvProtocolDecoder extends BaseProtocolDecoder { + +@@ -180,7 +181,7 @@ public class TrvProtocolDecoder extends BaseProtocolDecoder { + channel.writeAndFlush(new NetworkMessage(responseHeader + "," + time + ",0#", remoteAddress)); + } else if (type.equals("AP14") && !id.equals("IW")) { + channel.writeAndFlush(new NetworkMessage(responseHeader + ",0.000,0.000#", remoteAddress)); +- } else if (!type.equals("AP12") && !type.equals("AP14") ++ } else if (!Set.of("AP12", "AP14", "AP33", "AP34", "AP84", "AP85").contains(type) + && !sentence.substring(responseHeader.length() + 1).matches("^\\d{6}$")) { + channel.writeAndFlush(new NetworkMessage(responseHeader + "#", remoteAddress)); + } diff --git a/tasks/traccar__traccar-5426/tests/test.sh b/tasks/traccar__traccar-5426/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5341a958cd03b065c113f3346d04671a3f198d42 --- /dev/null +++ b/tasks/traccar__traccar-5426/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 efdd5fdd44afab2c29a2ed2ffce2a755684eb0d9 > "$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/traccar__traccar-5426/tests/verifier.py b/tasks/traccar__traccar-5426/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5426/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/traccar__traccar-5441/environment/Dockerfile b/tasks/traccar__traccar-5441/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4ed78fa4e1aa13b640b42909b49019ec9af53532 --- /dev/null +++ b/tasks/traccar__traccar-5441/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b1c36134dc14fdbb80ac22306db15280d9b251b5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b1c36134dc14fdbb80ac22306db15280d9b251b5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b1c36134dc14fdbb80ac22306db15280d9b251b5 \ + && 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/traccar__traccar-5441/instruction.md b/tasks/traccar__traccar-5441/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..217dc54d47ef7131cb7d73a03c165fb08d967a1f --- /dev/null +++ b/tasks/traccar__traccar-5441/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Add attributes to Wialon forwarder + +## Description + +PositionForwarderWialon seems pretty good and i have no idea why this doesn't described in configuration docs. +But this missing important attributes, so now forwarder looks well. + +Test on Wialon: +![image](https://github.com/user-attachments/assets/bb2c83b4-4146-4442-8465-de1ff662a4e3) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b1c36134dc14`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5441/solution/patch.diff b/tasks/traccar__traccar-5441/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ff60572f5618ef3fef33ffc11f85a60624c5f8b4 --- /dev/null +++ b/tasks/traccar__traccar-5441/solution/patch.diff @@ -0,0 +1,63 @@ +diff --git a/src/main/java/org/traccar/forward/PositionForwarderWialon.java b/src/main/java/org/traccar/forward/PositionForwarderWialon.java +index ac8bfd472..b111e065e 100644 +--- a/src/main/java/org/traccar/forward/PositionForwarderWialon.java ++++ b/src/main/java/org/traccar/forward/PositionForwarderWialon.java +@@ -31,8 +31,10 @@ import java.nio.ByteBuffer; + import java.nio.charset.StandardCharsets; + import java.text.DateFormat; + import java.text.SimpleDateFormat; ++import java.util.Map; + import java.util.TimeZone; + import java.util.concurrent.ExecutorService; ++import java.util.stream.Collectors; + + public class PositionForwarderWialon implements PositionForwarder { + +@@ -74,7 +76,7 @@ public class PositionForwarderWialon implements PositionForwarder { + String uniqueId = positionData.getDevice().getUniqueId(); + + String payload = String.format( +- "%s;%02d%.5f;%s;%03d%.5f;%s;%d;%d;%d;NA;NA;NA;NA;;%s;NA", ++ "%s;%02d%.5f;%s;%03d%.5f;%s;%d;%d;%d;NA;NA;NA;NA;;%s;%s", + dateFormat.format(position.getFixTime()), + (int) Math.abs(position.getLatitude()), + Math.abs(position.getLatitude()) % 1 * 60, +@@ -85,7 +87,8 @@ public class PositionForwarderWialon implements PositionForwarder { + (int) UnitsConverter.kphFromKnots(position.getSpeed()), + (int) position.getCourse(), + (int) position.getAltitude(), +- position.getString(Position.KEY_DRIVER_UNIQUE_ID, "NA")); ++ position.getString(Position.KEY_DRIVER_UNIQUE_ID, "NA"), ++ formatAttributes(position.getAttributes(), "NA")); + + String message; + if (version.startsWith("2")) { +@@ -108,4 +111,28 @@ public class PositionForwarderWialon implements PositionForwarder { + } + } + ++ public static String formatAttributes(Map attributes, String defaultValue) { ++ if (attributes.isEmpty()) { ++ return defaultValue; ++ } ++ ++ return attributes.entrySet().stream() ++ .map(entry -> { ++ String key = entry.getKey(); ++ Object value = entry.getValue(); ++ ++ String type; ++ if (value instanceof Integer || value instanceof Long) { ++ type = "1"; ++ } else if (value instanceof Double || value instanceof Float) { ++ type = "2"; ++ } else { ++ type = "3"; ++ } ++ ++ return key + ":" + type + ":" + value.toString(); ++ }) ++ .collect(Collectors.joining(",")); ++ } ++ + } diff --git a/tasks/traccar__traccar-5441/solution/solve.sh b/tasks/traccar__traccar-5441/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5441/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/traccar__traccar-5441/task.toml b/tasks/traccar__traccar-5441/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fae78ffda69c0d79dd4b680b9ff1265826479f2c --- /dev/null +++ b/tasks/traccar__traccar-5441/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5441" +description = "Add attributes to Wialon forwarder" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "b1c36134dc14fdbb80ac22306db15280d9b251b5" +reference = "https://github.com/traccar/traccar/pull/5441" +source_access = "auto" +built_at = "2026-11-16T16:09:42.672318+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c54dc9b7dc7e282e1566270b96b01fe7cccd568f5414e470efff07b2d37d0e77" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-21T04:36:39Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/forward/PositionForwarderWialon.java", +] +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:03.440260+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f20a018182da4eb82bc6de0579f39e1334ce1b00a7c2a584ad1b3594a3320dc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5441/tests/capture.py b/tasks/traccar__traccar-5441/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5441/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/traccar__traccar-5441/tests/instruction.md b/tasks/traccar__traccar-5441/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..217dc54d47ef7131cb7d73a03c165fb08d967a1f --- /dev/null +++ b/tasks/traccar__traccar-5441/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Add attributes to Wialon forwarder + +## Description + +PositionForwarderWialon seems pretty good and i have no idea why this doesn't described in configuration docs. +But this missing important attributes, so now forwarder looks well. + +Test on Wialon: +![image](https://github.com/user-attachments/assets/bb2c83b4-4146-4442-8465-de1ff662a4e3) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b1c36134dc14`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5441/tests/oracle.patch b/tasks/traccar__traccar-5441/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ff60572f5618ef3fef33ffc11f85a60624c5f8b4 --- /dev/null +++ b/tasks/traccar__traccar-5441/tests/oracle.patch @@ -0,0 +1,63 @@ +diff --git a/src/main/java/org/traccar/forward/PositionForwarderWialon.java b/src/main/java/org/traccar/forward/PositionForwarderWialon.java +index ac8bfd472..b111e065e 100644 +--- a/src/main/java/org/traccar/forward/PositionForwarderWialon.java ++++ b/src/main/java/org/traccar/forward/PositionForwarderWialon.java +@@ -31,8 +31,10 @@ import java.nio.ByteBuffer; + import java.nio.charset.StandardCharsets; + import java.text.DateFormat; + import java.text.SimpleDateFormat; ++import java.util.Map; + import java.util.TimeZone; + import java.util.concurrent.ExecutorService; ++import java.util.stream.Collectors; + + public class PositionForwarderWialon implements PositionForwarder { + +@@ -74,7 +76,7 @@ public class PositionForwarderWialon implements PositionForwarder { + String uniqueId = positionData.getDevice().getUniqueId(); + + String payload = String.format( +- "%s;%02d%.5f;%s;%03d%.5f;%s;%d;%d;%d;NA;NA;NA;NA;;%s;NA", ++ "%s;%02d%.5f;%s;%03d%.5f;%s;%d;%d;%d;NA;NA;NA;NA;;%s;%s", + dateFormat.format(position.getFixTime()), + (int) Math.abs(position.getLatitude()), + Math.abs(position.getLatitude()) % 1 * 60, +@@ -85,7 +87,8 @@ public class PositionForwarderWialon implements PositionForwarder { + (int) UnitsConverter.kphFromKnots(position.getSpeed()), + (int) position.getCourse(), + (int) position.getAltitude(), +- position.getString(Position.KEY_DRIVER_UNIQUE_ID, "NA")); ++ position.getString(Position.KEY_DRIVER_UNIQUE_ID, "NA"), ++ formatAttributes(position.getAttributes(), "NA")); + + String message; + if (version.startsWith("2")) { +@@ -108,4 +111,28 @@ public class PositionForwarderWialon implements PositionForwarder { + } + } + ++ public static String formatAttributes(Map attributes, String defaultValue) { ++ if (attributes.isEmpty()) { ++ return defaultValue; ++ } ++ ++ return attributes.entrySet().stream() ++ .map(entry -> { ++ String key = entry.getKey(); ++ Object value = entry.getValue(); ++ ++ String type; ++ if (value instanceof Integer || value instanceof Long) { ++ type = "1"; ++ } else if (value instanceof Double || value instanceof Float) { ++ type = "2"; ++ } else { ++ type = "3"; ++ } ++ ++ return key + ":" + type + ":" + value.toString(); ++ }) ++ .collect(Collectors.joining(",")); ++ } ++ + } diff --git a/tasks/traccar__traccar-5441/tests/test.sh b/tasks/traccar__traccar-5441/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..29f191e252f99e6db9dffe4be98d469f5cf5b57b --- /dev/null +++ b/tasks/traccar__traccar-5441/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 b1c36134dc14fdbb80ac22306db15280d9b251b5 > "$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/traccar__traccar-5441/tests/verifier.py b/tasks/traccar__traccar-5441/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5441/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/traccar__traccar-5455/environment/Dockerfile b/tasks/traccar__traccar-5455/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ee140c50ebdd433bfd06821c231b89366ec1366d --- /dev/null +++ b/tasks/traccar__traccar-5455/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin aab17315038ae4c2fc5b3f9e233a99b95821e53a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard aab17315038ae4c2fc5b3f9e233a99b95821e53a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base aab17315038ae4c2fc5b3f9e233a99b95821e53a \ + && 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/traccar__traccar-5455/instruction.md b/tasks/traccar__traccar-5455/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..347dda861676bfb08393a9744f8299682829b545 --- /dev/null +++ b/tasks/traccar__traccar-5455/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Add data compression to PositionForwarderWialon + +## Description + +If data is bigger then MTU, UDP won't allow to send this. I try to change UDP to TCP, chunk data, but compression do it's best. +Compression is described at the end of this docs: https://extapi.wialon.com/hw/cfg/Wialon%20IPS_en_v_2_0.pdf +Tested on Wialon and build looks fine. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `aab17315038a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5455/solution/patch.diff b/tasks/traccar__traccar-5455/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..20521b48b6b0ceacf69e897081cd4fa101608325 --- /dev/null +++ b/tasks/traccar__traccar-5455/solution/patch.diff @@ -0,0 +1,101 @@ +diff --git a/src/main/java/org/traccar/MainModule.java b/src/main/java/org/traccar/MainModule.java +index 0df85d614..ff159ed03 100644 +--- a/src/main/java/org/traccar/MainModule.java ++++ b/src/main/java/org/traccar/MainModule.java +@@ -371,7 +371,7 @@ public class MainModule extends AbstractModule { + case "kafka" -> new PositionForwarderKafka(config, objectMapper); + case "mqtt" -> new PositionForwarderMqtt(config, objectMapper); + case "redis" -> new PositionForwarderRedis(config, objectMapper); +- case "wialon" -> new PositionForwarderWialon(config, executorService, "1.0"); ++ case "wialon" -> new PositionForwarderWialon(config, executorService, "1.0", false); + default -> new PositionForwarderUrl(config, client, objectMapper); + }; + } +diff --git a/src/main/java/org/traccar/forward/PositionForwarderWialon.java b/src/main/java/org/traccar/forward/PositionForwarderWialon.java +index d4d934694..cf403d7bd 100644 +--- a/src/main/java/org/traccar/forward/PositionForwarderWialon.java ++++ b/src/main/java/org/traccar/forward/PositionForwarderWialon.java +@@ -15,6 +15,8 @@ + */ + package org.traccar.forward; + ++import io.netty.buffer.ByteBuf; ++import io.netty.buffer.Unpooled; + import org.traccar.config.Config; + import org.traccar.config.Keys; + import org.traccar.helper.Checksum; +@@ -35,17 +37,24 @@ import java.util.Map; + import java.util.TimeZone; + import java.util.concurrent.ExecutorService; + import java.util.stream.Collectors; ++import java.util.zip.Deflater; + + public class PositionForwarderWialon implements PositionForwarder { + + private final String version; ++ private final boolean useCompression; + + private final DatagramSocket socket; + private final InetAddress address; + private final int port; + +- public PositionForwarderWialon(Config config, ExecutorService executorService, String version) { ++ public PositionForwarderWialon( ++ Config config, ++ ExecutorService executorService, ++ String version, ++ boolean useCompression) { + this.version = version; ++ this.useCompression = useCompression; + try { + URI url = new URI(config.getString(Keys.FORWARD_URL)); + address = InetAddress.getByName(url.getHost()); +@@ -101,7 +110,14 @@ public class PositionForwarderWialon implements PositionForwarder { + } + + byte[] buffer = message.getBytes(); +- DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port); ++ DatagramPacket packet; ++ ++ if (useCompression) { ++ ByteBuf container = compressData(buffer); ++ packet = new DatagramPacket(container.array(), container.readableBytes(), address, port); ++ } else { ++ packet = new DatagramPacket(buffer, buffer.length, address, port); ++ } + + try { + socket.send(packet); +@@ -111,6 +127,32 @@ public class PositionForwarderWialon implements PositionForwarder { + } + } + ++ public static ByteBuf compressData(byte[] data) { ++ ByteBuf container; ++ Deflater deflater = new Deflater(); ++ deflater.setInput(data); ++ deflater.finish(); ++ ++ ByteBuf compressedData = Unpooled.buffer(data.length); ++ byte[] tempBuffer = new byte[1024]; ++ ++ try { ++ while (!deflater.finished()) { ++ int count = deflater.deflate(tempBuffer); ++ compressedData.writeBytes(tempBuffer, 0, count); ++ } ++ container = Unpooled.buffer(3 + compressedData.readableBytes()); ++ container.writeByte(0xFF); ++ container.writeShortLE(compressedData.readableBytes()); ++ container.writeBytes(compressedData); ++ } finally { ++ deflater.end(); ++ compressedData.release(); ++ } ++ ++ return container; ++ } ++ + public static String formatAttributes(Map attributes) { + if (attributes.isEmpty()) { + return "NA"; diff --git a/tasks/traccar__traccar-5455/solution/solve.sh b/tasks/traccar__traccar-5455/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5455/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/traccar__traccar-5455/task.toml b/tasks/traccar__traccar-5455/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..edf704b564720dc3a54c661a4364b54f83f5e4b5 --- /dev/null +++ b/tasks/traccar__traccar-5455/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5455" +description = "Add data compression to PositionForwarderWialon" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "aab17315038ae4c2fc5b3f9e233a99b95821e53a" +reference = "https://github.com/traccar/traccar/pull/5455" +source_access = "auto" +built_at = "2026-11-16T16:09:42.670438+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:edf37135ffe42f76cb6147d1878ec2423f8f280d67503450737732b59c115de3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-28T04:47:18Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/MainModule.java", + "src/main/java/org/traccar/forward/PositionForwarderWialon.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 48 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.440789+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c4d179b15784c4070447a7d5670f0e89ec1e127c5f7b4b4fc560d91abc199cf4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5455/tests/capture.py b/tasks/traccar__traccar-5455/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5455/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/traccar__traccar-5455/tests/instruction.md b/tasks/traccar__traccar-5455/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..347dda861676bfb08393a9744f8299682829b545 --- /dev/null +++ b/tasks/traccar__traccar-5455/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Add data compression to PositionForwarderWialon + +## Description + +If data is bigger then MTU, UDP won't allow to send this. I try to change UDP to TCP, chunk data, but compression do it's best. +Compression is described at the end of this docs: https://extapi.wialon.com/hw/cfg/Wialon%20IPS_en_v_2_0.pdf +Tested on Wialon and build looks fine. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `aab17315038a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5455/tests/oracle.patch b/tasks/traccar__traccar-5455/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..20521b48b6b0ceacf69e897081cd4fa101608325 --- /dev/null +++ b/tasks/traccar__traccar-5455/tests/oracle.patch @@ -0,0 +1,101 @@ +diff --git a/src/main/java/org/traccar/MainModule.java b/src/main/java/org/traccar/MainModule.java +index 0df85d614..ff159ed03 100644 +--- a/src/main/java/org/traccar/MainModule.java ++++ b/src/main/java/org/traccar/MainModule.java +@@ -371,7 +371,7 @@ public class MainModule extends AbstractModule { + case "kafka" -> new PositionForwarderKafka(config, objectMapper); + case "mqtt" -> new PositionForwarderMqtt(config, objectMapper); + case "redis" -> new PositionForwarderRedis(config, objectMapper); +- case "wialon" -> new PositionForwarderWialon(config, executorService, "1.0"); ++ case "wialon" -> new PositionForwarderWialon(config, executorService, "1.0", false); + default -> new PositionForwarderUrl(config, client, objectMapper); + }; + } +diff --git a/src/main/java/org/traccar/forward/PositionForwarderWialon.java b/src/main/java/org/traccar/forward/PositionForwarderWialon.java +index d4d934694..cf403d7bd 100644 +--- a/src/main/java/org/traccar/forward/PositionForwarderWialon.java ++++ b/src/main/java/org/traccar/forward/PositionForwarderWialon.java +@@ -15,6 +15,8 @@ + */ + package org.traccar.forward; + ++import io.netty.buffer.ByteBuf; ++import io.netty.buffer.Unpooled; + import org.traccar.config.Config; + import org.traccar.config.Keys; + import org.traccar.helper.Checksum; +@@ -35,17 +37,24 @@ import java.util.Map; + import java.util.TimeZone; + import java.util.concurrent.ExecutorService; + import java.util.stream.Collectors; ++import java.util.zip.Deflater; + + public class PositionForwarderWialon implements PositionForwarder { + + private final String version; ++ private final boolean useCompression; + + private final DatagramSocket socket; + private final InetAddress address; + private final int port; + +- public PositionForwarderWialon(Config config, ExecutorService executorService, String version) { ++ public PositionForwarderWialon( ++ Config config, ++ ExecutorService executorService, ++ String version, ++ boolean useCompression) { + this.version = version; ++ this.useCompression = useCompression; + try { + URI url = new URI(config.getString(Keys.FORWARD_URL)); + address = InetAddress.getByName(url.getHost()); +@@ -101,7 +110,14 @@ public class PositionForwarderWialon implements PositionForwarder { + } + + byte[] buffer = message.getBytes(); +- DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port); ++ DatagramPacket packet; ++ ++ if (useCompression) { ++ ByteBuf container = compressData(buffer); ++ packet = new DatagramPacket(container.array(), container.readableBytes(), address, port); ++ } else { ++ packet = new DatagramPacket(buffer, buffer.length, address, port); ++ } + + try { + socket.send(packet); +@@ -111,6 +127,32 @@ public class PositionForwarderWialon implements PositionForwarder { + } + } + ++ public static ByteBuf compressData(byte[] data) { ++ ByteBuf container; ++ Deflater deflater = new Deflater(); ++ deflater.setInput(data); ++ deflater.finish(); ++ ++ ByteBuf compressedData = Unpooled.buffer(data.length); ++ byte[] tempBuffer = new byte[1024]; ++ ++ try { ++ while (!deflater.finished()) { ++ int count = deflater.deflate(tempBuffer); ++ compressedData.writeBytes(tempBuffer, 0, count); ++ } ++ container = Unpooled.buffer(3 + compressedData.readableBytes()); ++ container.writeByte(0xFF); ++ container.writeShortLE(compressedData.readableBytes()); ++ container.writeBytes(compressedData); ++ } finally { ++ deflater.end(); ++ compressedData.release(); ++ } ++ ++ return container; ++ } ++ + public static String formatAttributes(Map attributes) { + if (attributes.isEmpty()) { + return "NA"; diff --git a/tasks/traccar__traccar-5455/tests/test.sh b/tasks/traccar__traccar-5455/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6ae6694250fafafdf4bcb05a9eddd1808db871fc --- /dev/null +++ b/tasks/traccar__traccar-5455/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 aab17315038ae4c2fc5b3f9e233a99b95821e53a > "$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/traccar__traccar-5455/tests/verifier.py b/tasks/traccar__traccar-5455/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5455/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/traccar__traccar-5462/environment/Dockerfile b/tasks/traccar__traccar-5462/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2174481960220053315a4c6a49f9735662fda306 --- /dev/null +++ b/tasks/traccar__traccar-5462/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7c6911318b214868029a454449a8970c41ae164a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7c6911318b214868029a454449a8970c41ae164a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7c6911318b214868029a454449a8970c41ae164a \ + && 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/traccar__traccar-5462/instruction.md b/tasks/traccar__traccar-5462/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c9e7d2bb842af8c9e289bfec67e846c30df06de3 --- /dev/null +++ b/tasks/traccar__traccar-5462/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add Alarm attribute to Minifinder2ProtocolDecoder.java + +## Description + +Add Alarm attribute to the Minifinder2 protocol to get the raw alarm data. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7c6911318b21`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5462/solution/patch.diff b/tasks/traccar__traccar-5462/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..68a41425dbb01a7813d89b0a492e3cbe9dc2788c --- /dev/null +++ b/tasks/traccar__traccar-5462/solution/patch.diff @@ -0,0 +1,38 @@ +diff --git a/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java +index aa588a5b1..8f39953ef 100644 +--- a/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java +@@ -165,12 +165,25 @@ public class Minifinder2ProtocolDecoder extends BaseProtocolDecoder { + if (BitUtil.check(alarm, 2)) { + position.addAlarm(Position.ALARM_FALL_DOWN); + } ++ for (int i = 0; i < 4; i++) { ++ if (BitUtil.check(alarm, i + 4)) { ++ if (BitUtil.check(alarm, i + 26)) { ++ position.addAlarm(Position.ALARM_GEOFENCE_ENTER); ++ } else { ++ position.addAlarm(Position.ALARM_GEOFENCE_EXIT); ++ } ++ position.set(Position.KEY_GEOFENCE, i + 1); ++ } ++ } + if (BitUtil.check(alarm, 8)) { + position.addAlarm(Position.ALARM_POWER_OFF); + } + if (BitUtil.check(alarm, 9)) { + position.addAlarm(Position.ALARM_POWER_ON); + } ++ if (BitUtil.check(alarm, 10)) { ++ position.addAlarm(Position.ALARM_MOVEMENT); ++ } + if (BitUtil.check(alarm, 12)) { + position.addAlarm(Position.ALARM_SOS); + } +@@ -180,6 +193,7 @@ public class Minifinder2ProtocolDecoder extends BaseProtocolDecoder { + if (length == 5) { + position.setDeviceTime(new Date(buf.readUnsignedIntLE() * 1000)); + } ++ position.set(Position.KEY_EVENT, alarm); + break; + case 0x14: + position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); diff --git a/tasks/traccar__traccar-5462/solution/solve.sh b/tasks/traccar__traccar-5462/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5462/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/traccar__traccar-5462/task.toml b/tasks/traccar__traccar-5462/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..236f24703c4080bd37accb4e46a03b4f1e7d641f --- /dev/null +++ b/tasks/traccar__traccar-5462/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5462" +description = "Add Alarm attribute to Minifinder2ProtocolDecoder.java" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "7c6911318b214868029a454449a8970c41ae164a" +reference = "https://github.com/traccar/traccar/pull/5462" +source_access = "auto" +built_at = "2026-11-16T16:09:42.654623+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5ee52006e4c475f28985e34cebfeb3727e6bc72a4a3cf8b4ce6b9ac67d95d359" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-02-28T16:21:33Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.441286+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fb62143d8e0443a530311c70738d0f0cd918d45b87f375183bfe4d8f4bf0fdf0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5462/tests/capture.py b/tasks/traccar__traccar-5462/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5462/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/traccar__traccar-5462/tests/instruction.md b/tasks/traccar__traccar-5462/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c9e7d2bb842af8c9e289bfec67e846c30df06de3 --- /dev/null +++ b/tasks/traccar__traccar-5462/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add Alarm attribute to Minifinder2ProtocolDecoder.java + +## Description + +Add Alarm attribute to the Minifinder2 protocol to get the raw alarm data. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7c6911318b21`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5462/tests/oracle.patch b/tasks/traccar__traccar-5462/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..68a41425dbb01a7813d89b0a492e3cbe9dc2788c --- /dev/null +++ b/tasks/traccar__traccar-5462/tests/oracle.patch @@ -0,0 +1,38 @@ +diff --git a/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java +index aa588a5b1..8f39953ef 100644 +--- a/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java +@@ -165,12 +165,25 @@ public class Minifinder2ProtocolDecoder extends BaseProtocolDecoder { + if (BitUtil.check(alarm, 2)) { + position.addAlarm(Position.ALARM_FALL_DOWN); + } ++ for (int i = 0; i < 4; i++) { ++ if (BitUtil.check(alarm, i + 4)) { ++ if (BitUtil.check(alarm, i + 26)) { ++ position.addAlarm(Position.ALARM_GEOFENCE_ENTER); ++ } else { ++ position.addAlarm(Position.ALARM_GEOFENCE_EXIT); ++ } ++ position.set(Position.KEY_GEOFENCE, i + 1); ++ } ++ } + if (BitUtil.check(alarm, 8)) { + position.addAlarm(Position.ALARM_POWER_OFF); + } + if (BitUtil.check(alarm, 9)) { + position.addAlarm(Position.ALARM_POWER_ON); + } ++ if (BitUtil.check(alarm, 10)) { ++ position.addAlarm(Position.ALARM_MOVEMENT); ++ } + if (BitUtil.check(alarm, 12)) { + position.addAlarm(Position.ALARM_SOS); + } +@@ -180,6 +193,7 @@ public class Minifinder2ProtocolDecoder extends BaseProtocolDecoder { + if (length == 5) { + position.setDeviceTime(new Date(buf.readUnsignedIntLE() * 1000)); + } ++ position.set(Position.KEY_EVENT, alarm); + break; + case 0x14: + position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); diff --git a/tasks/traccar__traccar-5462/tests/test.sh b/tasks/traccar__traccar-5462/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9eb8c88edbd45db9cc7b412da4cd5b7429ed4e0a --- /dev/null +++ b/tasks/traccar__traccar-5462/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 7c6911318b214868029a454449a8970c41ae164a > "$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/traccar__traccar-5462/tests/verifier.py b/tasks/traccar__traccar-5462/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5462/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/traccar__traccar-5466/environment/Dockerfile b/tasks/traccar__traccar-5466/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f15983550111d57d7a8a986523525e0217e09ecb --- /dev/null +++ b/tasks/traccar__traccar-5466/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2c14a8ebd162cfa21d4e366a1d3d988c0423b320 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2c14a8ebd162cfa21d4e366a1d3d988c0423b320 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2c14a8ebd162cfa21d4e366a1d3d988c0423b320 \ + && 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/traccar__traccar-5466/instruction.md b/tasks/traccar__traccar-5466/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9a2d0932e3865e9d35663fa524484975b2347ee4 --- /dev/null +++ b/tasks/traccar__traccar-5466/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Fix: Set UTF-8 Encoding for Proper Rendering of Chinese Characters in Server Title + +## Description + +The server title in the Traccar web interface was displaying as garbled characters when set to Chinese strings due to a missing charset=utf-8 in the response Content-Type header. This change ensures that the server title is rendered correctly by explicitly setting the response's character encoding to UTF-8. + +Changes: +- Modified the OverrideFilter class to set response.setCharacterEncoding("UTF-8"). +- Ensured proper rendering of the title/description in the web interface. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2c14a8ebd162`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5466/solution/patch.diff b/tasks/traccar__traccar-5466/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d799c5dfe97d9af96b717148186c5cc06bf393f7 --- /dev/null +++ b/tasks/traccar__traccar-5466/solution/patch.diff @@ -0,0 +1,27 @@ +diff --git a/src/main/java/org/traccar/web/OverrideFilter.java b/src/main/java/org/traccar/web/OverrideFilter.java +index 9780c9ede..067e03c08 100644 +--- a/src/main/java/org/traccar/web/OverrideFilter.java ++++ b/src/main/java/org/traccar/web/OverrideFilter.java +@@ -30,6 +30,7 @@ import jakarta.servlet.ServletResponse; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; ++import java.nio.charset.StandardCharsets; + + @Singleton + public class OverrideFilter implements Filter { +@@ -70,12 +71,12 @@ public class OverrideFilter implements Filter { + String description = server.getString("description", "Traccar GPS Tracking System"); + String colorPrimary = server.getString("colorPrimary", "#1a237e"); + +- String alteredContent = new String(wrappedResponse.getCapture()) ++ String alteredContent = new String(wrappedResponse.getCapture(), StandardCharsets.UTF_8) + .replace("${title}", title) + .replace("${description}", description) + .replace("${colorPrimary}", colorPrimary); + +- byte[] data = alteredContent.getBytes(); ++ byte[] data = alteredContent.getBytes(StandardCharsets.UTF_8); + response.setContentLength(data.length); + response.getOutputStream().write(data); + diff --git a/tasks/traccar__traccar-5466/solution/solve.sh b/tasks/traccar__traccar-5466/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5466/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/traccar__traccar-5466/task.toml b/tasks/traccar__traccar-5466/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..233116575153a9a2c8760dd7cac3ed4ef6eedb60 --- /dev/null +++ b/tasks/traccar__traccar-5466/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5466" +description = "Fix: Set UTF-8 Encoding for Proper Rendering of Chinese Characters in Server Title" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "2c14a8ebd162cfa21d4e366a1d3d988c0423b320" +reference = "https://github.com/traccar/traccar/pull/5466" +source_access = "auto" +built_at = "2026-11-16T16:09:42.668923+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:43b82fffa5a97a63bcc69f41dac16d0817a034e6d70b06d75631e1a9055963e5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-11-18T01:56:17Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/web/OverrideFilter.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.441837+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:84c56d746c894c4e59a09bc2088e9a177c7695fbe27386b8cfabd3b14b6bd38a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5466/tests/capture.py b/tasks/traccar__traccar-5466/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5466/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/traccar__traccar-5466/tests/instruction.md b/tasks/traccar__traccar-5466/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9a2d0932e3865e9d35663fa524484975b2347ee4 --- /dev/null +++ b/tasks/traccar__traccar-5466/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Fix: Set UTF-8 Encoding for Proper Rendering of Chinese Characters in Server Title + +## Description + +The server title in the Traccar web interface was displaying as garbled characters when set to Chinese strings due to a missing charset=utf-8 in the response Content-Type header. This change ensures that the server title is rendered correctly by explicitly setting the response's character encoding to UTF-8. + +Changes: +- Modified the OverrideFilter class to set response.setCharacterEncoding("UTF-8"). +- Ensured proper rendering of the title/description in the web interface. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2c14a8ebd162`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5466/tests/oracle.patch b/tasks/traccar__traccar-5466/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d799c5dfe97d9af96b717148186c5cc06bf393f7 --- /dev/null +++ b/tasks/traccar__traccar-5466/tests/oracle.patch @@ -0,0 +1,27 @@ +diff --git a/src/main/java/org/traccar/web/OverrideFilter.java b/src/main/java/org/traccar/web/OverrideFilter.java +index 9780c9ede..067e03c08 100644 +--- a/src/main/java/org/traccar/web/OverrideFilter.java ++++ b/src/main/java/org/traccar/web/OverrideFilter.java +@@ -30,6 +30,7 @@ import jakarta.servlet.ServletResponse; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; ++import java.nio.charset.StandardCharsets; + + @Singleton + public class OverrideFilter implements Filter { +@@ -70,12 +71,12 @@ public class OverrideFilter implements Filter { + String description = server.getString("description", "Traccar GPS Tracking System"); + String colorPrimary = server.getString("colorPrimary", "#1a237e"); + +- String alteredContent = new String(wrappedResponse.getCapture()) ++ String alteredContent = new String(wrappedResponse.getCapture(), StandardCharsets.UTF_8) + .replace("${title}", title) + .replace("${description}", description) + .replace("${colorPrimary}", colorPrimary); + +- byte[] data = alteredContent.getBytes(); ++ byte[] data = alteredContent.getBytes(StandardCharsets.UTF_8); + response.setContentLength(data.length); + response.getOutputStream().write(data); + diff --git a/tasks/traccar__traccar-5466/tests/test.sh b/tasks/traccar__traccar-5466/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0d28615e1fc8712a0a86ce7fbbf0d85cf241a516 --- /dev/null +++ b/tasks/traccar__traccar-5466/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 2c14a8ebd162cfa21d4e366a1d3d988c0423b320 > "$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/traccar__traccar-5466/tests/verifier.py b/tasks/traccar__traccar-5466/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5466/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/traccar__traccar-5474/environment/Dockerfile b/tasks/traccar__traccar-5474/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dabdfee99179d201e739669122ee95002cc76ff5 --- /dev/null +++ b/tasks/traccar__traccar-5474/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f207007903ecaa4923cf3f7f247899c813ccea40 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f207007903ecaa4923cf3f7f247899c813ccea40 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f207007903ecaa4923cf3f7f247899c813ccea40 \ + && 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/traccar__traccar-5474/instruction.md b/tasks/traccar__traccar-5474/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..99f42256b78e7a98c5d1c00acea117d9c192cd86 --- /dev/null +++ b/tasks/traccar__traccar-5474/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** X3Tech NT20 new location message + +## Description + +[NT11 NT20 NT26 NT40 NT46 Protocol rev3.33.pdf](https://github.com/user-attachments/files/18044962/NT11.NT20.NT26.NT40.NT46.Protocol.rev3.33.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f207007903ec`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5474/solution/patch.diff b/tasks/traccar__traccar-5474/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..fd1dfc47e88712d6e0a0a9dbe1a7023f96607f5c --- /dev/null +++ b/tasks/traccar__traccar-5474/solution/patch.diff @@ -0,0 +1,202 @@ +diff --git a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +index 2d875cf71..d03fa0b02 100644 +--- a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +@@ -161,8 +161,8 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + .number("(dd):(dd):(dd)") // time + .compile(); + +- private static boolean isSupported(int type) { +- return hasGps(type) || hasLbs(type) || hasStatus(type); ++ private static boolean isSupported(int type, String model) { ++ return hasGps(type) || hasLbs(type) || hasStatus(type, model); + } + + private static boolean hasGps(int type) { +@@ -217,7 +217,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + } + +- private static boolean hasStatus(int type) { ++ private static boolean hasStatus(int type, String model) { + switch (type) { + case MSG_STATUS: + case MSG_STATUS_2: +@@ -230,6 +230,8 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + case MSG_FENCE_MULTI: + case MSG_LBS_ALARM: + return true; ++ case MSG_GPS_LBS_2: ++ return "NT20".equalsIgnoreCase(model); + default: + return false; + } +@@ -458,6 +460,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + + String model = deviceSession != null ? getDeviceModel(deviceSession) : null; + boolean modelLW = model != null && model.toUpperCase().startsWith("LW"); ++ boolean modelNt20 = model != null && model.equalsIgnoreCase("NT20"); + + if (type == MSG_LOGIN) { + +@@ -666,11 +669,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + || type == MSG_LBS_EXTEND || type == MSG_LBS_WIFI || type == MSG_LBS_2 || type == MSG_LBS_3 + || (type == MSG_WIFI_3 && variant != Variant.LW4G) || type == MSG_WIFI_5) { + +- DateBuilder dateBuilder = new DateBuilder((TimeZone) deviceSession.get(DeviceSession.KEY_TIMEZONE)) +- .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) +- .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); +- +- getLastLocation(position, dateBuilder.getDate()); ++ getLastLocation(position, decodeDate(buf, deviceSession)); + + if (variant == Variant.WANWAY_S20 || variant == Variant.SL4X) { + buf.readUnsignedByte(); // ta +@@ -786,7 +785,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + double temperature = BitUtil.to(value, 15) * 0.1; + position.set(Position.PREFIX_TEMP + 1, BitUtil.check(value, 15) ? temperature : -temperature); + +- } else if (isSupported(type)) { ++ } else if (isSupported(type, model)) { + + if (type == MSG_LBS_STATUS && variant == Variant.SPACE10X) { + return null; // multi-lbs message +@@ -794,6 +793,12 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + + position.set(Position.KEY_TYPE, type); + ++ if (type == MSG_GPS_LBS_2 && modelNt20) { ++ buf.readUnsignedByte(); // location source type ++ buf.skipBytes(8); // imei ++ position.setDeviceTime(decodeDate(buf, deviceSession)); ++ } ++ + if (hasGps(type)) { + decodeGps(position, buf, false, deviceSession.get(DeviceSession.KEY_TIMEZONE)); + } else { +@@ -801,7 +806,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + + if (hasLbs(type) && buf.readableBytes() > 6) { +- boolean hasLength = hasStatus(type) ++ boolean hasLength = hasStatus(type, model) + && type != MSG_LBS_STATUS + && type != MSG_LBS_ALARM + && (type != MSG_GPS_LBS_STATUS_1 || variant != Variant.VXT01) +@@ -809,7 +814,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + decodeLbs(position, buf, type, hasLength); + } + +- if (hasStatus(type)) { ++ if (hasStatus(type, model)) { + if (type == MSG_GPS_LBS_STATUS_5) { + buf.readUnsignedByte(); // network indicator + } +@@ -830,13 +835,16 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.PREFIX_TEMP + 1, buf.readShort() / 10.0); + } + } else { +- if (type == MSG_GPS_LBS_STATUS_5) { ++ if (type == MSG_GPS_LBS_STATUS_5 || (modelNt20 && type == MSG_GPS_LBS_2)) { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); + } + if (type == MSG_STATUS && "R11".equals(model)) { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); + } else { + int battery = buf.readUnsignedByte(); ++ if (modelNt20 && type == MSG_GPS_LBS_2) { ++ battery = battery / 10; ++ } + if (battery <= 6) { + position.set(Position.KEY_BATTERY_LEVEL, battery * 100 / 6); + } else if (battery <= 100) { +@@ -950,7 +958,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + + if ((type == MSG_GPS_LBS_2 || type == MSG_GPS_LBS_3 || type == MSG_GPS_LBS_4 || type == MSG_GPS_LBS_5) +- && buf.readableBytes() >= 3 + 6) { ++ && buf.readableBytes() >= 3 + 6 && !modelNt20) { + position.set(Position.KEY_IGNITION, buf.readUnsignedByte() > 0); + position.set(Position.KEY_EVENT, buf.readUnsignedByte()); // reason + position.set(Position.KEY_ARCHIVE, buf.readUnsignedByte() > 0); +@@ -978,6 +986,12 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + buf.readUnsignedByte(); // validity + } + ++ if (modelNt20 && type == MSG_GPS_LBS_2) { ++ buf.readUnsignedByte(); // language ++ position.set(Position.KEY_ODOMETER, buf.readMedium()); ++ position.set(Position.KEY_HOURS, buf.readMedium() * 60 * 1000); ++ } ++ + if (buf.readableBytes() == 3 + 6 || buf.readableBytes() == 3 + 4 + 6) { + position.set(Position.KEY_IGNITION, buf.readUnsignedByte() > 0); + buf.readUnsignedByte(); // upload mode +@@ -1005,10 +1019,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + position, buf, false, jc400, jc400, jc400, jc400, + deviceSession.get(DeviceSession.KEY_TIMEZONE)); + } else { +- DateBuilder dateBuilder = new DateBuilder((TimeZone) deviceSession.get(DeviceSession.KEY_TIMEZONE)) +- .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) +- .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); +- getLastLocation(position, dateBuilder.getDate()); ++ getLastLocation(position, decodeDate(buf, deviceSession)); + } + if (variant == Variant.JC400) { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.1); +@@ -1051,6 +1062,13 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + return position; + } + ++ private static Date decodeDate(ByteBuf buf, DeviceSession deviceSession) { ++ DateBuilder dateBuilder = new DateBuilder((TimeZone) deviceSession.get(DeviceSession.KEY_TIMEZONE)) ++ .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) ++ .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); ++ return dateBuilder.getDate(); ++ } ++ + private Object decodeExtended(Channel channel, SocketAddress remoteAddress, ByteBuf buf) { + + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); +@@ -1131,10 +1149,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } else if (subType == 0x05) { + + if (buf.readableBytes() >= 6 + 1 + 6) { +- DateBuilder dateBuilder = new DateBuilder((TimeZone) deviceSession.get(DeviceSession.KEY_TIMEZONE)) +- .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) +- .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); +- position.setDeviceTime(dateBuilder.getDate()); ++ position.setDeviceTime(decodeDate(buf, deviceSession)); + } + + int flags = buf.readUnsignedByte(); +@@ -1237,11 +1252,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + + } else if (type == MSG_OBD) { + +- DateBuilder dateBuilder = new DateBuilder((TimeZone) deviceSession.get(DeviceSession.KEY_TIMEZONE)) +- .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) +- .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); +- +- getLastLocation(position, dateBuilder.getDate()); ++ getLastLocation(position, decodeDate(buf, deviceSession)); + + position.set(Position.KEY_IGNITION, buf.readUnsignedByte() > 0); + +diff --git a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +index eb16c5e40..1a29e637c 100644 +--- a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +@@ -558,6 +558,12 @@ public class Gt06ProtocolDecoderTest extends ProtocolTest { + "78780a13460b120400160642c20d0a"), + Position.KEY_POWER, 28.34); + ++ decoder.setModelOverride("NT20"); ++ ++ verifyAttribute(decoder, binary( ++ "78783c22010357789648774484180c06142038180c06142038cb03313ee4061fe98300185e090000000000000000460984284c000200000000017101d6f35d0d0a"), ++ Position.KEY_HOURS, 22140000); ++ + } + + } diff --git a/tasks/traccar__traccar-5474/solution/solve.sh b/tasks/traccar__traccar-5474/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5474/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/traccar__traccar-5474/task.toml b/tasks/traccar__traccar-5474/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..64dd81fe6b2b0f525850c564d90f8991024f72d5 --- /dev/null +++ b/tasks/traccar__traccar-5474/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5474" +description = "X3Tech NT20 new location message" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "f207007903ecaa4923cf3f7f247899c813ccea40" +reference = "https://github.com/traccar/traccar/pull/5474" +source_access = "auto" +built_at = "2026-11-16T16:09:42.667490+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8b2170860959ad460effff4ffeca36c51f336d000015a5abb1aff166bf88eb93" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-08T18:44:40Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java", +] +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:03.442369+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:11d2754904fecaea2e1f1633d04335310f9358c183573a5247d213c0ea8a67c4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5474/tests/capture.py b/tasks/traccar__traccar-5474/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5474/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/traccar__traccar-5474/tests/instruction.md b/tasks/traccar__traccar-5474/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..99f42256b78e7a98c5d1c00acea117d9c192cd86 --- /dev/null +++ b/tasks/traccar__traccar-5474/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** X3Tech NT20 new location message + +## Description + +[NT11 NT20 NT26 NT40 NT46 Protocol rev3.33.pdf](https://github.com/user-attachments/files/18044962/NT11.NT20.NT26.NT40.NT46.Protocol.rev3.33.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f207007903ec`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5474/tests/oracle.patch b/tasks/traccar__traccar-5474/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..fd1dfc47e88712d6e0a0a9dbe1a7023f96607f5c --- /dev/null +++ b/tasks/traccar__traccar-5474/tests/oracle.patch @@ -0,0 +1,202 @@ +diff --git a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +index 2d875cf71..d03fa0b02 100644 +--- a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +@@ -161,8 +161,8 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + .number("(dd):(dd):(dd)") // time + .compile(); + +- private static boolean isSupported(int type) { +- return hasGps(type) || hasLbs(type) || hasStatus(type); ++ private static boolean isSupported(int type, String model) { ++ return hasGps(type) || hasLbs(type) || hasStatus(type, model); + } + + private static boolean hasGps(int type) { +@@ -217,7 +217,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + } + +- private static boolean hasStatus(int type) { ++ private static boolean hasStatus(int type, String model) { + switch (type) { + case MSG_STATUS: + case MSG_STATUS_2: +@@ -230,6 +230,8 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + case MSG_FENCE_MULTI: + case MSG_LBS_ALARM: + return true; ++ case MSG_GPS_LBS_2: ++ return "NT20".equalsIgnoreCase(model); + default: + return false; + } +@@ -458,6 +460,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + + String model = deviceSession != null ? getDeviceModel(deviceSession) : null; + boolean modelLW = model != null && model.toUpperCase().startsWith("LW"); ++ boolean modelNt20 = model != null && model.equalsIgnoreCase("NT20"); + + if (type == MSG_LOGIN) { + +@@ -666,11 +669,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + || type == MSG_LBS_EXTEND || type == MSG_LBS_WIFI || type == MSG_LBS_2 || type == MSG_LBS_3 + || (type == MSG_WIFI_3 && variant != Variant.LW4G) || type == MSG_WIFI_5) { + +- DateBuilder dateBuilder = new DateBuilder((TimeZone) deviceSession.get(DeviceSession.KEY_TIMEZONE)) +- .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) +- .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); +- +- getLastLocation(position, dateBuilder.getDate()); ++ getLastLocation(position, decodeDate(buf, deviceSession)); + + if (variant == Variant.WANWAY_S20 || variant == Variant.SL4X) { + buf.readUnsignedByte(); // ta +@@ -786,7 +785,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + double temperature = BitUtil.to(value, 15) * 0.1; + position.set(Position.PREFIX_TEMP + 1, BitUtil.check(value, 15) ? temperature : -temperature); + +- } else if (isSupported(type)) { ++ } else if (isSupported(type, model)) { + + if (type == MSG_LBS_STATUS && variant == Variant.SPACE10X) { + return null; // multi-lbs message +@@ -794,6 +793,12 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + + position.set(Position.KEY_TYPE, type); + ++ if (type == MSG_GPS_LBS_2 && modelNt20) { ++ buf.readUnsignedByte(); // location source type ++ buf.skipBytes(8); // imei ++ position.setDeviceTime(decodeDate(buf, deviceSession)); ++ } ++ + if (hasGps(type)) { + decodeGps(position, buf, false, deviceSession.get(DeviceSession.KEY_TIMEZONE)); + } else { +@@ -801,7 +806,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + + if (hasLbs(type) && buf.readableBytes() > 6) { +- boolean hasLength = hasStatus(type) ++ boolean hasLength = hasStatus(type, model) + && type != MSG_LBS_STATUS + && type != MSG_LBS_ALARM + && (type != MSG_GPS_LBS_STATUS_1 || variant != Variant.VXT01) +@@ -809,7 +814,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + decodeLbs(position, buf, type, hasLength); + } + +- if (hasStatus(type)) { ++ if (hasStatus(type, model)) { + if (type == MSG_GPS_LBS_STATUS_5) { + buf.readUnsignedByte(); // network indicator + } +@@ -830,13 +835,16 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.PREFIX_TEMP + 1, buf.readShort() / 10.0); + } + } else { +- if (type == MSG_GPS_LBS_STATUS_5) { ++ if (type == MSG_GPS_LBS_STATUS_5 || (modelNt20 && type == MSG_GPS_LBS_2)) { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); + } + if (type == MSG_STATUS && "R11".equals(model)) { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); + } else { + int battery = buf.readUnsignedByte(); ++ if (modelNt20 && type == MSG_GPS_LBS_2) { ++ battery = battery / 10; ++ } + if (battery <= 6) { + position.set(Position.KEY_BATTERY_LEVEL, battery * 100 / 6); + } else if (battery <= 100) { +@@ -950,7 +958,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + + if ((type == MSG_GPS_LBS_2 || type == MSG_GPS_LBS_3 || type == MSG_GPS_LBS_4 || type == MSG_GPS_LBS_5) +- && buf.readableBytes() >= 3 + 6) { ++ && buf.readableBytes() >= 3 + 6 && !modelNt20) { + position.set(Position.KEY_IGNITION, buf.readUnsignedByte() > 0); + position.set(Position.KEY_EVENT, buf.readUnsignedByte()); // reason + position.set(Position.KEY_ARCHIVE, buf.readUnsignedByte() > 0); +@@ -978,6 +986,12 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + buf.readUnsignedByte(); // validity + } + ++ if (modelNt20 && type == MSG_GPS_LBS_2) { ++ buf.readUnsignedByte(); // language ++ position.set(Position.KEY_ODOMETER, buf.readMedium()); ++ position.set(Position.KEY_HOURS, buf.readMedium() * 60 * 1000); ++ } ++ + if (buf.readableBytes() == 3 + 6 || buf.readableBytes() == 3 + 4 + 6) { + position.set(Position.KEY_IGNITION, buf.readUnsignedByte() > 0); + buf.readUnsignedByte(); // upload mode +@@ -1005,10 +1019,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + position, buf, false, jc400, jc400, jc400, jc400, + deviceSession.get(DeviceSession.KEY_TIMEZONE)); + } else { +- DateBuilder dateBuilder = new DateBuilder((TimeZone) deviceSession.get(DeviceSession.KEY_TIMEZONE)) +- .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) +- .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); +- getLastLocation(position, dateBuilder.getDate()); ++ getLastLocation(position, decodeDate(buf, deviceSession)); + } + if (variant == Variant.JC400) { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.1); +@@ -1051,6 +1062,13 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + return position; + } + ++ private static Date decodeDate(ByteBuf buf, DeviceSession deviceSession) { ++ DateBuilder dateBuilder = new DateBuilder((TimeZone) deviceSession.get(DeviceSession.KEY_TIMEZONE)) ++ .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) ++ .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); ++ return dateBuilder.getDate(); ++ } ++ + private Object decodeExtended(Channel channel, SocketAddress remoteAddress, ByteBuf buf) { + + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); +@@ -1131,10 +1149,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } else if (subType == 0x05) { + + if (buf.readableBytes() >= 6 + 1 + 6) { +- DateBuilder dateBuilder = new DateBuilder((TimeZone) deviceSession.get(DeviceSession.KEY_TIMEZONE)) +- .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) +- .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); +- position.setDeviceTime(dateBuilder.getDate()); ++ position.setDeviceTime(decodeDate(buf, deviceSession)); + } + + int flags = buf.readUnsignedByte(); +@@ -1237,11 +1252,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + + } else if (type == MSG_OBD) { + +- DateBuilder dateBuilder = new DateBuilder((TimeZone) deviceSession.get(DeviceSession.KEY_TIMEZONE)) +- .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) +- .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); +- +- getLastLocation(position, dateBuilder.getDate()); ++ getLastLocation(position, decodeDate(buf, deviceSession)); + + position.set(Position.KEY_IGNITION, buf.readUnsignedByte() > 0); + +diff --git a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +index eb16c5e40..1a29e637c 100644 +--- a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +@@ -558,6 +558,12 @@ public class Gt06ProtocolDecoderTest extends ProtocolTest { + "78780a13460b120400160642c20d0a"), + Position.KEY_POWER, 28.34); + ++ decoder.setModelOverride("NT20"); ++ ++ verifyAttribute(decoder, binary( ++ "78783c22010357789648774484180c06142038180c06142038cb03313ee4061fe98300185e090000000000000000460984284c000200000000017101d6f35d0d0a"), ++ Position.KEY_HOURS, 22140000); ++ + } + + } diff --git a/tasks/traccar__traccar-5474/tests/test.sh b/tasks/traccar__traccar-5474/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a1a53045352c0cd70aac307b8ca628946c3664ea --- /dev/null +++ b/tasks/traccar__traccar-5474/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 f207007903ecaa4923cf3f7f247899c813ccea40 > "$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/traccar__traccar-5474/tests/verifier.py b/tasks/traccar__traccar-5474/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5474/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/traccar__traccar-5478/environment/Dockerfile b/tasks/traccar__traccar-5478/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..83c30e502e549e895bcfcfae806d0ade2011a06d --- /dev/null +++ b/tasks/traccar__traccar-5478/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d88101460345f7b2e788d1610a174774b5109fb0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d88101460345f7b2e788d1610a174774b5109fb0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d88101460345f7b2e788d1610a174774b5109fb0 \ + && 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/traccar__traccar-5478/instruction.md b/tasks/traccar__traccar-5478/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6af949b20545ffebe85b644e5e26f01b73516fac --- /dev/null +++ b/tasks/traccar__traccar-5478/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix GTCAN in GV355CEU + +## Description + +[GV355CEU@Track_Air_Interface_Protocol_v0704.pdf](https://github.com/user-attachments/files/18134033/GV355CEU%40Track_Air_Interface_Protocol_v0704.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d88101460345`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5478/solution/patch.diff b/tasks/traccar__traccar-5478/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cdfced46a79164333b28ea6eb5b80c29ff300ca7 --- /dev/null +++ b/tasks/traccar__traccar-5478/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +index e3470c47f..865b8abba 100644 +--- a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +@@ -632,7 +632,7 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + reportMaskExt = Long.parseLong(v[index - 1], 16); + } + if (BitUtil.check(reportMaskExt, 0) && !v[index++].isEmpty()) { +- position.set("adBlueLevel", Integer.parseInt(v[index - 1])); ++ position.set("adBlueLevel", Double.parseDouble(v[index - 1].substring(1))); + } + if (BitUtil.check(reportMaskExt, 1) && !v[index++].isEmpty()) { + position.set("axleWeight1", Integer.parseInt(v[index - 1])); +diff --git a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +index 9ad37d8e7..3403f614a 100644 +--- a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Gl200TextProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Gl200TextProtocolDecoder(null)); + ++ verifyAttribute(decoder, buffer( ++ "+BUFF:GTCAN,8020050402,867488060267845,,00,1,E00FFFFF,YS2K4X20001928588,1,H149381,4236.08,0,0,58,,P94.80,,0,529.00,0.03,0.33,0.77,8688,0008,0042,00,00,001FFFFF,P100.00,5571,,,0,0,,,20,7,0,0.36,0.00,0.00,0,E E05653940B000003,,C*********,,4054MTX,0000,,,1,0.0,101,698.5,-3.647673,40.481997,20241213113715,0214,0003,04D2,B801,00,20241213113715,1A47$"), ++ "adBlueLevel", 100.0); ++ + verifyAttribute(decoder, buffer( + "+RESP:GTINF,C20113,869653060997976,,1A,89464278206103756482,19,0,11,12295,13985,4.25,0,0,,,20241104220934,0,0,,00,00,,,20241104162009,06D6$"), + "power2", 13.985); diff --git a/tasks/traccar__traccar-5478/solution/solve.sh b/tasks/traccar__traccar-5478/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5478/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/traccar__traccar-5478/task.toml b/tasks/traccar__traccar-5478/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..23d3cfd285d5ddcd00618848e641a09defdb2e08 --- /dev/null +++ b/tasks/traccar__traccar-5478/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5478" +description = "Fix GTCAN in GV355CEU" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "d88101460345f7b2e788d1610a174774b5109fb0" +reference = "https://github.com/traccar/traccar/pull/5478" +source_access = "auto" +built_at = "2026-11-16T16:09:42.666059+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7297b71c557042bc756527d3c668e9082a00ce53f17f78fa9275d43d963a461e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-14T05:38:36Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.442892+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ccac73a09d22dd341a34a9a11337fec47f5e32cfdf918d563ab3ee95c1ce5df9" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5478/tests/capture.py b/tasks/traccar__traccar-5478/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5478/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/traccar__traccar-5478/tests/instruction.md b/tasks/traccar__traccar-5478/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6af949b20545ffebe85b644e5e26f01b73516fac --- /dev/null +++ b/tasks/traccar__traccar-5478/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix GTCAN in GV355CEU + +## Description + +[GV355CEU@Track_Air_Interface_Protocol_v0704.pdf](https://github.com/user-attachments/files/18134033/GV355CEU%40Track_Air_Interface_Protocol_v0704.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d88101460345`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5478/tests/oracle.patch b/tasks/traccar__traccar-5478/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cdfced46a79164333b28ea6eb5b80c29ff300ca7 --- /dev/null +++ b/tasks/traccar__traccar-5478/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +index e3470c47f..865b8abba 100644 +--- a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +@@ -632,7 +632,7 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + reportMaskExt = Long.parseLong(v[index - 1], 16); + } + if (BitUtil.check(reportMaskExt, 0) && !v[index++].isEmpty()) { +- position.set("adBlueLevel", Integer.parseInt(v[index - 1])); ++ position.set("adBlueLevel", Double.parseDouble(v[index - 1].substring(1))); + } + if (BitUtil.check(reportMaskExt, 1) && !v[index++].isEmpty()) { + position.set("axleWeight1", Integer.parseInt(v[index - 1])); +diff --git a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +index 9ad37d8e7..3403f614a 100644 +--- a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Gl200TextProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Gl200TextProtocolDecoder(null)); + ++ verifyAttribute(decoder, buffer( ++ "+BUFF:GTCAN,8020050402,867488060267845,,00,1,E00FFFFF,YS2K4X20001928588,1,H149381,4236.08,0,0,58,,P94.80,,0,529.00,0.03,0.33,0.77,8688,0008,0042,00,00,001FFFFF,P100.00,5571,,,0,0,,,20,7,0,0.36,0.00,0.00,0,E E05653940B000003,,C*********,,4054MTX,0000,,,1,0.0,101,698.5,-3.647673,40.481997,20241213113715,0214,0003,04D2,B801,00,20241213113715,1A47$"), ++ "adBlueLevel", 100.0); ++ + verifyAttribute(decoder, buffer( + "+RESP:GTINF,C20113,869653060997976,,1A,89464278206103756482,19,0,11,12295,13985,4.25,0,0,,,20241104220934,0,0,,00,00,,,20241104162009,06D6$"), + "power2", 13.985); diff --git a/tasks/traccar__traccar-5478/tests/test.sh b/tasks/traccar__traccar-5478/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9124fa02d51a3732390049aa0afb426ef8d8ca64 --- /dev/null +++ b/tasks/traccar__traccar-5478/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 d88101460345f7b2e788d1610a174774b5109fb0 > "$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/traccar__traccar-5478/tests/verifier.py b/tasks/traccar__traccar-5478/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5478/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/traccar__traccar-5483/environment/Dockerfile b/tasks/traccar__traccar-5483/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..301763ba824956cb586baba8c1c434c3b92fab42 --- /dev/null +++ b/tasks/traccar__traccar-5483/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3372cf03a9c9312d14a929bd44dabd69ab3395ef 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3372cf03a9c9312d14a929bd44dabd69ab3395ef \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3372cf03a9c9312d14a929bd44dabd69ab3395ef \ + && 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/traccar__traccar-5483/instruction.md b/tasks/traccar__traccar-5483/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..880e37c104ff083db91d2e12df88bb0079d5ae2b --- /dev/null +++ b/tasks/traccar__traccar-5483/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Add custom group claim + +## Description + +Some OIDC providers don't have "groups" claim in id token, but have "roles". With this setting in traccar.xml there is ability to change it to work properly. + +Example is +` roles` + +I didn't find how to add new commits to PR so opened new one + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3372cf03a9c9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5483/solution/patch.diff b/tasks/traccar__traccar-5483/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8be6f51191c6ddb59ef8c31c0adc4a55e4dd5fc1 --- /dev/null +++ b/tasks/traccar__traccar-5483/solution/patch.diff @@ -0,0 +1,74 @@ +diff --git a/src/main/java/org/traccar/config/Keys.java b/src/main/java/org/traccar/config/Keys.java +index dcd9aaa28..9142c5c01 100644 +--- a/src/main/java/org/traccar/config/Keys.java ++++ b/src/main/java/org/traccar/config/Keys.java +@@ -698,6 +698,15 @@ public final class Keys { + "openid.userInfoUrl", + List.of(KeyType.CONFIG)); + ++ /** ++ * OpenID Connect group scope claim name. ++ * If this is not provided, Traccar will use name "groups" scope. ++ */ ++ public static final ConfigKey OPENID_GROUPS_CLAIM_NAME = new StringConfigKey( ++ "openid.groupsClaimName", ++ List.of(KeyType.CONFIG), ++ "groups"); ++ + /** + * OpenID Connect group to restrict access to. + * If this is not provided, all OpenID users will have access to Traccar. +diff --git a/src/main/java/org/traccar/database/OpenIdProvider.java b/src/main/java/org/traccar/database/OpenIdProvider.java +index 93297f7ab..a310d0278 100644 +--- a/src/main/java/org/traccar/database/OpenIdProvider.java ++++ b/src/main/java/org/traccar/database/OpenIdProvider.java +@@ -33,6 +33,7 @@ import java.security.GeneralSecurityException; + import java.util.List; + import java.util.Map; + import java.io.IOException; ++ + import jakarta.servlet.http.HttpServletRequest; + + import com.fasterxml.jackson.core.type.TypeReference; +@@ -73,6 +74,7 @@ public class OpenIdProvider { + private final URI baseUrl; + private final String adminGroup; + private final String allowGroup; ++ private final String groupsClaimName; + + private final LoginService loginService; + +@@ -111,13 +113,14 @@ public class OpenIdProvider { + + adminGroup = config.getString(Keys.OPENID_ADMIN_GROUP); + allowGroup = config.getString(Keys.OPENID_ALLOW_GROUP); ++ groupsClaimName = config.getString(Keys.OPENID_GROUPS_CLAIM_NAME); + } + + public URI createAuthUri() { + Scope scope = new Scope("openid", "profile", "email"); + + if (adminGroup != null) { +- scope.add("groups"); ++ scope.add(groupsClaimName); + } + + AuthenticationRequest.Builder request = new AuthenticationRequest.Builder( +@@ -155,7 +158,7 @@ public class OpenIdProvider { + + if (!userInfoResponse.indicatesSuccess()) { + throw new GeneralSecurityException( +- "Failed to access OpenID Connect user info endpoint. Please contact your administrator."); ++ "Failed to access OpenID Connect user info endpoint. Please contact your administrator."); + } + + return userInfoResponse.toSuccessResponse().getUserInfo(); +@@ -182,7 +185,7 @@ public class OpenIdProvider { + + UserInfo userInfo = getUserInfo(bearerToken); + +- List userGroups = userInfo.getStringListClaim("groups"); ++ List userGroups = userInfo.getStringListClaim(groupsClaimName); + boolean administrator = adminGroup != null && userGroups.contains(adminGroup); + + if (!(administrator || allowGroup == null || userGroups.contains(allowGroup))) { diff --git a/tasks/traccar__traccar-5483/solution/solve.sh b/tasks/traccar__traccar-5483/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5483/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/traccar__traccar-5483/task.toml b/tasks/traccar__traccar-5483/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fad86a0675247ea58ffe5b3892e9b8776d5dc09e --- /dev/null +++ b/tasks/traccar__traccar-5483/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5483" +description = "Add custom group claim" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "3372cf03a9c9312d14a929bd44dabd69ab3395ef" +reference = "https://github.com/traccar/traccar/pull/5483" +source_access = "auto" +built_at = "2026-11-16T16:09:42.663049+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:83de0b39ea4680f11a3611deb74c9b2a01041352f53454e2f8d5c75c74f7a759" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-22T17:08:14Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/config/Keys.java", + "src/main/java/org/traccar/database/OpenIdProvider.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.443425+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ca54e2fd5917af8da11968e8abf5e0d582cbcd0225e68426dc54b15fcffe4d46" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5483/tests/capture.py b/tasks/traccar__traccar-5483/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5483/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/traccar__traccar-5483/tests/instruction.md b/tasks/traccar__traccar-5483/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..880e37c104ff083db91d2e12df88bb0079d5ae2b --- /dev/null +++ b/tasks/traccar__traccar-5483/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Add custom group claim + +## Description + +Some OIDC providers don't have "groups" claim in id token, but have "roles". With this setting in traccar.xml there is ability to change it to work properly. + +Example is +` roles` + +I didn't find how to add new commits to PR so opened new one + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3372cf03a9c9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5483/tests/oracle.patch b/tasks/traccar__traccar-5483/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8be6f51191c6ddb59ef8c31c0adc4a55e4dd5fc1 --- /dev/null +++ b/tasks/traccar__traccar-5483/tests/oracle.patch @@ -0,0 +1,74 @@ +diff --git a/src/main/java/org/traccar/config/Keys.java b/src/main/java/org/traccar/config/Keys.java +index dcd9aaa28..9142c5c01 100644 +--- a/src/main/java/org/traccar/config/Keys.java ++++ b/src/main/java/org/traccar/config/Keys.java +@@ -698,6 +698,15 @@ public final class Keys { + "openid.userInfoUrl", + List.of(KeyType.CONFIG)); + ++ /** ++ * OpenID Connect group scope claim name. ++ * If this is not provided, Traccar will use name "groups" scope. ++ */ ++ public static final ConfigKey OPENID_GROUPS_CLAIM_NAME = new StringConfigKey( ++ "openid.groupsClaimName", ++ List.of(KeyType.CONFIG), ++ "groups"); ++ + /** + * OpenID Connect group to restrict access to. + * If this is not provided, all OpenID users will have access to Traccar. +diff --git a/src/main/java/org/traccar/database/OpenIdProvider.java b/src/main/java/org/traccar/database/OpenIdProvider.java +index 93297f7ab..a310d0278 100644 +--- a/src/main/java/org/traccar/database/OpenIdProvider.java ++++ b/src/main/java/org/traccar/database/OpenIdProvider.java +@@ -33,6 +33,7 @@ import java.security.GeneralSecurityException; + import java.util.List; + import java.util.Map; + import java.io.IOException; ++ + import jakarta.servlet.http.HttpServletRequest; + + import com.fasterxml.jackson.core.type.TypeReference; +@@ -73,6 +74,7 @@ public class OpenIdProvider { + private final URI baseUrl; + private final String adminGroup; + private final String allowGroup; ++ private final String groupsClaimName; + + private final LoginService loginService; + +@@ -111,13 +113,14 @@ public class OpenIdProvider { + + adminGroup = config.getString(Keys.OPENID_ADMIN_GROUP); + allowGroup = config.getString(Keys.OPENID_ALLOW_GROUP); ++ groupsClaimName = config.getString(Keys.OPENID_GROUPS_CLAIM_NAME); + } + + public URI createAuthUri() { + Scope scope = new Scope("openid", "profile", "email"); + + if (adminGroup != null) { +- scope.add("groups"); ++ scope.add(groupsClaimName); + } + + AuthenticationRequest.Builder request = new AuthenticationRequest.Builder( +@@ -155,7 +158,7 @@ public class OpenIdProvider { + + if (!userInfoResponse.indicatesSuccess()) { + throw new GeneralSecurityException( +- "Failed to access OpenID Connect user info endpoint. Please contact your administrator."); ++ "Failed to access OpenID Connect user info endpoint. Please contact your administrator."); + } + + return userInfoResponse.toSuccessResponse().getUserInfo(); +@@ -182,7 +185,7 @@ public class OpenIdProvider { + + UserInfo userInfo = getUserInfo(bearerToken); + +- List userGroups = userInfo.getStringListClaim("groups"); ++ List userGroups = userInfo.getStringListClaim(groupsClaimName); + boolean administrator = adminGroup != null && userGroups.contains(adminGroup); + + if (!(administrator || allowGroup == null || userGroups.contains(allowGroup))) { diff --git a/tasks/traccar__traccar-5483/tests/test.sh b/tasks/traccar__traccar-5483/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..144ac22b96996d876fff99dd019b51cd231a3777 --- /dev/null +++ b/tasks/traccar__traccar-5483/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 3372cf03a9c9312d14a929bd44dabd69ab3395ef > "$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/traccar__traccar-5483/tests/verifier.py b/tasks/traccar__traccar-5483/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5483/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/traccar__traccar-5484/environment/Dockerfile b/tasks/traccar__traccar-5484/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..301763ba824956cb586baba8c1c434c3b92fab42 --- /dev/null +++ b/tasks/traccar__traccar-5484/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3372cf03a9c9312d14a929bd44dabd69ab3395ef 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3372cf03a9c9312d14a929bd44dabd69ab3395ef \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3372cf03a9c9312d14a929bd44dabd69ab3395ef \ + && 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/traccar__traccar-5484/instruction.md b/tasks/traccar__traccar-5484/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6be3be2510a84206696f49c19001ca8ed9eb9cb2 --- /dev/null +++ b/tasks/traccar__traccar-5484/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add quantity of fuel drop/increase in notification + +## Description + +Added quantity of fuel drop/increase in email notification + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3372cf03a9c9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5484/solution/patch.diff b/tasks/traccar__traccar-5484/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7960de5ad2dfd88e642973c1301393967ba088e6 --- /dev/null +++ b/tasks/traccar__traccar-5484/solution/patch.diff @@ -0,0 +1,52 @@ +diff --git a/src/main/java/org/traccar/handler/events/FuelEventHandler.java b/src/main/java/org/traccar/handler/events/FuelEventHandler.java +index 348526d31..91d26e277 100644 +--- a/src/main/java/org/traccar/handler/events/FuelEventHandler.java ++++ b/src/main/java/org/traccar/handler/events/FuelEventHandler.java +@@ -55,13 +55,19 @@ public class FuelEventHandler extends BaseEventHandler { + double threshold = AttributeUtil.lookup( + cacheManager, Keys.EVENT_FUEL_INCREASE_THRESHOLD, position.getDeviceId()); + if (threshold > 0 && change >= threshold) { +- callback.eventDetected(new Event(Event.TYPE_DEVICE_FUEL_INCREASE, position)); ++ Event event = new Event(Event.TYPE_DEVICE_FUEL_INCREASE, position); ++ event.set("before", before); ++ event.set("after", after); ++ callback.eventDetected(event); + } + } else if (change < 0) { + double threshold = AttributeUtil.lookup( + cacheManager, Keys.EVENT_FUEL_DROP_THRESHOLD, position.getDeviceId()); + if (threshold > 0 && Math.abs(change) >= threshold) { +- callback.eventDetected(new Event(Event.TYPE_DEVICE_FUEL_DROP, position)); ++ Event event = new Event(Event.TYPE_DEVICE_FUEL_DROP, position); ++ event.set("before", before); ++ event.set("after", after); ++ callback.eventDetected(event); + } + } + } +diff --git a/templates/full/deviceFuelDrop.vm b/templates/full/deviceFuelDrop.vm +index 3fb9aa63c..6b4538d66 100644 +--- a/templates/full/deviceFuelDrop.vm ++++ b/templates/full/deviceFuelDrop.vm +@@ -4,6 +4,8 @@ + + Device: $device.name
+ Time: $dateTool.format("YYYY-MM-dd HH:mm:ss", $event.eventTime, $locale, $timezone)
++Quantity Before: $event.attributes.before
++Quantity After: $event.attributes.after
+ Point: #{if}($position.address)$position.address#{else}$position.latitude°, $position.longitude°#{end}
+
+ Unsubscribe +diff --git a/templates/full/deviceFuelIncrease.vm b/templates/full/deviceFuelIncrease.vm +index 9d4474e1a..cbeb3fc20 100644 +--- a/templates/full/deviceFuelIncrease.vm ++++ b/templates/full/deviceFuelIncrease.vm +@@ -4,6 +4,8 @@ + + Device: $device.name
+ Time: $dateTool.format("YYYY-MM-dd HH:mm:ss", $event.eventTime, $locale, $timezone)
++Quantity Before: $event.attributes.before
++Quantity After: $event.attributes.after
+ Point: #{if}($position.address)$position.address#{else}$position.latitude°, $position.longitude°#{end}
+
+ Unsubscribe diff --git a/tasks/traccar__traccar-5484/solution/solve.sh b/tasks/traccar__traccar-5484/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5484/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/traccar__traccar-5484/task.toml b/tasks/traccar__traccar-5484/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49c7db26a6763a6929313e2cfd31421e66ee248d --- /dev/null +++ b/tasks/traccar__traccar-5484/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5484" +description = "Add quantity of fuel drop/increase in notification" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "3372cf03a9c9312d14a929bd44dabd69ab3395ef" +reference = "https://github.com/traccar/traccar/pull/5484" +source_access = "auto" +built_at = "2026-11-16T16:09:42.664495+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:adb176374627c88c084b89450255390644beaa853f41a1546d0b87a101aedd18" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-19T23:11:10Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/handler/events/FuelEventHandler.java", + "templates/full/deviceFuelDrop.vm", + "templates/full/deviceFuelIncrease.vm", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.443949+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ca54e2fd5917af8da11968e8abf5e0d582cbcd0225e68426dc54b15fcffe4d46" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5484/tests/capture.py b/tasks/traccar__traccar-5484/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5484/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/traccar__traccar-5484/tests/instruction.md b/tasks/traccar__traccar-5484/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6be3be2510a84206696f49c19001ca8ed9eb9cb2 --- /dev/null +++ b/tasks/traccar__traccar-5484/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add quantity of fuel drop/increase in notification + +## Description + +Added quantity of fuel drop/increase in email notification + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3372cf03a9c9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5484/tests/oracle.patch b/tasks/traccar__traccar-5484/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7960de5ad2dfd88e642973c1301393967ba088e6 --- /dev/null +++ b/tasks/traccar__traccar-5484/tests/oracle.patch @@ -0,0 +1,52 @@ +diff --git a/src/main/java/org/traccar/handler/events/FuelEventHandler.java b/src/main/java/org/traccar/handler/events/FuelEventHandler.java +index 348526d31..91d26e277 100644 +--- a/src/main/java/org/traccar/handler/events/FuelEventHandler.java ++++ b/src/main/java/org/traccar/handler/events/FuelEventHandler.java +@@ -55,13 +55,19 @@ public class FuelEventHandler extends BaseEventHandler { + double threshold = AttributeUtil.lookup( + cacheManager, Keys.EVENT_FUEL_INCREASE_THRESHOLD, position.getDeviceId()); + if (threshold > 0 && change >= threshold) { +- callback.eventDetected(new Event(Event.TYPE_DEVICE_FUEL_INCREASE, position)); ++ Event event = new Event(Event.TYPE_DEVICE_FUEL_INCREASE, position); ++ event.set("before", before); ++ event.set("after", after); ++ callback.eventDetected(event); + } + } else if (change < 0) { + double threshold = AttributeUtil.lookup( + cacheManager, Keys.EVENT_FUEL_DROP_THRESHOLD, position.getDeviceId()); + if (threshold > 0 && Math.abs(change) >= threshold) { +- callback.eventDetected(new Event(Event.TYPE_DEVICE_FUEL_DROP, position)); ++ Event event = new Event(Event.TYPE_DEVICE_FUEL_DROP, position); ++ event.set("before", before); ++ event.set("after", after); ++ callback.eventDetected(event); + } + } + } +diff --git a/templates/full/deviceFuelDrop.vm b/templates/full/deviceFuelDrop.vm +index 3fb9aa63c..6b4538d66 100644 +--- a/templates/full/deviceFuelDrop.vm ++++ b/templates/full/deviceFuelDrop.vm +@@ -4,6 +4,8 @@ + + Device: $device.name
+ Time: $dateTool.format("YYYY-MM-dd HH:mm:ss", $event.eventTime, $locale, $timezone)
++Quantity Before: $event.attributes.before
++Quantity After: $event.attributes.after
+ Point: #{if}($position.address)$position.address#{else}$position.latitude°, $position.longitude°#{end}
+
+ Unsubscribe +diff --git a/templates/full/deviceFuelIncrease.vm b/templates/full/deviceFuelIncrease.vm +index 9d4474e1a..cbeb3fc20 100644 +--- a/templates/full/deviceFuelIncrease.vm ++++ b/templates/full/deviceFuelIncrease.vm +@@ -4,6 +4,8 @@ + + Device: $device.name
+ Time: $dateTool.format("YYYY-MM-dd HH:mm:ss", $event.eventTime, $locale, $timezone)
++Quantity Before: $event.attributes.before
++Quantity After: $event.attributes.after
+ Point: #{if}($position.address)$position.address#{else}$position.latitude°, $position.longitude°#{end}
+
+ Unsubscribe diff --git a/tasks/traccar__traccar-5484/tests/test.sh b/tasks/traccar__traccar-5484/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..144ac22b96996d876fff99dd019b51cd231a3777 --- /dev/null +++ b/tasks/traccar__traccar-5484/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 3372cf03a9c9312d14a929bd44dabd69ab3395ef > "$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/traccar__traccar-5484/tests/verifier.py b/tasks/traccar__traccar-5484/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5484/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/traccar__traccar-5493/environment/Dockerfile b/tasks/traccar__traccar-5493/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7c9fa37c4d3b3338eb8f2296bb86b7c1ca9e1081 --- /dev/null +++ b/tasks/traccar__traccar-5493/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f807e6f604caee26dbaad20cbac20320df9a3f9e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f807e6f604caee26dbaad20cbac20320df9a3f9e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f807e6f604caee26dbaad20cbac20320df9a3f9e \ + && 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/traccar__traccar-5493/instruction.md b/tasks/traccar__traccar-5493/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f79a92aa4d6b7e16645327b256a705ac5d55a9bf --- /dev/null +++ b/tasks/traccar__traccar-5493/instruction.md @@ -0,0 +1,55 @@ +# Issue + +**Title:** OpenAPI yaml: Set nullable fields as nullable (Device, User schemas) + +## Description + +### Background + +2 months ago I opened a for a specific case of this issue, which was accepted and solved the issue. Now with more experience of Traccar, I address other cases of the same issue. + +This PR marks several fields as nullable in the OpenAPI schema, matched to fields which are regularly null in the traccar server db under normal operation. This is limited to models I am familiar with and anticipate using the API for. + +### Issue - current example + +Parsing error during `get_devices.sync()` while parsing `last_update (= None)`: + +```py +# Generated python client library snippet (Device) + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.device_attributes import DeviceAttributes + + d = src_dict.copy() + ... + _last_update = d.pop("lastUpdate", UNSET) + last_update: Union[Unset, datetime.datetime] + if isinstance(_last_update, Unset): # evaluates False since "lastUpdate" exists in src_dict and is None + last_update = UNSET + else: + last_update = isoparse(_last_update) # error parsing None +``` + +### Considerations + +Several other nullable fields are not marked as nullable in the OpenAPI schemas for Device and User, which could cause similar issues, e.g.: + +```yaml + Device: + type: object + ... + lastUpdate: + type: string + description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + positionId: + type: integer + groupId: + type: integer + phone: + type: string +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f807e6f604ca`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5493/solution/patch.diff b/tasks/traccar__traccar-5493/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..44f3666db8296589b64b715133de24344811429e --- /dev/null +++ b/tasks/traccar__traccar-5493/solution/patch.diff @@ -0,0 +1,61 @@ +diff --git a/openapi.yaml b/openapi.yaml +index 9398d3d56..3a6126f7a 100644 +--- a/openapi.yaml ++++ b/openapi.yaml +@@ -1781,12 +1781,14 @@ components: + type: string + phone: + type: string ++ nullable: true + readonly: + type: boolean + administrator: + type: boolean + map: + type: string ++ nullable: true + latitude: + type: number + longitude: +@@ -1797,6 +1799,7 @@ components: + type: string + coordinateFormat: + type: string ++ nullable: true + disabled: + type: boolean + expirationTime: +@@ -1816,6 +1819,7 @@ components: + type: boolean + poiLayer: + type: string ++ nullable: true + attributes: + type: object + properties: {} +@@ -1890,18 +1894,25 @@ components: + type: string + description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time ++ nullable: true + positionId: + type: integer ++ nullable: true + groupId: + type: integer ++ nullable: true + phone: + type: string ++ nullable: true + model: + type: string ++ nullable: true + contact: + type: string ++ nullable: true + category: + type: string ++ nullable: true + attributes: + type: object + properties: {} diff --git a/tasks/traccar__traccar-5493/solution/solve.sh b/tasks/traccar__traccar-5493/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5493/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/traccar__traccar-5493/task.toml b/tasks/traccar__traccar-5493/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2cb47a0ceac708546497028c5e7a0d1302ad679f --- /dev/null +++ b/tasks/traccar__traccar-5493/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5493" +description = "OpenAPI yaml: Set nullable fields as nullable (Device, User schemas)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "f807e6f604caee26dbaad20cbac20320df9a3f9e" +reference = "https://github.com/traccar/traccar/pull/5493" +source_access = "auto" +built_at = "2026-11-16T16:09:42.661631+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ad6389e9755229da6a730808e75526bd86d82c551ebf8c942424ff49602d7a28" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-01-14T14:21:28Z" +diff_format = "unified" +context_files = [ + "openapi.yaml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 11 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.444512+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6c760b2f53268a201b12a18abbe08961b875655c4d43aa7508435e0969fbe449" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5493/tests/capture.py b/tasks/traccar__traccar-5493/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5493/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/traccar__traccar-5493/tests/instruction.md b/tasks/traccar__traccar-5493/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f79a92aa4d6b7e16645327b256a705ac5d55a9bf --- /dev/null +++ b/tasks/traccar__traccar-5493/tests/instruction.md @@ -0,0 +1,55 @@ +# Issue + +**Title:** OpenAPI yaml: Set nullable fields as nullable (Device, User schemas) + +## Description + +### Background + +2 months ago I opened a for a specific case of this issue, which was accepted and solved the issue. Now with more experience of Traccar, I address other cases of the same issue. + +This PR marks several fields as nullable in the OpenAPI schema, matched to fields which are regularly null in the traccar server db under normal operation. This is limited to models I am familiar with and anticipate using the API for. + +### Issue - current example + +Parsing error during `get_devices.sync()` while parsing `last_update (= None)`: + +```py +# Generated python client library snippet (Device) + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + from ..models.device_attributes import DeviceAttributes + + d = src_dict.copy() + ... + _last_update = d.pop("lastUpdate", UNSET) + last_update: Union[Unset, datetime.datetime] + if isinstance(_last_update, Unset): # evaluates False since "lastUpdate" exists in src_dict and is None + last_update = UNSET + else: + last_update = isoparse(_last_update) # error parsing None +``` + +### Considerations + +Several other nullable fields are not marked as nullable in the OpenAPI schemas for Device and User, which could cause similar issues, e.g.: + +```yaml + Device: + type: object + ... + lastUpdate: + type: string + description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + positionId: + type: integer + groupId: + type: integer + phone: + type: string +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f807e6f604ca`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5493/tests/oracle.patch b/tasks/traccar__traccar-5493/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..44f3666db8296589b64b715133de24344811429e --- /dev/null +++ b/tasks/traccar__traccar-5493/tests/oracle.patch @@ -0,0 +1,61 @@ +diff --git a/openapi.yaml b/openapi.yaml +index 9398d3d56..3a6126f7a 100644 +--- a/openapi.yaml ++++ b/openapi.yaml +@@ -1781,12 +1781,14 @@ components: + type: string + phone: + type: string ++ nullable: true + readonly: + type: boolean + administrator: + type: boolean + map: + type: string ++ nullable: true + latitude: + type: number + longitude: +@@ -1797,6 +1799,7 @@ components: + type: string + coordinateFormat: + type: string ++ nullable: true + disabled: + type: boolean + expirationTime: +@@ -1816,6 +1819,7 @@ components: + type: boolean + poiLayer: + type: string ++ nullable: true + attributes: + type: object + properties: {} +@@ -1890,18 +1894,25 @@ components: + type: string + description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time ++ nullable: true + positionId: + type: integer ++ nullable: true + groupId: + type: integer ++ nullable: true + phone: + type: string ++ nullable: true + model: + type: string ++ nullable: true + contact: + type: string ++ nullable: true + category: + type: string ++ nullable: true + attributes: + type: object + properties: {} diff --git a/tasks/traccar__traccar-5493/tests/test.sh b/tasks/traccar__traccar-5493/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1b102cd2396cde40ac4b6e0725b7ebcc57e93cf4 --- /dev/null +++ b/tasks/traccar__traccar-5493/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 f807e6f604caee26dbaad20cbac20320df9a3f9e > "$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/traccar__traccar-5493/tests/verifier.py b/tasks/traccar__traccar-5493/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5493/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/traccar__traccar-5494/environment/Dockerfile b/tasks/traccar__traccar-5494/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5c7e363dfad10fdc8db9d528da68d4a94342550d --- /dev/null +++ b/tasks/traccar__traccar-5494/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0436abf3bafbfa3bb7f7b489bdf47302124a6398 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0436abf3bafbfa3bb7f7b489bdf47302124a6398 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0436abf3bafbfa3bb7f7b489bdf47302124a6398 \ + && 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/traccar__traccar-5494/instruction.md b/tasks/traccar__traccar-5494/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5bb3cb50f742fdafc13701a6caca10e5a9d8e9ad --- /dev/null +++ b/tasks/traccar__traccar-5494/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Complete OwnTracks decoder cleanup with updated test cases #5486 + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0436abf3bafb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5494/solution/patch.diff b/tasks/traccar__traccar-5494/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..23c75be869ec7c4df8d0db239adf7d0cbf035297 --- /dev/null +++ b/tasks/traccar__traccar-5494/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java b/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java +index 10a811a7b..74d7f02a7 100644 +--- a/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java +@@ -51,7 +51,13 @@ public class OwnTracksProtocolDecoder extends BaseHttpProtocolDecoder { + return null; + } + +- String uniqueId = root.getString("tid"); ++ String uniqueId = null; ++ if (root.containsKey("topic")) { ++ uniqueId = root.getString("topic"); ++ } else if (root.containsKey("tid")) { ++ uniqueId = root.getString("tid"); ++ } ++ + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, uniqueId); + if (deviceSession == null) { + sendResponse(channel, HttpResponseStatus.BAD_REQUEST); +diff --git a/src/test/java/org/traccar/protocol/OwnTracksProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/OwnTracksProtocolDecoderTest.java +index ba0eaec01..8d5c0c796 100644 +--- a/src/test/java/org/traccar/protocol/OwnTracksProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/OwnTracksProtocolDecoderTest.java +@@ -22,6 +22,12 @@ public class OwnTracksProtocolDecoderTest extends ProtocolTest { + + verifyPosition(decoder, request(HttpMethod.POST, "/", + buffer("{\"lat\":48.85,\"lon\":2.295,\"_type\":\"location\",\"tid\":\"JJ\",\"tst\":1497476456}"))); ++ ++ verifyPosition(decoder, request(HttpMethod.POST, "/", ++ buffer("{\"lon\":-122,\"acc\":5,\"created_at\":1736161415,\"lat\":37,\"topic\":\"owntracks/ckrey/22A67880-15C3-41A6-9157-25545C7993AC\",\"t\":\"u\",\"m\":1,\"tst\":1736161169,\"conn\":\"w\",\"alt\":0,\"_type\":\"location\",\"tid\":\"AC\"}"))); ++ ++ verifyPosition(decoder, request(HttpMethod.POST, "/", ++ buffer("{\"topic\":\"owntracks/qtripp/865284041968706\",\"lat\":47.420051,\"lon\":13.654704,\"vel\":0,\"cog\":113,\"tst\":1736519167,\"mcc\":232,\"mnc\":1,\"lac\":\"4F4D\",\"cid\":\"673A\",\"_type\":\"location\",\"acc\":10,\"alt\":1113,\"t\":\"I\",\"don\":105,\"tid\":\"CS\"}"))); + } + + } diff --git a/tasks/traccar__traccar-5494/solution/solve.sh b/tasks/traccar__traccar-5494/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5494/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/traccar__traccar-5494/task.toml b/tasks/traccar__traccar-5494/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f638cfa608c5fd40b9240ae5da49f1a14cc7002b --- /dev/null +++ b/tasks/traccar__traccar-5494/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5494" +description = "Complete OwnTracks decoder cleanup with updated test cases #5486" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "0436abf3bafbfa3bb7f7b489bdf47302124a6398" +reference = "https://github.com/traccar/traccar/pull/5494" +source_access = "auto" +built_at = "2026-11-16T16:09:42.526240+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b223f7a91ff2b7c97d103ce37049ccdc20a79dfa5043b2a37f5598367e947838" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-15T13:40:04Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java", + "src/test/java/org/traccar/protocol/OwnTracksProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.445045+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:102ff3c53420174b4b1ce35fedbae40246d8ba4c9acfdb2420aa836b74dba363" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5494/tests/capture.py b/tasks/traccar__traccar-5494/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5494/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/traccar__traccar-5494/tests/instruction.md b/tasks/traccar__traccar-5494/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5bb3cb50f742fdafc13701a6caca10e5a9d8e9ad --- /dev/null +++ b/tasks/traccar__traccar-5494/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Complete OwnTracks decoder cleanup with updated test cases #5486 + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0436abf3bafb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5494/tests/oracle.patch b/tasks/traccar__traccar-5494/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..23c75be869ec7c4df8d0db239adf7d0cbf035297 --- /dev/null +++ b/tasks/traccar__traccar-5494/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java b/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java +index 10a811a7b..74d7f02a7 100644 +--- a/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java +@@ -51,7 +51,13 @@ public class OwnTracksProtocolDecoder extends BaseHttpProtocolDecoder { + return null; + } + +- String uniqueId = root.getString("tid"); ++ String uniqueId = null; ++ if (root.containsKey("topic")) { ++ uniqueId = root.getString("topic"); ++ } else if (root.containsKey("tid")) { ++ uniqueId = root.getString("tid"); ++ } ++ + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, uniqueId); + if (deviceSession == null) { + sendResponse(channel, HttpResponseStatus.BAD_REQUEST); +diff --git a/src/test/java/org/traccar/protocol/OwnTracksProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/OwnTracksProtocolDecoderTest.java +index ba0eaec01..8d5c0c796 100644 +--- a/src/test/java/org/traccar/protocol/OwnTracksProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/OwnTracksProtocolDecoderTest.java +@@ -22,6 +22,12 @@ public class OwnTracksProtocolDecoderTest extends ProtocolTest { + + verifyPosition(decoder, request(HttpMethod.POST, "/", + buffer("{\"lat\":48.85,\"lon\":2.295,\"_type\":\"location\",\"tid\":\"JJ\",\"tst\":1497476456}"))); ++ ++ verifyPosition(decoder, request(HttpMethod.POST, "/", ++ buffer("{\"lon\":-122,\"acc\":5,\"created_at\":1736161415,\"lat\":37,\"topic\":\"owntracks/ckrey/22A67880-15C3-41A6-9157-25545C7993AC\",\"t\":\"u\",\"m\":1,\"tst\":1736161169,\"conn\":\"w\",\"alt\":0,\"_type\":\"location\",\"tid\":\"AC\"}"))); ++ ++ verifyPosition(decoder, request(HttpMethod.POST, "/", ++ buffer("{\"topic\":\"owntracks/qtripp/865284041968706\",\"lat\":47.420051,\"lon\":13.654704,\"vel\":0,\"cog\":113,\"tst\":1736519167,\"mcc\":232,\"mnc\":1,\"lac\":\"4F4D\",\"cid\":\"673A\",\"_type\":\"location\",\"acc\":10,\"alt\":1113,\"t\":\"I\",\"don\":105,\"tid\":\"CS\"}"))); + } + + } diff --git a/tasks/traccar__traccar-5494/tests/test.sh b/tasks/traccar__traccar-5494/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..26e27842d7c250b324c28403dafcea9734e00b33 --- /dev/null +++ b/tasks/traccar__traccar-5494/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 0436abf3bafbfa3bb7f7b489bdf47302124a6398 > "$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/traccar__traccar-5494/tests/verifier.py b/tasks/traccar__traccar-5494/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5494/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/traccar__traccar-5502/environment/Dockerfile b/tasks/traccar__traccar-5502/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bfb0c91e0ca1925ca28c17ca28e5f2205524777d --- /dev/null +++ b/tasks/traccar__traccar-5502/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 66e6c1fd57906175cdad9dba626d2f67a6462aec 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 66e6c1fd57906175cdad9dba626d2f67a6462aec \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 66e6c1fd57906175cdad9dba626d2f67a6462aec \ + && 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/traccar__traccar-5502/instruction.md b/tasks/traccar__traccar-5502/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cc03fa68ad9464abcb374757443d249ff5e69571 --- /dev/null +++ b/tasks/traccar__traccar-5502/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Wialon: interpret LBS data from parameters + +## Description + +According to the Wialon protocol specifications, the LBS data is transmitted as parameters. +https://wialon.com/hw/files/Wialon%20IPS%20v.2.2%20%28RU%29.pdf + +Added LBS decoding from the custom parameters +Added device-specific temp and battery level readings + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `66e6c1fd5790`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5502/solution/patch.diff b/tasks/traccar__traccar-5502/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..98ac93820cbc2cfc212c90828669677a4ed59940 --- /dev/null +++ b/tasks/traccar__traccar-5502/solution/patch.diff @@ -0,0 +1,139 @@ +diff --git a/src/main/java/org/traccar/model/Network.java b/src/main/java/org/traccar/model/Network.java +index b31c53c38..cfe5b3a33 100644 +--- a/src/main/java/org/traccar/model/Network.java ++++ b/src/main/java/org/traccar/model/Network.java +@@ -27,12 +27,16 @@ public class Network { + public Network() { + } + +- public Network(CellTower cellTower) { +- addCellTower(cellTower); ++ public Network(CellTower... cellTowers) { ++ for (var tower : cellTowers) { ++ addCellTower(tower); ++ } + } + +- public Network(WifiAccessPoint wifiAccessPoint) { +- addWifiAccessPoint(wifiAccessPoint); ++ public Network(WifiAccessPoint... wifiAccessPoints) { ++ for (var accessPoint : wifiAccessPoints) { ++ addWifiAccessPoint(accessPoint); ++ } + } + + private Integer homeMobileCountryCode; +diff --git a/src/main/java/org/traccar/protocol/WialonProtocolDecoder.java b/src/main/java/org/traccar/protocol/WialonProtocolDecoder.java +index fbb845a7b..3b94bc5a7 100644 +--- a/src/main/java/org/traccar/protocol/WialonProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/WialonProtocolDecoder.java +@@ -17,6 +17,8 @@ package org.traccar.protocol; + + import io.netty.channel.Channel; + import org.traccar.BaseProtocolDecoder; ++import org.traccar.model.CellTower; ++import org.traccar.model.Network; + import org.traccar.session.DeviceSession; + import org.traccar.NetworkMessage; + import org.traccar.Protocol; +@@ -140,11 +142,7 @@ public class WialonProtocolDecoder extends BaseProtocolDecoder { + String key = paramParser.group(1).toLowerCase(); + String value = paramParser.group(2); + try { +- if (key.equals("accuracy")) { +- position.setAccuracy(Double.parseDouble(value)); +- } else { +- position.set(key, Double.parseDouble(value)); +- } ++ position.set(key, Double.parseDouble(value)); + } catch (NumberFormatException e) { + if (value.equalsIgnoreCase("true")) { + position.set(key, true); +@@ -156,11 +154,50 @@ public class WialonProtocolDecoder extends BaseProtocolDecoder { + } + } + } ++ ++ if (position.hasAttribute("accuracy")) { ++ position.setAccuracy(position.removeDouble("accuracy")); ++ } ++ ++ if (position.hasAttribute("bat")) { ++ position.set(Position.KEY_BATTERY_LEVEL, position.removeInteger("bat")); ++ } ++ ++ if (position.hasAttribute("temp")) { ++ position.set(Position.KEY_DEVICE_TEMP, position.removeInteger("temp")); ++ } ++ ++ Network network = new Network(); ++ decodeCellData(position, network, ""); ++ for (int i = 1; i <= 9; i++) { ++ if (!decodeCellData(position, network, String.valueOf(i))) { ++ break; ++ } ++ } ++ ++ if (network.getCellTowers() != null) { ++ position.setNetwork(network); ++ } + } + + return position; + } + ++ private static boolean decodeCellData(Position position, Network network, String suffix) { ++ if (position.hasAttribute("mnc" + suffix) ++ && position.hasAttribute("mcc" + suffix) ++ && position.hasAttribute("lac" + suffix) ++ && position.hasAttribute("cell_id" + suffix)) { ++ network.addCellTower(CellTower.from( ++ position.removeInteger("mcc" + suffix), ++ position.removeInteger("mnc" + suffix), ++ position.removeInteger("lac" + suffix), ++ position.getLong("cell_id" + suffix))); ++ return true; ++ } ++ return false; ++ } ++ + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { +diff --git a/src/test/java/org/traccar/protocol/WialonProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/WialonProtocolDecoderTest.java +index 7346798f0..1e4776492 100644 +--- a/src/test/java/org/traccar/protocol/WialonProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/WialonProtocolDecoderTest.java +@@ -2,6 +2,9 @@ package org.traccar.protocol; + + import org.junit.jupiter.api.Test; + import org.traccar.ProtocolTest; ++import org.traccar.model.CellTower; ++import org.traccar.model.Network; ++import org.traccar.model.Position; + + public class WialonProtocolDecoderTest extends ProtocolTest { + +@@ -86,6 +89,22 @@ public class WialonProtocolDecoderTest extends ProtocolTest { + "#D#120319;112003;NA;NA;NA;NA;0.000;NA;NA;0;NA;NA;NA;NA;NA;motion:3:false"), + "motion", false); + ++ verifyAttribute( ++ decoder, ++ text("#D#NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;;NA;mnc1:1:02,mcc1:1:250,lac1:1:5901,cell_id1:1:45542,mnc2:1:22,mcc2:1:222,lac2:1:2222,cell_id2:1:22222,mcc3:1:333"), ++ "network", new Network( ++ CellTower.from(250, 2, 5901, 45542), ++ CellTower.from(222, 22, 2222, 22222))); ++ ++ verifyAttribute( ++ decoder, ++ text("#D#NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;;NA;SOS:1:0,temp:3:18,bat:3:99"), ++ Position.KEY_DEVICE_TEMP, 18); ++ ++ verifyAttribute( ++ decoder, ++ text("#D#NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;;NA;SOS:1:0,temp:3:18,bat:3:99"), ++ Position.KEY_BATTERY_LEVEL, 99); + } + + } diff --git a/tasks/traccar__traccar-5502/solution/solve.sh b/tasks/traccar__traccar-5502/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5502/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/traccar__traccar-5502/task.toml b/tasks/traccar__traccar-5502/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b5485efe67061504288233e12aced30848e9f520 --- /dev/null +++ b/tasks/traccar__traccar-5502/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5502" +description = "Wialon: interpret LBS data from parameters" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "66e6c1fd57906175cdad9dba626d2f67a6462aec" +reference = "https://github.com/traccar/traccar/pull/5502" +source_access = "auto" +built_at = "2026-11-16T16:09:42.658779+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d225c5598750200de36692b10b6c4bca924abdea339aed2ccc434eeb8cbf7214" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-02-06T01:29:15Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/model/Network.java", + "src/main/java/org/traccar/protocol/WialonProtocolDecoder.java", + "src/test/java/org/traccar/protocol/WialonProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 78 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.445628+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8be0f9d79619b61696e8306f083cf2c2da99414dde9ba2facd6f3e283ce839c1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5502/tests/capture.py b/tasks/traccar__traccar-5502/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5502/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/traccar__traccar-5502/tests/instruction.md b/tasks/traccar__traccar-5502/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cc03fa68ad9464abcb374757443d249ff5e69571 --- /dev/null +++ b/tasks/traccar__traccar-5502/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Wialon: interpret LBS data from parameters + +## Description + +According to the Wialon protocol specifications, the LBS data is transmitted as parameters. +https://wialon.com/hw/files/Wialon%20IPS%20v.2.2%20%28RU%29.pdf + +Added LBS decoding from the custom parameters +Added device-specific temp and battery level readings + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `66e6c1fd5790`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5502/tests/oracle.patch b/tasks/traccar__traccar-5502/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..98ac93820cbc2cfc212c90828669677a4ed59940 --- /dev/null +++ b/tasks/traccar__traccar-5502/tests/oracle.patch @@ -0,0 +1,139 @@ +diff --git a/src/main/java/org/traccar/model/Network.java b/src/main/java/org/traccar/model/Network.java +index b31c53c38..cfe5b3a33 100644 +--- a/src/main/java/org/traccar/model/Network.java ++++ b/src/main/java/org/traccar/model/Network.java +@@ -27,12 +27,16 @@ public class Network { + public Network() { + } + +- public Network(CellTower cellTower) { +- addCellTower(cellTower); ++ public Network(CellTower... cellTowers) { ++ for (var tower : cellTowers) { ++ addCellTower(tower); ++ } + } + +- public Network(WifiAccessPoint wifiAccessPoint) { +- addWifiAccessPoint(wifiAccessPoint); ++ public Network(WifiAccessPoint... wifiAccessPoints) { ++ for (var accessPoint : wifiAccessPoints) { ++ addWifiAccessPoint(accessPoint); ++ } + } + + private Integer homeMobileCountryCode; +diff --git a/src/main/java/org/traccar/protocol/WialonProtocolDecoder.java b/src/main/java/org/traccar/protocol/WialonProtocolDecoder.java +index fbb845a7b..3b94bc5a7 100644 +--- a/src/main/java/org/traccar/protocol/WialonProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/WialonProtocolDecoder.java +@@ -17,6 +17,8 @@ package org.traccar.protocol; + + import io.netty.channel.Channel; + import org.traccar.BaseProtocolDecoder; ++import org.traccar.model.CellTower; ++import org.traccar.model.Network; + import org.traccar.session.DeviceSession; + import org.traccar.NetworkMessage; + import org.traccar.Protocol; +@@ -140,11 +142,7 @@ public class WialonProtocolDecoder extends BaseProtocolDecoder { + String key = paramParser.group(1).toLowerCase(); + String value = paramParser.group(2); + try { +- if (key.equals("accuracy")) { +- position.setAccuracy(Double.parseDouble(value)); +- } else { +- position.set(key, Double.parseDouble(value)); +- } ++ position.set(key, Double.parseDouble(value)); + } catch (NumberFormatException e) { + if (value.equalsIgnoreCase("true")) { + position.set(key, true); +@@ -156,11 +154,50 @@ public class WialonProtocolDecoder extends BaseProtocolDecoder { + } + } + } ++ ++ if (position.hasAttribute("accuracy")) { ++ position.setAccuracy(position.removeDouble("accuracy")); ++ } ++ ++ if (position.hasAttribute("bat")) { ++ position.set(Position.KEY_BATTERY_LEVEL, position.removeInteger("bat")); ++ } ++ ++ if (position.hasAttribute("temp")) { ++ position.set(Position.KEY_DEVICE_TEMP, position.removeInteger("temp")); ++ } ++ ++ Network network = new Network(); ++ decodeCellData(position, network, ""); ++ for (int i = 1; i <= 9; i++) { ++ if (!decodeCellData(position, network, String.valueOf(i))) { ++ break; ++ } ++ } ++ ++ if (network.getCellTowers() != null) { ++ position.setNetwork(network); ++ } + } + + return position; + } + ++ private static boolean decodeCellData(Position position, Network network, String suffix) { ++ if (position.hasAttribute("mnc" + suffix) ++ && position.hasAttribute("mcc" + suffix) ++ && position.hasAttribute("lac" + suffix) ++ && position.hasAttribute("cell_id" + suffix)) { ++ network.addCellTower(CellTower.from( ++ position.removeInteger("mcc" + suffix), ++ position.removeInteger("mnc" + suffix), ++ position.removeInteger("lac" + suffix), ++ position.getLong("cell_id" + suffix))); ++ return true; ++ } ++ return false; ++ } ++ + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { +diff --git a/src/test/java/org/traccar/protocol/WialonProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/WialonProtocolDecoderTest.java +index 7346798f0..1e4776492 100644 +--- a/src/test/java/org/traccar/protocol/WialonProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/WialonProtocolDecoderTest.java +@@ -2,6 +2,9 @@ package org.traccar.protocol; + + import org.junit.jupiter.api.Test; + import org.traccar.ProtocolTest; ++import org.traccar.model.CellTower; ++import org.traccar.model.Network; ++import org.traccar.model.Position; + + public class WialonProtocolDecoderTest extends ProtocolTest { + +@@ -86,6 +89,22 @@ public class WialonProtocolDecoderTest extends ProtocolTest { + "#D#120319;112003;NA;NA;NA;NA;0.000;NA;NA;0;NA;NA;NA;NA;NA;motion:3:false"), + "motion", false); + ++ verifyAttribute( ++ decoder, ++ text("#D#NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;;NA;mnc1:1:02,mcc1:1:250,lac1:1:5901,cell_id1:1:45542,mnc2:1:22,mcc2:1:222,lac2:1:2222,cell_id2:1:22222,mcc3:1:333"), ++ "network", new Network( ++ CellTower.from(250, 2, 5901, 45542), ++ CellTower.from(222, 22, 2222, 22222))); ++ ++ verifyAttribute( ++ decoder, ++ text("#D#NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;;NA;SOS:1:0,temp:3:18,bat:3:99"), ++ Position.KEY_DEVICE_TEMP, 18); ++ ++ verifyAttribute( ++ decoder, ++ text("#D#NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;NA;;NA;SOS:1:0,temp:3:18,bat:3:99"), ++ Position.KEY_BATTERY_LEVEL, 99); + } + + } diff --git a/tasks/traccar__traccar-5502/tests/test.sh b/tasks/traccar__traccar-5502/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ece518a0126be8f2c9af716413135830f4e6bd62 --- /dev/null +++ b/tasks/traccar__traccar-5502/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 66e6c1fd57906175cdad9dba626d2f67a6462aec > "$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/traccar__traccar-5502/tests/verifier.py b/tasks/traccar__traccar-5502/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5502/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/traccar__traccar-5508/environment/Dockerfile b/tasks/traccar__traccar-5508/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4ed68f74add888e6e4e4a98111545ff73155268c --- /dev/null +++ b/tasks/traccar__traccar-5508/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ae2fd76f799e63e33609c682bc2868c237d3a89f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ae2fd76f799e63e33609c682bc2868c237d3a89f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ae2fd76f799e63e33609c682bc2868c237d3a89f \ + && 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/traccar__traccar-5508/instruction.md b/tasks/traccar__traccar-5508/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e7f93db5814523842cb89142032e55c6d186d788 --- /dev/null +++ b/tasks/traccar__traccar-5508/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Update TrvProtocolDecoder.java + +## Description + +No response for following IWAP Commands: +AP86 +AP87 + +Attached is the protocol where the changes are visible. On page 24 you can see AP86 and on Page 27 you can see AP87. +[Gps Watch protocol_2023.pdf](https://github.com/user-attachments/files/18641865/Gps.Watch.protocol_2023.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ae2fd76f799e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5508/solution/patch.diff b/tasks/traccar__traccar-5508/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f0538e6fa8243b2a9b0e6fc8a53c26e8fb9288d2 --- /dev/null +++ b/tasks/traccar__traccar-5508/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java b/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java +index 693155b46..cd1b5e670 100644 +--- a/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java +@@ -37,6 +37,11 @@ import java.util.Set; + + public class TrvProtocolDecoder extends BaseProtocolDecoder { + ++ private static final Set IGNORE_RESPONSE = Set.of( ++ "AP12", "AP14", "AP33", "AP34", "AP40", ++ "AP76", "AP77", "AP84", "AP85", "AP86", "AP87" ++ ); ++ + public TrvProtocolDecoder(Protocol protocol) { + super(protocol); + } +@@ -181,7 +186,7 @@ public class TrvProtocolDecoder extends BaseProtocolDecoder { + channel.writeAndFlush(new NetworkMessage(responseHeader + "," + time + ",0#", remoteAddress)); + } else if (type.equals("AP14") && !id.equals("IW")) { + channel.writeAndFlush(new NetworkMessage(responseHeader + ",0.000,0.000#", remoteAddress)); +- } else if (!Set.of("AP12", "AP14", "AP33", "AP34", "AP40", "AP76", "AP77", "AP84", "AP85").contains(type) ++ } else if (!IGNORE_RESPONSE.contains(type) + && !sentence.substring(responseHeader.length() + 1).matches("^\\d{6}$")) { + channel.writeAndFlush(new NetworkMessage(responseHeader + "#", remoteAddress)); + } diff --git a/tasks/traccar__traccar-5508/solution/solve.sh b/tasks/traccar__traccar-5508/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5508/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/traccar__traccar-5508/task.toml b/tasks/traccar__traccar-5508/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b6d17f9be509e4ed601b65a8dedd69d14ae08bc7 --- /dev/null +++ b/tasks/traccar__traccar-5508/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5508" +description = "Update TrvProtocolDecoder.java" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "ae2fd76f799e63e33609c682bc2868c237d3a89f" +reference = "https://github.com/traccar/traccar/pull/5508" +source_access = "auto" +built_at = "2026-11-16T16:09:42.660265+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1984e99e57519b35402a9f70ba1178ad9eb1a8db906e4a0d4654b90c4a5b3843" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-02-03T15:44:20Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/TrvProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 7 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.446195+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8b06f5747e5a7916455ca132ba5a18493a40cbb83944e7553d72b25e36721c1a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5508/tests/capture.py b/tasks/traccar__traccar-5508/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5508/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/traccar__traccar-5508/tests/instruction.md b/tasks/traccar__traccar-5508/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e7f93db5814523842cb89142032e55c6d186d788 --- /dev/null +++ b/tasks/traccar__traccar-5508/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Update TrvProtocolDecoder.java + +## Description + +No response for following IWAP Commands: +AP86 +AP87 + +Attached is the protocol where the changes are visible. On page 24 you can see AP86 and on Page 27 you can see AP87. +[Gps Watch protocol_2023.pdf](https://github.com/user-attachments/files/18641865/Gps.Watch.protocol_2023.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ae2fd76f799e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5508/tests/oracle.patch b/tasks/traccar__traccar-5508/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f0538e6fa8243b2a9b0e6fc8a53c26e8fb9288d2 --- /dev/null +++ b/tasks/traccar__traccar-5508/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java b/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java +index 693155b46..cd1b5e670 100644 +--- a/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TrvProtocolDecoder.java +@@ -37,6 +37,11 @@ import java.util.Set; + + public class TrvProtocolDecoder extends BaseProtocolDecoder { + ++ private static final Set IGNORE_RESPONSE = Set.of( ++ "AP12", "AP14", "AP33", "AP34", "AP40", ++ "AP76", "AP77", "AP84", "AP85", "AP86", "AP87" ++ ); ++ + public TrvProtocolDecoder(Protocol protocol) { + super(protocol); + } +@@ -181,7 +186,7 @@ public class TrvProtocolDecoder extends BaseProtocolDecoder { + channel.writeAndFlush(new NetworkMessage(responseHeader + "," + time + ",0#", remoteAddress)); + } else if (type.equals("AP14") && !id.equals("IW")) { + channel.writeAndFlush(new NetworkMessage(responseHeader + ",0.000,0.000#", remoteAddress)); +- } else if (!Set.of("AP12", "AP14", "AP33", "AP34", "AP40", "AP76", "AP77", "AP84", "AP85").contains(type) ++ } else if (!IGNORE_RESPONSE.contains(type) + && !sentence.substring(responseHeader.length() + 1).matches("^\\d{6}$")) { + channel.writeAndFlush(new NetworkMessage(responseHeader + "#", remoteAddress)); + } diff --git a/tasks/traccar__traccar-5508/tests/test.sh b/tasks/traccar__traccar-5508/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3258fe70b9759bef6fe3bf46a8bf6d4d7eb10777 --- /dev/null +++ b/tasks/traccar__traccar-5508/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 ae2fd76f799e63e33609c682bc2868c237d3a89f > "$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/traccar__traccar-5508/tests/verifier.py b/tasks/traccar__traccar-5508/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5508/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/traccar__traccar-5517/environment/Dockerfile b/tasks/traccar__traccar-5517/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..155d5314e1215e48c04d90bb0930459a57ddbf20 --- /dev/null +++ b/tasks/traccar__traccar-5517/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ee005164810e4025d20ece06a8cfe76b8da9e6a3 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ee005164810e4025d20ece06a8cfe76b8da9e6a3 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ee005164810e4025d20ece06a8cfe76b8da9e6a3 \ + && 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/traccar__traccar-5517/instruction.md b/tasks/traccar__traccar-5517/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ae88580c3d0d7459abc1297dc645670a1ba0333 --- /dev/null +++ b/tasks/traccar__traccar-5517/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Implement mobilogix commands + +## Description + +[EI_2021_0018__MOBILOGIX__MT2000_PROTOCOL_OVER_THE_AIR__19_08_2021__V1_3_7.pdf](https://github.com/user-attachments/files/18919508/EI_2021_0018__MOBILOGIX__MT2000_PROTOCOL_OVER_THE_AIR__19_08_2021__V1_3_7.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ee005164810e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5517/solution/patch.diff b/tasks/traccar__traccar-5517/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..36d4e45439c97720a2d1fdfbf602aede5d8be033 --- /dev/null +++ b/tasks/traccar__traccar-5517/solution/patch.diff @@ -0,0 +1,120 @@ +diff --git a/src/main/java/org/traccar/protocol/MobilogixProtocol.java b/src/main/java/org/traccar/protocol/MobilogixProtocol.java +index 36d6b5ed2..ae2481921 100644 +--- a/src/main/java/org/traccar/protocol/MobilogixProtocol.java ++++ b/src/main/java/org/traccar/protocol/MobilogixProtocol.java +@@ -22,6 +22,7 @@ import org.traccar.CharacterDelimiterFrameDecoder; + import org.traccar.PipelineBuilder; + import org.traccar.TrackerServer; + import org.traccar.config.Config; ++import org.traccar.model.Command; + + import jakarta.inject.Inject; + +@@ -29,12 +30,17 @@ public class MobilogixProtocol extends BaseProtocol { + + @Inject + public MobilogixProtocol(Config config) { ++ setSupportedDataCommands( ++ Command.TYPE_CUSTOM, ++ Command.TYPE_ENGINE_RESUME, ++ Command.TYPE_ENGINE_STOP); + addServer(new TrackerServer(config, getName(), false) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline, Config config) { + pipeline.addLast(new CharacterDelimiterFrameDecoder(1024, ']')); + pipeline.addLast(new StringEncoder()); + pipeline.addLast(new StringDecoder()); ++ pipeline.addLast(new MobilogixProtocolEncoder(MobilogixProtocol.this)); + pipeline.addLast(new MobilogixProtocolDecoder(MobilogixProtocol.this)); + } + }); +diff --git a/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java b/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java +new file mode 100644 +index 000000000..c17fffb5d +--- /dev/null ++++ b/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java +@@ -0,0 +1,48 @@ ++/* ++ * Copyright 2025 Joaquim Cardeira (joaquim@cardeira.org) ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.traccar.protocol; ++ ++import org.traccar.Protocol; ++import org.traccar.StringProtocolEncoder; ++import org.traccar.helper.DateUtil; ++import org.traccar.model.Command; ++ ++import java.util.Date; ++ ++public class MobilogixProtocolEncoder extends StringProtocolEncoder { ++ ++ public MobilogixProtocolEncoder(Protocol protocol) { ++ super(protocol); ++ } ++ ++ private Object encodeCommand(Date time, String param) { ++ return String.format("[%s,S6,%s]", DateUtil.formatDate(time, false), param); ++ } ++ ++ @Override ++ protected Object encodeCommand(Command command) { ++ return encodeCommand(command, new Date()); ++ } ++ ++ protected Object encodeCommand(Command command, Date time) { ++ return switch (command.getType()) { ++ case Command.TYPE_CUSTOM -> encodeCommand(time, command.getString(Command.KEY_DATA)); ++ case Command.TYPE_ENGINE_RESUME -> encodeCommand(time, "RELAY=0"); ++ case Command.TYPE_ENGINE_STOP -> encodeCommand(time, "RELAY=1"); ++ default -> null; ++ }; ++ } ++} +diff --git a/src/test/java/org/traccar/protocol/MobilogixProtocolEncoderTest.java b/src/test/java/org/traccar/protocol/MobilogixProtocolEncoderTest.java +new file mode 100644 +index 000000000..c9cea3425 +--- /dev/null ++++ b/src/test/java/org/traccar/protocol/MobilogixProtocolEncoderTest.java +@@ -0,0 +1,30 @@ ++package org.traccar.protocol; ++ ++import org.junit.jupiter.api.Test; ++import org.traccar.ProtocolTest; ++import org.traccar.model.Command; ++ ++import java.time.LocalDate; ++import java.time.LocalDateTime; ++import java.time.LocalTime; ++import java.time.ZoneOffset; ++import java.util.Date; ++ ++import static org.junit.jupiter.api.Assertions.assertEquals; ++ ++public class MobilogixProtocolEncoderTest extends ProtocolTest { ++ private final Date time = Date.from( ++ LocalDateTime.of(LocalDate.of(2025, 2, 22), LocalTime.of(1, 2, 3)).atZone(ZoneOffset.systemDefault()).toInstant()); ++ ++ @Test ++ public void testEncode() throws Exception { ++ ++ var encoder = inject(new MobilogixProtocolEncoder(null)); ++ ++ Command command = new Command(); ++ command.setDeviceId(1); ++ command.setType(Command.TYPE_ENGINE_STOP); ++ ++ assertEquals("[2025-02-22 01:02:03,S6,RELAY=1]", encoder.encodeCommand(command, time)); ++ } ++} diff --git a/tasks/traccar__traccar-5517/solution/solve.sh b/tasks/traccar__traccar-5517/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5517/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/traccar__traccar-5517/task.toml b/tasks/traccar__traccar-5517/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b5ccc3917416e7b9362f1866beec43d6d712c3c7 --- /dev/null +++ b/tasks/traccar__traccar-5517/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5517" +description = "Implement mobilogix commands" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "ee005164810e4025d20ece06a8cfe76b8da9e6a3" +reference = "https://github.com/traccar/traccar/pull/5517" +source_access = "auto" +built_at = "2026-11-16T16:09:42.657370+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7989716ad7a2bdd1bfcad3620052df77e1cbb1be7e1a38eccd925436c7a782b5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-02-22T16:35:24Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/MobilogixProtocol.java", + "src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java", + "src/test/java/org/traccar/protocol/MobilogixProtocolEncoderTest.java", +] +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:03.446762+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:dd41393f64eadb28f3c9be4167eed13f2e372785c112be5565c92b2a8040db52" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5517/tests/capture.py b/tasks/traccar__traccar-5517/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5517/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/traccar__traccar-5517/tests/instruction.md b/tasks/traccar__traccar-5517/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ae88580c3d0d7459abc1297dc645670a1ba0333 --- /dev/null +++ b/tasks/traccar__traccar-5517/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Implement mobilogix commands + +## Description + +[EI_2021_0018__MOBILOGIX__MT2000_PROTOCOL_OVER_THE_AIR__19_08_2021__V1_3_7.pdf](https://github.com/user-attachments/files/18919508/EI_2021_0018__MOBILOGIX__MT2000_PROTOCOL_OVER_THE_AIR__19_08_2021__V1_3_7.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ee005164810e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5517/tests/oracle.patch b/tasks/traccar__traccar-5517/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..36d4e45439c97720a2d1fdfbf602aede5d8be033 --- /dev/null +++ b/tasks/traccar__traccar-5517/tests/oracle.patch @@ -0,0 +1,120 @@ +diff --git a/src/main/java/org/traccar/protocol/MobilogixProtocol.java b/src/main/java/org/traccar/protocol/MobilogixProtocol.java +index 36d6b5ed2..ae2481921 100644 +--- a/src/main/java/org/traccar/protocol/MobilogixProtocol.java ++++ b/src/main/java/org/traccar/protocol/MobilogixProtocol.java +@@ -22,6 +22,7 @@ import org.traccar.CharacterDelimiterFrameDecoder; + import org.traccar.PipelineBuilder; + import org.traccar.TrackerServer; + import org.traccar.config.Config; ++import org.traccar.model.Command; + + import jakarta.inject.Inject; + +@@ -29,12 +30,17 @@ public class MobilogixProtocol extends BaseProtocol { + + @Inject + public MobilogixProtocol(Config config) { ++ setSupportedDataCommands( ++ Command.TYPE_CUSTOM, ++ Command.TYPE_ENGINE_RESUME, ++ Command.TYPE_ENGINE_STOP); + addServer(new TrackerServer(config, getName(), false) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline, Config config) { + pipeline.addLast(new CharacterDelimiterFrameDecoder(1024, ']')); + pipeline.addLast(new StringEncoder()); + pipeline.addLast(new StringDecoder()); ++ pipeline.addLast(new MobilogixProtocolEncoder(MobilogixProtocol.this)); + pipeline.addLast(new MobilogixProtocolDecoder(MobilogixProtocol.this)); + } + }); +diff --git a/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java b/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java +new file mode 100644 +index 000000000..c17fffb5d +--- /dev/null ++++ b/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java +@@ -0,0 +1,48 @@ ++/* ++ * Copyright 2025 Joaquim Cardeira (joaquim@cardeira.org) ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.traccar.protocol; ++ ++import org.traccar.Protocol; ++import org.traccar.StringProtocolEncoder; ++import org.traccar.helper.DateUtil; ++import org.traccar.model.Command; ++ ++import java.util.Date; ++ ++public class MobilogixProtocolEncoder extends StringProtocolEncoder { ++ ++ public MobilogixProtocolEncoder(Protocol protocol) { ++ super(protocol); ++ } ++ ++ private Object encodeCommand(Date time, String param) { ++ return String.format("[%s,S6,%s]", DateUtil.formatDate(time, false), param); ++ } ++ ++ @Override ++ protected Object encodeCommand(Command command) { ++ return encodeCommand(command, new Date()); ++ } ++ ++ protected Object encodeCommand(Command command, Date time) { ++ return switch (command.getType()) { ++ case Command.TYPE_CUSTOM -> encodeCommand(time, command.getString(Command.KEY_DATA)); ++ case Command.TYPE_ENGINE_RESUME -> encodeCommand(time, "RELAY=0"); ++ case Command.TYPE_ENGINE_STOP -> encodeCommand(time, "RELAY=1"); ++ default -> null; ++ }; ++ } ++} +diff --git a/src/test/java/org/traccar/protocol/MobilogixProtocolEncoderTest.java b/src/test/java/org/traccar/protocol/MobilogixProtocolEncoderTest.java +new file mode 100644 +index 000000000..c9cea3425 +--- /dev/null ++++ b/src/test/java/org/traccar/protocol/MobilogixProtocolEncoderTest.java +@@ -0,0 +1,30 @@ ++package org.traccar.protocol; ++ ++import org.junit.jupiter.api.Test; ++import org.traccar.ProtocolTest; ++import org.traccar.model.Command; ++ ++import java.time.LocalDate; ++import java.time.LocalDateTime; ++import java.time.LocalTime; ++import java.time.ZoneOffset; ++import java.util.Date; ++ ++import static org.junit.jupiter.api.Assertions.assertEquals; ++ ++public class MobilogixProtocolEncoderTest extends ProtocolTest { ++ private final Date time = Date.from( ++ LocalDateTime.of(LocalDate.of(2025, 2, 22), LocalTime.of(1, 2, 3)).atZone(ZoneOffset.systemDefault()).toInstant()); ++ ++ @Test ++ public void testEncode() throws Exception { ++ ++ var encoder = inject(new MobilogixProtocolEncoder(null)); ++ ++ Command command = new Command(); ++ command.setDeviceId(1); ++ command.setType(Command.TYPE_ENGINE_STOP); ++ ++ assertEquals("[2025-02-22 01:02:03,S6,RELAY=1]", encoder.encodeCommand(command, time)); ++ } ++} diff --git a/tasks/traccar__traccar-5517/tests/test.sh b/tasks/traccar__traccar-5517/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..903c9e96b512ba5eeeb2ef734d0be26ba4a6da03 --- /dev/null +++ b/tasks/traccar__traccar-5517/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 ee005164810e4025d20ece06a8cfe76b8da9e6a3 > "$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/traccar__traccar-5517/tests/verifier.py b/tasks/traccar__traccar-5517/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5517/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/traccar__traccar-5518/environment/Dockerfile b/tasks/traccar__traccar-5518/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..21ae593d50eba0b8d2e61fad86bab51fdb1c5fe1 --- /dev/null +++ b/tasks/traccar__traccar-5518/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b83857ebf8ce6ea9b754297c105b3502b43a13b5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b83857ebf8ce6ea9b754297c105b3502b43a13b5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b83857ebf8ce6ea9b754297c105b3502b43a13b5 \ + && 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/traccar__traccar-5518/instruction.md b/tasks/traccar__traccar-5518/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f397096ec90262c5b6cd425a96bf74da63d14d44 --- /dev/null +++ b/tasks/traccar__traccar-5518/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Mobilogix + +## Description + +S6 Ack can cause loop. +Single position and reset commands. +Blocked and charge attributes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b83857ebf8ce`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5518/solution/patch.diff b/tasks/traccar__traccar-5518/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6cda864e9458e0df9ee4447c02f00d795a34bdbd --- /dev/null +++ b/tasks/traccar__traccar-5518/solution/patch.diff @@ -0,0 +1,65 @@ +diff --git a/src/main/java/org/traccar/protocol/MobilogixProtocol.java b/src/main/java/org/traccar/protocol/MobilogixProtocol.java +index ae2481921..299b371bc 100644 +--- a/src/main/java/org/traccar/protocol/MobilogixProtocol.java ++++ b/src/main/java/org/traccar/protocol/MobilogixProtocol.java +@@ -33,7 +33,9 @@ public class MobilogixProtocol extends BaseProtocol { + setSupportedDataCommands( + Command.TYPE_CUSTOM, + Command.TYPE_ENGINE_RESUME, +- Command.TYPE_ENGINE_STOP); ++ Command.TYPE_ENGINE_STOP, ++ Command.TYPE_POSITION_SINGLE, ++ Command.TYPE_REBOOT_DEVICE); + addServer(new TrackerServer(config, getName(), false) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline, Config config) { +diff --git a/src/main/java/org/traccar/protocol/MobilogixProtocolDecoder.java b/src/main/java/org/traccar/protocol/MobilogixProtocolDecoder.java +index 9f245b10c..b64cb6316 100644 +--- a/src/main/java/org/traccar/protocol/MobilogixProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/MobilogixProtocolDecoder.java +@@ -78,7 +78,7 @@ public class MobilogixProtocolDecoder extends BaseProtocolDecoder { + String sentence = ((String) msg).trim(); + String type = sentence.substring(21, sentence.indexOf(',', 21)); + +- if (channel != null) { ++ if (channel != null && !type.equals("T6")) { + String time = sentence.substring(1, 20); + String response; + if (type.equals("T1")) { +@@ -111,6 +111,10 @@ public class MobilogixProtocolDecoder extends BaseProtocolDecoder { + position.addAlarm(decodeAlarm(type)); + + int status = parser.nextHexInt(); ++ position.set(Position.KEY_BLOCKED, !BitUtil.check(status, 0)); ++ if (BitUtil.check(status, 1)) { ++ position.set(Position.KEY_CHARGE, true); ++ } + position.set(Position.KEY_IGNITION, BitUtil.check(status, 2)); + position.set(Position.KEY_MOTION, BitUtil.check(status, 3)); + position.set(Position.KEY_STATUS, status); +diff --git a/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java b/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java +index c17fffb5d..1aee3937c 100644 +--- a/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java +@@ -29,7 +29,7 @@ public class MobilogixProtocolEncoder extends StringProtocolEncoder { + } + + private Object encodeCommand(Date time, String param) { +- return String.format("[%s,S6,%s]", DateUtil.formatDate(time, false), param); ++ return String.format("[%s,%s]", DateUtil.formatDate(time, false), param); + } + + @Override +@@ -40,8 +40,10 @@ public class MobilogixProtocolEncoder extends StringProtocolEncoder { + protected Object encodeCommand(Command command, Date time) { + return switch (command.getType()) { + case Command.TYPE_CUSTOM -> encodeCommand(time, command.getString(Command.KEY_DATA)); +- case Command.TYPE_ENGINE_RESUME -> encodeCommand(time, "RELAY=0"); +- case Command.TYPE_ENGINE_STOP -> encodeCommand(time, "RELAY=1"); ++ case Command.TYPE_ENGINE_RESUME -> encodeCommand(time, "S6,RELAY=0"); ++ case Command.TYPE_ENGINE_STOP -> encodeCommand(time, "S6,RELAY=1"); ++ case Command.TYPE_POSITION_SINGLE -> encodeCommand(time, "S4,1,1"); ++ case Command.TYPE_REBOOT_DEVICE -> encodeCommand(time, "S7"); + default -> null; + }; + } diff --git a/tasks/traccar__traccar-5518/solution/solve.sh b/tasks/traccar__traccar-5518/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5518/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/traccar__traccar-5518/task.toml b/tasks/traccar__traccar-5518/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..db8bce4ea37dd3d2183711debc74f7b14e135fec --- /dev/null +++ b/tasks/traccar__traccar-5518/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5518" +description = "Mobilogix" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "b83857ebf8ce6ea9b754297c105b3502b43a13b5" +reference = "https://github.com/traccar/traccar/pull/5518" +source_access = "auto" +built_at = "2026-11-16T16:09:42.656063+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0dfd6a589dfed23c44501b1542333ae3ae914867f5de6532edb68054b1eae8b0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-02-22T17:13:46Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/MobilogixProtocol.java", + "src/main/java/org/traccar/protocol/MobilogixProtocolDecoder.java", + "src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.447336+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:91adc1902edcccae70a07a1f7114b5b2c07994d45618b1d81295090c2d1f5e01" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5518/tests/capture.py b/tasks/traccar__traccar-5518/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5518/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/traccar__traccar-5518/tests/instruction.md b/tasks/traccar__traccar-5518/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f397096ec90262c5b6cd425a96bf74da63d14d44 --- /dev/null +++ b/tasks/traccar__traccar-5518/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Mobilogix + +## Description + +S6 Ack can cause loop. +Single position and reset commands. +Blocked and charge attributes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b83857ebf8ce`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5518/tests/oracle.patch b/tasks/traccar__traccar-5518/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6cda864e9458e0df9ee4447c02f00d795a34bdbd --- /dev/null +++ b/tasks/traccar__traccar-5518/tests/oracle.patch @@ -0,0 +1,65 @@ +diff --git a/src/main/java/org/traccar/protocol/MobilogixProtocol.java b/src/main/java/org/traccar/protocol/MobilogixProtocol.java +index ae2481921..299b371bc 100644 +--- a/src/main/java/org/traccar/protocol/MobilogixProtocol.java ++++ b/src/main/java/org/traccar/protocol/MobilogixProtocol.java +@@ -33,7 +33,9 @@ public class MobilogixProtocol extends BaseProtocol { + setSupportedDataCommands( + Command.TYPE_CUSTOM, + Command.TYPE_ENGINE_RESUME, +- Command.TYPE_ENGINE_STOP); ++ Command.TYPE_ENGINE_STOP, ++ Command.TYPE_POSITION_SINGLE, ++ Command.TYPE_REBOOT_DEVICE); + addServer(new TrackerServer(config, getName(), false) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline, Config config) { +diff --git a/src/main/java/org/traccar/protocol/MobilogixProtocolDecoder.java b/src/main/java/org/traccar/protocol/MobilogixProtocolDecoder.java +index 9f245b10c..b64cb6316 100644 +--- a/src/main/java/org/traccar/protocol/MobilogixProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/MobilogixProtocolDecoder.java +@@ -78,7 +78,7 @@ public class MobilogixProtocolDecoder extends BaseProtocolDecoder { + String sentence = ((String) msg).trim(); + String type = sentence.substring(21, sentence.indexOf(',', 21)); + +- if (channel != null) { ++ if (channel != null && !type.equals("T6")) { + String time = sentence.substring(1, 20); + String response; + if (type.equals("T1")) { +@@ -111,6 +111,10 @@ public class MobilogixProtocolDecoder extends BaseProtocolDecoder { + position.addAlarm(decodeAlarm(type)); + + int status = parser.nextHexInt(); ++ position.set(Position.KEY_BLOCKED, !BitUtil.check(status, 0)); ++ if (BitUtil.check(status, 1)) { ++ position.set(Position.KEY_CHARGE, true); ++ } + position.set(Position.KEY_IGNITION, BitUtil.check(status, 2)); + position.set(Position.KEY_MOTION, BitUtil.check(status, 3)); + position.set(Position.KEY_STATUS, status); +diff --git a/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java b/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java +index c17fffb5d..1aee3937c 100644 +--- a/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/MobilogixProtocolEncoder.java +@@ -29,7 +29,7 @@ public class MobilogixProtocolEncoder extends StringProtocolEncoder { + } + + private Object encodeCommand(Date time, String param) { +- return String.format("[%s,S6,%s]", DateUtil.formatDate(time, false), param); ++ return String.format("[%s,%s]", DateUtil.formatDate(time, false), param); + } + + @Override +@@ -40,8 +40,10 @@ public class MobilogixProtocolEncoder extends StringProtocolEncoder { + protected Object encodeCommand(Command command, Date time) { + return switch (command.getType()) { + case Command.TYPE_CUSTOM -> encodeCommand(time, command.getString(Command.KEY_DATA)); +- case Command.TYPE_ENGINE_RESUME -> encodeCommand(time, "RELAY=0"); +- case Command.TYPE_ENGINE_STOP -> encodeCommand(time, "RELAY=1"); ++ case Command.TYPE_ENGINE_RESUME -> encodeCommand(time, "S6,RELAY=0"); ++ case Command.TYPE_ENGINE_STOP -> encodeCommand(time, "S6,RELAY=1"); ++ case Command.TYPE_POSITION_SINGLE -> encodeCommand(time, "S4,1,1"); ++ case Command.TYPE_REBOOT_DEVICE -> encodeCommand(time, "S7"); + default -> null; + }; + } diff --git a/tasks/traccar__traccar-5518/tests/test.sh b/tasks/traccar__traccar-5518/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..90eaa974f3bbf6b3160c56cd60b7a0beb865ee14 --- /dev/null +++ b/tasks/traccar__traccar-5518/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 b83857ebf8ce6ea9b754297c105b3502b43a13b5 > "$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/traccar__traccar-5518/tests/verifier.py b/tasks/traccar__traccar-5518/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5518/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/traccar__traccar-5522/environment/Dockerfile b/tasks/traccar__traccar-5522/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..057cafaa4ba84ec3af5404c498b149a6ea77a749 --- /dev/null +++ b/tasks/traccar__traccar-5522/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8e89c0413405270fbcbbcd9dd706e7c5f26e4a7c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8e89c0413405270fbcbbcd9dd706e7c5f26e4a7c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8e89c0413405270fbcbbcd9dd706e7c5f26e4a7c \ + && 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/traccar__traccar-5522/instruction.md b/tasks/traccar__traccar-5522/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db87ff2026064bce21fff5cfddfd9f33f5b94fd4 --- /dev/null +++ b/tasks/traccar__traccar-5522/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** Teltonika add Auto Geofence Alarm + +## Description + +Teltonika Devices can be configured to create a Geofence when the ignition is off. +If the device is moved out of the geofence with the ignition off, it creates an alarm. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8e89c0413405`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5522/solution/patch.diff b/tasks/traccar__traccar-5522/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4d4099588fe647a07ea205dd8b5049c48f3de84a --- /dev/null +++ b/tasks/traccar__traccar-5522/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +index 1b98665f1..47bff9b08 100644 +--- a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +@@ -287,6 +287,9 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + case 3 -> p.addAlarm(Position.ALARM_CORNERING); + } + }); ++ register(175, fmbXXX, (p, b) -> { ++ p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_GEOFENCE_ENTER : Position.ALARM_GEOFENCE_EXIT); ++ }); + register(636, fmbXXX, (p, b) -> p.set("cid4g", b.readUnsignedInt())); + register(662, fmbXXX, (p, b) -> p.set(Position.KEY_DOOR, b.readUnsignedByte() > 0)); + register(10800, fmbXXX, (p, b) -> p.set("eyeTemp1", b.readShort() / 100.0)); diff --git a/tasks/traccar__traccar-5522/solution/solve.sh b/tasks/traccar__traccar-5522/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5522/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/traccar__traccar-5522/task.toml b/tasks/traccar__traccar-5522/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..91e6e965cc38b5e1472fb556ada2c61c24d97c95 --- /dev/null +++ b/tasks/traccar__traccar-5522/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5522" +description = "Teltonika add Auto Geofence Alarm" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "8e89c0413405270fbcbbcd9dd706e7c5f26e4a7c" +reference = "https://github.com/traccar/traccar/pull/5522" +source_access = "auto" +built_at = "2026-11-16T16:09:42.653382+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:667fea6f4eac68c49274ee9207c08cb0e73733bc159e11e61f3499006a6eb9fa" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-12T00:20:06Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.447880+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0eb649629635320c5689a9fdaebd458f167b55cc758c3692012b9d70ff2087b1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5522/tests/capture.py b/tasks/traccar__traccar-5522/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5522/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/traccar__traccar-5522/tests/instruction.md b/tasks/traccar__traccar-5522/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db87ff2026064bce21fff5cfddfd9f33f5b94fd4 --- /dev/null +++ b/tasks/traccar__traccar-5522/tests/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** Teltonika add Auto Geofence Alarm + +## Description + +Teltonika Devices can be configured to create a Geofence when the ignition is off. +If the device is moved out of the geofence with the ignition off, it creates an alarm. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8e89c0413405`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5522/tests/oracle.patch b/tasks/traccar__traccar-5522/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4d4099588fe647a07ea205dd8b5049c48f3de84a --- /dev/null +++ b/tasks/traccar__traccar-5522/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +index 1b98665f1..47bff9b08 100644 +--- a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +@@ -287,6 +287,9 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + case 3 -> p.addAlarm(Position.ALARM_CORNERING); + } + }); ++ register(175, fmbXXX, (p, b) -> { ++ p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_GEOFENCE_ENTER : Position.ALARM_GEOFENCE_EXIT); ++ }); + register(636, fmbXXX, (p, b) -> p.set("cid4g", b.readUnsignedInt())); + register(662, fmbXXX, (p, b) -> p.set(Position.KEY_DOOR, b.readUnsignedByte() > 0)); + register(10800, fmbXXX, (p, b) -> p.set("eyeTemp1", b.readShort() / 100.0)); diff --git a/tasks/traccar__traccar-5522/tests/test.sh b/tasks/traccar__traccar-5522/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..919a44ae9e90ef42e432124120bf65f82698e541 --- /dev/null +++ b/tasks/traccar__traccar-5522/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 8e89c0413405270fbcbbcd9dd706e7c5f26e4a7c > "$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/traccar__traccar-5522/tests/verifier.py b/tasks/traccar__traccar-5522/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5522/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/traccar__traccar-5536/environment/Dockerfile b/tasks/traccar__traccar-5536/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c44c072220bfb0642ff4253406be100370c3daf4 --- /dev/null +++ b/tasks/traccar__traccar-5536/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a4d40cb6807d5b9dfc977494f351e35bbab4848e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a4d40cb6807d5b9dfc977494f351e35bbab4848e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a4d40cb6807d5b9dfc977494f351e35bbab4848e \ + && 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/traccar__traccar-5536/instruction.md b/tasks/traccar__traccar-5536/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ff1402c475c53938a758fcf86dc90fbe1dad1db9 --- /dev/null +++ b/tasks/traccar__traccar-5536/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Flespi add power cut Alarm + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a4d40cb6807d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5536/solution/patch.diff b/tasks/traccar__traccar-5536/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..736b1e9bd2660285ee1a8d3658c59a39d00873e6 --- /dev/null +++ b/tasks/traccar__traccar-5536/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java b/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java +index 1e9abfc59..a4395fe77 100644 +--- a/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java +@@ -266,6 +266,12 @@ public class FlespiProtocolDecoder extends BaseHttpProtocolDecoder { + } + yield true; + } ++ case "external.powersource.status" -> { ++ if (value == JsonValue.TRUE) { ++ position.addAlarm(Position.ALARM_POWER_CUT); ++ } ++ yield true; ++ } + case "custom.wln_accel_max" -> { + position.set("maxAcceleration", ((JsonNumber) value).doubleValue()); + yield true; diff --git a/tasks/traccar__traccar-5536/solution/solve.sh b/tasks/traccar__traccar-5536/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5536/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/traccar__traccar-5536/task.toml b/tasks/traccar__traccar-5536/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..54308127c958996c5ea05241a2494f2060e08f7e --- /dev/null +++ b/tasks/traccar__traccar-5536/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5536" +description = "Flespi add power cut Alarm" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "a4d40cb6807d5b9dfc977494f351e35bbab4848e" +reference = "https://github.com/traccar/traccar/pull/5536" +source_access = "auto" +built_at = "2026-11-16T16:09:42.651929+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e281b74848ec0be01141a242c0b94161f5668f88f86a3fc7ab40456de9226b36" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-31T21:36:23Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.448423+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f26f3763ceadba169273521712ef8b3074187a63afabd3c9029a2e8d40334169" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5536/tests/capture.py b/tasks/traccar__traccar-5536/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5536/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/traccar__traccar-5536/tests/instruction.md b/tasks/traccar__traccar-5536/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ff1402c475c53938a758fcf86dc90fbe1dad1db9 --- /dev/null +++ b/tasks/traccar__traccar-5536/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Flespi add power cut Alarm + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a4d40cb6807d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5536/tests/oracle.patch b/tasks/traccar__traccar-5536/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..736b1e9bd2660285ee1a8d3658c59a39d00873e6 --- /dev/null +++ b/tasks/traccar__traccar-5536/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java b/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java +index 1e9abfc59..a4395fe77 100644 +--- a/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java +@@ -266,6 +266,12 @@ public class FlespiProtocolDecoder extends BaseHttpProtocolDecoder { + } + yield true; + } ++ case "external.powersource.status" -> { ++ if (value == JsonValue.TRUE) { ++ position.addAlarm(Position.ALARM_POWER_CUT); ++ } ++ yield true; ++ } + case "custom.wln_accel_max" -> { + position.set("maxAcceleration", ((JsonNumber) value).doubleValue()); + yield true; diff --git a/tasks/traccar__traccar-5536/tests/test.sh b/tasks/traccar__traccar-5536/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5964a8f9c5d62763d0d3b60439cd2c699a148973 --- /dev/null +++ b/tasks/traccar__traccar-5536/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 a4d40cb6807d5b9dfc977494f351e35bbab4848e > "$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/traccar__traccar-5536/tests/verifier.py b/tasks/traccar__traccar-5536/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5536/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/traccar__traccar-5537/environment/Dockerfile b/tasks/traccar__traccar-5537/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c44c072220bfb0642ff4253406be100370c3daf4 --- /dev/null +++ b/tasks/traccar__traccar-5537/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a4d40cb6807d5b9dfc977494f351e35bbab4848e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a4d40cb6807d5b9dfc977494f351e35bbab4848e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a4d40cb6807d5b9dfc977494f351e35bbab4848e \ + && 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/traccar__traccar-5537/instruction.md b/tasks/traccar__traccar-5537/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e27be714a8937cfb5b7a888dbbd1baddcb9398b6 --- /dev/null +++ b/tasks/traccar__traccar-5537/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Add api endpoint to delete a singular position + +## Description + +I found and the coresponding PR for its implementation which I based this on. + +I already have some ids from the `/api/positions` endpoint which I want to easliy remove without constructing deviceId/from/to parameters. + +I hope that request makes sense and the implementation isn't _too_ bad, I'm not often doing Java stuff. Thanks for maintaining this cool project (: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a4d40cb6807d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5537/solution/patch.diff b/tasks/traccar__traccar-5537/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3934287eb2396741d640b34b4ae8065528b8483e --- /dev/null +++ b/tasks/traccar__traccar-5537/solution/patch.diff @@ -0,0 +1,65 @@ +diff --git a/openapi.yaml b/openapi.yaml +index 3a6126f7a..86ff751d4 100644 +--- a/openapi.yaml ++++ b/openapi.yaml +@@ -600,6 +600,24 @@ paths: + '400': + description: Bad Request + content: {} ++ /positions/{id}: ++ delete: ++ summary: Delete a Position ++ tags: ++ - Positions ++ parameters: ++ - name: id ++ in: path ++ required: true ++ schema: ++ type: integer ++ responses: ++ '204': ++ description: No Content ++ content: {} ++ '404': ++ description: Not Found ++ content: {} + /server: + get: + summary: Fetch Server information +diff --git a/src/main/java/org/traccar/api/resource/PositionResource.java b/src/main/java/org/traccar/api/resource/PositionResource.java +index 0d783a0fe..a466e7fcf 100644 +--- a/src/main/java/org/traccar/api/resource/PositionResource.java ++++ b/src/main/java/org/traccar/api/resource/PositionResource.java +@@ -33,6 +33,7 @@ import jakarta.ws.rs.Consumes; + import jakarta.ws.rs.GET; + import jakarta.ws.rs.DELETE; + import jakarta.ws.rs.Path; ++import jakarta.ws.rs.PathParam; + import jakarta.ws.rs.Produces; + import jakarta.ws.rs.QueryParam; + import jakarta.ws.rs.WebApplicationException; +@@ -88,6 +89,23 @@ public class PositionResource extends BaseResource { + } + } + ++ @Path("{id}") ++ @DELETE ++ public Response removeById(@PathParam("id") long positionId) throws StorageException { ++ permissionsService.checkRestriction(getUserId(), UserRestrictions::getReadonly); ++ ++ Request request = new Request(new Columns.All(), new Condition.Equals("id", positionId)); ++ Position position = storage.getObject(Position.class, request); ++ if (position == null) { ++ return Response.status(Response.Status.NOT_FOUND).build(); ++ } ++ ++ permissionsService.checkPermission(Device.class, getUserId(), position.getDeviceId()); ++ ++ storage.removeObject(Position.class, request); ++ return Response.status(Response.Status.NO_CONTENT).build(); ++ } ++ + @DELETE + public Response remove( + @QueryParam("deviceId") long deviceId, diff --git a/tasks/traccar__traccar-5537/solution/solve.sh b/tasks/traccar__traccar-5537/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5537/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/traccar__traccar-5537/task.toml b/tasks/traccar__traccar-5537/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fa58d55f265646aae3ef3975df05723417722255 --- /dev/null +++ b/tasks/traccar__traccar-5537/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5537" +description = "Add api endpoint to delete a singular position" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "a4d40cb6807d5b9dfc977494f351e35bbab4848e" +reference = "https://github.com/traccar/traccar/pull/5537" +source_access = "auto" +built_at = "2026-11-16T16:09:42.650682+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e79e45c6038c31788b77a1c1fd2d88734b70800a59455c252a7da1ceb58074cb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-31T21:39:32Z" +diff_format = "unified" +context_files = [ + "openapi.yaml", + "src/main/java/org/traccar/api/resource/PositionResource.java", +] +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:03.448952+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f26f3763ceadba169273521712ef8b3074187a63afabd3c9029a2e8d40334169" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5537/tests/capture.py b/tasks/traccar__traccar-5537/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5537/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/traccar__traccar-5537/tests/instruction.md b/tasks/traccar__traccar-5537/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e27be714a8937cfb5b7a888dbbd1baddcb9398b6 --- /dev/null +++ b/tasks/traccar__traccar-5537/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Add api endpoint to delete a singular position + +## Description + +I found and the coresponding PR for its implementation which I based this on. + +I already have some ids from the `/api/positions` endpoint which I want to easliy remove without constructing deviceId/from/to parameters. + +I hope that request makes sense and the implementation isn't _too_ bad, I'm not often doing Java stuff. Thanks for maintaining this cool project (: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a4d40cb6807d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5537/tests/oracle.patch b/tasks/traccar__traccar-5537/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3934287eb2396741d640b34b4ae8065528b8483e --- /dev/null +++ b/tasks/traccar__traccar-5537/tests/oracle.patch @@ -0,0 +1,65 @@ +diff --git a/openapi.yaml b/openapi.yaml +index 3a6126f7a..86ff751d4 100644 +--- a/openapi.yaml ++++ b/openapi.yaml +@@ -600,6 +600,24 @@ paths: + '400': + description: Bad Request + content: {} ++ /positions/{id}: ++ delete: ++ summary: Delete a Position ++ tags: ++ - Positions ++ parameters: ++ - name: id ++ in: path ++ required: true ++ schema: ++ type: integer ++ responses: ++ '204': ++ description: No Content ++ content: {} ++ '404': ++ description: Not Found ++ content: {} + /server: + get: + summary: Fetch Server information +diff --git a/src/main/java/org/traccar/api/resource/PositionResource.java b/src/main/java/org/traccar/api/resource/PositionResource.java +index 0d783a0fe..a466e7fcf 100644 +--- a/src/main/java/org/traccar/api/resource/PositionResource.java ++++ b/src/main/java/org/traccar/api/resource/PositionResource.java +@@ -33,6 +33,7 @@ import jakarta.ws.rs.Consumes; + import jakarta.ws.rs.GET; + import jakarta.ws.rs.DELETE; + import jakarta.ws.rs.Path; ++import jakarta.ws.rs.PathParam; + import jakarta.ws.rs.Produces; + import jakarta.ws.rs.QueryParam; + import jakarta.ws.rs.WebApplicationException; +@@ -88,6 +89,23 @@ public class PositionResource extends BaseResource { + } + } + ++ @Path("{id}") ++ @DELETE ++ public Response removeById(@PathParam("id") long positionId) throws StorageException { ++ permissionsService.checkRestriction(getUserId(), UserRestrictions::getReadonly); ++ ++ Request request = new Request(new Columns.All(), new Condition.Equals("id", positionId)); ++ Position position = storage.getObject(Position.class, request); ++ if (position == null) { ++ return Response.status(Response.Status.NOT_FOUND).build(); ++ } ++ ++ permissionsService.checkPermission(Device.class, getUserId(), position.getDeviceId()); ++ ++ storage.removeObject(Position.class, request); ++ return Response.status(Response.Status.NO_CONTENT).build(); ++ } ++ + @DELETE + public Response remove( + @QueryParam("deviceId") long deviceId, diff --git a/tasks/traccar__traccar-5537/tests/test.sh b/tasks/traccar__traccar-5537/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5964a8f9c5d62763d0d3b60439cd2c699a148973 --- /dev/null +++ b/tasks/traccar__traccar-5537/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 a4d40cb6807d5b9dfc977494f351e35bbab4848e > "$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/traccar__traccar-5537/tests/verifier.py b/tasks/traccar__traccar-5537/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5537/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/traccar__traccar-5538/environment/Dockerfile b/tasks/traccar__traccar-5538/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..db4b76f2fed213b26c579e0dfce7f2fab1eb2af6 --- /dev/null +++ b/tasks/traccar__traccar-5538/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 677ecedd932106dd8f62039ca16ccddd1714863a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 677ecedd932106dd8f62039ca16ccddd1714863a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 677ecedd932106dd8f62039ca16ccddd1714863a \ + && 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/traccar__traccar-5538/instruction.md b/tasks/traccar__traccar-5538/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6ead0e7f20c52909f10b604cef2015d39aeaf16b --- /dev/null +++ b/tasks/traccar__traccar-5538/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** AOVX devices + +## Description + +Movement alarm in AL300 and GL100 +Fix invalid accident alarm in VL300 +Motion, light, temp and humidity in AOVX +Custom commands in AOVX +Engine stop / resume in VL300 + +[V_Series Protocol.pdf](https://github.com/user-attachments/files/19577356/V_Series.Protocol.pdf) +[GA_Series Protocol.pdf](https://github.com/user-attachments/files/19577357/GA_Series.Protocol.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `677ecedd9321`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5538/solution/patch.diff b/tasks/traccar__traccar-5538/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6ac6a2eb8791048e67f79407c32c2d64bf433e96 --- /dev/null +++ b/tasks/traccar__traccar-5538/solution/patch.diff @@ -0,0 +1,134 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index fd6c2e62b..056d149d6 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -74,6 +74,7 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_PARAMETER_SETTING = 0x0310; + public static final int MSG_SEND_TEXT_MESSAGE = 0x8300; + public static final int MSG_REPORT_TEXT_MESSAGE = 0x6006; ++ public static final int MSG_CONFIGURATION_PARAMETERS = 0x8103; + + public static final int RESULT_SUCCESS = 0; + +@@ -132,6 +133,10 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + if (BitUtil.check(value, 1)) { + position.addAlarm(Position.ALARM_TAMPERING); + } ++ } else if (model != null && Set.of("AL300", "GL100").contains(model)) { ++ if (BitUtil.check(value, 16)) { ++ position.addAlarm(Position.ALARM_MOVEMENT); ++ } + } else { + if (BitUtil.check(value, 0)) { + position.addAlarm(Position.ALARM_SOS); +@@ -165,7 +170,9 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + position.addAlarm(Position.ALARM_MOVEMENT); + } + if (BitUtil.check(value, 29) || BitUtil.check(value, 30)) { +- position.addAlarm(Position.ALARM_ACCIDENT); ++ if (model == null || !model.equals("VL300")) { ++ position.addAlarm(Position.ALARM_ACCIDENT); ++ } + } + } + } +@@ -471,6 +478,7 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + int length = buf.readUnsignedByte(); + int endIndex = buf.readerIndex() + length; + String stringValue; ++ int event; + switch (subtype) { + case 0x01: + position.set(Position.KEY_ODOMETER, buf.readUnsignedInt() * 100); +@@ -535,7 +543,7 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + buf.skipBytes(4); // reserved + break; + case 0x60: +- int event = buf.readUnsignedShort(); ++ event = buf.readUnsignedShort(); + position.set(Position.KEY_EVENT, event); + if (event >= 0x0061 && event <= 0x0066) { + buf.skipBytes(6); // lock id +@@ -785,14 +793,21 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + } + break; + case 0xF6: +- position.set(Position.KEY_EVENT, buf.readUnsignedByte()); ++ event = buf.readUnsignedByte(); ++ position.set(Position.KEY_EVENT, event); ++ if (event == 2) { ++ position.set(Position.KEY_MOTION, true); ++ } + int fieldMask = buf.readUnsignedByte(); + if (BitUtil.check(fieldMask, 0)) { +- buf.readUnsignedShort(); // light ++ position.set("lightSensor", buf.readUnsignedShort()); + } + if (BitUtil.check(fieldMask, 1)) { + position.set(Position.PREFIX_TEMP + 1, buf.readShort() * 0.1); + } ++ if (BitUtil.check(fieldMask, 2)) { ++ position.set(Position.KEY_HUMIDITY, buf.readShort() * 0.1); ++ } + break; + case 0xF7: + position.set(Position.KEY_BATTERY, buf.readUnsignedInt() * 0.001); +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolEncoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolEncoder.java +index 4f8e8ff47..e2a92a454 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolEncoder.java +@@ -28,6 +28,7 @@ import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.text.SimpleDateFormat; + import java.util.Date; ++import java.util.Set; + + public class HuabaoProtocolEncoder extends BaseProtocolEncoder { + +@@ -49,7 +50,15 @@ public class HuabaoProtocolEncoder extends BaseProtocolEncoder { + + switch (command.getType()) { + case Command.TYPE_CUSTOM: +- if ("BSJ".equals(getDeviceModel(command.getDeviceId()))) { ++ if (Set.of("AL300", "GL100", "VL300").contains(getDeviceModel(command.getDeviceId()))) { ++ data.writeByte(1); // number of parameters ++ data.writeInt(0xF030); // AT command transparent transmission ++ int length = command.getString(Command.KEY_DATA).length(); ++ data.writeByte(length); ++ data.writeCharSequence(command.getString(Command.KEY_DATA), StandardCharsets.US_ASCII); ++ return HuabaoProtocolDecoder.formatMessage( ++ 0x7e, HuabaoProtocolDecoder.MSG_CONFIGURATION_PARAMETERS, id, false, data); ++ } else if ("BSJ".equals(getDeviceModel(command.getDeviceId()))) { + data.writeByte(1); // flag + var charset = Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII; + data.writeCharSequence(command.getString(Command.KEY_DATA), charset); +@@ -90,7 +99,12 @@ public class HuabaoProtocolEncoder extends BaseProtocolEncoder { + return HuabaoProtocolDecoder.formatMessage( + 0x7e, HuabaoProtocolDecoder.MSG_OIL_CONTROL, id, false, data); + } else { +- data.writeByte(command.getType().equals(Command.TYPE_ENGINE_STOP) ? 0xf0 : 0xf1); ++ if ("VL300".equals(getDeviceModel(command.getDeviceId()))) { ++ data.writeCharSequence(command.getType().equals(Command.TYPE_ENGINE_STOP) ? "#0;1" : "#0;0", ++ StandardCharsets.US_ASCII); ++ } else { ++ data.writeByte(command.getType().equals(Command.TYPE_ENGINE_STOP) ? 0xf0 : 0xf1); ++ } + return HuabaoProtocolDecoder.formatMessage( + 0x7e, HuabaoProtocolDecoder.MSG_TERMINAL_CONTROL, id, false, data); + } +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 272a63a41..554c2f1b8 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -264,6 +264,11 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + "7E020000964130564801050048000000001000004F01651E2E02CAEC3802E80000001524062616002101040000000330011F31010EF1040000308CF231414F56585F564C3330302D4C415F48322E315F4547393135554C4141425230334130324D30385F56322E312E305F763130F3011FF400F5080000000000000001F6084008FFFFFFFD0009F70600000E870246F912000F000000010000062A00082406261600184D7E"), + Position.KEY_POWER, 12.428); + ++ decoder.setModelOverride("AL300"); ++ verifyAttribute(decoder, binary( ++ "7e020000ec6710704387730579000100009058000e015baf2c029bb433001200000129250310035204300111310108f03402d400020f720e0f00007d8b8e02d400020f720e0b00007d8b8c02d400020f720d0b00007d8b8a02d4000b092bf3030000c9a588f231414f56585f414c3330302d4c415f48322e305f4547393135554c4141425230334130344d30385f56322e312e303a763031f40e18ef3a6ae1c6be00bb252515d3b5f614021901cb006d0099052005dc002800000032000af70600000d6f003cf81d04086967107043877389550327001051953711414c3330302d4c410000f912000f0000000100000000000b2503100352322a7e"), ++ Position.KEY_ALARM, Position.ALARM_MOVEMENT); ++ + } + + } diff --git a/tasks/traccar__traccar-5538/solution/solve.sh b/tasks/traccar__traccar-5538/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5538/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/traccar__traccar-5538/task.toml b/tasks/traccar__traccar-5538/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9150a3d36f5676c57573b24c61f6532a5661bbfc --- /dev/null +++ b/tasks/traccar__traccar-5538/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5538" +description = "AOVX devices" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "677ecedd932106dd8f62039ca16ccddd1714863a" +reference = "https://github.com/traccar/traccar/pull/5538" +source_access = "auto" +built_at = "2026-11-16T16:09:42.647521+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8ef9f2e1e4fa6a2ec237eabd89f51dd6d719180a7505d4422281c53394dde5df" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-04-03T04:50:24Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java", + "src/main/java/org/traccar/protocol/HuabaoProtocolEncoder.java", + "src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 46 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.449490+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:91bebe8cd59a45b854a036d9fdd8ba6e9f94170a1cc4e1e17d5d5b2e0ef21e66" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5538/tests/capture.py b/tasks/traccar__traccar-5538/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5538/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/traccar__traccar-5538/tests/instruction.md b/tasks/traccar__traccar-5538/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6ead0e7f20c52909f10b604cef2015d39aeaf16b --- /dev/null +++ b/tasks/traccar__traccar-5538/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** AOVX devices + +## Description + +Movement alarm in AL300 and GL100 +Fix invalid accident alarm in VL300 +Motion, light, temp and humidity in AOVX +Custom commands in AOVX +Engine stop / resume in VL300 + +[V_Series Protocol.pdf](https://github.com/user-attachments/files/19577356/V_Series.Protocol.pdf) +[GA_Series Protocol.pdf](https://github.com/user-attachments/files/19577357/GA_Series.Protocol.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `677ecedd9321`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5538/tests/oracle.patch b/tasks/traccar__traccar-5538/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6ac6a2eb8791048e67f79407c32c2d64bf433e96 --- /dev/null +++ b/tasks/traccar__traccar-5538/tests/oracle.patch @@ -0,0 +1,134 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index fd6c2e62b..056d149d6 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -74,6 +74,7 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_PARAMETER_SETTING = 0x0310; + public static final int MSG_SEND_TEXT_MESSAGE = 0x8300; + public static final int MSG_REPORT_TEXT_MESSAGE = 0x6006; ++ public static final int MSG_CONFIGURATION_PARAMETERS = 0x8103; + + public static final int RESULT_SUCCESS = 0; + +@@ -132,6 +133,10 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + if (BitUtil.check(value, 1)) { + position.addAlarm(Position.ALARM_TAMPERING); + } ++ } else if (model != null && Set.of("AL300", "GL100").contains(model)) { ++ if (BitUtil.check(value, 16)) { ++ position.addAlarm(Position.ALARM_MOVEMENT); ++ } + } else { + if (BitUtil.check(value, 0)) { + position.addAlarm(Position.ALARM_SOS); +@@ -165,7 +170,9 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + position.addAlarm(Position.ALARM_MOVEMENT); + } + if (BitUtil.check(value, 29) || BitUtil.check(value, 30)) { +- position.addAlarm(Position.ALARM_ACCIDENT); ++ if (model == null || !model.equals("VL300")) { ++ position.addAlarm(Position.ALARM_ACCIDENT); ++ } + } + } + } +@@ -471,6 +478,7 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + int length = buf.readUnsignedByte(); + int endIndex = buf.readerIndex() + length; + String stringValue; ++ int event; + switch (subtype) { + case 0x01: + position.set(Position.KEY_ODOMETER, buf.readUnsignedInt() * 100); +@@ -535,7 +543,7 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + buf.skipBytes(4); // reserved + break; + case 0x60: +- int event = buf.readUnsignedShort(); ++ event = buf.readUnsignedShort(); + position.set(Position.KEY_EVENT, event); + if (event >= 0x0061 && event <= 0x0066) { + buf.skipBytes(6); // lock id +@@ -785,14 +793,21 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + } + break; + case 0xF6: +- position.set(Position.KEY_EVENT, buf.readUnsignedByte()); ++ event = buf.readUnsignedByte(); ++ position.set(Position.KEY_EVENT, event); ++ if (event == 2) { ++ position.set(Position.KEY_MOTION, true); ++ } + int fieldMask = buf.readUnsignedByte(); + if (BitUtil.check(fieldMask, 0)) { +- buf.readUnsignedShort(); // light ++ position.set("lightSensor", buf.readUnsignedShort()); + } + if (BitUtil.check(fieldMask, 1)) { + position.set(Position.PREFIX_TEMP + 1, buf.readShort() * 0.1); + } ++ if (BitUtil.check(fieldMask, 2)) { ++ position.set(Position.KEY_HUMIDITY, buf.readShort() * 0.1); ++ } + break; + case 0xF7: + position.set(Position.KEY_BATTERY, buf.readUnsignedInt() * 0.001); +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolEncoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolEncoder.java +index 4f8e8ff47..e2a92a454 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolEncoder.java +@@ -28,6 +28,7 @@ import java.nio.charset.Charset; + import java.nio.charset.StandardCharsets; + import java.text.SimpleDateFormat; + import java.util.Date; ++import java.util.Set; + + public class HuabaoProtocolEncoder extends BaseProtocolEncoder { + +@@ -49,7 +50,15 @@ public class HuabaoProtocolEncoder extends BaseProtocolEncoder { + + switch (command.getType()) { + case Command.TYPE_CUSTOM: +- if ("BSJ".equals(getDeviceModel(command.getDeviceId()))) { ++ if (Set.of("AL300", "GL100", "VL300").contains(getDeviceModel(command.getDeviceId()))) { ++ data.writeByte(1); // number of parameters ++ data.writeInt(0xF030); // AT command transparent transmission ++ int length = command.getString(Command.KEY_DATA).length(); ++ data.writeByte(length); ++ data.writeCharSequence(command.getString(Command.KEY_DATA), StandardCharsets.US_ASCII); ++ return HuabaoProtocolDecoder.formatMessage( ++ 0x7e, HuabaoProtocolDecoder.MSG_CONFIGURATION_PARAMETERS, id, false, data); ++ } else if ("BSJ".equals(getDeviceModel(command.getDeviceId()))) { + data.writeByte(1); // flag + var charset = Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII; + data.writeCharSequence(command.getString(Command.KEY_DATA), charset); +@@ -90,7 +99,12 @@ public class HuabaoProtocolEncoder extends BaseProtocolEncoder { + return HuabaoProtocolDecoder.formatMessage( + 0x7e, HuabaoProtocolDecoder.MSG_OIL_CONTROL, id, false, data); + } else { +- data.writeByte(command.getType().equals(Command.TYPE_ENGINE_STOP) ? 0xf0 : 0xf1); ++ if ("VL300".equals(getDeviceModel(command.getDeviceId()))) { ++ data.writeCharSequence(command.getType().equals(Command.TYPE_ENGINE_STOP) ? "#0;1" : "#0;0", ++ StandardCharsets.US_ASCII); ++ } else { ++ data.writeByte(command.getType().equals(Command.TYPE_ENGINE_STOP) ? 0xf0 : 0xf1); ++ } + return HuabaoProtocolDecoder.formatMessage( + 0x7e, HuabaoProtocolDecoder.MSG_TERMINAL_CONTROL, id, false, data); + } +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 272a63a41..554c2f1b8 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -264,6 +264,11 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + "7E020000964130564801050048000000001000004F01651E2E02CAEC3802E80000001524062616002101040000000330011F31010EF1040000308CF231414F56585F564C3330302D4C415F48322E315F4547393135554C4141425230334130324D30385F56322E312E305F763130F3011FF400F5080000000000000001F6084008FFFFFFFD0009F70600000E870246F912000F000000010000062A00082406261600184D7E"), + Position.KEY_POWER, 12.428); + ++ decoder.setModelOverride("AL300"); ++ verifyAttribute(decoder, binary( ++ "7e020000ec6710704387730579000100009058000e015baf2c029bb433001200000129250310035204300111310108f03402d400020f720e0f00007d8b8e02d400020f720e0b00007d8b8c02d400020f720d0b00007d8b8a02d4000b092bf3030000c9a588f231414f56585f414c3330302d4c415f48322e305f4547393135554c4141425230334130344d30385f56322e312e303a763031f40e18ef3a6ae1c6be00bb252515d3b5f614021901cb006d0099052005dc002800000032000af70600000d6f003cf81d04086967107043877389550327001051953711414c3330302d4c410000f912000f0000000100000000000b2503100352322a7e"), ++ Position.KEY_ALARM, Position.ALARM_MOVEMENT); ++ + } + + } diff --git a/tasks/traccar__traccar-5538/tests/test.sh b/tasks/traccar__traccar-5538/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d2ca893a610a1bdb496e9405e09eeced472b2931 --- /dev/null +++ b/tasks/traccar__traccar-5538/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 677ecedd932106dd8f62039ca16ccddd1714863a > "$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/traccar__traccar-5538/tests/verifier.py b/tasks/traccar__traccar-5538/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5538/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/traccar__traccar-5539/environment/Dockerfile b/tasks/traccar__traccar-5539/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..db4b76f2fed213b26c579e0dfce7f2fab1eb2af6 --- /dev/null +++ b/tasks/traccar__traccar-5539/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 677ecedd932106dd8f62039ca16ccddd1714863a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 677ecedd932106dd8f62039ca16ccddd1714863a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 677ecedd932106dd8f62039ca16ccddd1714863a \ + && 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/traccar__traccar-5539/instruction.md b/tasks/traccar__traccar-5539/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bb876f543b368978b7f09d8e6cd45686d9757360 --- /dev/null +++ b/tasks/traccar__traccar-5539/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** Update teltonika protocol + +## Description + +- Engine stop / resume commands +- Engine load, milDistance, hybridBatteryPackLevel and RPM + +https://wiki.teltonika-gps.com/view/FMB003_Teltonika_Data_Sending_Parameters_ID + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `677ecedd9321`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5539/solution/patch.diff b/tasks/traccar__traccar-5539/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..08148d6dc5d1c7363bfec41ad8538b77da6f4df5 --- /dev/null +++ b/tasks/traccar__traccar-5539/solution/patch.diff @@ -0,0 +1,65 @@ +diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocol.java b/src/main/java/org/traccar/protocol/TeltonikaProtocol.java +index f2d610251..17f7592fc 100644 +--- a/src/main/java/org/traccar/protocol/TeltonikaProtocol.java ++++ b/src/main/java/org/traccar/protocol/TeltonikaProtocol.java +@@ -28,7 +28,9 @@ public class TeltonikaProtocol extends BaseProtocol { + @Inject + public TeltonikaProtocol(Config config) { + setSupportedDataCommands( +- Command.TYPE_CUSTOM); ++ Command.TYPE_CUSTOM, ++ Command.TYPE_ENGINE_STOP, ++ Command.TYPE_ENGINE_RESUME); + addServer(new TrackerServer(config, getName(), false) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline, Config config) { +diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +index e6623c609..9c8045737 100644 +--- a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +@@ -218,7 +218,11 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + register(27, null, (p, b) -> p.set("bleTemp3", b.readShort() * 0.01)); + register(28, null, (p, b) -> p.set("bleTemp4", b.readShort() * 0.01)); + register(30, fmbXXX, (p, b) -> p.set("faultCount", b.readUnsignedByte())); ++ register(31, fmbXXX, (p, b) -> p.set(Position.KEY_ENGINE_LOAD, b.readUnsignedByte())); + register(32, fmbXXX, (p, b) -> p.set(Position.KEY_COOLANT_TEMP, b.readByte())); ++ register(36, fmbXXX, (p, b) -> p.set(Position.KEY_RPM, b.readUnsignedShort())); ++ register(43, fmbXXX, (p, b) -> p.set("milDistance", b.readUnsignedShort())); ++ register(57, fmbXXX, (p, b) -> p.set("hybridBatteryLevel", b.readByte())); + register(66, null, (p, b) -> p.set(Position.KEY_POWER, b.readUnsignedShort() * 0.001)); + register(67, null, (p, b) -> p.set(Position.KEY_BATTERY, b.readUnsignedShort() * 0.001)); + register(68, fmbXXX, (p, b) -> p.set("batteryCurrent", b.readUnsignedShort() * 0.001)); +diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolEncoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolEncoder.java +index 8a614618a..a1a4f099d 100644 +--- a/src/main/java/org/traccar/protocol/TeltonikaProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolEncoder.java +@@ -51,17 +51,19 @@ public class TeltonikaProtocolEncoder extends BaseProtocolEncoder { + + @Override + protected Object encodeCommand(Command command) { +- +- if (command.getType().equals(Command.TYPE_CUSTOM)) { +- String data = command.getString(Command.KEY_DATA); +- if (data.matches("(\\p{XDigit}{2})+")) { +- return encodeContent(DataConverter.parseHex(data)); +- } else { +- return encodeContent((data + "\r\n").getBytes(StandardCharsets.US_ASCII)); ++ return switch (command.getType()) { ++ case Command.TYPE_ENGINE_STOP -> encodeContent("setdigout 1\r\n".getBytes(StandardCharsets.US_ASCII)); ++ case Command.TYPE_ENGINE_RESUME -> encodeContent("setdigout 0\r\n".getBytes(StandardCharsets.US_ASCII)); ++ case Command.TYPE_CUSTOM -> { ++ String data = command.getString(Command.KEY_DATA); ++ if (data.matches("(\\p{XDigit}{2})+")) { ++ yield encodeContent(DataConverter.parseHex(data)); ++ } else { ++ yield encodeContent((data + "\r\n").getBytes(StandardCharsets.US_ASCII)); ++ } + } +- } else { +- return null; +- } ++ default -> null; ++ }; + } + + } diff --git a/tasks/traccar__traccar-5539/solution/solve.sh b/tasks/traccar__traccar-5539/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5539/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/traccar__traccar-5539/task.toml b/tasks/traccar__traccar-5539/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e36ddcf8d5d7e4b9f88912b4300b46fe4862976a --- /dev/null +++ b/tasks/traccar__traccar-5539/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5539" +description = "Update teltonika protocol" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "677ecedd932106dd8f62039ca16ccddd1714863a" +reference = "https://github.com/traccar/traccar/pull/5539" +source_access = "auto" +built_at = "2026-11-16T16:09:42.649148+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f49fd7d41e0e7fc4f801b5da3a00554edbe99f3fd5571d1234959268cd672f42" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-04-03T13:57:54Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/TeltonikaProtocol.java", + "src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java", + "src/main/java/org/traccar/protocol/TeltonikaProtocolEncoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 30 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.450008+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:91bebe8cd59a45b854a036d9fdd8ba6e9f94170a1cc4e1e17d5d5b2e0ef21e66" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5539/tests/capture.py b/tasks/traccar__traccar-5539/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5539/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/traccar__traccar-5539/tests/instruction.md b/tasks/traccar__traccar-5539/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bb876f543b368978b7f09d8e6cd45686d9757360 --- /dev/null +++ b/tasks/traccar__traccar-5539/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** Update teltonika protocol + +## Description + +- Engine stop / resume commands +- Engine load, milDistance, hybridBatteryPackLevel and RPM + +https://wiki.teltonika-gps.com/view/FMB003_Teltonika_Data_Sending_Parameters_ID + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `677ecedd9321`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5539/tests/oracle.patch b/tasks/traccar__traccar-5539/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..08148d6dc5d1c7363bfec41ad8538b77da6f4df5 --- /dev/null +++ b/tasks/traccar__traccar-5539/tests/oracle.patch @@ -0,0 +1,65 @@ +diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocol.java b/src/main/java/org/traccar/protocol/TeltonikaProtocol.java +index f2d610251..17f7592fc 100644 +--- a/src/main/java/org/traccar/protocol/TeltonikaProtocol.java ++++ b/src/main/java/org/traccar/protocol/TeltonikaProtocol.java +@@ -28,7 +28,9 @@ public class TeltonikaProtocol extends BaseProtocol { + @Inject + public TeltonikaProtocol(Config config) { + setSupportedDataCommands( +- Command.TYPE_CUSTOM); ++ Command.TYPE_CUSTOM, ++ Command.TYPE_ENGINE_STOP, ++ Command.TYPE_ENGINE_RESUME); + addServer(new TrackerServer(config, getName(), false) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline, Config config) { +diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +index e6623c609..9c8045737 100644 +--- a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +@@ -218,7 +218,11 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + register(27, null, (p, b) -> p.set("bleTemp3", b.readShort() * 0.01)); + register(28, null, (p, b) -> p.set("bleTemp4", b.readShort() * 0.01)); + register(30, fmbXXX, (p, b) -> p.set("faultCount", b.readUnsignedByte())); ++ register(31, fmbXXX, (p, b) -> p.set(Position.KEY_ENGINE_LOAD, b.readUnsignedByte())); + register(32, fmbXXX, (p, b) -> p.set(Position.KEY_COOLANT_TEMP, b.readByte())); ++ register(36, fmbXXX, (p, b) -> p.set(Position.KEY_RPM, b.readUnsignedShort())); ++ register(43, fmbXXX, (p, b) -> p.set("milDistance", b.readUnsignedShort())); ++ register(57, fmbXXX, (p, b) -> p.set("hybridBatteryLevel", b.readByte())); + register(66, null, (p, b) -> p.set(Position.KEY_POWER, b.readUnsignedShort() * 0.001)); + register(67, null, (p, b) -> p.set(Position.KEY_BATTERY, b.readUnsignedShort() * 0.001)); + register(68, fmbXXX, (p, b) -> p.set("batteryCurrent", b.readUnsignedShort() * 0.001)); +diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolEncoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolEncoder.java +index 8a614618a..a1a4f099d 100644 +--- a/src/main/java/org/traccar/protocol/TeltonikaProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolEncoder.java +@@ -51,17 +51,19 @@ public class TeltonikaProtocolEncoder extends BaseProtocolEncoder { + + @Override + protected Object encodeCommand(Command command) { +- +- if (command.getType().equals(Command.TYPE_CUSTOM)) { +- String data = command.getString(Command.KEY_DATA); +- if (data.matches("(\\p{XDigit}{2})+")) { +- return encodeContent(DataConverter.parseHex(data)); +- } else { +- return encodeContent((data + "\r\n").getBytes(StandardCharsets.US_ASCII)); ++ return switch (command.getType()) { ++ case Command.TYPE_ENGINE_STOP -> encodeContent("setdigout 1\r\n".getBytes(StandardCharsets.US_ASCII)); ++ case Command.TYPE_ENGINE_RESUME -> encodeContent("setdigout 0\r\n".getBytes(StandardCharsets.US_ASCII)); ++ case Command.TYPE_CUSTOM -> { ++ String data = command.getString(Command.KEY_DATA); ++ if (data.matches("(\\p{XDigit}{2})+")) { ++ yield encodeContent(DataConverter.parseHex(data)); ++ } else { ++ yield encodeContent((data + "\r\n").getBytes(StandardCharsets.US_ASCII)); ++ } + } +- } else { +- return null; +- } ++ default -> null; ++ }; + } + + } diff --git a/tasks/traccar__traccar-5539/tests/test.sh b/tasks/traccar__traccar-5539/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d2ca893a610a1bdb496e9405e09eeced472b2931 --- /dev/null +++ b/tasks/traccar__traccar-5539/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 677ecedd932106dd8f62039ca16ccddd1714863a > "$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/traccar__traccar-5539/tests/verifier.py b/tasks/traccar__traccar-5539/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5539/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/traccar__traccar-5543/environment/Dockerfile b/tasks/traccar__traccar-5543/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..647f610ef7101a0d2402727c8624f55f99ce0f30 --- /dev/null +++ b/tasks/traccar__traccar-5543/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 38580c85909c70df1d668e9f767d32147df3b85e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 38580c85909c70df1d668e9f767d32147df3b85e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 38580c85909c70df1d668e9f767d32147df3b85e \ + && 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/traccar__traccar-5543/instruction.md b/tasks/traccar__traccar-5543/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a6bc550096a5b43dc01423e348b597a299b58044 --- /dev/null +++ b/tasks/traccar__traccar-5543/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Implement Getscale RFID reader with AOVX + +## Description + +https://www.getscale.com.br/gs-404 +[GS404_protocolo.pdf](https://github.com/user-attachments/files/19676439/GS404_protocolo.pdf) +[V_Series Protocol.pdf](https://github.com/user-attachments/files/19676449/V_Series.Protocol.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `38580c85909c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5543/solution/patch.diff b/tasks/traccar__traccar-5543/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4362383c7628c21c1d19d7713446d346c8281b67 --- /dev/null +++ b/tasks/traccar__traccar-5543/solution/patch.diff @@ -0,0 +1,42 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index 0b7a1911f..00b66303d 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -1012,7 +1012,21 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + + int type = buf.readUnsignedByte(); + +- if (type == 0x41) { ++ if (type == 0x40) { ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ getLastLocation(position, null); ++ String data = buf.readCharSequence(buf.readableBytes(), StandardCharsets.US_ASCII).toString().trim(); ++ if (data.startsWith("GTSL")) { ++ String[] values = data.split("\\|"); ++ if (values.length > 4) { ++ position.set(Position.KEY_DRIVER_UNIQUE_ID, values[4]); ++ return position; ++ } ++ } ++ ++ } else if (type == 0x41) { + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 437db509c..6cc1039ab 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new HuabaoProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "7e0900001b41305888975883194000184754534c7c367c317c307c31303231383039347c317c0d0ab47e"), ++ Position.KEY_DRIVER_UNIQUE_ID, "10218094"); ++ + verifyAttribute(decoder, binary( + "7e0200001f01207646327900400000000000006002015c7ab706d20469003b0000000025040216362606013e6b7e"), + Position.KEY_BATTERY_LEVEL, 62); diff --git a/tasks/traccar__traccar-5543/solution/solve.sh b/tasks/traccar__traccar-5543/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5543/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/traccar__traccar-5543/task.toml b/tasks/traccar__traccar-5543/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..de5f247ae70e83406c5b369c72cbf596b57aa65d --- /dev/null +++ b/tasks/traccar__traccar-5543/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5543" +description = "Implement Getscale RFID reader with AOVX" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "38580c85909c70df1d668e9f767d32147df3b85e" +reference = "https://github.com/traccar/traccar/pull/5543" +source_access = "auto" +built_at = "2026-11-16T16:09:42.646055+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:508fb0d8d15a7a9d66265493ad97f9a711b72c75afda52870ac58bfc69f50c50" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-04-10T23:13:20Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java", + "src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java", +] +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:03.450563+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1191163f3e90962632ff1e488c30e69202e173ac6f6e3c76cd6257fc82e729c0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5543/tests/capture.py b/tasks/traccar__traccar-5543/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5543/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/traccar__traccar-5543/tests/instruction.md b/tasks/traccar__traccar-5543/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a6bc550096a5b43dc01423e348b597a299b58044 --- /dev/null +++ b/tasks/traccar__traccar-5543/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Implement Getscale RFID reader with AOVX + +## Description + +https://www.getscale.com.br/gs-404 +[GS404_protocolo.pdf](https://github.com/user-attachments/files/19676439/GS404_protocolo.pdf) +[V_Series Protocol.pdf](https://github.com/user-attachments/files/19676449/V_Series.Protocol.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `38580c85909c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5543/tests/oracle.patch b/tasks/traccar__traccar-5543/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4362383c7628c21c1d19d7713446d346c8281b67 --- /dev/null +++ b/tasks/traccar__traccar-5543/tests/oracle.patch @@ -0,0 +1,42 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index 0b7a1911f..00b66303d 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -1012,7 +1012,21 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + + int type = buf.readUnsignedByte(); + +- if (type == 0x41) { ++ if (type == 0x40) { ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ getLastLocation(position, null); ++ String data = buf.readCharSequence(buf.readableBytes(), StandardCharsets.US_ASCII).toString().trim(); ++ if (data.startsWith("GTSL")) { ++ String[] values = data.split("\\|"); ++ if (values.length > 4) { ++ position.set(Position.KEY_DRIVER_UNIQUE_ID, values[4]); ++ return position; ++ } ++ } ++ ++ } else if (type == 0x41) { + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 437db509c..6cc1039ab 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new HuabaoProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "7e0900001b41305888975883194000184754534c7c367c317c307c31303231383039347c317c0d0ab47e"), ++ Position.KEY_DRIVER_UNIQUE_ID, "10218094"); ++ + verifyAttribute(decoder, binary( + "7e0200001f01207646327900400000000000006002015c7ab706d20469003b0000000025040216362606013e6b7e"), + Position.KEY_BATTERY_LEVEL, 62); diff --git a/tasks/traccar__traccar-5543/tests/test.sh b/tasks/traccar__traccar-5543/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..fbfd1b212922f717de52983204080e58270ab29e --- /dev/null +++ b/tasks/traccar__traccar-5543/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 38580c85909c70df1d668e9f767d32147df3b85e > "$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/traccar__traccar-5543/tests/verifier.py b/tasks/traccar__traccar-5543/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5543/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/traccar__traccar-5548/environment/Dockerfile b/tasks/traccar__traccar-5548/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..031aa7055cd84be9214b417bdec01acc9f80bfc3 --- /dev/null +++ b/tasks/traccar__traccar-5548/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f1b9754a87ee64f209768f039c09912238b10823 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f1b9754a87ee64f209768f039c09912238b10823 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f1b9754a87ee64f209768f039c09912238b10823 \ + && 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/traccar__traccar-5548/instruction.md b/tasks/traccar__traccar-5548/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dd11b63dd0bffc6a5687e0b6088e52e746554734 --- /dev/null +++ b/tasks/traccar__traccar-5548/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Huabao additional for Charge status & Battery level (Fixed) + +## Description + +Fixed conflicts. HuabaoProtocolDecoder to additional information Charge and Battery Level. + +refer from Request: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f1b9754a87ee`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5548/solution/patch.diff b/tasks/traccar__traccar-5548/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..16a5a5f038a69b5e475d6a93298a5482ecfeb414 --- /dev/null +++ b/tasks/traccar__traccar-5548/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index a85ae056a..dc7244181 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -699,6 +699,12 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); + position.set(Position.KEY_BATTERY, buf.readUnsignedShort() / 100.0); + break; ++ case 0xE4: ++ if (buf.readUnsignedByte() == 0) { ++ position.set(Position.KEY_CHARGE, true); ++ } ++ position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); ++ break; + case 0xE6: + while (buf.readerIndex() < endIndex) { + int sensorIndex = buf.readUnsignedByte(); +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 9bd1ce6c5..cd95436f0 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -11,6 +11,14 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new HuabaoProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "7e02000072014310709432043a00000000000c000000d17bb3060107f900000000000025042312214001040000189b30011a310100e4020056e50101e60100e7080000000400000000ec2330de4bf67368cec65bbec0fac6b8f0090d353c03b87890a2f4b01eaa6420e36e35e6a8e10c020800040013b202e4648300f50101457e"), ++ Position.KEY_BATTERY_LEVEL, 86 ); ++ ++ verifyAttribute(decoder, binary( ++ "7e02000072014310709432043a00000000000c000000d17bb3060107f900000000000025042312214001040000189b30011a310100e4020056e50101e60100e7080000000400000000ec2330de4bf67368cec65bbec0fac6b8f0090d353c03b87890a2f4b01eaa6420e36e35e6a8e10c020800040013b202e4648300f50101457e"), ++ Position.KEY_CHARGE, true ); ++ + verifyAttribute(decoder, binary( + "7e070100150120764632790008000000114d442c53455420434f4e464947204f4b21187e"), + Position.KEY_RESULT, "MD,SET CONFIG OK!"); diff --git a/tasks/traccar__traccar-5548/solution/solve.sh b/tasks/traccar__traccar-5548/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5548/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/traccar__traccar-5548/task.toml b/tasks/traccar__traccar-5548/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..353cc9f2e720fe153ceca1897148bb2d26425b5a --- /dev/null +++ b/tasks/traccar__traccar-5548/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5548" +description = "Huabao additional for Charge status & Battery level (Fixed)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "f1b9754a87ee64f209768f039c09912238b10823" +reference = "https://github.com/traccar/traccar/pull/5548" +source_access = "auto" +built_at = "2026-11-16T16:09:42.644608+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:dfb518d8f61bd41eb2ff3d0ca4e7462828e4a6520ce4062758de849f7b262c2a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-04-24T04:12:28Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java", + "src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.451088+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:404b40a421bdee2fbecdb44d67bd8fbf5d99f327df85966fb9c9eaa3377eceff" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5548/tests/capture.py b/tasks/traccar__traccar-5548/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5548/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/traccar__traccar-5548/tests/instruction.md b/tasks/traccar__traccar-5548/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dd11b63dd0bffc6a5687e0b6088e52e746554734 --- /dev/null +++ b/tasks/traccar__traccar-5548/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Huabao additional for Charge status & Battery level (Fixed) + +## Description + +Fixed conflicts. HuabaoProtocolDecoder to additional information Charge and Battery Level. + +refer from Request: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f1b9754a87ee`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5548/tests/oracle.patch b/tasks/traccar__traccar-5548/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..16a5a5f038a69b5e475d6a93298a5482ecfeb414 --- /dev/null +++ b/tasks/traccar__traccar-5548/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index a85ae056a..dc7244181 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -699,6 +699,12 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); + position.set(Position.KEY_BATTERY, buf.readUnsignedShort() / 100.0); + break; ++ case 0xE4: ++ if (buf.readUnsignedByte() == 0) { ++ position.set(Position.KEY_CHARGE, true); ++ } ++ position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); ++ break; + case 0xE6: + while (buf.readerIndex() < endIndex) { + int sensorIndex = buf.readUnsignedByte(); +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 9bd1ce6c5..cd95436f0 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -11,6 +11,14 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new HuabaoProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "7e02000072014310709432043a00000000000c000000d17bb3060107f900000000000025042312214001040000189b30011a310100e4020056e50101e60100e7080000000400000000ec2330de4bf67368cec65bbec0fac6b8f0090d353c03b87890a2f4b01eaa6420e36e35e6a8e10c020800040013b202e4648300f50101457e"), ++ Position.KEY_BATTERY_LEVEL, 86 ); ++ ++ verifyAttribute(decoder, binary( ++ "7e02000072014310709432043a00000000000c000000d17bb3060107f900000000000025042312214001040000189b30011a310100e4020056e50101e60100e7080000000400000000ec2330de4bf67368cec65bbec0fac6b8f0090d353c03b87890a2f4b01eaa6420e36e35e6a8e10c020800040013b202e4648300f50101457e"), ++ Position.KEY_CHARGE, true ); ++ + verifyAttribute(decoder, binary( + "7e070100150120764632790008000000114d442c53455420434f4e464947204f4b21187e"), + Position.KEY_RESULT, "MD,SET CONFIG OK!"); diff --git a/tasks/traccar__traccar-5548/tests/test.sh b/tasks/traccar__traccar-5548/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..45a2bd440db5d1b160b1a85999d208f308387e56 --- /dev/null +++ b/tasks/traccar__traccar-5548/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 f1b9754a87ee64f209768f039c09912238b10823 > "$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/traccar__traccar-5548/tests/verifier.py b/tasks/traccar__traccar-5548/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5548/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/traccar__traccar-5553/environment/Dockerfile b/tasks/traccar__traccar-5553/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cf1f047f8a0f96e68c385886cf8a0960262fe804 --- /dev/null +++ b/tasks/traccar__traccar-5553/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6579f56586dd32182078f5e9c6d820f5b9f7d5c3 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6579f56586dd32182078f5e9c6d820f5b9f7d5c3 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6579f56586dd32182078f5e9c6d820f5b9f7d5c3 \ + && 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/traccar__traccar-5553/instruction.md b/tasks/traccar__traccar-5553/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db2203da5c6a38b7918e60f4e5be3ae324792c2c --- /dev/null +++ b/tasks/traccar__traccar-5553/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** suntech ST340UR and HBM=2 support + +## Description + +This PR fixes multiple NullPointerExceptions that occurred when the device sent position data without required timestamps such as fixTime or deviceTime. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6579f56586dd`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5553/solution/patch.diff b/tasks/traccar__traccar-5553/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..65d639428573add613623861a2f969e31580ff3d --- /dev/null +++ b/tasks/traccar__traccar-5553/solution/patch.diff @@ -0,0 +1,87 @@ +diff --git a/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java b/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java +index ffbb2900f..43da664c6 100644 +--- a/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java +@@ -352,6 +352,7 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_TYPE, type); + + if (result) { ++ getLastLocation(position, null); + position.set(Position.KEY_RESULT, String.join(";", Arrays.copyOfRange(values, index, values.length))); + return position; + } +@@ -413,7 +414,8 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { + case "UEX" -> index = decodeSerialData(position, values, index); + } + +- if (getHbm(deviceSession.getDeviceId()) == 1) { ++ int hbm = getHbm(deviceSession.getDeviceId()); ++ if (hbm >= 1) { + + if (index < values.length) { + position.set(Position.KEY_HOURS, UnitsConverter.msFromMinutes(Integer.parseInt(values[index++]))); +@@ -439,7 +441,7 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_RPM, Integer.parseInt(values[index++])); + } + +- if (values.length - index >= 2) { ++ if (values.length - index >= (hbm == 1 ? 2 : 7)) { + String driverUniqueId = values[index++]; + if (!driverUniqueId.isEmpty()) { + position.set(Position.KEY_DRIVER_UNIQUE_ID, driverUniqueId); +@@ -458,6 +460,17 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { + + } + ++ if (hbm >= 2) { ++ if (values.length - index >= 5) { ++ int cid = Integer.parseInt(values[index++]); ++ int mcc = Integer.parseInt(values[index++]); ++ int mnc = Integer.parseInt(values[index++]); ++ int rssi = Integer.parseInt(values[index++]); ++ int lac = Integer.parseInt(values[index++]); ++ position.setNetwork(new Network(CellTower.from(mcc, mnc, lac, cid, rssi))); ++ } ++ } ++ + } + + return position; +diff --git a/src/test/java/org/traccar/protocol/SuntechProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/SuntechProtocolDecoderTest.java +index 1ee642a5e..c242eb4bc 100644 +--- a/src/test/java/org/traccar/protocol/SuntechProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/SuntechProtocolDecoderTest.java +@@ -206,6 +206,8 @@ public class SuntechProtocolDecoderTest extends ProtocolTest { + verifyAttribute(decoder, buffer( + "ST300CMD;Res;511848119;315;PresetA;NTW;0;eseye.com;user;pass;rastreamento.inviocar.com;6011;;;;;RPT;1800;80;80;3;1200;0;0;0;0;EVT;0;10;0;12;3;9;1;30;0;5;7;1;0;0;0;0;0;0;0;9;9;0;0;0;GSM;0;;;;;0;;;;;;;;SVC;1;200;0;0;0;0;1;0;1;0;0;0;0;ADP;T;T;0;;0;0;0;0;0;0;MSR;600;0.10;0.10;0.70;MBV;0.00;0.00;17.20;9.00;18.00;0.00;0.00;NPT;25.0;0;30;0;0;500;300;5;10;100;5;180;100;1;DEV;0;0;0;1;0;0;0;"), + Position.KEY_RESULT, "315;PresetA;NTW;0;eseye.com;user;pass;rastreamento.inviocar.com;6011;;;;;RPT;1800;80;80;3;1200;0;0;0;0;EVT;0;10;0;12;3;9;1;30;0;5;7;1;0;0;0;0;0;0;0;9;9;0;0;0;GSM;0;;;;;0;;;;;;;;SVC;1;200;0;0;0;0;1;0;1;0;0;0;0;ADP;T;T;0;;0;0;0;0;0;0;MSR;600;0.10;0.10;0.70;MBV;0.00;0.00;17.20;9.00;18.00;0.00;0.00;NPT;25.0;0;30;0;0;500;300;5;10;100;5;180;100;1;DEV;0;0;0;1;0;0;0;"); ++ ++ verifyAttribute(decoder, buffer("ST300CMD;Res;511848119;319H;Disable1"), Position.KEY_RESULT, "319H;Disable1"); + + decoder.setProtocolType(1); + +@@ -224,6 +226,11 @@ public class SuntechProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, buffer( + "ST910;Emergency;238569;528;20170403;00:02:09;7574160020;+19.661292;-099.144473;000.176;000.00;1;228638;1")); + ++ decoder.setHbm(2); ++ ++ verifyPosition(decoder, buffer( ++ "ST300STT;007878646;40;319H;20250521;21:52:14;54728;-30.021829;-051.204818;000.000;077.61;0;0;35310247;14.33;000000;1;1306;069596;4.1;1;23675;724;5;-75;1351;1")); ++ + } + + @Disabled +@@ -313,6 +320,12 @@ public class SuntechProtocolDecoderTest extends ProtocolTest { + "ST300STT;807469112;45;315;20231215;15:25:03;104147;-16.030168;-047.989150;000.000;000.00;19;1;8600;12.14;000010;1;0456;000373;4.1;1;01B54221010000;0"), + Position.KEY_DRIVER_UNIQUE_ID, "01B54221010000"); + ++ decoder.setHbm(2); ++ ++ verifyAttribute(decoder, buffer( ++ "ST300STT;007878646;40;319H;20250521;21:52:14;54728;-30.021829;-051.204818;000.000;077.61;0;0;35310247;14.33;000000;1;1306;069596;4.1;1;23675;724;5;-75;1351;1"), ++ Position.KEY_DRIVER_UNIQUE_ID, null); ++ + } + + } diff --git a/tasks/traccar__traccar-5553/solution/solve.sh b/tasks/traccar__traccar-5553/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5553/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/traccar__traccar-5553/task.toml b/tasks/traccar__traccar-5553/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..81de0ee46275a8165e89a09ccfa04532de69c32b --- /dev/null +++ b/tasks/traccar__traccar-5553/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5553" +description = "suntech ST340UR and HBM=2 support" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "6579f56586dd32182078f5e9c6d820f5b9f7d5c3" +reference = "https://github.com/traccar/traccar/pull/5553" +source_access = "auto" +built_at = "2026-11-16T16:09:42.642941+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2c7569e4a8bb9dfccc2d21f34dae107c8e27403ee8b333c06431565fc68fea45" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-05-23T23:18:55Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java", + "src/test/java/org/traccar/protocol/SuntechProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 30 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.451657+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b9693eeb19c647d3ee9c71bcadf71ea0ebb001316e7a22f88c0b642d91929689" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5553/tests/capture.py b/tasks/traccar__traccar-5553/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5553/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/traccar__traccar-5553/tests/instruction.md b/tasks/traccar__traccar-5553/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db2203da5c6a38b7918e60f4e5be3ae324792c2c --- /dev/null +++ b/tasks/traccar__traccar-5553/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** suntech ST340UR and HBM=2 support + +## Description + +This PR fixes multiple NullPointerExceptions that occurred when the device sent position data without required timestamps such as fixTime or deviceTime. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6579f56586dd`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5553/tests/oracle.patch b/tasks/traccar__traccar-5553/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..65d639428573add613623861a2f969e31580ff3d --- /dev/null +++ b/tasks/traccar__traccar-5553/tests/oracle.patch @@ -0,0 +1,87 @@ +diff --git a/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java b/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java +index ffbb2900f..43da664c6 100644 +--- a/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java +@@ -352,6 +352,7 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_TYPE, type); + + if (result) { ++ getLastLocation(position, null); + position.set(Position.KEY_RESULT, String.join(";", Arrays.copyOfRange(values, index, values.length))); + return position; + } +@@ -413,7 +414,8 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { + case "UEX" -> index = decodeSerialData(position, values, index); + } + +- if (getHbm(deviceSession.getDeviceId()) == 1) { ++ int hbm = getHbm(deviceSession.getDeviceId()); ++ if (hbm >= 1) { + + if (index < values.length) { + position.set(Position.KEY_HOURS, UnitsConverter.msFromMinutes(Integer.parseInt(values[index++]))); +@@ -439,7 +441,7 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_RPM, Integer.parseInt(values[index++])); + } + +- if (values.length - index >= 2) { ++ if (values.length - index >= (hbm == 1 ? 2 : 7)) { + String driverUniqueId = values[index++]; + if (!driverUniqueId.isEmpty()) { + position.set(Position.KEY_DRIVER_UNIQUE_ID, driverUniqueId); +@@ -458,6 +460,17 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { + + } + ++ if (hbm >= 2) { ++ if (values.length - index >= 5) { ++ int cid = Integer.parseInt(values[index++]); ++ int mcc = Integer.parseInt(values[index++]); ++ int mnc = Integer.parseInt(values[index++]); ++ int rssi = Integer.parseInt(values[index++]); ++ int lac = Integer.parseInt(values[index++]); ++ position.setNetwork(new Network(CellTower.from(mcc, mnc, lac, cid, rssi))); ++ } ++ } ++ + } + + return position; +diff --git a/src/test/java/org/traccar/protocol/SuntechProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/SuntechProtocolDecoderTest.java +index 1ee642a5e..c242eb4bc 100644 +--- a/src/test/java/org/traccar/protocol/SuntechProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/SuntechProtocolDecoderTest.java +@@ -206,6 +206,8 @@ public class SuntechProtocolDecoderTest extends ProtocolTest { + verifyAttribute(decoder, buffer( + "ST300CMD;Res;511848119;315;PresetA;NTW;0;eseye.com;user;pass;rastreamento.inviocar.com;6011;;;;;RPT;1800;80;80;3;1200;0;0;0;0;EVT;0;10;0;12;3;9;1;30;0;5;7;1;0;0;0;0;0;0;0;9;9;0;0;0;GSM;0;;;;;0;;;;;;;;SVC;1;200;0;0;0;0;1;0;1;0;0;0;0;ADP;T;T;0;;0;0;0;0;0;0;MSR;600;0.10;0.10;0.70;MBV;0.00;0.00;17.20;9.00;18.00;0.00;0.00;NPT;25.0;0;30;0;0;500;300;5;10;100;5;180;100;1;DEV;0;0;0;1;0;0;0;"), + Position.KEY_RESULT, "315;PresetA;NTW;0;eseye.com;user;pass;rastreamento.inviocar.com;6011;;;;;RPT;1800;80;80;3;1200;0;0;0;0;EVT;0;10;0;12;3;9;1;30;0;5;7;1;0;0;0;0;0;0;0;9;9;0;0;0;GSM;0;;;;;0;;;;;;;;SVC;1;200;0;0;0;0;1;0;1;0;0;0;0;ADP;T;T;0;;0;0;0;0;0;0;MSR;600;0.10;0.10;0.70;MBV;0.00;0.00;17.20;9.00;18.00;0.00;0.00;NPT;25.0;0;30;0;0;500;300;5;10;100;5;180;100;1;DEV;0;0;0;1;0;0;0;"); ++ ++ verifyAttribute(decoder, buffer("ST300CMD;Res;511848119;319H;Disable1"), Position.KEY_RESULT, "319H;Disable1"); + + decoder.setProtocolType(1); + +@@ -224,6 +226,11 @@ public class SuntechProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, buffer( + "ST910;Emergency;238569;528;20170403;00:02:09;7574160020;+19.661292;-099.144473;000.176;000.00;1;228638;1")); + ++ decoder.setHbm(2); ++ ++ verifyPosition(decoder, buffer( ++ "ST300STT;007878646;40;319H;20250521;21:52:14;54728;-30.021829;-051.204818;000.000;077.61;0;0;35310247;14.33;000000;1;1306;069596;4.1;1;23675;724;5;-75;1351;1")); ++ + } + + @Disabled +@@ -313,6 +320,12 @@ public class SuntechProtocolDecoderTest extends ProtocolTest { + "ST300STT;807469112;45;315;20231215;15:25:03;104147;-16.030168;-047.989150;000.000;000.00;19;1;8600;12.14;000010;1;0456;000373;4.1;1;01B54221010000;0"), + Position.KEY_DRIVER_UNIQUE_ID, "01B54221010000"); + ++ decoder.setHbm(2); ++ ++ verifyAttribute(decoder, buffer( ++ "ST300STT;007878646;40;319H;20250521;21:52:14;54728;-30.021829;-051.204818;000.000;077.61;0;0;35310247;14.33;000000;1;1306;069596;4.1;1;23675;724;5;-75;1351;1"), ++ Position.KEY_DRIVER_UNIQUE_ID, null); ++ + } + + } diff --git a/tasks/traccar__traccar-5553/tests/test.sh b/tasks/traccar__traccar-5553/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a6faf8f944538f85a640d5a65a3df7d7437ed0c6 --- /dev/null +++ b/tasks/traccar__traccar-5553/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 6579f56586dd32182078f5e9c6d820f5b9f7d5c3 > "$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/traccar__traccar-5553/tests/verifier.py b/tasks/traccar__traccar-5553/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5553/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/traccar__traccar-5557/environment/Dockerfile b/tasks/traccar__traccar-5557/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a43a0f74cf9ec07be3c5fa91718480f9ab43d1ae --- /dev/null +++ b/tasks/traccar__traccar-5557/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 12387fe0ebbca062385ecbf153c2731a200c1f13 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 12387fe0ebbca062385ecbf153c2731a200c1f13 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 12387fe0ebbca062385ecbf153c2731a200c1f13 \ + && 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/traccar__traccar-5557/instruction.md b/tasks/traccar__traccar-5557/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d323e6962d46c9c0c0ba5446bf1828b80a837904 --- /dev/null +++ b/tasks/traccar__traccar-5557/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Replace netty-all with modular dependencies + +## Description + +## Summary +- avoid using the aggregated `netty-all` artifact +- define `nettyVersion` variable and reference each required Netty module + +## Testing +- `./gradlew --version` *(fails: No route to host)* + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `12387fe0ebbc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5557/solution/patch.diff b/tasks/traccar__traccar-5557/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..95bf8e8e130f2592e5d523db0dba88833260b172 --- /dev/null +++ b/tasks/traccar__traccar-5557/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/build.gradle b/build.gradle +index c41519812..741b42b60 100644 +--- a/build.gradle ++++ b/build.gradle +@@ -35,6 +35,7 @@ ext { + jettyVersion = "11.0.25" + jerseyVersion = "3.1.10" + jacksonVersion = "2.18.2" // same version as jersey-media-json-jackson dependency ++ nettyVersion = "4.2.1.Final" + protobufVersion = "4.31.0" + jxlsVersion = "2.14.0" // version 3 has breaking changes + } +@@ -53,7 +54,14 @@ dependencies { + implementation "org.postgresql:postgresql:42.7.5" + implementation "com.microsoft.sqlserver:mssql-jdbc:12.10.0.jre11" + implementation "com.zaxxer:HikariCP:6.3.0" +- implementation "io.netty:netty-all:4.2.1.Final" ++ implementation "io.netty:netty-buffer:$nettyVersion" ++ implementation "io.netty:netty-codec:$nettyVersion" ++ implementation "io.netty:netty-codec-http:$nettyVersion" ++ implementation "io.netty:netty-codec-mqtt:$nettyVersion" ++ implementation "io.netty:netty-handler:$nettyVersion" ++ implementation "io.netty:netty-resolver:$nettyVersion" ++ implementation "io.netty:netty-resolver-dns:$nettyVersion" ++ implementation "io.netty:netty-transport:$nettyVersion" + implementation "org.slf4j:slf4j-jdk14:2.0.17" + implementation "com.google.inject:guice:$guiceVersion" + implementation "com.google.inject.extensions:guice-servlet:$guiceVersion" diff --git a/tasks/traccar__traccar-5557/solution/solve.sh b/tasks/traccar__traccar-5557/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5557/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/traccar__traccar-5557/task.toml b/tasks/traccar__traccar-5557/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e8aa21288cdb836103d46c5f8688e36e651bac70 --- /dev/null +++ b/tasks/traccar__traccar-5557/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5557" +description = "Replace netty-all with modular dependencies" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "12387fe0ebbca062385ecbf153c2731a200c1f13" +reference = "https://github.com/traccar/traccar/pull/5557" +source_access = "auto" +built_at = "2026-11-16T16:09:42.641494+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c187c6c70298ef487fdc76dfb4e58ac45c1aa5f01451199c7e1a26828ee4f91d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-05-19T01:36:47Z" +diff_format = "unified" +context_files = [ + "build.gradle", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 10 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.452207+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:139b33bdca9189157e0e8f477987fc2eb04ae610e2aa97adad5d14cb0f70b9b9" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5557/tests/capture.py b/tasks/traccar__traccar-5557/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5557/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/traccar__traccar-5557/tests/instruction.md b/tasks/traccar__traccar-5557/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d323e6962d46c9c0c0ba5446bf1828b80a837904 --- /dev/null +++ b/tasks/traccar__traccar-5557/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Replace netty-all with modular dependencies + +## Description + +## Summary +- avoid using the aggregated `netty-all` artifact +- define `nettyVersion` variable and reference each required Netty module + +## Testing +- `./gradlew --version` *(fails: No route to host)* + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `12387fe0ebbc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5557/tests/oracle.patch b/tasks/traccar__traccar-5557/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..95bf8e8e130f2592e5d523db0dba88833260b172 --- /dev/null +++ b/tasks/traccar__traccar-5557/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/build.gradle b/build.gradle +index c41519812..741b42b60 100644 +--- a/build.gradle ++++ b/build.gradle +@@ -35,6 +35,7 @@ ext { + jettyVersion = "11.0.25" + jerseyVersion = "3.1.10" + jacksonVersion = "2.18.2" // same version as jersey-media-json-jackson dependency ++ nettyVersion = "4.2.1.Final" + protobufVersion = "4.31.0" + jxlsVersion = "2.14.0" // version 3 has breaking changes + } +@@ -53,7 +54,14 @@ dependencies { + implementation "org.postgresql:postgresql:42.7.5" + implementation "com.microsoft.sqlserver:mssql-jdbc:12.10.0.jre11" + implementation "com.zaxxer:HikariCP:6.3.0" +- implementation "io.netty:netty-all:4.2.1.Final" ++ implementation "io.netty:netty-buffer:$nettyVersion" ++ implementation "io.netty:netty-codec:$nettyVersion" ++ implementation "io.netty:netty-codec-http:$nettyVersion" ++ implementation "io.netty:netty-codec-mqtt:$nettyVersion" ++ implementation "io.netty:netty-handler:$nettyVersion" ++ implementation "io.netty:netty-resolver:$nettyVersion" ++ implementation "io.netty:netty-resolver-dns:$nettyVersion" ++ implementation "io.netty:netty-transport:$nettyVersion" + implementation "org.slf4j:slf4j-jdk14:2.0.17" + implementation "com.google.inject:guice:$guiceVersion" + implementation "com.google.inject.extensions:guice-servlet:$guiceVersion" diff --git a/tasks/traccar__traccar-5557/tests/test.sh b/tasks/traccar__traccar-5557/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5049ca469bd983b6bba5cb1ef9b13b327f8b8b43 --- /dev/null +++ b/tasks/traccar__traccar-5557/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 12387fe0ebbca062385ecbf153c2731a200c1f13 > "$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/traccar__traccar-5557/tests/verifier.py b/tasks/traccar__traccar-5557/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5557/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/traccar__traccar-5568/environment/Dockerfile b/tasks/traccar__traccar-5568/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6a1647136844498a97bae846f51f93e2ad329a75 --- /dev/null +++ b/tasks/traccar__traccar-5568/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 028b55bd74ec2472e7381b511a51ae03cc1dd99c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 028b55bd74ec2472e7381b511a51ae03cc1dd99c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 028b55bd74ec2472e7381b511a51ae03cc1dd99c \ + && 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/traccar__traccar-5568/instruction.md b/tasks/traccar__traccar-5568/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..538ed03c7080b4e267b8a51a1289979a991c2d83 --- /dev/null +++ b/tasks/traccar__traccar-5568/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Fix Notification schema in OpenAPI docs + +## Description + +## Summary +- correct Notification fields in `openapi.yaml` to match the Java model + +## Testing +- `./gradlew test --no-daemon -q` *(fails: No route to host)* + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `028b55bd74ec`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5568/solution/patch.diff b/tasks/traccar__traccar-5568/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d4b7df6bf68182a85fef6495acf221f2c6bd785c --- /dev/null +++ b/tasks/traccar__traccar-5568/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/openapi.yaml b/openapi.yaml +index 495801406..1bfddcf5a 100644 +--- a/openapi.yaml ++++ b/openapi.yaml +@@ -2019,14 +2019,15 @@ components: + type: integer + type: + type: string ++ description: ++ type: string ++ nullable: true + always: + type: boolean +- web: +- type: boolean +- mail: +- type: boolean +- sms: +- type: boolean ++ commandId: ++ type: integer ++ notificators: ++ type: string + calendarId: + type: integer + attributes: diff --git a/tasks/traccar__traccar-5568/solution/solve.sh b/tasks/traccar__traccar-5568/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5568/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/traccar__traccar-5568/task.toml b/tasks/traccar__traccar-5568/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..309fbc2c0ae3d4a6fc3ccefc9a03274c575f1baa --- /dev/null +++ b/tasks/traccar__traccar-5568/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5568" +description = "Fix Notification schema in OpenAPI docs" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "028b55bd74ec2472e7381b511a51ae03cc1dd99c" +reference = "https://github.com/traccar/traccar/pull/5568" +source_access = "auto" +built_at = "2026-11-16T16:09:42.639851+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:48d607b154f6f81a3062e111c8c84b3bfd6ef3369c1c8c1eb55f9dac7e41cc3b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-05-29T02:12:38Z" +diff_format = "unified" +context_files = [ + "openapi.yaml", +] +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:03.452769+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2227d3274d244f3d142aa9df77989593f96fe9dcb72b9ae3c93078f8fc9ce3cd" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5568/tests/capture.py b/tasks/traccar__traccar-5568/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5568/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/traccar__traccar-5568/tests/instruction.md b/tasks/traccar__traccar-5568/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..538ed03c7080b4e267b8a51a1289979a991c2d83 --- /dev/null +++ b/tasks/traccar__traccar-5568/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Fix Notification schema in OpenAPI docs + +## Description + +## Summary +- correct Notification fields in `openapi.yaml` to match the Java model + +## Testing +- `./gradlew test --no-daemon -q` *(fails: No route to host)* + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `028b55bd74ec`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5568/tests/oracle.patch b/tasks/traccar__traccar-5568/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d4b7df6bf68182a85fef6495acf221f2c6bd785c --- /dev/null +++ b/tasks/traccar__traccar-5568/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/openapi.yaml b/openapi.yaml +index 495801406..1bfddcf5a 100644 +--- a/openapi.yaml ++++ b/openapi.yaml +@@ -2019,14 +2019,15 @@ components: + type: integer + type: + type: string ++ description: ++ type: string ++ nullable: true + always: + type: boolean +- web: +- type: boolean +- mail: +- type: boolean +- sms: +- type: boolean ++ commandId: ++ type: integer ++ notificators: ++ type: string + calendarId: + type: integer + attributes: diff --git a/tasks/traccar__traccar-5568/tests/test.sh b/tasks/traccar__traccar-5568/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..870246ec1bb90da5fd9776f34579ff46f2463b06 --- /dev/null +++ b/tasks/traccar__traccar-5568/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 028b55bd74ec2472e7381b511a51ae03cc1dd99c > "$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/traccar__traccar-5568/tests/verifier.py b/tasks/traccar__traccar-5568/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5568/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/traccar__traccar-5570/environment/Dockerfile b/tasks/traccar__traccar-5570/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..302546e0a1dfb27edd9c6e77a3b42d38de787116 --- /dev/null +++ b/tasks/traccar__traccar-5570/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3500b143e7e73b55ca8ddfa360872acd6b9537d9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3500b143e7e73b55ca8ddfa360872acd6b9537d9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3500b143e7e73b55ca8ddfa360872acd6b9537d9 \ + && 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/traccar__traccar-5570/instruction.md b/tasks/traccar__traccar-5570/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..369aadf1d4e09b66ece3977a42af5754f0964d00 --- /dev/null +++ b/tasks/traccar__traccar-5570/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Fix openapi mismatches + +## Description + +## Summary +- correct spelling of ISO 8601 in spec +- mark ID fields as int64 +- represent `driverUniqueId` as string + +## Testing +- `./gradlew test` *(fails: No route to host)* + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3500b143e7e7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5570/solution/patch.diff b/tasks/traccar__traccar-5570/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..781772ed30d2884b7e62e221f12a293987cbb428 --- /dev/null +++ b/tasks/traccar__traccar-5570/solution/patch.diff @@ -0,0 +1,531 @@ +diff --git a/openapi.yaml b/openapi.yaml +index 1bfddcf5a..0e547feb7 100644 +--- a/openapi.yaml ++++ b/openapi.yaml +@@ -531,13 +531,13 @@ paths: + type: integer + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + schema: + type: string + format: date-time +@@ -581,14 +581,14 @@ paths: + required: true + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + schema: + type: string + format: date-time + required: true + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + schema: + type: string + format: date-time +@@ -1076,14 +1076,14 @@ paths: + type: integer + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1136,14 +1136,14 @@ paths: + type: string + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1189,14 +1189,14 @@ paths: + type: integer + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1242,14 +1242,14 @@ paths: + type: integer + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1295,14 +1295,14 @@ paths: + type: integer + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1329,14 +1329,14 @@ paths: + parameters: + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1743,21 +1743,23 @@ components: + properties: + id: + type: integer ++ format: int64 + deviceId: + type: integer ++ format: int64 + protocol: + type: string + deviceTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + fixTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + serverTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + outdated: + type: boolean +@@ -1793,6 +1795,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + email: +@@ -1822,7 +1825,7 @@ components: + type: boolean + expirationTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + nullable: true + deviceLimit: +@@ -1846,6 +1849,7 @@ components: + properties: + id: + type: integer ++ format: int64 + registration: + type: boolean + readonly: +@@ -1886,8 +1890,10 @@ components: + properties: + id: + type: integer ++ format: int64 + deviceId: + type: integer ++ format: int64 + description: + type: string + type: +@@ -1900,6 +1906,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + uniqueId: +@@ -1910,14 +1917,16 @@ components: + type: boolean + lastUpdate: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + nullable: true + positionId: + type: integer ++ format: int64 + nullable: true + groupId: + type: integer ++ format: int64 + nullable: true + phone: + type: string +@@ -1939,10 +1948,12 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + groupId: + type: integer ++ format: int64 + attributes: + type: object + properties: {} +@@ -1951,41 +1962,51 @@ components: + properties: + userId: + type: integer ++ format: int64 + description: User id, can be only first parameter + deviceId: + type: integer ++ format: int64 + description: >- + Device id, can be first parameter or second only in combination with + userId + groupId: + type: integer ++ format: int64 + description: >- + Group id, can be first parameter or second only in combination with + userId + geofenceId: + type: integer ++ format: int64 + description: Geofence id, can be second parameter only + notificationId: + type: integer ++ format: int64 + description: Notification id, can be second parameter only + calendarId: + type: integer ++ format: int64 + description: >- + Calendar id, can be second parameter only and only in combination + with userId + attributeId: + type: integer ++ format: int64 + description: Computed attribute id, can be second parameter only + driverId: + type: integer ++ format: int64 + description: Driver id, can be second parameter only + managedUserId: + type: integer ++ format: int64 + description: >- + User id, can be second parameter only and only in combination with + userId + commandId: + type: integer ++ format: int64 + description: Saved command id, can be second parameter only + description: >- + This is a permission map that contain two object indexes. It is used to +@@ -2001,6 +2022,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + description: +@@ -2009,6 +2031,7 @@ components: + type: string + calendarId: + type: integer ++ format: int64 + attributes: + type: object + properties: {} +@@ -2017,6 +2040,7 @@ components: + properties: + id: + type: integer ++ format: int64 + type: + type: string + description: +@@ -2026,10 +2050,12 @@ components: + type: boolean + commandId: + type: integer ++ format: int64 + notificators: + type: string + calendarId: + type: integer ++ format: int64 + attributes: + type: object + properties: {} +@@ -2043,18 +2069,22 @@ components: + properties: + id: + type: integer ++ format: int64 + type: + type: string + eventTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + deviceId: + type: integer ++ format: int64 + positionId: + type: integer ++ format: int64 + geofenceId: + type: integer ++ format: int64 + maintenanceId: + type: integer + attributes: +@@ -2065,6 +2095,7 @@ components: + properties: + deviceId: + type: integer ++ format: int64 + deviceName: + type: string + maxSpeed: +@@ -2086,6 +2117,7 @@ components: + properties: + deviceId: + type: integer ++ format: int64 + deviceName: + type: string + maxSpeed: +@@ -2104,7 +2136,7 @@ components: + type: integer + startTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + startAddress: + type: string +@@ -2114,7 +2146,7 @@ components: + type: number + endTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + endAddress: + type: string +@@ -2123,7 +2155,7 @@ components: + endLon: + type: number + driverUniqueId: +- type: integer ++ type: string + driverName: + type: string + ReportStops: +@@ -2131,13 +2163,14 @@ components: + properties: + deviceId: + type: integer ++ format: int64 + deviceName: + type: string + duration: + type: integer + startTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + address: + type: string +@@ -2147,7 +2180,7 @@ components: + type: number + endTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + spentFuel: + type: number +@@ -2159,7 +2192,7 @@ components: + properties: + captureTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + activeUsers: + type: integer +@@ -2176,6 +2209,7 @@ components: + properties: + deviceId: + type: integer ++ format: int64 + totalDistance: + type: number + description: in meters +@@ -2186,6 +2220,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + data: +@@ -2199,6 +2234,7 @@ components: + properties: + id: + type: integer ++ format: int64 + description: + type: string + attribute: +@@ -2213,6 +2249,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + uniqueId: +@@ -2225,6 +2262,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + type: +@@ -2243,6 +2281,7 @@ components: + required: true + schema: + type: integer ++ format: int64 + all: + name: all + in: query +@@ -2260,18 +2299,21 @@ components: + description: Standard users can use this only with their own _userId_ + schema: + type: integer ++ format: int64 + deviceId: + name: deviceId + in: query + description: Standard users can use this only with _deviceId_s, they have access to + schema: + type: integer ++ format: int64 + groupId: + name: groupId + in: query + description: Standard users can use this only with _groupId_s, they have access to + schema: + type: integer ++ format: int64 + deviceIdArray: + name: deviceId + in: query +@@ -2281,6 +2323,7 @@ components: + type: array + items: + type: integer ++ format: int64 + groupIdArray: + name: groupId + in: query +@@ -2290,10 +2333,11 @@ components: + type: array + items: + type: integer ++ format: int64 + fromTime: + name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -2301,7 +2345,7 @@ components: + toTime: + name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string diff --git a/tasks/traccar__traccar-5570/solution/solve.sh b/tasks/traccar__traccar-5570/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5570/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/traccar__traccar-5570/task.toml b/tasks/traccar__traccar-5570/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e7b72ee42fc06e6fa3342de7740094de1c0b57df --- /dev/null +++ b/tasks/traccar__traccar-5570/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5570" +description = "Fix openapi mismatches" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "3500b143e7e73b55ca8ddfa360872acd6b9537d9" +reference = "https://github.com/traccar/traccar/pull/5570" +source_access = "auto" +built_at = "2026-11-16T16:09:42.638151+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:93ef4e81981d9f3fec6f0a22b6b4617cdbc5f3afafd4b0e122bb42868eeee60f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-05-29T02:32:40Z" +diff_format = "unified" +context_files = [ + "openapi.yaml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 104 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.453255+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2aef44fb15e1aeb9a6725b2a36d2d30ce23322600c02840ed476329221d49c6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5570/tests/capture.py b/tasks/traccar__traccar-5570/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5570/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/traccar__traccar-5570/tests/instruction.md b/tasks/traccar__traccar-5570/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..369aadf1d4e09b66ece3977a42af5754f0964d00 --- /dev/null +++ b/tasks/traccar__traccar-5570/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Fix openapi mismatches + +## Description + +## Summary +- correct spelling of ISO 8601 in spec +- mark ID fields as int64 +- represent `driverUniqueId` as string + +## Testing +- `./gradlew test` *(fails: No route to host)* + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3500b143e7e7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5570/tests/oracle.patch b/tasks/traccar__traccar-5570/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..781772ed30d2884b7e62e221f12a293987cbb428 --- /dev/null +++ b/tasks/traccar__traccar-5570/tests/oracle.patch @@ -0,0 +1,531 @@ +diff --git a/openapi.yaml b/openapi.yaml +index 1bfddcf5a..0e547feb7 100644 +--- a/openapi.yaml ++++ b/openapi.yaml +@@ -531,13 +531,13 @@ paths: + type: integer + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + schema: + type: string + format: date-time +@@ -581,14 +581,14 @@ paths: + required: true + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + schema: + type: string + format: date-time + required: true + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + schema: + type: string + format: date-time +@@ -1076,14 +1076,14 @@ paths: + type: integer + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1136,14 +1136,14 @@ paths: + type: string + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1189,14 +1189,14 @@ paths: + type: integer + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1242,14 +1242,14 @@ paths: + type: integer + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1295,14 +1295,14 @@ paths: + type: integer + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1329,14 +1329,14 @@ paths: + parameters: + - name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string + format: date-time + - name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -1743,21 +1743,23 @@ components: + properties: + id: + type: integer ++ format: int64 + deviceId: + type: integer ++ format: int64 + protocol: + type: string + deviceTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + fixTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + serverTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + outdated: + type: boolean +@@ -1793,6 +1795,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + email: +@@ -1822,7 +1825,7 @@ components: + type: boolean + expirationTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + nullable: true + deviceLimit: +@@ -1846,6 +1849,7 @@ components: + properties: + id: + type: integer ++ format: int64 + registration: + type: boolean + readonly: +@@ -1886,8 +1890,10 @@ components: + properties: + id: + type: integer ++ format: int64 + deviceId: + type: integer ++ format: int64 + description: + type: string + type: +@@ -1900,6 +1906,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + uniqueId: +@@ -1910,14 +1917,16 @@ components: + type: boolean + lastUpdate: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + nullable: true + positionId: + type: integer ++ format: int64 + nullable: true + groupId: + type: integer ++ format: int64 + nullable: true + phone: + type: string +@@ -1939,10 +1948,12 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + groupId: + type: integer ++ format: int64 + attributes: + type: object + properties: {} +@@ -1951,41 +1962,51 @@ components: + properties: + userId: + type: integer ++ format: int64 + description: User id, can be only first parameter + deviceId: + type: integer ++ format: int64 + description: >- + Device id, can be first parameter or second only in combination with + userId + groupId: + type: integer ++ format: int64 + description: >- + Group id, can be first parameter or second only in combination with + userId + geofenceId: + type: integer ++ format: int64 + description: Geofence id, can be second parameter only + notificationId: + type: integer ++ format: int64 + description: Notification id, can be second parameter only + calendarId: + type: integer ++ format: int64 + description: >- + Calendar id, can be second parameter only and only in combination + with userId + attributeId: + type: integer ++ format: int64 + description: Computed attribute id, can be second parameter only + driverId: + type: integer ++ format: int64 + description: Driver id, can be second parameter only + managedUserId: + type: integer ++ format: int64 + description: >- + User id, can be second parameter only and only in combination with + userId + commandId: + type: integer ++ format: int64 + description: Saved command id, can be second parameter only + description: >- + This is a permission map that contain two object indexes. It is used to +@@ -2001,6 +2022,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + description: +@@ -2009,6 +2031,7 @@ components: + type: string + calendarId: + type: integer ++ format: int64 + attributes: + type: object + properties: {} +@@ -2017,6 +2040,7 @@ components: + properties: + id: + type: integer ++ format: int64 + type: + type: string + description: +@@ -2026,10 +2050,12 @@ components: + type: boolean + commandId: + type: integer ++ format: int64 + notificators: + type: string + calendarId: + type: integer ++ format: int64 + attributes: + type: object + properties: {} +@@ -2043,18 +2069,22 @@ components: + properties: + id: + type: integer ++ format: int64 + type: + type: string + eventTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + deviceId: + type: integer ++ format: int64 + positionId: + type: integer ++ format: int64 + geofenceId: + type: integer ++ format: int64 + maintenanceId: + type: integer + attributes: +@@ -2065,6 +2095,7 @@ components: + properties: + deviceId: + type: integer ++ format: int64 + deviceName: + type: string + maxSpeed: +@@ -2086,6 +2117,7 @@ components: + properties: + deviceId: + type: integer ++ format: int64 + deviceName: + type: string + maxSpeed: +@@ -2104,7 +2136,7 @@ components: + type: integer + startTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + startAddress: + type: string +@@ -2114,7 +2146,7 @@ components: + type: number + endTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + endAddress: + type: string +@@ -2123,7 +2155,7 @@ components: + endLon: + type: number + driverUniqueId: +- type: integer ++ type: string + driverName: + type: string + ReportStops: +@@ -2131,13 +2163,14 @@ components: + properties: + deviceId: + type: integer ++ format: int64 + deviceName: + type: string + duration: + type: integer + startTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + address: + type: string +@@ -2147,7 +2180,7 @@ components: + type: number + endTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + spentFuel: + type: number +@@ -2159,7 +2192,7 @@ components: + properties: + captureTime: + type: string +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + format: date-time + activeUsers: + type: integer +@@ -2176,6 +2209,7 @@ components: + properties: + deviceId: + type: integer ++ format: int64 + totalDistance: + type: number + description: in meters +@@ -2186,6 +2220,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + data: +@@ -2199,6 +2234,7 @@ components: + properties: + id: + type: integer ++ format: int64 + description: + type: string + attribute: +@@ -2213,6 +2249,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + uniqueId: +@@ -2225,6 +2262,7 @@ components: + properties: + id: + type: integer ++ format: int64 + name: + type: string + type: +@@ -2243,6 +2281,7 @@ components: + required: true + schema: + type: integer ++ format: int64 + all: + name: all + in: query +@@ -2260,18 +2299,21 @@ components: + description: Standard users can use this only with their own _userId_ + schema: + type: integer ++ format: int64 + deviceId: + name: deviceId + in: query + description: Standard users can use this only with _deviceId_s, they have access to + schema: + type: integer ++ format: int64 + groupId: + name: groupId + in: query + description: Standard users can use this only with _groupId_s, they have access to + schema: + type: integer ++ format: int64 + deviceIdArray: + name: deviceId + in: query +@@ -2281,6 +2323,7 @@ components: + type: array + items: + type: integer ++ format: int64 + groupIdArray: + name: groupId + in: query +@@ -2290,10 +2333,11 @@ components: + type: array + items: + type: integer ++ format: int64 + fromTime: + name: from + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string +@@ -2301,7 +2345,7 @@ components: + toTime: + name: to + in: query +- description: in IS0 8601 format. eg. `1963-11-22T18:30:00Z` ++ description: in ISO 8601 format. eg. `1963-11-22T18:30:00Z` + required: true + schema: + type: string diff --git a/tasks/traccar__traccar-5570/tests/test.sh b/tasks/traccar__traccar-5570/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..dac80716fc3ff338e2e3ae76a2a816e78e134049 --- /dev/null +++ b/tasks/traccar__traccar-5570/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 3500b143e7e73b55ca8ddfa360872acd6b9537d9 > "$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/traccar__traccar-5570/tests/verifier.py b/tasks/traccar__traccar-5570/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5570/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/traccar__traccar-5590/environment/Dockerfile b/tasks/traccar__traccar-5590/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1c43a03b22d7083e6e9274053d0c41c494823d34 --- /dev/null +++ b/tasks/traccar__traccar-5590/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c05dc48b8c2f5d26c638f935fa5afd57f88b388f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c05dc48b8c2f5d26c638f935fa5afd57f88b388f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c05dc48b8c2f5d26c638f935fa5afd57f88b388f \ + && 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/traccar__traccar-5590/instruction.md b/tasks/traccar__traccar-5590/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63ef9dc98c986f92dd38bc7e7423ce044a2251e9 --- /dev/null +++ b/tasks/traccar__traccar-5590/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Add release delivery to Docker Hub and GHCR + +## Description + +@tananaev, +I have migrated and refactored the build and publication of Docker traccar/tracker images from the [traccar/traccar-docker repository](https://github.com/traccar/traccar-docker). Along with the creation of the new release, Docker images will be published on the Docker Hub and GitHub Container Registry. + +To parallelize the publication, I split the submission into S3 and the Docker build. In the future can add another task to create a release on GitHub. + +Before the first launch, you need to add the secrets `DOCKERHUB_USERNAME` and `DOCKERHUB_TOKEN`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c05dc48b8c2f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5590/solution/patch.diff b/tasks/traccar__traccar-5590/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0fc0c36c34be06934ae76b03b09a4080cdc51083 --- /dev/null +++ b/tasks/traccar__traccar-5590/solution/patch.diff @@ -0,0 +1,231 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index dcde68f46..8927f7630 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -1,23 +1,24 @@ +-name: Build Installers ++name: Build Release + + on: + workflow_dispatch: + inputs: + version: +- description: 'Version' ++ description: Version + required: true +- default: 'preview' ++ default: preview + + jobs: +- release: +- runs-on: ubuntu-22.04 ++ build: ++ name: Build installers ++ runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + submodules: true +- - run: git checkout ${{ github.ref_name }} +- working-directory: ./traccar-web ++ - working-directory: ./traccar-web ++ run: git checkout ${{ github.ref_name }} + - uses: actions/setup-java@v4 + with: + distribution: temurin +@@ -29,24 +30,115 @@ jobs: + node-version: 21 + cache: npm + cache-dependency-path: traccar-web/package-lock.json +- - run: npm ci && npm run build +- working-directory: ./traccar-web ++ - working-directory: ./traccar-web ++ run: npm ci && npm run build + - run: | + sudo dpkg --add-architecture i386 + sudo apt-get update + sudo apt-get install libgcc-s1:i386 libstdc++6:i386 +- sudo apt-get install innoextract makeself wine32 s3cmd +- - name: Build installers +- working-directory: ./setup ++ sudo apt-get install innoextract makeself wine32 ++ - working-directory: ./setup + run: | + wget -q http://files.jrsoftware.org/is/5/isetup-5.5.6.exe + wget -q https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_x64_windows_hotspot_21.0.4_7.zip + wget -q https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_x64_linux_hotspot_21.0.4_7.tar.gz + wget -q https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_aarch64_linux_hotspot_21.0.4_7.tar.gz + ./package.sh ${{ github.event.inputs.version }} +- - name: Upload installers +- working-directory: ./setup +- env: ++ - uses: actions/upload-artifact@v4 ++ with: ++ name: installers ++ path: setup/traccar-*.zip ++ compression-level: 0 ++ retention-days: 1 ++ upload: ++ name: Upload installers ++ needs: build ++ runs-on: ubuntu-latest ++ steps: ++ - uses: actions/download-artifact@v4 ++ - env: + S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} + S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }} +- run: s3cmd --acl-public put traccar-*.zip s3://traccar/builds/ --host=nyc3.digitaloceanspaces.com --host-bucket=traccar --access_key="$S3_ACCESS_KEY" --secret_key="$S3_SECRET_KEY" ++ run: | ++ sudo apt-get install s3cmd ++ s3cmd --acl-public put installers/traccar-*.zip s3://traccar/builds/ --host=nyc3.digitaloceanspaces.com --host-bucket=traccar --access_key="$S3_ACCESS_KEY" --secret_key="$S3_SECRET_KEY" ++ release: ++ name: Create release with installers ++ needs: build ++ if: ${{ github.event.inputs.version != 'preview' }} ++ runs-on: ubuntu-latest ++ steps: ++ - uses: actions/checkout@v4 ++ with: ++ fetch-depth: 0 ++ - uses: actions/github-script@v6 ++ with: ++ script: | ++ github.rest.git.createRef({ ++ owner: context.repo.owner, ++ repo: context.repo.repo, ++ ref: 'refs/tags/v${{ github.event.inputs.version }}', ++ sha: context.sha ++ }) ++ - uses: actions/download-artifact@v4 ++ - uses: softprops/action-gh-release@v2 ++ with: ++ tag_name: v${{ github.event.inputs.version }} ++ files: installers/traccar-*.zip ++ docker: ++ name: Build and push docker images ++ needs: build ++ if: ${{ github.event.inputs.version != 'preview' }} ++ runs-on: ubuntu-latest ++ strategy: ++ matrix: ++ os: [alpine, debian, ubuntu] ++ include: ++ - os: alpine ++ platforms: linux/amd64,linux/arm64 ++ - platforms: linux/amd64,linux/arm64,linux/arm/v7 ++ steps: ++ - uses: actions/checkout@v4 ++ with: ++ fetch-depth: 0 ++ - uses: actions/download-artifact@v4 ++ with: ++ path: docker ++ - uses: docker/setup-qemu-action@v3 ++ - uses: docker/setup-buildx-action@v3 ++ - uses: docker/login-action@v3 ++ with: ++ username: ${{ secrets.DOCKERHUB_USERNAME }} ++ password: ${{ secrets.DOCKERHUB_TOKEN }} ++ - uses: docker/login-action@v3 ++ with: ++ registry: ghcr.io ++ username: ${{ github.actor }} ++ password: ${{ secrets.GITHUB_TOKEN }} ++ - id: meta ++ uses: docker/metadata-action@v5 ++ with: ++ flavor: latest=false ++ images: | ++ traccar/traccar ++ ghcr.io/traccar/traccar ++ tags: | ++ type=semver,pattern={{major}}.{{minor}}.{{patch}},suffix=-${{ matrix.os }},value=v${{ github.event.inputs.version }} ++ type=semver,pattern={{major}}.{{minor}},suffix=-${{ matrix.os }},value=v${{ github.event.inputs.version }} ++ type=semver,pattern={{major}},suffix=-${{ matrix.os }},value=v${{ github.event.inputs.version }} ++ type=semver,pattern={{major}}.{{minor}}.{{patch}},value=v${{ github.event.inputs.version }},enable=${{ matrix.os == 'alpine' }} ++ type=semver,pattern={{major}}.{{minor}},value=v${{ github.event.inputs.version }},enable=${{ matrix.os == 'alpine' }} ++ type=semver,pattern={{major}},value=v${{ github.event.inputs.version }},enable=${{ matrix.os == 'alpine' }} ++ type=raw,value=latest,enable=${{ matrix.os == 'alpine' }} ++ type=raw,value=${{ matrix.os }} ++ labels: | ++ org.opencontainers.image.version=${{ github.event.inputs.version }} ++ - uses: docker/build-push-action@v6 ++ with: ++ context: docker ++ file: docker/Dockerfile.${{ matrix.os }} ++ build-args: VERSION=${{ github.event.inputs.version }} ++ tags: ${{ steps.meta.outputs.tags }} ++ labels: ${{ steps.meta.outputs.labels }} ++ platforms: ${{ matrix.platforms }} ++ push: true +diff --git a/docker/Dockerfile.alpine b/docker/Dockerfile.alpine +new file mode 100644 +index 000000000..b6386d032 +--- /dev/null ++++ b/docker/Dockerfile.alpine +@@ -0,0 +1,14 @@ ++FROM alpine:3.22 ++ ++ARG VERSION ++COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++ ++WORKDIR /opt/traccar ++ ++RUN set -ex; \ ++ apk add --no-cache --no-progress openjdk17-jre-headless; \ ++ unzip -qo /tmp/traccar.zip -d .; \ ++ rm /tmp/traccar.zip ++ ++ENTRYPOINT ["java"] ++CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] +diff --git a/docker/Dockerfile.debian b/docker/Dockerfile.debian +new file mode 100644 +index 000000000..e827b5d37 +--- /dev/null ++++ b/docker/Dockerfile.debian +@@ -0,0 +1,19 @@ ++FROM debian:12-slim ++ ++ARG VERSION ++COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++ ++WORKDIR /opt/traccar ++ ++RUN set -ex; \ ++ apt-get update; \ ++ TERM=xterm DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \ ++ openjdk-17-jre-headless \ ++ unzip; \ ++ unzip -qo /tmp/traccar.zip -d .; \ ++ apt-get autoremove --yes unzip; \ ++ apt-get clean; \ ++ rm -rf /var/lib/apt/lists/* /tmp/* ++ ++ENTRYPOINT ["java"] ++CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] +diff --git a/docker/Dockerfile.ubuntu b/docker/Dockerfile.ubuntu +new file mode 100644 +index 000000000..457178ac4 +--- /dev/null ++++ b/docker/Dockerfile.ubuntu +@@ -0,0 +1,19 @@ ++FROM ubuntu:24.04 ++ ++ARG VERSION ++COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++ ++WORKDIR /opt/traccar ++ ++RUN set -ex; \ ++ apt-get update; \ ++ TERM=xterm DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \ ++ openjdk-17-jre-headless \ ++ unzip; \ ++ unzip -qo /tmp/traccar.zip -d .; \ ++ apt-get autoremove --yes unzip; \ ++ apt-get clean; \ ++ rm -rf /var/lib/apt/lists/* /tmp/* ++ ++ENTRYPOINT ["java"] ++CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] diff --git a/tasks/traccar__traccar-5590/solution/solve.sh b/tasks/traccar__traccar-5590/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5590/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/traccar__traccar-5590/task.toml b/tasks/traccar__traccar-5590/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..78f81f8b8311aa7aa88c21aae3df0c8521b51865 --- /dev/null +++ b/tasks/traccar__traccar-5590/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5590" +description = "Add release delivery to Docker Hub and GHCR" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "c05dc48b8c2f5d26c638f935fa5afd57f88b388f" +reference = "https://github.com/traccar/traccar/pull/5590" +source_access = "auto" +built_at = "2026-11-16T16:09:42.490906+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:80defac80a15063a90fb6686e1db35cdd02259aae18a2474d1ac52a2079e93a4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-07-04T00:59:15Z" +diff_format = "unified" +context_files = [ + ".github/workflows/release.yml", + "docker/Dockerfile.alpine", + "docker/Dockerfile.debian", + "docker/Dockerfile.ubuntu", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 176 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.453771+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:135bdb00c0d0a288f44ae53554f78cf7ed39482462855d9e9d8548641891b8fc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5590/tests/capture.py b/tasks/traccar__traccar-5590/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5590/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/traccar__traccar-5590/tests/instruction.md b/tasks/traccar__traccar-5590/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63ef9dc98c986f92dd38bc7e7423ce044a2251e9 --- /dev/null +++ b/tasks/traccar__traccar-5590/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Add release delivery to Docker Hub and GHCR + +## Description + +@tananaev, +I have migrated and refactored the build and publication of Docker traccar/tracker images from the [traccar/traccar-docker repository](https://github.com/traccar/traccar-docker). Along with the creation of the new release, Docker images will be published on the Docker Hub and GitHub Container Registry. + +To parallelize the publication, I split the submission into S3 and the Docker build. In the future can add another task to create a release on GitHub. + +Before the first launch, you need to add the secrets `DOCKERHUB_USERNAME` and `DOCKERHUB_TOKEN`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c05dc48b8c2f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5590/tests/oracle.patch b/tasks/traccar__traccar-5590/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0fc0c36c34be06934ae76b03b09a4080cdc51083 --- /dev/null +++ b/tasks/traccar__traccar-5590/tests/oracle.patch @@ -0,0 +1,231 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index dcde68f46..8927f7630 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -1,23 +1,24 @@ +-name: Build Installers ++name: Build Release + + on: + workflow_dispatch: + inputs: + version: +- description: 'Version' ++ description: Version + required: true +- default: 'preview' ++ default: preview + + jobs: +- release: +- runs-on: ubuntu-22.04 ++ build: ++ name: Build installers ++ runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + submodules: true +- - run: git checkout ${{ github.ref_name }} +- working-directory: ./traccar-web ++ - working-directory: ./traccar-web ++ run: git checkout ${{ github.ref_name }} + - uses: actions/setup-java@v4 + with: + distribution: temurin +@@ -29,24 +30,115 @@ jobs: + node-version: 21 + cache: npm + cache-dependency-path: traccar-web/package-lock.json +- - run: npm ci && npm run build +- working-directory: ./traccar-web ++ - working-directory: ./traccar-web ++ run: npm ci && npm run build + - run: | + sudo dpkg --add-architecture i386 + sudo apt-get update + sudo apt-get install libgcc-s1:i386 libstdc++6:i386 +- sudo apt-get install innoextract makeself wine32 s3cmd +- - name: Build installers +- working-directory: ./setup ++ sudo apt-get install innoextract makeself wine32 ++ - working-directory: ./setup + run: | + wget -q http://files.jrsoftware.org/is/5/isetup-5.5.6.exe + wget -q https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_x64_windows_hotspot_21.0.4_7.zip + wget -q https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_x64_linux_hotspot_21.0.4_7.tar.gz + wget -q https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.4+7/OpenJDK21U-jdk_aarch64_linux_hotspot_21.0.4_7.tar.gz + ./package.sh ${{ github.event.inputs.version }} +- - name: Upload installers +- working-directory: ./setup +- env: ++ - uses: actions/upload-artifact@v4 ++ with: ++ name: installers ++ path: setup/traccar-*.zip ++ compression-level: 0 ++ retention-days: 1 ++ upload: ++ name: Upload installers ++ needs: build ++ runs-on: ubuntu-latest ++ steps: ++ - uses: actions/download-artifact@v4 ++ - env: + S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} + S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }} +- run: s3cmd --acl-public put traccar-*.zip s3://traccar/builds/ --host=nyc3.digitaloceanspaces.com --host-bucket=traccar --access_key="$S3_ACCESS_KEY" --secret_key="$S3_SECRET_KEY" ++ run: | ++ sudo apt-get install s3cmd ++ s3cmd --acl-public put installers/traccar-*.zip s3://traccar/builds/ --host=nyc3.digitaloceanspaces.com --host-bucket=traccar --access_key="$S3_ACCESS_KEY" --secret_key="$S3_SECRET_KEY" ++ release: ++ name: Create release with installers ++ needs: build ++ if: ${{ github.event.inputs.version != 'preview' }} ++ runs-on: ubuntu-latest ++ steps: ++ - uses: actions/checkout@v4 ++ with: ++ fetch-depth: 0 ++ - uses: actions/github-script@v6 ++ with: ++ script: | ++ github.rest.git.createRef({ ++ owner: context.repo.owner, ++ repo: context.repo.repo, ++ ref: 'refs/tags/v${{ github.event.inputs.version }}', ++ sha: context.sha ++ }) ++ - uses: actions/download-artifact@v4 ++ - uses: softprops/action-gh-release@v2 ++ with: ++ tag_name: v${{ github.event.inputs.version }} ++ files: installers/traccar-*.zip ++ docker: ++ name: Build and push docker images ++ needs: build ++ if: ${{ github.event.inputs.version != 'preview' }} ++ runs-on: ubuntu-latest ++ strategy: ++ matrix: ++ os: [alpine, debian, ubuntu] ++ include: ++ - os: alpine ++ platforms: linux/amd64,linux/arm64 ++ - platforms: linux/amd64,linux/arm64,linux/arm/v7 ++ steps: ++ - uses: actions/checkout@v4 ++ with: ++ fetch-depth: 0 ++ - uses: actions/download-artifact@v4 ++ with: ++ path: docker ++ - uses: docker/setup-qemu-action@v3 ++ - uses: docker/setup-buildx-action@v3 ++ - uses: docker/login-action@v3 ++ with: ++ username: ${{ secrets.DOCKERHUB_USERNAME }} ++ password: ${{ secrets.DOCKERHUB_TOKEN }} ++ - uses: docker/login-action@v3 ++ with: ++ registry: ghcr.io ++ username: ${{ github.actor }} ++ password: ${{ secrets.GITHUB_TOKEN }} ++ - id: meta ++ uses: docker/metadata-action@v5 ++ with: ++ flavor: latest=false ++ images: | ++ traccar/traccar ++ ghcr.io/traccar/traccar ++ tags: | ++ type=semver,pattern={{major}}.{{minor}}.{{patch}},suffix=-${{ matrix.os }},value=v${{ github.event.inputs.version }} ++ type=semver,pattern={{major}}.{{minor}},suffix=-${{ matrix.os }},value=v${{ github.event.inputs.version }} ++ type=semver,pattern={{major}},suffix=-${{ matrix.os }},value=v${{ github.event.inputs.version }} ++ type=semver,pattern={{major}}.{{minor}}.{{patch}},value=v${{ github.event.inputs.version }},enable=${{ matrix.os == 'alpine' }} ++ type=semver,pattern={{major}}.{{minor}},value=v${{ github.event.inputs.version }},enable=${{ matrix.os == 'alpine' }} ++ type=semver,pattern={{major}},value=v${{ github.event.inputs.version }},enable=${{ matrix.os == 'alpine' }} ++ type=raw,value=latest,enable=${{ matrix.os == 'alpine' }} ++ type=raw,value=${{ matrix.os }} ++ labels: | ++ org.opencontainers.image.version=${{ github.event.inputs.version }} ++ - uses: docker/build-push-action@v6 ++ with: ++ context: docker ++ file: docker/Dockerfile.${{ matrix.os }} ++ build-args: VERSION=${{ github.event.inputs.version }} ++ tags: ${{ steps.meta.outputs.tags }} ++ labels: ${{ steps.meta.outputs.labels }} ++ platforms: ${{ matrix.platforms }} ++ push: true +diff --git a/docker/Dockerfile.alpine b/docker/Dockerfile.alpine +new file mode 100644 +index 000000000..b6386d032 +--- /dev/null ++++ b/docker/Dockerfile.alpine +@@ -0,0 +1,14 @@ ++FROM alpine:3.22 ++ ++ARG VERSION ++COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++ ++WORKDIR /opt/traccar ++ ++RUN set -ex; \ ++ apk add --no-cache --no-progress openjdk17-jre-headless; \ ++ unzip -qo /tmp/traccar.zip -d .; \ ++ rm /tmp/traccar.zip ++ ++ENTRYPOINT ["java"] ++CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] +diff --git a/docker/Dockerfile.debian b/docker/Dockerfile.debian +new file mode 100644 +index 000000000..e827b5d37 +--- /dev/null ++++ b/docker/Dockerfile.debian +@@ -0,0 +1,19 @@ ++FROM debian:12-slim ++ ++ARG VERSION ++COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++ ++WORKDIR /opt/traccar ++ ++RUN set -ex; \ ++ apt-get update; \ ++ TERM=xterm DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \ ++ openjdk-17-jre-headless \ ++ unzip; \ ++ unzip -qo /tmp/traccar.zip -d .; \ ++ apt-get autoremove --yes unzip; \ ++ apt-get clean; \ ++ rm -rf /var/lib/apt/lists/* /tmp/* ++ ++ENTRYPOINT ["java"] ++CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] +diff --git a/docker/Dockerfile.ubuntu b/docker/Dockerfile.ubuntu +new file mode 100644 +index 000000000..457178ac4 +--- /dev/null ++++ b/docker/Dockerfile.ubuntu +@@ -0,0 +1,19 @@ ++FROM ubuntu:24.04 ++ ++ARG VERSION ++COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++ ++WORKDIR /opt/traccar ++ ++RUN set -ex; \ ++ apt-get update; \ ++ TERM=xterm DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \ ++ openjdk-17-jre-headless \ ++ unzip; \ ++ unzip -qo /tmp/traccar.zip -d .; \ ++ apt-get autoremove --yes unzip; \ ++ apt-get clean; \ ++ rm -rf /var/lib/apt/lists/* /tmp/* ++ ++ENTRYPOINT ["java"] ++CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] diff --git a/tasks/traccar__traccar-5590/tests/test.sh b/tasks/traccar__traccar-5590/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a213a4d7fafb718a82ce31b617665415c54ea6c8 --- /dev/null +++ b/tasks/traccar__traccar-5590/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 c05dc48b8c2f5d26c638f935fa5afd57f88b388f > "$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/traccar__traccar-5590/tests/verifier.py b/tasks/traccar__traccar-5590/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5590/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/traccar__traccar-5595/environment/Dockerfile b/tasks/traccar__traccar-5595/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9078649e8e36079a549225baf37307da9c7b9041 --- /dev/null +++ b/tasks/traccar__traccar-5595/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d545ea7b2941c57678a26aea7e0855322ab9b26b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d545ea7b2941c57678a26aea7e0855322ab9b26b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d545ea7b2941c57678a26aea7e0855322ab9b26b \ + && 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/traccar__traccar-5595/instruction.md b/tasks/traccar__traccar-5595/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3f5bdfbb11703d52d098131d6e7aa9e7a94aea3e --- /dev/null +++ b/tasks/traccar__traccar-5595/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Extend support for Micodus MV710G and MV810G devices + +## Description + +- Add support for external power voltage (reported directly as additional info, not nested as an extension) +- Add handler for door alarm (reported in the status field) + +Protocol description found at https://www.traccar.org/forums/topic/micodus-mv710g-voltage/ : +- https://drive.google.com/file/d/1QliuWpScGtZedV9DBuFGNox0kFsPECY9/view?usp=sharing + +Partially + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d545ea7b2941`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5595/solution/patch.diff b/tasks/traccar__traccar-5595/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0cb9f28e14677c7c9494802c71243726ff2dd895 --- /dev/null +++ b/tasks/traccar__traccar-5595/solution/patch.diff @@ -0,0 +1,73 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index bde07657b..f72a9c62b 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -423,6 +423,12 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + + String model = getDeviceModel(deviceSession); + ++ // handling door status for micodus MV810G and MV710G ++ if (model != null && Set.of("MV810G", "MV710G").contains(model)) { ++ position.set(Position.KEY_DOOR, BitUtil.check(status, 16)); ++ } ++ ++ + position.set(Position.KEY_IGNITION, BitUtil.check(status, 0)); + if ("G1C Pro".equals(model)) { + position.set(Position.KEY_MOTION, BitUtil.check(status, 4)); +@@ -559,7 +565,12 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + position.addAlarm(BitUtil.check(alarm, 9) ? Position.ALARM_BRAKING : null); + position.addAlarm(BitUtil.check(alarm, 10) ? Position.ALARM_CORNERING : null); + buf.readUnsignedShort(); // external switch state +- buf.skipBytes(4); // reserved ++ if (model != null && Set.of("MV810G", "MV710G").contains(model)) { ++ int reserved = buf.readInt(); ++ position.addAlarm(BitUtil.check(reserved, 16) ? Position.ALARM_DOOR : null); ++ } else { ++ buf.skipBytes(4); // reserved ++ } + break; + case 0x60: + event = buf.readUnsignedShort(); +@@ -623,6 +634,9 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + endIndex = buf.writerIndex() - 2; + decodeExtension(position, buf, endIndex); + break; ++ case 0x82: ++ position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.1); ++ break; + case 0x91: + position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.1); + position.set(Position.KEY_RPM, buf.readUnsignedShort()); +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 4491a5c21..532abb0a0 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -288,6 +288,27 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + "7E020000964130564801050048000000001000004F01651E2E02CAEC3802E80000001524062616002101040000000330011F31010EF1040000308CF231414F56585F564C3330302D4C415F48322E315F4547393135554C4141425230334130324D30385F56322E312E305F763130F3011FF400F5080000000000000001F6084008FFFFFFFD0009F70600000E870246F912000F000000010000062A00082406261600184D7E"), + Position.KEY_POWER, 12.428); + ++ verifyAttribute(decoder, binary( ++ "7e0200003601911111000000d2000000000000004202b71a72008dbba000000000000025070208082901040000000030011731010e5708000000000000000082020082367e"), ++ Position.KEY_POWER, 13.0); ++ ++ decoder.setModelOverride("MV710G"); ++ ++ // door open, no door alarm ++ verifyAttribute(decoder, binary( ++ "7e02000036019111110000007b000000000001004202b71a72008dbba000000000000025070208082901040000000030011731010e57080000000000000000820200829e7e"), ++ Position.KEY_DOOR, true); ++ verifyAttribute(decoder, binary( ++ "7e02000036019111110000007b000000000001004202b71a72008dbba000000000000025070208082901040000000030011731010e57080000000000000000820200829e7e"), ++ Position.KEY_ALARM, null); ++ // door open, no door alarm ++ verifyAttribute(decoder, binary( ++ "7e02000036019111110000007a000000000001004202b71a72008dbba000000000000025070208082901040000000030011731010e57080000000000010000820200829e7e"), ++ Position.KEY_DOOR, true); ++ verifyAttribute(decoder, binary( ++ "7e02000036019111110000007a000000000001004202b71a72008dbba000000000000025070208082901040000000030011731010e57080000000000010000820200829e7e"), ++ Position.KEY_ALARM, Position.ALARM_DOOR); ++ + decoder.setModelOverride("AL300"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5595/solution/solve.sh b/tasks/traccar__traccar-5595/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5595/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/traccar__traccar-5595/task.toml b/tasks/traccar__traccar-5595/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3d60e10bbcfc72a2f64eeb90275678d3c4c0166c --- /dev/null +++ b/tasks/traccar__traccar-5595/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5595" +description = "Extend support for Micodus MV710G and MV810G devices" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "d545ea7b2941c57678a26aea7e0855322ab9b26b" +reference = "https://github.com/traccar/traccar/pull/5595" +source_access = "auto" +built_at = "2026-11-16T16:09:42.636517+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:908aa29aeca96b1d98f568a807df78907640dc452472645dfd6ef4723663e431" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-07-04T13:27:19Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java", + "src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 37 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.454317+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:68f2b42a62effd270c39fbef909510346467be209ed7c58ab33a2e3bc44e3b22" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5595/tests/capture.py b/tasks/traccar__traccar-5595/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5595/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/traccar__traccar-5595/tests/instruction.md b/tasks/traccar__traccar-5595/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3f5bdfbb11703d52d098131d6e7aa9e7a94aea3e --- /dev/null +++ b/tasks/traccar__traccar-5595/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Extend support for Micodus MV710G and MV810G devices + +## Description + +- Add support for external power voltage (reported directly as additional info, not nested as an extension) +- Add handler for door alarm (reported in the status field) + +Protocol description found at https://www.traccar.org/forums/topic/micodus-mv710g-voltage/ : +- https://drive.google.com/file/d/1QliuWpScGtZedV9DBuFGNox0kFsPECY9/view?usp=sharing + +Partially + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d545ea7b2941`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5595/tests/oracle.patch b/tasks/traccar__traccar-5595/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0cb9f28e14677c7c9494802c71243726ff2dd895 --- /dev/null +++ b/tasks/traccar__traccar-5595/tests/oracle.patch @@ -0,0 +1,73 @@ +diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +index bde07657b..f72a9c62b 100644 +--- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +@@ -423,6 +423,12 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + + String model = getDeviceModel(deviceSession); + ++ // handling door status for micodus MV810G and MV710G ++ if (model != null && Set.of("MV810G", "MV710G").contains(model)) { ++ position.set(Position.KEY_DOOR, BitUtil.check(status, 16)); ++ } ++ ++ + position.set(Position.KEY_IGNITION, BitUtil.check(status, 0)); + if ("G1C Pro".equals(model)) { + position.set(Position.KEY_MOTION, BitUtil.check(status, 4)); +@@ -559,7 +565,12 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + position.addAlarm(BitUtil.check(alarm, 9) ? Position.ALARM_BRAKING : null); + position.addAlarm(BitUtil.check(alarm, 10) ? Position.ALARM_CORNERING : null); + buf.readUnsignedShort(); // external switch state +- buf.skipBytes(4); // reserved ++ if (model != null && Set.of("MV810G", "MV710G").contains(model)) { ++ int reserved = buf.readInt(); ++ position.addAlarm(BitUtil.check(reserved, 16) ? Position.ALARM_DOOR : null); ++ } else { ++ buf.skipBytes(4); // reserved ++ } + break; + case 0x60: + event = buf.readUnsignedShort(); +@@ -623,6 +634,9 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { + endIndex = buf.writerIndex() - 2; + decodeExtension(position, buf, endIndex); + break; ++ case 0x82: ++ position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.1); ++ break; + case 0x91: + position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.1); + position.set(Position.KEY_RPM, buf.readUnsignedShort()); +diff --git a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +index 4491a5c21..532abb0a0 100644 +--- a/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/HuabaoProtocolDecoderTest.java +@@ -288,6 +288,27 @@ public class HuabaoProtocolDecoderTest extends ProtocolTest { + "7E020000964130564801050048000000001000004F01651E2E02CAEC3802E80000001524062616002101040000000330011F31010EF1040000308CF231414F56585F564C3330302D4C415F48322E315F4547393135554C4141425230334130324D30385F56322E312E305F763130F3011FF400F5080000000000000001F6084008FFFFFFFD0009F70600000E870246F912000F000000010000062A00082406261600184D7E"), + Position.KEY_POWER, 12.428); + ++ verifyAttribute(decoder, binary( ++ "7e0200003601911111000000d2000000000000004202b71a72008dbba000000000000025070208082901040000000030011731010e5708000000000000000082020082367e"), ++ Position.KEY_POWER, 13.0); ++ ++ decoder.setModelOverride("MV710G"); ++ ++ // door open, no door alarm ++ verifyAttribute(decoder, binary( ++ "7e02000036019111110000007b000000000001004202b71a72008dbba000000000000025070208082901040000000030011731010e57080000000000000000820200829e7e"), ++ Position.KEY_DOOR, true); ++ verifyAttribute(decoder, binary( ++ "7e02000036019111110000007b000000000001004202b71a72008dbba000000000000025070208082901040000000030011731010e57080000000000000000820200829e7e"), ++ Position.KEY_ALARM, null); ++ // door open, no door alarm ++ verifyAttribute(decoder, binary( ++ "7e02000036019111110000007a000000000001004202b71a72008dbba000000000000025070208082901040000000030011731010e57080000000000010000820200829e7e"), ++ Position.KEY_DOOR, true); ++ verifyAttribute(decoder, binary( ++ "7e02000036019111110000007a000000000001004202b71a72008dbba000000000000025070208082901040000000030011731010e57080000000000010000820200829e7e"), ++ Position.KEY_ALARM, Position.ALARM_DOOR); ++ + decoder.setModelOverride("AL300"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5595/tests/test.sh b/tasks/traccar__traccar-5595/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..28521d5645c1bf1f772af3d4b8beadee6bf343c1 --- /dev/null +++ b/tasks/traccar__traccar-5595/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 d545ea7b2941c57678a26aea7e0855322ab9b26b > "$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/traccar__traccar-5595/tests/verifier.py b/tasks/traccar__traccar-5595/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5595/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/traccar__traccar-5598/environment/Dockerfile b/tasks/traccar__traccar-5598/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1f7fa768fae313e57c26e4c4d6d5a9cff36e559b --- /dev/null +++ b/tasks/traccar__traccar-5598/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 46317e403ab9cb914e2d45406af7dd9a1173bf4e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 46317e403ab9cb914e2d45406af7dd9a1173bf4e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 46317e403ab9cb914e2d45406af7dd9a1173bf4e \ + && 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/traccar__traccar-5598/instruction.md b/tasks/traccar__traccar-5598/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..335d0d2241365a433ea8f7c6a8828aea9bfb9091 --- /dev/null +++ b/tasks/traccar__traccar-5598/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Optimize Docker images + +## Description + +@magna-z what do you think about doing images like this? + +Basically 3 stages: +1. Unzip Traccar package. Separate stage means that we can reuse this code between all images and don't need to worry about installing and cleaning up unzip. +2. Package minimal version of JRE. This is what we do for official installers. Makes sense to do it for docker as well. It can save us quite a bit in size. It's also reusable. The only difference is that alpine needs a different base package. +3. Final docker image. It's basically the same across all with different base. + +In my local testing it saved about 100MB on alpine image size. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `46317e403ab9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5598/solution/patch.diff b/tasks/traccar__traccar-5598/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..02e7b6b0b3858967aeb09bfba1334183def895d8 --- /dev/null +++ b/tasks/traccar__traccar-5598/solution/patch.diff @@ -0,0 +1,100 @@ +diff --git a/docker/Dockerfile.alpine b/docker/Dockerfile.alpine +index b6386d032..14f200006 100644 +--- a/docker/Dockerfile.alpine ++++ b/docker/Dockerfile.alpine +@@ -1,14 +1,16 @@ +-FROM alpine:3.22 +- ++FROM alpine AS package + ARG VERSION + COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++RUN unzip -qo /tmp/traccar.zip -d /traccar + +-WORKDIR /opt/traccar +- +-RUN set -ex; \ +- apk add --no-cache --no-progress openjdk17-jre-headless; \ +- unzip -qo /tmp/traccar.zip -d .; \ +- rm /tmp/traccar.zip ++FROM eclipse-temurin:21-alpine AS jdk ++RUN jlink --module-path $JAVA_HOME/jmods \ ++ --add-modules java.se,jdk.charsets,jdk.crypto.ec,jdk.unsupported \ ++ --strip-debug --no-header-files --no-man-pages --compress=2 --output /jre + +-ENTRYPOINT ["java"] ++FROM alpine:3.22 ++COPY --from=package /traccar /opt/traccar ++COPY --from=jdk /jre /opt/traccar/jre ++WORKDIR /opt/traccar ++ENTRYPOINT ["/opt/traccar/jre/bin/java"] + CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] +diff --git a/docker/Dockerfile.debian b/docker/Dockerfile.debian +index e827b5d37..ef7a82e6d 100644 +--- a/docker/Dockerfile.debian ++++ b/docker/Dockerfile.debian +@@ -1,19 +1,16 @@ +-FROM debian:12-slim +- ++FROM alpine AS package + ARG VERSION + COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++RUN unzip -qo /tmp/traccar.zip -d /traccar + +-WORKDIR /opt/traccar +- +-RUN set -ex; \ +- apt-get update; \ +- TERM=xterm DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \ +- openjdk-17-jre-headless \ +- unzip; \ +- unzip -qo /tmp/traccar.zip -d .; \ +- apt-get autoremove --yes unzip; \ +- apt-get clean; \ +- rm -rf /var/lib/apt/lists/* /tmp/* ++FROM eclipse-temurin:21 AS jdk ++RUN jlink --module-path $JAVA_HOME/jmods \ ++ --add-modules java.se,jdk.charsets,jdk.crypto.ec,jdk.unsupported \ ++ --strip-debug --no-header-files --no-man-pages --compress=2 --output /jre + +-ENTRYPOINT ["java"] ++FROM debian:12-slim ++COPY --from=package /traccar /opt/traccar ++COPY --from=jdk /jre /opt/traccar/jre ++WORKDIR /opt/traccar ++ENTRYPOINT ["/opt/traccar/jre/bin/java"] + CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] +diff --git a/docker/Dockerfile.ubuntu b/docker/Dockerfile.ubuntu +index 457178ac4..f16ed530a 100644 +--- a/docker/Dockerfile.ubuntu ++++ b/docker/Dockerfile.ubuntu +@@ -1,19 +1,16 @@ +-FROM ubuntu:24.04 +- ++FROM alpine AS package + ARG VERSION + COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++RUN unzip -qo /tmp/traccar.zip -d /traccar + +-WORKDIR /opt/traccar +- +-RUN set -ex; \ +- apt-get update; \ +- TERM=xterm DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \ +- openjdk-17-jre-headless \ +- unzip; \ +- unzip -qo /tmp/traccar.zip -d .; \ +- apt-get autoremove --yes unzip; \ +- apt-get clean; \ +- rm -rf /var/lib/apt/lists/* /tmp/* ++FROM eclipse-temurin:21 AS jdk ++RUN jlink --module-path $JAVA_HOME/jmods \ ++ --add-modules java.se,jdk.charsets,jdk.crypto.ec,jdk.unsupported \ ++ --strip-debug --no-header-files --no-man-pages --compress=2 --output /jre + +-ENTRYPOINT ["java"] ++FROM ubuntu:24.04 ++COPY --from=package /traccar /opt/traccar ++COPY --from=jdk /jre /opt/traccar/jre ++WORKDIR /opt/traccar ++ENTRYPOINT ["/opt/traccar/jre/bin/java"] + CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] diff --git a/tasks/traccar__traccar-5598/solution/solve.sh b/tasks/traccar__traccar-5598/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5598/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/traccar__traccar-5598/task.toml b/tasks/traccar__traccar-5598/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..25ece3efbacf75006a51596a3f2240c8fa329a5f --- /dev/null +++ b/tasks/traccar__traccar-5598/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5598" +description = "Optimize Docker images" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "46317e403ab9cb914e2d45406af7dd9a1173bf4e" +reference = "https://github.com/traccar/traccar/pull/5598" +source_access = "auto" +built_at = "2026-11-16T16:09:42.630095+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3d28e58cee1bce20ab9cbabcc39ce0f576cdf0e876fb6c75067c2fc646382383" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-07-06T15:48:13Z" +diff_format = "unified" +context_files = [ + "docker/Dockerfile.alpine", + "docker/Dockerfile.debian", + "docker/Dockerfile.ubuntu", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 70 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.454852+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:079e57d885935fe6196c520301dca757b337c6f3f5f3e67c2b247eb9cb46ef9e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5598/tests/capture.py b/tasks/traccar__traccar-5598/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5598/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/traccar__traccar-5598/tests/instruction.md b/tasks/traccar__traccar-5598/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..335d0d2241365a433ea8f7c6a8828aea9bfb9091 --- /dev/null +++ b/tasks/traccar__traccar-5598/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Optimize Docker images + +## Description + +@magna-z what do you think about doing images like this? + +Basically 3 stages: +1. Unzip Traccar package. Separate stage means that we can reuse this code between all images and don't need to worry about installing and cleaning up unzip. +2. Package minimal version of JRE. This is what we do for official installers. Makes sense to do it for docker as well. It can save us quite a bit in size. It's also reusable. The only difference is that alpine needs a different base package. +3. Final docker image. It's basically the same across all with different base. + +In my local testing it saved about 100MB on alpine image size. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `46317e403ab9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5598/tests/oracle.patch b/tasks/traccar__traccar-5598/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..02e7b6b0b3858967aeb09bfba1334183def895d8 --- /dev/null +++ b/tasks/traccar__traccar-5598/tests/oracle.patch @@ -0,0 +1,100 @@ +diff --git a/docker/Dockerfile.alpine b/docker/Dockerfile.alpine +index b6386d032..14f200006 100644 +--- a/docker/Dockerfile.alpine ++++ b/docker/Dockerfile.alpine +@@ -1,14 +1,16 @@ +-FROM alpine:3.22 +- ++FROM alpine AS package + ARG VERSION + COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++RUN unzip -qo /tmp/traccar.zip -d /traccar + +-WORKDIR /opt/traccar +- +-RUN set -ex; \ +- apk add --no-cache --no-progress openjdk17-jre-headless; \ +- unzip -qo /tmp/traccar.zip -d .; \ +- rm /tmp/traccar.zip ++FROM eclipse-temurin:21-alpine AS jdk ++RUN jlink --module-path $JAVA_HOME/jmods \ ++ --add-modules java.se,jdk.charsets,jdk.crypto.ec,jdk.unsupported \ ++ --strip-debug --no-header-files --no-man-pages --compress=2 --output /jre + +-ENTRYPOINT ["java"] ++FROM alpine:3.22 ++COPY --from=package /traccar /opt/traccar ++COPY --from=jdk /jre /opt/traccar/jre ++WORKDIR /opt/traccar ++ENTRYPOINT ["/opt/traccar/jre/bin/java"] + CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] +diff --git a/docker/Dockerfile.debian b/docker/Dockerfile.debian +index e827b5d37..ef7a82e6d 100644 +--- a/docker/Dockerfile.debian ++++ b/docker/Dockerfile.debian +@@ -1,19 +1,16 @@ +-FROM debian:12-slim +- ++FROM alpine AS package + ARG VERSION + COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++RUN unzip -qo /tmp/traccar.zip -d /traccar + +-WORKDIR /opt/traccar +- +-RUN set -ex; \ +- apt-get update; \ +- TERM=xterm DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \ +- openjdk-17-jre-headless \ +- unzip; \ +- unzip -qo /tmp/traccar.zip -d .; \ +- apt-get autoremove --yes unzip; \ +- apt-get clean; \ +- rm -rf /var/lib/apt/lists/* /tmp/* ++FROM eclipse-temurin:21 AS jdk ++RUN jlink --module-path $JAVA_HOME/jmods \ ++ --add-modules java.se,jdk.charsets,jdk.crypto.ec,jdk.unsupported \ ++ --strip-debug --no-header-files --no-man-pages --compress=2 --output /jre + +-ENTRYPOINT ["java"] ++FROM debian:12-slim ++COPY --from=package /traccar /opt/traccar ++COPY --from=jdk /jre /opt/traccar/jre ++WORKDIR /opt/traccar ++ENTRYPOINT ["/opt/traccar/jre/bin/java"] + CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] +diff --git a/docker/Dockerfile.ubuntu b/docker/Dockerfile.ubuntu +index 457178ac4..f16ed530a 100644 +--- a/docker/Dockerfile.ubuntu ++++ b/docker/Dockerfile.ubuntu +@@ -1,19 +1,16 @@ +-FROM ubuntu:24.04 +- ++FROM alpine AS package + ARG VERSION + COPY installers/traccar-other-$VERSION.zip /tmp/traccar.zip ++RUN unzip -qo /tmp/traccar.zip -d /traccar + +-WORKDIR /opt/traccar +- +-RUN set -ex; \ +- apt-get update; \ +- TERM=xterm DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \ +- openjdk-17-jre-headless \ +- unzip; \ +- unzip -qo /tmp/traccar.zip -d .; \ +- apt-get autoremove --yes unzip; \ +- apt-get clean; \ +- rm -rf /var/lib/apt/lists/* /tmp/* ++FROM eclipse-temurin:21 AS jdk ++RUN jlink --module-path $JAVA_HOME/jmods \ ++ --add-modules java.se,jdk.charsets,jdk.crypto.ec,jdk.unsupported \ ++ --strip-debug --no-header-files --no-man-pages --compress=2 --output /jre + +-ENTRYPOINT ["java"] ++FROM ubuntu:24.04 ++COPY --from=package /traccar /opt/traccar ++COPY --from=jdk /jre /opt/traccar/jre ++WORKDIR /opt/traccar ++ENTRYPOINT ["/opt/traccar/jre/bin/java"] + CMD ["-jar", "tracker-server.jar", "conf/traccar.xml"] diff --git a/tasks/traccar__traccar-5598/tests/test.sh b/tasks/traccar__traccar-5598/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7a056fd13b0e5801720b8656e83f5a33e2bdfd03 --- /dev/null +++ b/tasks/traccar__traccar-5598/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 46317e403ab9cb914e2d45406af7dd9a1173bf4e > "$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/traccar__traccar-5598/tests/verifier.py b/tasks/traccar__traccar-5598/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5598/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/traccar__traccar-5610/environment/Dockerfile b/tasks/traccar__traccar-5610/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..875a2fa3a02e87594327315d9b408f4f2d207fda --- /dev/null +++ b/tasks/traccar__traccar-5610/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7df466455f2aec3fd659e048cbcdc2beb19c30eb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7df466455f2aec3fd659e048cbcdc2beb19c30eb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7df466455f2aec3fd659e048cbcdc2beb19c30eb \ + && 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/traccar__traccar-5610/instruction.md b/tasks/traccar__traccar-5610/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5cbeedffb1de7c0196503ea298374afabe9d013c --- /dev/null +++ b/tasks/traccar__traccar-5610/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** Streaming in PositionResource + +## Description + +This does not optimize for the case where only positionIds are used or when we request just latest positions, as those datasets are typically small. +I'm slightly concerned about flushing after every record, but I fear that if we don't flush explicitly, the stream will only flush once it's closed. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7df466455f2a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5610/solution/patch.diff b/tasks/traccar__traccar-5610/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ac757434bff1cb124f2e970efe61cbffd14f9973 --- /dev/null +++ b/tasks/traccar__traccar-5610/solution/patch.diff @@ -0,0 +1,409 @@ +diff --git a/src/main/java/org/traccar/api/StreamWriter.java b/src/main/java/org/traccar/api/StreamWriter.java +new file mode 100644 +index 000000000..b26c28a60 +--- /dev/null ++++ b/src/main/java/org/traccar/api/StreamWriter.java +@@ -0,0 +1,40 @@ ++package org.traccar.api; ++ ++import com.fasterxml.jackson.databind.ObjectMapper; ++import jakarta.ws.rs.Produces; ++import jakarta.ws.rs.core.MediaType; ++import jakarta.ws.rs.core.MultivaluedMap; ++import jakarta.ws.rs.ext.MessageBodyWriter; ++import jakarta.ws.rs.ext.Provider; ++ ++import java.io.IOException; ++import java.io.OutputStream; ++import java.lang.annotation.Annotation; ++import java.lang.reflect.Type; ++import java.util.Iterator; ++import java.util.stream.Stream; ++ ++@Provider ++@Produces(MediaType.APPLICATION_JSON) ++public class StreamWriter implements MessageBodyWriter> { ++ ++ private final ObjectMapper objectMapper = new ObjectMapper(); ++ ++ @Override ++ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { ++ return Stream.class.isAssignableFrom(type); ++ } ++ ++ @Override ++ public void writeTo(Stream stream, Class type, Type genericType, Annotation[] annotations, ++ MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) ++ throws IOException { ++ try (stream; var generator = objectMapper.createGenerator(entityStream)) { ++ generator.writeStartArray(); ++ for (Iterator it = stream.iterator(); it.hasNext();) { ++ objectMapper.writeValue(generator, it.next()); ++ } ++ generator.writeEndArray(); ++ } ++ } ++} +diff --git a/src/main/java/org/traccar/api/resource/PositionResource.java b/src/main/java/org/traccar/api/resource/PositionResource.java +index c22b6403e..946e174e1 100644 +--- a/src/main/java/org/traccar/api/resource/PositionResource.java ++++ b/src/main/java/org/traccar/api/resource/PositionResource.java +@@ -42,10 +42,10 @@ import jakarta.ws.rs.core.MediaType; + import jakarta.ws.rs.core.Response; + import jakarta.ws.rs.core.StreamingOutput; + import java.util.ArrayList; +-import java.util.Collection; + import java.util.Date; + import java.util.List; + import java.util.LinkedList; ++import java.util.stream.Stream; + + @Path("positions") + @Produces(MediaType.APPLICATION_JSON) +@@ -62,7 +62,7 @@ public class PositionResource extends BaseResource { + private GpxExportProvider gpxExportProvider; + + @GET +- public Collection getJson( ++ public Stream getJson( + @QueryParam("deviceId") long deviceId, @QueryParam("id") List positionIds, + @QueryParam("from") Date from, @QueryParam("to") Date to) + throws StorageException { +@@ -74,18 +74,18 @@ public class PositionResource extends BaseResource { + permissionsService.checkPermission(Device.class, getUserId(), position.getDeviceId()); + positions.add(position); + } +- return positions; ++ return positions.stream(); + } else if (deviceId > 0) { + permissionsService.checkPermission(Device.class, getUserId(), deviceId); + if (from != null && to != null) { + permissionsService.checkRestriction(getUserId(), UserRestrictions::getDisableReports); +- return PositionUtil.getPositions(storage, deviceId, from, to); ++ return PositionUtil.getPositionsStream(storage, deviceId, from, to); + } else { +- return storage.getObjects(Position.class, new Request( ++ return storage.getObjectsStream(Position.class, new Request( + new Columns.All(), new Condition.LatestPositions(deviceId))); + } + } else { +- return PositionUtil.getLatestPositions(storage, getUserId()); ++ return PositionUtil.getLatestPositions(storage, getUserId()).stream(); + } + } + +diff --git a/src/main/java/org/traccar/helper/model/PositionUtil.java b/src/main/java/org/traccar/helper/model/PositionUtil.java +index ff311e306..aa8ad6ab2 100644 +--- a/src/main/java/org/traccar/helper/model/PositionUtil.java ++++ b/src/main/java/org/traccar/helper/model/PositionUtil.java +@@ -30,6 +30,7 @@ import org.traccar.storage.query.Request; + import java.util.Date; + import java.util.List; + import java.util.stream.Collectors; ++import java.util.stream.Stream; + + public final class PositionUtil { + +@@ -56,7 +57,14 @@ public final class PositionUtil { + + public static List getPositions( + Storage storage, long deviceId, Date from, Date to) throws StorageException { +- return storage.getObjects(Position.class, new Request( ++ try (var positions = getPositionsStream(storage, deviceId, from, to)) { ++ return positions.collect(Collectors.toList()); ++ } ++ } ++ ++ public static Stream getPositionsStream( ++ Storage storage, long deviceId, Date from, Date to) throws StorageException { ++ return storage.getObjectsStream(Position.class, new Request( + new Columns.All(), + new Condition.And( + new Condition.Equals("deviceId", deviceId), +diff --git a/src/main/java/org/traccar/web/WebServer.java b/src/main/java/org/traccar/web/WebServer.java +index 1101a5e9e..a01b12eba 100644 +--- a/src/main/java/org/traccar/web/WebServer.java ++++ b/src/main/java/org/traccar/web/WebServer.java +@@ -45,6 +45,7 @@ import org.traccar.LifecycleObject; + import org.traccar.api.CorsResponseFilter; + import org.traccar.api.DateParameterConverterProvider; + import org.traccar.api.ResourceErrorHandler; ++import org.traccar.api.StreamWriter; + import org.traccar.api.resource.ServerResource; + import org.traccar.api.security.SecurityRequestFilter; + import org.traccar.config.Config; +@@ -172,7 +173,8 @@ public class WebServer implements LifecycleObject { + DateParameterConverterProvider.class, + SecurityRequestFilter.class, + CorsResponseFilter.class, +- ResourceErrorHandler.class); ++ ResourceErrorHandler.class, ++ StreamWriter.class); + resourceConfig.packages(ServerResource.class.getPackage().getName()); + if (resourceConfig.getClasses().stream().filter(ServerResource.class::equals).findAny().isEmpty()) { + LOGGER.warn("Failed to load API resources"); +diff --git a/src/test/java/org/traccar/reports/ReportUtilsTest.java b/src/test/java/org/traccar/reports/ReportUtilsTest.java +index 0f14577fd..b340f516a 100644 +--- a/src/test/java/org/traccar/reports/ReportUtilsTest.java ++++ b/src/test/java/org/traccar/reports/ReportUtilsTest.java +@@ -25,6 +25,7 @@ import java.util.Iterator; + import java.util.List; + import java.util.Map; + import java.util.TimeZone; ++import java.util.stream.Stream; + + import static org.junit.jupiter.api.Assertions.assertEquals; + import static org.junit.jupiter.api.Assertions.assertFalse; +@@ -36,9 +37,9 @@ import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + + public class ReportUtilsTest extends BaseTest { +- ++ + private Storage storage; +- ++ + @BeforeEach + public void init() throws StorageException { + storage = mock(Storage.class); +@@ -76,7 +77,7 @@ public class ReportUtilsTest extends BaseTest { + Keys.REPORT_TRIP_USE_IGNITION.getKey(), useIgnition)); + return device; + } +- ++ + @Test + public void testCalculateDistance() { + Position startPosition = new Position(); +@@ -104,7 +105,7 @@ public class ReportUtilsTest extends BaseTest { + @Test + public void testDetectTripsSimple() throws Exception { + +- List data = Arrays.asList( ++ Stream data = Stream.of( + position("2016-01-01 00:00:00.000", 0, 0), + position("2016-01-01 00:01:00.000", 0, 0), + position("2016-01-01 00:02:00.000", 10, 0), +@@ -113,7 +114,7 @@ public class ReportUtilsTest extends BaseTest { + position("2016-01-01 00:05:00.000", 0, 3000), + position("2016-01-01 00:15:00.000", 0, 3000), + position("2016-01-01 00:25:00.000", 0, 3000)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 300, 180, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -132,7 +133,24 @@ public class ReportUtilsTest extends BaseTest { + assertEquals(32.4, itemTrip.getAverageSpeed(), 0.01); + assertEquals(10, itemTrip.getMaxSpeed(), 0.01); + assertEquals(3000, itemTrip.getDistance(), 0.01); ++ } + ++ @Test ++ public void testDetectStopsSimple() throws Exception { ++ Stream data = Stream.of( ++ position("2016-01-01 00:00:00.000", 0, 0), ++ position("2016-01-01 00:01:00.000", 0, 0), ++ position("2016-01-01 00:02:00.000", 10, 0), ++ position("2016-01-01 00:03:00.000", 10, 1000), ++ position("2016-01-01 00:04:00.000", 10, 2000), ++ position("2016-01-01 00:05:00.000", 0, 3000), ++ position("2016-01-01 00:15:00.000", 0, 3000), ++ position("2016-01-01 00:25:00.000", 0, 3000)); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); ++ ++ Device device = mockDevice(500, 300, 180, 900, false); ++ ReportUtils reportUtils = new ReportUtils( ++ mock(Config.class), storage, mock(PermissionsService.class), mock(VelocityEngine.class), null); + var stops = reportUtils.slowTripsAndStops(device, new Date(), new Date(), StopReportItem.class); + + assertNotNull(stops); +@@ -166,7 +184,7 @@ public class ReportUtilsTest extends BaseTest { + position("2016-01-01 00:05:00.000", 0, 3000), + position("2016-01-01 00:15:00.000", 0, 3000), + position("2016-01-01 00:25:00.000", 0, 3000)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data.stream()); + + data.get(5).set(Position.KEY_IGNITION, false); + +@@ -187,20 +205,25 @@ public class ReportUtilsTest extends BaseTest { + assertEquals(32.4, itemTrip.getAverageSpeed(), 0.01); + assertEquals(10, itemTrip.getMaxSpeed(), 0.01); + assertEquals(3000, itemTrip.getDistance(), 0.01); ++ } + +- trips = reportUtils.slowTripsAndStops(device, new Date(), new Date(), TripReportItem.class); +- +- assertNotNull(trips); +- assertFalse(trips.isEmpty()); +- +- itemTrip = trips.iterator().next(); ++ @Test ++ public void testDetectStopsSimpleWithIgnition() throws Exception { ++ List data = Arrays.asList( ++ position("2016-01-01 00:00:00.000", 0, 0), ++ position("2016-01-01 00:01:00.000", 0, 0), ++ position("2016-01-01 00:02:00.000", 10, 0), ++ position("2016-01-01 00:03:00.000", 10, 1000), ++ position("2016-01-01 00:04:00.000", 10, 2000), ++ position("2016-01-01 00:05:00.000", 0, 3000), ++ position("2016-01-01 00:15:00.000", 0, 3000), ++ position("2016-01-01 00:25:00.000", 0, 3000)); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data.stream()); + +- assertEquals(date("2016-01-01 00:02:00.000"), itemTrip.getStartTime()); +- assertEquals(date("2016-01-01 00:05:00.000"), itemTrip.getEndTime()); +- assertEquals(180000, itemTrip.getDuration()); +- assertEquals(32.4, itemTrip.getAverageSpeed(), 0.01); +- assertEquals(10, itemTrip.getMaxSpeed(), 0.01); +- assertEquals(3000, itemTrip.getDistance(), 0.01); ++ data.get(5).set(Position.KEY_IGNITION, false); ++ Device device = mockDevice(500, 300, 180, 900, true); ++ ReportUtils reportUtils = new ReportUtils( ++ mock(Config.class), storage, mock(PermissionsService.class), mock(VelocityEngine.class), null); + + var stops = reportUtils.slowTripsAndStops(device, new Date(), new Date(), StopReportItem.class); + +@@ -226,7 +249,7 @@ public class ReportUtilsTest extends BaseTest { + @Test + public void testDetectTripsWithFluctuation() throws Exception { + +- List data = Arrays.asList( ++ Stream data = Stream.of( + position("2016-01-01 00:00:00.000", 0, 0), + position("2016-01-01 00:01:00.000", 0, 0), + position("2016-01-01 00:02:00.000", 10, 0), +@@ -239,7 +262,7 @@ public class ReportUtilsTest extends BaseTest { + position("2016-01-01 00:09:00.000", 0, 7000), + position("2016-01-01 00:19:00.000", 0, 7000), + position("2016-01-01 00:29:00.000", 0, 7000)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 300, 180, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -258,6 +281,27 @@ public class ReportUtilsTest extends BaseTest { + assertEquals(32.4, itemTrip.getAverageSpeed(), 0.01); + assertEquals(10, itemTrip.getMaxSpeed(), 0.01); + assertEquals(7000, itemTrip.getDistance(), 0.01); ++ } ++ ++ @Test ++ public void testDetectStopsWithFluctuation() throws Exception { ++ Stream data = Stream.of( ++ position("2016-01-01 00:00:00.000", 0, 0), ++ position("2016-01-01 00:01:00.000", 0, 0), ++ position("2016-01-01 00:02:00.000", 10, 0), ++ position("2016-01-01 00:03:00.000", 10, 1000), ++ position("2016-01-01 00:04:00.000", 10, 2000), ++ position("2016-01-01 00:05:00.000", 10, 3000), ++ position("2016-01-01 00:06:00.000", 10, 4000), ++ position("2016-01-01 00:07:00.000", 0, 5000), ++ position("2016-01-01 00:08:00.000", 10, 6000), ++ position("2016-01-01 00:09:00.000", 0, 7000), ++ position("2016-01-01 00:19:00.000", 0, 7000), ++ position("2016-01-01 00:29:00.000", 0, 7000)); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); ++ Device device = mockDevice(500, 300, 180, 900, false); ++ ReportUtils reportUtils = new ReportUtils( ++ mock(Config.class), storage, mock(PermissionsService.class), mock(VelocityEngine.class), null); + + var stops = reportUtils.slowTripsAndStops(device, new Date(), new Date(), StopReportItem.class); + +@@ -283,14 +327,14 @@ public class ReportUtilsTest extends BaseTest { + @Test + public void testDetectStopsOnly() throws Exception { + +- var data = Arrays.asList( ++ var data = Stream.of( + position("2016-01-01 00:00:00.000", 0, 0), + position("2016-01-01 00:01:00.000", 0, 0), + position("2016-01-01 00:02:00.000", 1, 0), + position("2016-01-01 00:03:00.000", 0, 0), + position("2016-01-01 00:04:00.000", 1, 0), + position("2016-01-01 00:05:00.000", 0, 0)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 300, 200, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -312,14 +356,14 @@ public class ReportUtilsTest extends BaseTest { + @Test + public void testDetectStopsWithTripCut() throws Exception { + +- var data = Arrays.asList( ++ var data = Stream.of( + position("2016-01-01 00:00:00.000", 0, 0), + position("2016-01-01 00:01:00.000", 0, 0), + position("2016-01-01 00:02:00.000", 0, 0), + position("2016-01-01 00:03:00.000", 0, 0), + position("2016-01-01 00:04:00.000", 1, 0), + position("2016-01-01 00:05:00.000", 2, 0)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 300, 200, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -341,14 +385,14 @@ public class ReportUtilsTest extends BaseTest { + @Test + public void testDetectStopsStartedFromTrip() throws Exception { + +- var data = Arrays.asList( ++ var data = Stream.of( + position("2016-01-01 00:00:00.000", 2, 0), + position("2016-01-01 00:01:00.000", 1, 0), + position("2016-01-01 00:02:00.000", 0, 0), + position("2016-01-01 00:12:00.000", 0, 0), + position("2016-01-01 00:22:00.000", 0, 0), + position("2016-01-01 00:32:00.000", 0, 0)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 300, 200, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -391,9 +435,9 @@ public class ReportUtilsTest extends BaseTest { + } + + @Test +- public void testDetectTripAndStopByGap() throws Exception { ++ public void testDetectTripByGap() throws Exception { + +- var data = Arrays.asList( ++ var data = Stream.of( + position("2016-01-01 00:00:00.000", 7, 100), + position("2016-01-01 00:01:00.000", 7, 300), + position("2016-01-01 00:02:00.000", 5, 500), +@@ -402,7 +446,7 @@ public class ReportUtilsTest extends BaseTest { + position("2016-01-01 00:23:00.000", 2, 700), + position("2016-01-01 00:24:00.000", 5, 800), + position("2016-01-01 00:25:00.000", 5, 900)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 200, 200, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -421,7 +465,23 @@ public class ReportUtilsTest extends BaseTest { + assertEquals(4.86, itemTrip.getAverageSpeed(), 0.01); + assertEquals(7, itemTrip.getMaxSpeed(), 0.01); + assertEquals(600, itemTrip.getDistance(), 0.01); ++ } + ++ @Test ++ public void testDetectStopByGap() throws Exception { ++ var data = Stream.of( ++ position("2016-01-01 00:00:00.000", 7, 100), ++ position("2016-01-01 00:01:00.000", 7, 300), ++ position("2016-01-01 00:02:00.000", 5, 500), ++ position("2016-01-01 00:03:00.000", 5, 600), ++ position("2016-01-01 00:04:00.000", 3, 700), ++ position("2016-01-01 00:23:00.000", 2, 700), ++ position("2016-01-01 00:24:00.000", 5, 800), ++ position("2016-01-01 00:25:00.000", 5, 900)); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); ++ ReportUtils reportUtils = new ReportUtils( ++ mock(Config.class), storage, mock(PermissionsService.class), mock(VelocityEngine.class), null); ++ Device device = mockDevice(500, 200, 200, 900, false); + var stops = reportUtils.slowTripsAndStops(device, new Date(), new Date(), StopReportItem.class); + + assertNotNull(stops); diff --git a/tasks/traccar__traccar-5610/solution/solve.sh b/tasks/traccar__traccar-5610/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5610/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/traccar__traccar-5610/task.toml b/tasks/traccar__traccar-5610/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..894c18c783377a2a47635efcdabb9320497442c2 --- /dev/null +++ b/tasks/traccar__traccar-5610/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5610" +description = "Streaming in PositionResource" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "7df466455f2aec3fd659e048cbcdc2beb19c30eb" +reference = "https://github.com/traccar/traccar/pull/5610" +source_access = "auto" +built_at = "2026-11-16T16:09:42.622766+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0b88b74aa06b12b958fc2e23dc37ff9ab683f585f3c951e8f7e0d342877d674f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-07-15T02:22:25Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/api/StreamWriter.java", + "src/main/java/org/traccar/api/resource/PositionResource.java", + "src/main/java/org/traccar/helper/model/PositionUtil.java", + "src/main/java/org/traccar/web/WebServer.java", + "src/test/java/org/traccar/reports/ReportUtilsTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 184 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.455392+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:226b7122e514f8a89bf73220d2e3d52304d58ad4ab054e86de3b63419626e11b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5610/tests/capture.py b/tasks/traccar__traccar-5610/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5610/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/traccar__traccar-5610/tests/instruction.md b/tasks/traccar__traccar-5610/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5cbeedffb1de7c0196503ea298374afabe9d013c --- /dev/null +++ b/tasks/traccar__traccar-5610/tests/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** Streaming in PositionResource + +## Description + +This does not optimize for the case where only positionIds are used or when we request just latest positions, as those datasets are typically small. +I'm slightly concerned about flushing after every record, but I fear that if we don't flush explicitly, the stream will only flush once it's closed. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7df466455f2a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5610/tests/oracle.patch b/tasks/traccar__traccar-5610/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ac757434bff1cb124f2e970efe61cbffd14f9973 --- /dev/null +++ b/tasks/traccar__traccar-5610/tests/oracle.patch @@ -0,0 +1,409 @@ +diff --git a/src/main/java/org/traccar/api/StreamWriter.java b/src/main/java/org/traccar/api/StreamWriter.java +new file mode 100644 +index 000000000..b26c28a60 +--- /dev/null ++++ b/src/main/java/org/traccar/api/StreamWriter.java +@@ -0,0 +1,40 @@ ++package org.traccar.api; ++ ++import com.fasterxml.jackson.databind.ObjectMapper; ++import jakarta.ws.rs.Produces; ++import jakarta.ws.rs.core.MediaType; ++import jakarta.ws.rs.core.MultivaluedMap; ++import jakarta.ws.rs.ext.MessageBodyWriter; ++import jakarta.ws.rs.ext.Provider; ++ ++import java.io.IOException; ++import java.io.OutputStream; ++import java.lang.annotation.Annotation; ++import java.lang.reflect.Type; ++import java.util.Iterator; ++import java.util.stream.Stream; ++ ++@Provider ++@Produces(MediaType.APPLICATION_JSON) ++public class StreamWriter implements MessageBodyWriter> { ++ ++ private final ObjectMapper objectMapper = new ObjectMapper(); ++ ++ @Override ++ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { ++ return Stream.class.isAssignableFrom(type); ++ } ++ ++ @Override ++ public void writeTo(Stream stream, Class type, Type genericType, Annotation[] annotations, ++ MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) ++ throws IOException { ++ try (stream; var generator = objectMapper.createGenerator(entityStream)) { ++ generator.writeStartArray(); ++ for (Iterator it = stream.iterator(); it.hasNext();) { ++ objectMapper.writeValue(generator, it.next()); ++ } ++ generator.writeEndArray(); ++ } ++ } ++} +diff --git a/src/main/java/org/traccar/api/resource/PositionResource.java b/src/main/java/org/traccar/api/resource/PositionResource.java +index c22b6403e..946e174e1 100644 +--- a/src/main/java/org/traccar/api/resource/PositionResource.java ++++ b/src/main/java/org/traccar/api/resource/PositionResource.java +@@ -42,10 +42,10 @@ import jakarta.ws.rs.core.MediaType; + import jakarta.ws.rs.core.Response; + import jakarta.ws.rs.core.StreamingOutput; + import java.util.ArrayList; +-import java.util.Collection; + import java.util.Date; + import java.util.List; + import java.util.LinkedList; ++import java.util.stream.Stream; + + @Path("positions") + @Produces(MediaType.APPLICATION_JSON) +@@ -62,7 +62,7 @@ public class PositionResource extends BaseResource { + private GpxExportProvider gpxExportProvider; + + @GET +- public Collection getJson( ++ public Stream getJson( + @QueryParam("deviceId") long deviceId, @QueryParam("id") List positionIds, + @QueryParam("from") Date from, @QueryParam("to") Date to) + throws StorageException { +@@ -74,18 +74,18 @@ public class PositionResource extends BaseResource { + permissionsService.checkPermission(Device.class, getUserId(), position.getDeviceId()); + positions.add(position); + } +- return positions; ++ return positions.stream(); + } else if (deviceId > 0) { + permissionsService.checkPermission(Device.class, getUserId(), deviceId); + if (from != null && to != null) { + permissionsService.checkRestriction(getUserId(), UserRestrictions::getDisableReports); +- return PositionUtil.getPositions(storage, deviceId, from, to); ++ return PositionUtil.getPositionsStream(storage, deviceId, from, to); + } else { +- return storage.getObjects(Position.class, new Request( ++ return storage.getObjectsStream(Position.class, new Request( + new Columns.All(), new Condition.LatestPositions(deviceId))); + } + } else { +- return PositionUtil.getLatestPositions(storage, getUserId()); ++ return PositionUtil.getLatestPositions(storage, getUserId()).stream(); + } + } + +diff --git a/src/main/java/org/traccar/helper/model/PositionUtil.java b/src/main/java/org/traccar/helper/model/PositionUtil.java +index ff311e306..aa8ad6ab2 100644 +--- a/src/main/java/org/traccar/helper/model/PositionUtil.java ++++ b/src/main/java/org/traccar/helper/model/PositionUtil.java +@@ -30,6 +30,7 @@ import org.traccar.storage.query.Request; + import java.util.Date; + import java.util.List; + import java.util.stream.Collectors; ++import java.util.stream.Stream; + + public final class PositionUtil { + +@@ -56,7 +57,14 @@ public final class PositionUtil { + + public static List getPositions( + Storage storage, long deviceId, Date from, Date to) throws StorageException { +- return storage.getObjects(Position.class, new Request( ++ try (var positions = getPositionsStream(storage, deviceId, from, to)) { ++ return positions.collect(Collectors.toList()); ++ } ++ } ++ ++ public static Stream getPositionsStream( ++ Storage storage, long deviceId, Date from, Date to) throws StorageException { ++ return storage.getObjectsStream(Position.class, new Request( + new Columns.All(), + new Condition.And( + new Condition.Equals("deviceId", deviceId), +diff --git a/src/main/java/org/traccar/web/WebServer.java b/src/main/java/org/traccar/web/WebServer.java +index 1101a5e9e..a01b12eba 100644 +--- a/src/main/java/org/traccar/web/WebServer.java ++++ b/src/main/java/org/traccar/web/WebServer.java +@@ -45,6 +45,7 @@ import org.traccar.LifecycleObject; + import org.traccar.api.CorsResponseFilter; + import org.traccar.api.DateParameterConverterProvider; + import org.traccar.api.ResourceErrorHandler; ++import org.traccar.api.StreamWriter; + import org.traccar.api.resource.ServerResource; + import org.traccar.api.security.SecurityRequestFilter; + import org.traccar.config.Config; +@@ -172,7 +173,8 @@ public class WebServer implements LifecycleObject { + DateParameterConverterProvider.class, + SecurityRequestFilter.class, + CorsResponseFilter.class, +- ResourceErrorHandler.class); ++ ResourceErrorHandler.class, ++ StreamWriter.class); + resourceConfig.packages(ServerResource.class.getPackage().getName()); + if (resourceConfig.getClasses().stream().filter(ServerResource.class::equals).findAny().isEmpty()) { + LOGGER.warn("Failed to load API resources"); +diff --git a/src/test/java/org/traccar/reports/ReportUtilsTest.java b/src/test/java/org/traccar/reports/ReportUtilsTest.java +index 0f14577fd..b340f516a 100644 +--- a/src/test/java/org/traccar/reports/ReportUtilsTest.java ++++ b/src/test/java/org/traccar/reports/ReportUtilsTest.java +@@ -25,6 +25,7 @@ import java.util.Iterator; + import java.util.List; + import java.util.Map; + import java.util.TimeZone; ++import java.util.stream.Stream; + + import static org.junit.jupiter.api.Assertions.assertEquals; + import static org.junit.jupiter.api.Assertions.assertFalse; +@@ -36,9 +37,9 @@ import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + + public class ReportUtilsTest extends BaseTest { +- ++ + private Storage storage; +- ++ + @BeforeEach + public void init() throws StorageException { + storage = mock(Storage.class); +@@ -76,7 +77,7 @@ public class ReportUtilsTest extends BaseTest { + Keys.REPORT_TRIP_USE_IGNITION.getKey(), useIgnition)); + return device; + } +- ++ + @Test + public void testCalculateDistance() { + Position startPosition = new Position(); +@@ -104,7 +105,7 @@ public class ReportUtilsTest extends BaseTest { + @Test + public void testDetectTripsSimple() throws Exception { + +- List data = Arrays.asList( ++ Stream data = Stream.of( + position("2016-01-01 00:00:00.000", 0, 0), + position("2016-01-01 00:01:00.000", 0, 0), + position("2016-01-01 00:02:00.000", 10, 0), +@@ -113,7 +114,7 @@ public class ReportUtilsTest extends BaseTest { + position("2016-01-01 00:05:00.000", 0, 3000), + position("2016-01-01 00:15:00.000", 0, 3000), + position("2016-01-01 00:25:00.000", 0, 3000)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 300, 180, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -132,7 +133,24 @@ public class ReportUtilsTest extends BaseTest { + assertEquals(32.4, itemTrip.getAverageSpeed(), 0.01); + assertEquals(10, itemTrip.getMaxSpeed(), 0.01); + assertEquals(3000, itemTrip.getDistance(), 0.01); ++ } + ++ @Test ++ public void testDetectStopsSimple() throws Exception { ++ Stream data = Stream.of( ++ position("2016-01-01 00:00:00.000", 0, 0), ++ position("2016-01-01 00:01:00.000", 0, 0), ++ position("2016-01-01 00:02:00.000", 10, 0), ++ position("2016-01-01 00:03:00.000", 10, 1000), ++ position("2016-01-01 00:04:00.000", 10, 2000), ++ position("2016-01-01 00:05:00.000", 0, 3000), ++ position("2016-01-01 00:15:00.000", 0, 3000), ++ position("2016-01-01 00:25:00.000", 0, 3000)); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); ++ ++ Device device = mockDevice(500, 300, 180, 900, false); ++ ReportUtils reportUtils = new ReportUtils( ++ mock(Config.class), storage, mock(PermissionsService.class), mock(VelocityEngine.class), null); + var stops = reportUtils.slowTripsAndStops(device, new Date(), new Date(), StopReportItem.class); + + assertNotNull(stops); +@@ -166,7 +184,7 @@ public class ReportUtilsTest extends BaseTest { + position("2016-01-01 00:05:00.000", 0, 3000), + position("2016-01-01 00:15:00.000", 0, 3000), + position("2016-01-01 00:25:00.000", 0, 3000)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data.stream()); + + data.get(5).set(Position.KEY_IGNITION, false); + +@@ -187,20 +205,25 @@ public class ReportUtilsTest extends BaseTest { + assertEquals(32.4, itemTrip.getAverageSpeed(), 0.01); + assertEquals(10, itemTrip.getMaxSpeed(), 0.01); + assertEquals(3000, itemTrip.getDistance(), 0.01); ++ } + +- trips = reportUtils.slowTripsAndStops(device, new Date(), new Date(), TripReportItem.class); +- +- assertNotNull(trips); +- assertFalse(trips.isEmpty()); +- +- itemTrip = trips.iterator().next(); ++ @Test ++ public void testDetectStopsSimpleWithIgnition() throws Exception { ++ List data = Arrays.asList( ++ position("2016-01-01 00:00:00.000", 0, 0), ++ position("2016-01-01 00:01:00.000", 0, 0), ++ position("2016-01-01 00:02:00.000", 10, 0), ++ position("2016-01-01 00:03:00.000", 10, 1000), ++ position("2016-01-01 00:04:00.000", 10, 2000), ++ position("2016-01-01 00:05:00.000", 0, 3000), ++ position("2016-01-01 00:15:00.000", 0, 3000), ++ position("2016-01-01 00:25:00.000", 0, 3000)); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data.stream()); + +- assertEquals(date("2016-01-01 00:02:00.000"), itemTrip.getStartTime()); +- assertEquals(date("2016-01-01 00:05:00.000"), itemTrip.getEndTime()); +- assertEquals(180000, itemTrip.getDuration()); +- assertEquals(32.4, itemTrip.getAverageSpeed(), 0.01); +- assertEquals(10, itemTrip.getMaxSpeed(), 0.01); +- assertEquals(3000, itemTrip.getDistance(), 0.01); ++ data.get(5).set(Position.KEY_IGNITION, false); ++ Device device = mockDevice(500, 300, 180, 900, true); ++ ReportUtils reportUtils = new ReportUtils( ++ mock(Config.class), storage, mock(PermissionsService.class), mock(VelocityEngine.class), null); + + var stops = reportUtils.slowTripsAndStops(device, new Date(), new Date(), StopReportItem.class); + +@@ -226,7 +249,7 @@ public class ReportUtilsTest extends BaseTest { + @Test + public void testDetectTripsWithFluctuation() throws Exception { + +- List data = Arrays.asList( ++ Stream data = Stream.of( + position("2016-01-01 00:00:00.000", 0, 0), + position("2016-01-01 00:01:00.000", 0, 0), + position("2016-01-01 00:02:00.000", 10, 0), +@@ -239,7 +262,7 @@ public class ReportUtilsTest extends BaseTest { + position("2016-01-01 00:09:00.000", 0, 7000), + position("2016-01-01 00:19:00.000", 0, 7000), + position("2016-01-01 00:29:00.000", 0, 7000)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 300, 180, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -258,6 +281,27 @@ public class ReportUtilsTest extends BaseTest { + assertEquals(32.4, itemTrip.getAverageSpeed(), 0.01); + assertEquals(10, itemTrip.getMaxSpeed(), 0.01); + assertEquals(7000, itemTrip.getDistance(), 0.01); ++ } ++ ++ @Test ++ public void testDetectStopsWithFluctuation() throws Exception { ++ Stream data = Stream.of( ++ position("2016-01-01 00:00:00.000", 0, 0), ++ position("2016-01-01 00:01:00.000", 0, 0), ++ position("2016-01-01 00:02:00.000", 10, 0), ++ position("2016-01-01 00:03:00.000", 10, 1000), ++ position("2016-01-01 00:04:00.000", 10, 2000), ++ position("2016-01-01 00:05:00.000", 10, 3000), ++ position("2016-01-01 00:06:00.000", 10, 4000), ++ position("2016-01-01 00:07:00.000", 0, 5000), ++ position("2016-01-01 00:08:00.000", 10, 6000), ++ position("2016-01-01 00:09:00.000", 0, 7000), ++ position("2016-01-01 00:19:00.000", 0, 7000), ++ position("2016-01-01 00:29:00.000", 0, 7000)); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); ++ Device device = mockDevice(500, 300, 180, 900, false); ++ ReportUtils reportUtils = new ReportUtils( ++ mock(Config.class), storage, mock(PermissionsService.class), mock(VelocityEngine.class), null); + + var stops = reportUtils.slowTripsAndStops(device, new Date(), new Date(), StopReportItem.class); + +@@ -283,14 +327,14 @@ public class ReportUtilsTest extends BaseTest { + @Test + public void testDetectStopsOnly() throws Exception { + +- var data = Arrays.asList( ++ var data = Stream.of( + position("2016-01-01 00:00:00.000", 0, 0), + position("2016-01-01 00:01:00.000", 0, 0), + position("2016-01-01 00:02:00.000", 1, 0), + position("2016-01-01 00:03:00.000", 0, 0), + position("2016-01-01 00:04:00.000", 1, 0), + position("2016-01-01 00:05:00.000", 0, 0)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 300, 200, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -312,14 +356,14 @@ public class ReportUtilsTest extends BaseTest { + @Test + public void testDetectStopsWithTripCut() throws Exception { + +- var data = Arrays.asList( ++ var data = Stream.of( + position("2016-01-01 00:00:00.000", 0, 0), + position("2016-01-01 00:01:00.000", 0, 0), + position("2016-01-01 00:02:00.000", 0, 0), + position("2016-01-01 00:03:00.000", 0, 0), + position("2016-01-01 00:04:00.000", 1, 0), + position("2016-01-01 00:05:00.000", 2, 0)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 300, 200, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -341,14 +385,14 @@ public class ReportUtilsTest extends BaseTest { + @Test + public void testDetectStopsStartedFromTrip() throws Exception { + +- var data = Arrays.asList( ++ var data = Stream.of( + position("2016-01-01 00:00:00.000", 2, 0), + position("2016-01-01 00:01:00.000", 1, 0), + position("2016-01-01 00:02:00.000", 0, 0), + position("2016-01-01 00:12:00.000", 0, 0), + position("2016-01-01 00:22:00.000", 0, 0), + position("2016-01-01 00:32:00.000", 0, 0)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 300, 200, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -391,9 +435,9 @@ public class ReportUtilsTest extends BaseTest { + } + + @Test +- public void testDetectTripAndStopByGap() throws Exception { ++ public void testDetectTripByGap() throws Exception { + +- var data = Arrays.asList( ++ var data = Stream.of( + position("2016-01-01 00:00:00.000", 7, 100), + position("2016-01-01 00:01:00.000", 7, 300), + position("2016-01-01 00:02:00.000", 5, 500), +@@ -402,7 +446,7 @@ public class ReportUtilsTest extends BaseTest { + position("2016-01-01 00:23:00.000", 2, 700), + position("2016-01-01 00:24:00.000", 5, 800), + position("2016-01-01 00:25:00.000", 5, 900)); +- when(storage.getObjects(eq(Position.class), any())).thenReturn(data); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); + + Device device = mockDevice(500, 200, 200, 900, false); + ReportUtils reportUtils = new ReportUtils( +@@ -421,7 +465,23 @@ public class ReportUtilsTest extends BaseTest { + assertEquals(4.86, itemTrip.getAverageSpeed(), 0.01); + assertEquals(7, itemTrip.getMaxSpeed(), 0.01); + assertEquals(600, itemTrip.getDistance(), 0.01); ++ } + ++ @Test ++ public void testDetectStopByGap() throws Exception { ++ var data = Stream.of( ++ position("2016-01-01 00:00:00.000", 7, 100), ++ position("2016-01-01 00:01:00.000", 7, 300), ++ position("2016-01-01 00:02:00.000", 5, 500), ++ position("2016-01-01 00:03:00.000", 5, 600), ++ position("2016-01-01 00:04:00.000", 3, 700), ++ position("2016-01-01 00:23:00.000", 2, 700), ++ position("2016-01-01 00:24:00.000", 5, 800), ++ position("2016-01-01 00:25:00.000", 5, 900)); ++ when(storage.getObjectsStream(eq(Position.class), any())).thenReturn(data); ++ ReportUtils reportUtils = new ReportUtils( ++ mock(Config.class), storage, mock(PermissionsService.class), mock(VelocityEngine.class), null); ++ Device device = mockDevice(500, 200, 200, 900, false); + var stops = reportUtils.slowTripsAndStops(device, new Date(), new Date(), StopReportItem.class); + + assertNotNull(stops); diff --git a/tasks/traccar__traccar-5610/tests/test.sh b/tasks/traccar__traccar-5610/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..257c5512d0ed80f3b6aaf994d22549a6770218d1 --- /dev/null +++ b/tasks/traccar__traccar-5610/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 7df466455f2aec3fd659e048cbcdc2beb19c30eb > "$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/traccar__traccar-5610/tests/verifier.py b/tasks/traccar__traccar-5610/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5610/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/traccar__traccar-5617/environment/Dockerfile b/tasks/traccar__traccar-5617/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..42b40b778397f539e6d8a7dcb38ccb4eb499acfd --- /dev/null +++ b/tasks/traccar__traccar-5617/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 225be0323361ce34c341365876888b508f175ed1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 225be0323361ce34c341365876888b508f175ed1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 225be0323361ce34c341365876888b508f175ed1 \ + && 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/traccar__traccar-5617/instruction.md b/tasks/traccar__traccar-5617/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f10fbd2ab50b80e90c7a6f33ec33da6a2e050bb --- /dev/null +++ b/tasks/traccar__traccar-5617/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Fix for failing docker compose healthchecks failing + +## Description + +In reference to #5615 and commit e5c8a22, the `wget` command in the Docker healthcheck used an invalid `-s` option (not supported in BusyBox wget). This caused the healthcheck to fail silently. + +This update: + +- Replaces `-s` with the correct `-S` to show server response +- Adds `--spider` to prevent wget from attempting to download and save the /api/health response as a file named `health,` which can lead to file conflicts and failing healthchecks + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `225be0323361`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5617/solution/patch.diff b/tasks/traccar__traccar-5617/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..afc343a939c058f167a86ddda09f594dcaa5fd24 --- /dev/null +++ b/tasks/traccar__traccar-5617/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/docker/compose/traccar-mysql.yaml b/docker/compose/traccar-mysql.yaml +index 2d625fd78..41c1dbc2e 100644 +--- a/docker/compose/traccar-mysql.yaml ++++ b/docker/compose/traccar-mysql.yaml +@@ -33,7 +33,7 @@ services: + DATABASE_USER: traccar + DATABASE_PASSWORD: traccar + healthcheck: +- test: [ "CMD", "wget", "-q", "-s", "http://localhost:8082/api/health" ] ++ test: [ "CMD", "wget", "--spider", "-q", "-S", "http://localhost:8082/api/health" ] + interval: 2m + timeout: 5s + start_period: 1h +diff --git a/docker/compose/traccar-timescaledb.yaml b/docker/compose/traccar-timescaledb.yaml +index 581c32983..a201fd3f2 100644 +--- a/docker/compose/traccar-timescaledb.yaml ++++ b/docker/compose/traccar-timescaledb.yaml +@@ -23,7 +23,7 @@ services: + DATABASE_USER: traccar + DATABASE_PASSWORD: traccar + healthcheck: +- test: [ "CMD", "wget", "-q", "-s", "http://localhost:8082/api/health" ] ++ test: [ "CMD", "wget", "--spider", "-q", "-S", "http://localhost:8082/api/health" ] + interval: 2m + timeout: 5s + start_period: 1h diff --git a/tasks/traccar__traccar-5617/solution/solve.sh b/tasks/traccar__traccar-5617/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5617/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/traccar__traccar-5617/task.toml b/tasks/traccar__traccar-5617/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bc1f94416ec581f93cb58222a2917c1ab8b28935 --- /dev/null +++ b/tasks/traccar__traccar-5617/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5617" +description = "Fix for failing docker compose healthchecks failing" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "225be0323361ce34c341365876888b508f175ed1" +reference = "https://github.com/traccar/traccar/pull/5617" +source_access = "auto" +built_at = "2026-11-16T16:09:42.621073+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0f77aec3aa89a6523a703beebad269725bfa3a9f9d8cf4e169dacdf779f8e399" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-07-20T21:38:22Z" +diff_format = "unified" +context_files = [ + "docker/compose/traccar-mysql.yaml", + "docker/compose/traccar-timescaledb.yaml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.455923+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9dd25eaad6834f24e12f3f8a221ce9e5745fe6e42e127ecaf7439a8822ae2244" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5617/tests/capture.py b/tasks/traccar__traccar-5617/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5617/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/traccar__traccar-5617/tests/instruction.md b/tasks/traccar__traccar-5617/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f10fbd2ab50b80e90c7a6f33ec33da6a2e050bb --- /dev/null +++ b/tasks/traccar__traccar-5617/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Fix for failing docker compose healthchecks failing + +## Description + +In reference to #5615 and commit e5c8a22, the `wget` command in the Docker healthcheck used an invalid `-s` option (not supported in BusyBox wget). This caused the healthcheck to fail silently. + +This update: + +- Replaces `-s` with the correct `-S` to show server response +- Adds `--spider` to prevent wget from attempting to download and save the /api/health response as a file named `health,` which can lead to file conflicts and failing healthchecks + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `225be0323361`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5617/tests/oracle.patch b/tasks/traccar__traccar-5617/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..afc343a939c058f167a86ddda09f594dcaa5fd24 --- /dev/null +++ b/tasks/traccar__traccar-5617/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/docker/compose/traccar-mysql.yaml b/docker/compose/traccar-mysql.yaml +index 2d625fd78..41c1dbc2e 100644 +--- a/docker/compose/traccar-mysql.yaml ++++ b/docker/compose/traccar-mysql.yaml +@@ -33,7 +33,7 @@ services: + DATABASE_USER: traccar + DATABASE_PASSWORD: traccar + healthcheck: +- test: [ "CMD", "wget", "-q", "-s", "http://localhost:8082/api/health" ] ++ test: [ "CMD", "wget", "--spider", "-q", "-S", "http://localhost:8082/api/health" ] + interval: 2m + timeout: 5s + start_period: 1h +diff --git a/docker/compose/traccar-timescaledb.yaml b/docker/compose/traccar-timescaledb.yaml +index 581c32983..a201fd3f2 100644 +--- a/docker/compose/traccar-timescaledb.yaml ++++ b/docker/compose/traccar-timescaledb.yaml +@@ -23,7 +23,7 @@ services: + DATABASE_USER: traccar + DATABASE_PASSWORD: traccar + healthcheck: +- test: [ "CMD", "wget", "-q", "-s", "http://localhost:8082/api/health" ] ++ test: [ "CMD", "wget", "--spider", "-q", "-S", "http://localhost:8082/api/health" ] + interval: 2m + timeout: 5s + start_period: 1h diff --git a/tasks/traccar__traccar-5617/tests/test.sh b/tasks/traccar__traccar-5617/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..44c23dd31890a29e504494f3f84fef6e6fb0acbb --- /dev/null +++ b/tasks/traccar__traccar-5617/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 225be0323361ce34c341365876888b508f175ed1 > "$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/traccar__traccar-5617/tests/verifier.py b/tasks/traccar__traccar-5617/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5617/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/traccar__traccar-5620/environment/Dockerfile b/tasks/traccar__traccar-5620/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d87c120d20f647f76b9b2d03cfec07ca90788e11 --- /dev/null +++ b/tasks/traccar__traccar-5620/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 63c63ec3267f32cc329cc5d582be905122d4ba4e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 63c63ec3267f32cc329cc5d582be905122d4ba4e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 63c63ec3267f32cc329cc5d582be905122d4ba4e \ + && 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/traccar__traccar-5620/instruction.md b/tasks/traccar__traccar-5620/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a9956b601ec1e0a7ceda0159f171ad2da35638d --- /dev/null +++ b/tasks/traccar__traccar-5620/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** JMAK - Fix hourmeter conversion from hours to milliseconds + +## Description + +Traccar was receiving the hourmeter value in hours—even though it expected milliseconds. This change converts the incoming hours to milliseconds (hours × 3 600 000) before processing, ensuring that the hourmeter readings display correctly in Traccar. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `63c63ec3267f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5620/solution/patch.diff b/tasks/traccar__traccar-5620/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7778d93b13f131b670ff92902e18fcfffbd77841 --- /dev/null +++ b/tasks/traccar__traccar-5620/solution/patch.diff @@ -0,0 +1,22 @@ +diff --git a/src/main/java/org/traccar/protocol/JmakProtocolDecoder.java b/src/main/java/org/traccar/protocol/JmakProtocolDecoder.java +index cd2ffe040..1faa52f18 100644 +--- a/src/main/java/org/traccar/protocol/JmakProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/JmakProtocolDecoder.java +@@ -148,7 +148,7 @@ public class JmakProtocolDecoder extends BaseProtocolDecoder { + } + + if (BitUtil.check(mask, 16)) { +- position.set(Position.KEY_HOURS, Double.parseDouble(values[index++])); ++ position.set(Position.KEY_HOURS, Double.parseDouble(values[index++]) * 3600000); + } + + if (BitUtil.check(mask, 17)) { +@@ -253,7 +253,7 @@ public class JmakProtocolDecoder extends BaseProtocolDecoder { + } + + if (BitUtil.check(mask, 1)) { +- position.set(Position.KEY_HOURS, Double.parseDouble(values[index++])); ++ position.set(Position.KEY_HOURS, Double.parseDouble(values[index++]) * 3600000); + } + + if (BitUtil.check(mask, 2)) { diff --git a/tasks/traccar__traccar-5620/solution/solve.sh b/tasks/traccar__traccar-5620/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5620/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/traccar__traccar-5620/task.toml b/tasks/traccar__traccar-5620/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f32d54761550f4835d33659269ef9157a811bbf2 --- /dev/null +++ b/tasks/traccar__traccar-5620/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5620" +description = "JMAK - Fix hourmeter conversion from hours to milliseconds" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "63c63ec3267f32cc329cc5d582be905122d4ba4e" +reference = "https://github.com/traccar/traccar/pull/5620" +source_access = "auto" +built_at = "2026-11-16T16:09:42.619517+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:276ee07296fb74180b28981dd8097062ee5824a917c3e6dceaaf12d081dd7cd1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-07-25T15:17:51Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/JmakProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.456482+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:60cf32cd85abc7274c7ee50f9ca0459d1ffbd068bf6e5acced046d4ebc322fea" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5620/tests/capture.py b/tasks/traccar__traccar-5620/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5620/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/traccar__traccar-5620/tests/instruction.md b/tasks/traccar__traccar-5620/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a9956b601ec1e0a7ceda0159f171ad2da35638d --- /dev/null +++ b/tasks/traccar__traccar-5620/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** JMAK - Fix hourmeter conversion from hours to milliseconds + +## Description + +Traccar was receiving the hourmeter value in hours—even though it expected milliseconds. This change converts the incoming hours to milliseconds (hours × 3 600 000) before processing, ensuring that the hourmeter readings display correctly in Traccar. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `63c63ec3267f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5620/tests/oracle.patch b/tasks/traccar__traccar-5620/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7778d93b13f131b670ff92902e18fcfffbd77841 --- /dev/null +++ b/tasks/traccar__traccar-5620/tests/oracle.patch @@ -0,0 +1,22 @@ +diff --git a/src/main/java/org/traccar/protocol/JmakProtocolDecoder.java b/src/main/java/org/traccar/protocol/JmakProtocolDecoder.java +index cd2ffe040..1faa52f18 100644 +--- a/src/main/java/org/traccar/protocol/JmakProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/JmakProtocolDecoder.java +@@ -148,7 +148,7 @@ public class JmakProtocolDecoder extends BaseProtocolDecoder { + } + + if (BitUtil.check(mask, 16)) { +- position.set(Position.KEY_HOURS, Double.parseDouble(values[index++])); ++ position.set(Position.KEY_HOURS, Double.parseDouble(values[index++]) * 3600000); + } + + if (BitUtil.check(mask, 17)) { +@@ -253,7 +253,7 @@ public class JmakProtocolDecoder extends BaseProtocolDecoder { + } + + if (BitUtil.check(mask, 1)) { +- position.set(Position.KEY_HOURS, Double.parseDouble(values[index++])); ++ position.set(Position.KEY_HOURS, Double.parseDouble(values[index++]) * 3600000); + } + + if (BitUtil.check(mask, 2)) { diff --git a/tasks/traccar__traccar-5620/tests/test.sh b/tasks/traccar__traccar-5620/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a8b7da28fa634360e9dbfc59a02357f095f0f319 --- /dev/null +++ b/tasks/traccar__traccar-5620/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 63c63ec3267f32cc329cc5d582be905122d4ba4e > "$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/traccar__traccar-5620/tests/verifier.py b/tasks/traccar__traccar-5620/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5620/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/traccar__traccar-5621/environment/Dockerfile b/tasks/traccar__traccar-5621/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b2d2de7a6f0be183a8efde1bc1d359165c5dbe52 --- /dev/null +++ b/tasks/traccar__traccar-5621/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b65df7cabe934966fc5726e597b57f02cfcece47 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b65df7cabe934966fc5726e597b57f02cfcece47 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b65df7cabe934966fc5726e597b57f02cfcece47 \ + && 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/traccar__traccar-5621/instruction.md b/tasks/traccar__traccar-5621/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ed208689b758d3ba5f8978d198ad61a415f09fd6 --- /dev/null +++ b/tasks/traccar__traccar-5621/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update Minifinder2ProtocolEncoder.java + +## Description + +Actually send Minifinder config read command. + +Also added an option to send arbitrary config data to the device. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b65df7cabe93`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5621/solution/patch.diff b/tasks/traccar__traccar-5621/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..74ee55f50ed3248bef7bddea0c6a1675456b52c1 --- /dev/null +++ b/tasks/traccar__traccar-5621/solution/patch.diff @@ -0,0 +1,29 @@ +diff --git a/src/main/java/org/traccar/protocol/Minifinder2ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Minifinder2ProtocolEncoder.java +index 6e330a4dd..77a4454d0 100644 +--- a/src/main/java/org/traccar/protocol/Minifinder2ProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/Minifinder2ProtocolEncoder.java +@@ -20,6 +20,7 @@ import io.netty.buffer.Unpooled; + import org.traccar.BaseProtocolEncoder; + import org.traccar.Protocol; + import org.traccar.helper.Checksum; ++import org.traccar.helper.DataConverter; + import org.traccar.model.Command; + + import java.nio.charset.StandardCharsets; +@@ -50,8 +51,14 @@ public class Minifinder2ProtocolEncoder extends BaseProtocolEncoder { + if (command.getType().equals(Command.TYPE_CONFIGURATION)) { + ByteBuf content = Unpooled.buffer(); + content.writeByte(Minifinder2ProtocolDecoder.MSG_CONFIGURATION); +- content.writeByte(1); // length +- content.writeByte(0xF0); // type ++ if (command.hasAttribute(Command.KEY_DATA)) { ++ byte[] data = DataConverter.parseHex(command.getString(Command.KEY_DATA)); ++ content.writeBytes(data); ++ } else { ++ content.writeByte(1); // length ++ content.writeByte(0xF0); // type ++ } ++ return encodeContent(content); + } + + if ("Nano".equalsIgnoreCase(getDeviceModel(command.getDeviceId()))) { diff --git a/tasks/traccar__traccar-5621/solution/solve.sh b/tasks/traccar__traccar-5621/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5621/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/traccar__traccar-5621/task.toml b/tasks/traccar__traccar-5621/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0fb957bb1ca02ce6cb4bebfbeaa1b453f338275f --- /dev/null +++ b/tasks/traccar__traccar-5621/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5621" +description = "Update Minifinder2ProtocolEncoder.java" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "b65df7cabe934966fc5726e597b57f02cfcece47" +reference = "https://github.com/traccar/traccar/pull/5621" +source_access = "auto" +built_at = "2026-11-16T16:09:42.618101+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:47452982c8547985e99f381518d4da60865e1efc9728076fb276109409835401" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-07-28T20:05:38Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Minifinder2ProtocolEncoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 11 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.456976+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ca15c113318bdef04358f5c7350c1aa17acf04b8d28ddae69c53569cb896c60e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5621/tests/capture.py b/tasks/traccar__traccar-5621/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5621/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/traccar__traccar-5621/tests/instruction.md b/tasks/traccar__traccar-5621/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ed208689b758d3ba5f8978d198ad61a415f09fd6 --- /dev/null +++ b/tasks/traccar__traccar-5621/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update Minifinder2ProtocolEncoder.java + +## Description + +Actually send Minifinder config read command. + +Also added an option to send arbitrary config data to the device. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b65df7cabe93`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5621/tests/oracle.patch b/tasks/traccar__traccar-5621/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..74ee55f50ed3248bef7bddea0c6a1675456b52c1 --- /dev/null +++ b/tasks/traccar__traccar-5621/tests/oracle.patch @@ -0,0 +1,29 @@ +diff --git a/src/main/java/org/traccar/protocol/Minifinder2ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Minifinder2ProtocolEncoder.java +index 6e330a4dd..77a4454d0 100644 +--- a/src/main/java/org/traccar/protocol/Minifinder2ProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/Minifinder2ProtocolEncoder.java +@@ -20,6 +20,7 @@ import io.netty.buffer.Unpooled; + import org.traccar.BaseProtocolEncoder; + import org.traccar.Protocol; + import org.traccar.helper.Checksum; ++import org.traccar.helper.DataConverter; + import org.traccar.model.Command; + + import java.nio.charset.StandardCharsets; +@@ -50,8 +51,14 @@ public class Minifinder2ProtocolEncoder extends BaseProtocolEncoder { + if (command.getType().equals(Command.TYPE_CONFIGURATION)) { + ByteBuf content = Unpooled.buffer(); + content.writeByte(Minifinder2ProtocolDecoder.MSG_CONFIGURATION); +- content.writeByte(1); // length +- content.writeByte(0xF0); // type ++ if (command.hasAttribute(Command.KEY_DATA)) { ++ byte[] data = DataConverter.parseHex(command.getString(Command.KEY_DATA)); ++ content.writeBytes(data); ++ } else { ++ content.writeByte(1); // length ++ content.writeByte(0xF0); // type ++ } ++ return encodeContent(content); + } + + if ("Nano".equalsIgnoreCase(getDeviceModel(command.getDeviceId()))) { diff --git a/tasks/traccar__traccar-5621/tests/test.sh b/tasks/traccar__traccar-5621/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..583927476d21013edfe3db325e8938893ef7f3bb --- /dev/null +++ b/tasks/traccar__traccar-5621/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 b65df7cabe934966fc5726e597b57f02cfcece47 > "$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/traccar__traccar-5621/tests/verifier.py b/tasks/traccar__traccar-5621/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5621/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/traccar__traccar-5628/environment/Dockerfile b/tasks/traccar__traccar-5628/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..14f2569983307fe5c485b8003ce7294d3fe289bd --- /dev/null +++ b/tasks/traccar__traccar-5628/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin df003df7a6fc22eb0bc01ce8791ecfdb8972f142 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard df003df7a6fc22eb0bc01ce8791ecfdb8972f142 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base df003df7a6fc22eb0bc01ce8791ecfdb8972f142 \ + && 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/traccar__traccar-5628/instruction.md b/tasks/traccar__traccar-5628/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21d32bee29e3e452ac534a13f86455df80e07170 --- /dev/null +++ b/tasks/traccar__traccar-5628/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Add support to decode car acc status for h02 protocol + +## Description + +This PR should add support for the ST906 battery reporting provided as reply to CXZT command: + +``` +2025-08-09 21:19:15 INFO: [T13cb679d: h02 > 1.2.3.4] CXZT +2025-08-09 21:19:15 INFO: [T13cb679d: h02 < 1.2.3.4] *HQ,11223344,SMS,ST906(70SACD)_TQ_V_2.0 2024/06/07\nID:11223344\nIP:1.2.3.4 5013\nUT:30,30,300\nVOLT:13.1V\nAPN:internet.example.com\nGPS:A-22-20\nGSM:26# +``` +My plan is to run CXZT command using API every hour and use computed attributes to have it in the logs and screen. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `df003df7a6fc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5628/solution/patch.diff b/tasks/traccar__traccar-5628/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4ec0af951a501ccbcc40bdd39b8aabdfaf147ec2 --- /dev/null +++ b/tasks/traccar__traccar-5628/solution/patch.diff @@ -0,0 +1,84 @@ +diff --git a/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java b/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java +index 477c68b6d..1c23fb03c 100644 +--- a/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java +@@ -300,6 +300,15 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { + .any() + .compile(); + ++ /* reply to CXZT command on ST906 V2 tracker */ ++ private static final Pattern PATTERN_SMS = new PatternBuilder() ++ .text("*HQ,") ++ .number("(d+),") // id ++ .text("SMS,") ++ .expression("(.+)") ++ .text("#") ++ .compile(); ++ + private void sendResponse(Channel channel, SocketAddress remoteAddress, String id, String type) { + if (channel != null && id != null) { + String response; +@@ -525,6 +534,26 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { + return position; + } + ++ private Position decodeSms(String sentence, Channel channel, SocketAddress remoteAddress) { ++ ++ Parser parser = new Parser(PATTERN_SMS, sentence); ++ if (!parser.matches()) { ++ return null; ++ } ++ ++ DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); ++ if (deviceSession == null) { ++ return null; ++ } ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ position.set(Position.KEY_RESULT, parser.next()); ++ getLastLocation(position, null); ++ return position; ++ } ++ ++ + private Position decodeVp1(String sentence, Channel channel, SocketAddress remoteAddress) { + + Parser parser = new Parser(PATTERN_VP1, sentence); +@@ -623,6 +652,7 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { + case "LINK" -> decodeLink(sentence, channel, remoteAddress); + case "V3" -> decodeV3(sentence, channel, remoteAddress); + case "VP1" -> decodeVp1(sentence, channel, remoteAddress); ++ case "SMS" -> decodeSms(sentence, channel, remoteAddress); + default -> decodeText(sentence, channel, remoteAddress); + }; + } else { +diff --git a/src/test/java/org/traccar/protocol/H02ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/H02ProtocolDecoderTest.java +index a63488960..d78ab08b1 100644 +--- a/src/test/java/org/traccar/protocol/H02ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/H02ProtocolDecoderTest.java +@@ -267,7 +267,23 @@ public class H02ProtocolDecoderTest extends ProtocolTest { + + verifyPosition(decoder, binary( + "24971305007205201916101533335008000073206976000000effffbffff000252776566060000000000000000000049")); +- ++ verifyAttribute(decoder, buffer( ++ "*HQ,5226073533,SMS,ST906(70SACD)_TQ_V_2.0 2024/06/07\\n" + // ++ "ID:5226073533\\n" + // ++ "IP:1.2.3.4 5013\\n" + // ++ "UT:30,30,300\\n" + // ++ "VOLT:12.9V\\n" + // ++ "APN:internet.example.com\\n" + // ++ "GPS:A-24-23\\n" + // ++ "GSM:26#"), ++ Position.KEY_RESULT, "ST906(70SACD)_TQ_V_2.0 2024/06/07\\n" + // ++ "ID:5226073533\\n" + // ++ "IP:1.2.3.4 5013\\n" + // ++ "UT:30,30,300\\n" + // ++ "VOLT:12.9V\\n" + // ++ "APN:internet.example.com\\n" + // ++ "GPS:A-24-23\\n" + // ++ "GSM:26"); + } + + @Test diff --git a/tasks/traccar__traccar-5628/solution/solve.sh b/tasks/traccar__traccar-5628/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5628/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/traccar__traccar-5628/task.toml b/tasks/traccar__traccar-5628/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ef7deb05bc86dd30bdc695e43b4591e751f4d88d --- /dev/null +++ b/tasks/traccar__traccar-5628/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5628" +description = "Add support to decode car acc status for h02 protocol" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "df003df7a6fc22eb0bc01ce8791ecfdb8972f142" +reference = "https://github.com/traccar/traccar/pull/5628" +source_access = "auto" +built_at = "2026-11-16T16:09:42.616801+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:926a5b3b79cb96887a96ce60337c3a2a35cdd5c46d1a6966a8cfc6400cac9e83" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-08-11T08:12:00Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/H02ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/H02ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 48 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.457494+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1a2ed1476c299a50bc700b28f03e0deecf7cdc73a74319257758232850ee877c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5628/tests/capture.py b/tasks/traccar__traccar-5628/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5628/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/traccar__traccar-5628/tests/instruction.md b/tasks/traccar__traccar-5628/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21d32bee29e3e452ac534a13f86455df80e07170 --- /dev/null +++ b/tasks/traccar__traccar-5628/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Add support to decode car acc status for h02 protocol + +## Description + +This PR should add support for the ST906 battery reporting provided as reply to CXZT command: + +``` +2025-08-09 21:19:15 INFO: [T13cb679d: h02 > 1.2.3.4] CXZT +2025-08-09 21:19:15 INFO: [T13cb679d: h02 < 1.2.3.4] *HQ,11223344,SMS,ST906(70SACD)_TQ_V_2.0 2024/06/07\nID:11223344\nIP:1.2.3.4 5013\nUT:30,30,300\nVOLT:13.1V\nAPN:internet.example.com\nGPS:A-22-20\nGSM:26# +``` +My plan is to run CXZT command using API every hour and use computed attributes to have it in the logs and screen. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `df003df7a6fc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5628/tests/oracle.patch b/tasks/traccar__traccar-5628/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4ec0af951a501ccbcc40bdd39b8aabdfaf147ec2 --- /dev/null +++ b/tasks/traccar__traccar-5628/tests/oracle.patch @@ -0,0 +1,84 @@ +diff --git a/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java b/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java +index 477c68b6d..1c23fb03c 100644 +--- a/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java +@@ -300,6 +300,15 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { + .any() + .compile(); + ++ /* reply to CXZT command on ST906 V2 tracker */ ++ private static final Pattern PATTERN_SMS = new PatternBuilder() ++ .text("*HQ,") ++ .number("(d+),") // id ++ .text("SMS,") ++ .expression("(.+)") ++ .text("#") ++ .compile(); ++ + private void sendResponse(Channel channel, SocketAddress remoteAddress, String id, String type) { + if (channel != null && id != null) { + String response; +@@ -525,6 +534,26 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { + return position; + } + ++ private Position decodeSms(String sentence, Channel channel, SocketAddress remoteAddress) { ++ ++ Parser parser = new Parser(PATTERN_SMS, sentence); ++ if (!parser.matches()) { ++ return null; ++ } ++ ++ DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); ++ if (deviceSession == null) { ++ return null; ++ } ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ position.set(Position.KEY_RESULT, parser.next()); ++ getLastLocation(position, null); ++ return position; ++ } ++ ++ + private Position decodeVp1(String sentence, Channel channel, SocketAddress remoteAddress) { + + Parser parser = new Parser(PATTERN_VP1, sentence); +@@ -623,6 +652,7 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { + case "LINK" -> decodeLink(sentence, channel, remoteAddress); + case "V3" -> decodeV3(sentence, channel, remoteAddress); + case "VP1" -> decodeVp1(sentence, channel, remoteAddress); ++ case "SMS" -> decodeSms(sentence, channel, remoteAddress); + default -> decodeText(sentence, channel, remoteAddress); + }; + } else { +diff --git a/src/test/java/org/traccar/protocol/H02ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/H02ProtocolDecoderTest.java +index a63488960..d78ab08b1 100644 +--- a/src/test/java/org/traccar/protocol/H02ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/H02ProtocolDecoderTest.java +@@ -267,7 +267,23 @@ public class H02ProtocolDecoderTest extends ProtocolTest { + + verifyPosition(decoder, binary( + "24971305007205201916101533335008000073206976000000effffbffff000252776566060000000000000000000049")); +- ++ verifyAttribute(decoder, buffer( ++ "*HQ,5226073533,SMS,ST906(70SACD)_TQ_V_2.0 2024/06/07\\n" + // ++ "ID:5226073533\\n" + // ++ "IP:1.2.3.4 5013\\n" + // ++ "UT:30,30,300\\n" + // ++ "VOLT:12.9V\\n" + // ++ "APN:internet.example.com\\n" + // ++ "GPS:A-24-23\\n" + // ++ "GSM:26#"), ++ Position.KEY_RESULT, "ST906(70SACD)_TQ_V_2.0 2024/06/07\\n" + // ++ "ID:5226073533\\n" + // ++ "IP:1.2.3.4 5013\\n" + // ++ "UT:30,30,300\\n" + // ++ "VOLT:12.9V\\n" + // ++ "APN:internet.example.com\\n" + // ++ "GPS:A-24-23\\n" + // ++ "GSM:26"); + } + + @Test diff --git a/tasks/traccar__traccar-5628/tests/test.sh b/tasks/traccar__traccar-5628/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4061a40d6855ecdf178a8f5778ca6c4ba934f2f0 --- /dev/null +++ b/tasks/traccar__traccar-5628/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 df003df7a6fc22eb0bc01ce8791ecfdb8972f142 > "$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/traccar__traccar-5628/tests/verifier.py b/tasks/traccar__traccar-5628/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5628/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/traccar__traccar-5663/environment/Dockerfile b/tasks/traccar__traccar-5663/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..641eb2c9a8f70f05167f8f8077d4d660e80cb93e --- /dev/null +++ b/tasks/traccar__traccar-5663/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f0c270f6f8bb9678003273159c3b5f464723335a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f0c270f6f8bb9678003273159c3b5f464723335a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f0c270f6f8bb9678003273159c3b5f464723335a \ + && 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/traccar__traccar-5663/instruction.md b/tasks/traccar__traccar-5663/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..48cf4d731399af7e35397de3e5ee221837e5913c --- /dev/null +++ b/tasks/traccar__traccar-5663/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** Updated NMEA protocol + +## Description + +Updated NMEA (T55) protocol: +- Added the altitude and number of sats to GGA message +- Added GLL message parser + +Updated PositionLogger to be able to show the altitude if it is configured in `logger.attributes`. + +But the speed, course, altitude any many other parameters in the `Position` structure are not optional and may contain invalid values. For example Ebyte E108-GN03G reports the following +``` +$GNGGA,193526.000,5332.16315,N,04921.33849,E,1,15,1.5,141.0,M,0.6,M,,*76\r\n +$GNGLL,5332.16315,N,04921.33849,E,193526.000,A,A*41\r\n +$GNGSA,A,3,03,06,12,24,25,32,195,,,,,,2.7,1.5,2.2,1*0B\r\n +$GNGSA,A,3,14,27,40,42,45,,,,,,,,2.7,1.5,2.2,4*36\r\n +$GNGSA,A,3,76,75,67,,,,,,,,,,2.7,1.5,2.2,2*31\r\n +$GPGSV,3,1,11,03,12,034,37,06,50,110,13,11,31,159,,12,57,286,38,0*6C\r\n +$GPGSV,3,2,11,17,24,062,35,19,49,065,35,22,16,105,35,24,49,214,19,0*67\r\n +$GPGSV,3,3,11,25,25,288,30,32,17,312,21,195,24,065,22,0*68\r\n +$BDGSV,2,1,07,14,07,359,29,27,36,056,23,33,,,37,36,79,223,30,0*4B\r\n +$BDGSV,2,2,07,40,30,062,25,42,07,334,16,45,44,297,33,0*48\r\n +$GLGSV,3,1,09,74,37,125,,66,15,299,,86,06,198,,76,25,310,35,0*7F\r\n +$GLGSV,3,2,09,75,85,357,32,84,55,052,,83,05,029,,85,59,170,,0*77\r\n +$GLGSV,3,3,09,67,15,354,25,0*40\r\n +$GNRMC,193526.000,A,5332.16315,N,04921.33849,E,1.91,0.00,110925,,,A,V*02\r\n +$GNVTG,0.00,T,,M,0.00,N,0.00,K,A*23\r\n +$GNZDA,193526.000,11,09,2025,00,00*4E\r\n +$GPTXT,01,01,01,ANTENNA OPEN*25\r\n +$GNDHV,193526.000,0.00,0.000,0.000,0.000,0.00,,,,,M*08\r\n +$GNGST,193526.000,23.4,,,,8.3,2.6,12.2*56\r\n +``` +Now GGA contains the altitude. RMC contains the speed. GLL contains coordinates but the speed and altitude are missing. The datetime of all messages is the same. +The log shows: +``` +id: 192.168.1.11, time: 2025-09-11 23:35:26, lat: 53.53605, lon: 49.35564, course: 0.0, altitude: 141.0, sat: 15, hdop: 1.5 +id: 192.168.1.11, time: 2025-09-11 23:35:26, lat: 53.53605, lon: 49.35564, course: 0.0 +id: 192.168.1.11, time: 2025-09-11 23:35:26, lat: 53.53605, lon: 49.35564, speed: 1.9, course: 0.0 +``` +It would be great to update records with the same time and missing data instead of adding new records. Now the diagram for the speed or altitude looks like a comb. And the device properties always shows the altitude 0.0 because the last message RMC does not contains the altitude. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f0c270f6f8bb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5663/solution/patch.diff b/tasks/traccar__traccar-5663/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..14a9b5c5a4ba19fdf54e6bfd6964afca92b151af --- /dev/null +++ b/tasks/traccar__traccar-5663/solution/patch.diff @@ -0,0 +1,100 @@ +diff --git a/src/main/java/org/traccar/helper/PositionLogger.java b/src/main/java/org/traccar/helper/PositionLogger.java +index 9f149edf4..f3a6a2d0e 100644 +--- a/src/main/java/org/traccar/helper/PositionLogger.java ++++ b/src/main/java/org/traccar/helper/PositionLogger.java +@@ -65,6 +65,9 @@ public class PositionLogger { + case "course": + builder.append(", course: ").append(String.format("%.1f", position.getCourse())); + break; ++ case "altitude": ++ builder.append(", altitude: ").append(String.format("%.1f", position.getAltitude())); ++ break; + case "accuracy": + if (position.getAccuracy() > 0) { + builder.append(", accuracy: ").append(String.format("%.1f", position.getAccuracy())); +diff --git a/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java b/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java +index 2538c914d..426c10aec 100644 +--- a/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java +@@ -72,6 +72,22 @@ public class T55ProtocolDecoder extends BaseProtocolDecoder { + .expression("([NS]),") + .number("(d+)(dd.d+),") // longitude + .expression("([EW]),") ++ .number("(d+),") // fix quality 0..8 ++ .number("(d+),") // sat used 00..99 ++ .number("(d+.?d*),") // HDOP ++ .number("(-?d+.?d*),") // altitude ++ .any() ++ .compile(); ++ ++ private static final Pattern PATTERN_GPGLL = new PatternBuilder() ++ .text("$") ++ .expression("G[PLN]GLL,") ++ .number("(d+)(dd.d+),") // latitude ++ .expression("([NS]),") ++ .number("(d+)(dd.d+),") // longitude ++ .expression("([EW]),") ++ .number("(dd)(dd)(dd).?d*,") // time (hhmmss) ++ .expression("([AV]),") // validity + .any() + .compile(); + +@@ -244,9 +260,35 @@ public class T55ProtocolDecoder extends BaseProtocolDecoder { + .setTime(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0)); + position.setTime(dateBuilder.getDate()); + +- position.setValid(true); + position.setLatitude(parser.nextCoordinate()); + position.setLongitude(parser.nextCoordinate()); ++ position.setValid(parser.nextInt(0) > 0); ++ position.set(Position.KEY_SATELLITES, parser.nextInt()); ++ position.set(Position.KEY_HDOP, parser.nextDouble()); ++ position.setAltitude(parser.nextDouble()); ++ ++ return position; ++ } ++ ++ private Position decodeGpgll(DeviceSession deviceSession, String sentence) { ++ ++ Parser parser = new Parser(PATTERN_GPGLL, sentence); ++ if (!parser.matches()) { ++ return null; ++ } ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ position.setLatitude(parser.nextCoordinate()); ++ position.setLongitude(parser.nextCoordinate()); ++ ++ DateBuilder dateBuilder = new DateBuilder() ++ .setCurrentDate() ++ .setTime(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0)); ++ position.setTime(dateBuilder.getDate()); ++ ++ position.setValid(parser.next().equals("A")); + + return position; + } +@@ -449,6 +491,8 @@ public class T55ProtocolDecoder extends BaseProtocolDecoder { + return decodeGprmc(deviceSession, sentence, remoteAddress, channel); + } else if (sentence.startsWith("GGA", 3) && deviceSession != null) { + return decodeGpgga(deviceSession, sentence); ++ } else if (sentence.startsWith("GLL", 3) && deviceSession != null) { ++ return decodeGpgll(deviceSession, sentence); + } else if (sentence.startsWith("$GPRMA") && deviceSession != null) { + return decodeGprma(deviceSession, sentence); + } else if (sentence.startsWith("$TRCCR") && deviceSession != null) { +diff --git a/src/test/java/org/traccar/protocol/T55ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/T55ProtocolDecoderTest.java +index 91020714c..525e9737a 100644 +--- a/src/test/java/org/traccar/protocol/T55ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/T55ProtocolDecoderTest.java +@@ -23,7 +23,7 @@ public class T55ProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, text( + "$GNGGA,164414.90,4650.5156500,N,01246.1059604,E,1,12,0.84,740.729,M,44.804,M,,*4E")); + +- verifyNull(decoder, text( ++ verifyPosition(decoder, text( + "$GNGLL,4650.5156500,N,01246.1059604,E,164414.90,A,A*77")); + + verifyPosition(decoder, text( diff --git a/tasks/traccar__traccar-5663/solution/solve.sh b/tasks/traccar__traccar-5663/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5663/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/traccar__traccar-5663/task.toml b/tasks/traccar__traccar-5663/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..551c281dce6893fccb56cf8b030f3721bb8366bc --- /dev/null +++ b/tasks/traccar__traccar-5663/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5663" +description = "Updated NMEA protocol" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "f0c270f6f8bb9678003273159c3b5f464723335a" +reference = "https://github.com/traccar/traccar/pull/5663" +source_access = "auto" +built_at = "2026-11-16T16:09:42.615267+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ce1aed1092ff49b4f125deacb179c66d2233bf3c4043971bc80fa512acda959e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-09-13T19:33:53Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/helper/PositionLogger.java", + "src/main/java/org/traccar/protocol/T55ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/T55ProtocolDecoderTest.java", +] +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:03.474954+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b88fffb1c1ecefa7e03e819393892df9cd224a4ac3bf841a0e3bf632982e9b5e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5663/tests/capture.py b/tasks/traccar__traccar-5663/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5663/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/traccar__traccar-5663/tests/instruction.md b/tasks/traccar__traccar-5663/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..48cf4d731399af7e35397de3e5ee221837e5913c --- /dev/null +++ b/tasks/traccar__traccar-5663/tests/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** Updated NMEA protocol + +## Description + +Updated NMEA (T55) protocol: +- Added the altitude and number of sats to GGA message +- Added GLL message parser + +Updated PositionLogger to be able to show the altitude if it is configured in `logger.attributes`. + +But the speed, course, altitude any many other parameters in the `Position` structure are not optional and may contain invalid values. For example Ebyte E108-GN03G reports the following +``` +$GNGGA,193526.000,5332.16315,N,04921.33849,E,1,15,1.5,141.0,M,0.6,M,,*76\r\n +$GNGLL,5332.16315,N,04921.33849,E,193526.000,A,A*41\r\n +$GNGSA,A,3,03,06,12,24,25,32,195,,,,,,2.7,1.5,2.2,1*0B\r\n +$GNGSA,A,3,14,27,40,42,45,,,,,,,,2.7,1.5,2.2,4*36\r\n +$GNGSA,A,3,76,75,67,,,,,,,,,,2.7,1.5,2.2,2*31\r\n +$GPGSV,3,1,11,03,12,034,37,06,50,110,13,11,31,159,,12,57,286,38,0*6C\r\n +$GPGSV,3,2,11,17,24,062,35,19,49,065,35,22,16,105,35,24,49,214,19,0*67\r\n +$GPGSV,3,3,11,25,25,288,30,32,17,312,21,195,24,065,22,0*68\r\n +$BDGSV,2,1,07,14,07,359,29,27,36,056,23,33,,,37,36,79,223,30,0*4B\r\n +$BDGSV,2,2,07,40,30,062,25,42,07,334,16,45,44,297,33,0*48\r\n +$GLGSV,3,1,09,74,37,125,,66,15,299,,86,06,198,,76,25,310,35,0*7F\r\n +$GLGSV,3,2,09,75,85,357,32,84,55,052,,83,05,029,,85,59,170,,0*77\r\n +$GLGSV,3,3,09,67,15,354,25,0*40\r\n +$GNRMC,193526.000,A,5332.16315,N,04921.33849,E,1.91,0.00,110925,,,A,V*02\r\n +$GNVTG,0.00,T,,M,0.00,N,0.00,K,A*23\r\n +$GNZDA,193526.000,11,09,2025,00,00*4E\r\n +$GPTXT,01,01,01,ANTENNA OPEN*25\r\n +$GNDHV,193526.000,0.00,0.000,0.000,0.000,0.00,,,,,M*08\r\n +$GNGST,193526.000,23.4,,,,8.3,2.6,12.2*56\r\n +``` +Now GGA contains the altitude. RMC contains the speed. GLL contains coordinates but the speed and altitude are missing. The datetime of all messages is the same. +The log shows: +``` +id: 192.168.1.11, time: 2025-09-11 23:35:26, lat: 53.53605, lon: 49.35564, course: 0.0, altitude: 141.0, sat: 15, hdop: 1.5 +id: 192.168.1.11, time: 2025-09-11 23:35:26, lat: 53.53605, lon: 49.35564, course: 0.0 +id: 192.168.1.11, time: 2025-09-11 23:35:26, lat: 53.53605, lon: 49.35564, speed: 1.9, course: 0.0 +``` +It would be great to update records with the same time and missing data instead of adding new records. Now the diagram for the speed or altitude looks like a comb. And the device properties always shows the altitude 0.0 because the last message RMC does not contains the altitude. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f0c270f6f8bb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5663/tests/oracle.patch b/tasks/traccar__traccar-5663/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..14a9b5c5a4ba19fdf54e6bfd6964afca92b151af --- /dev/null +++ b/tasks/traccar__traccar-5663/tests/oracle.patch @@ -0,0 +1,100 @@ +diff --git a/src/main/java/org/traccar/helper/PositionLogger.java b/src/main/java/org/traccar/helper/PositionLogger.java +index 9f149edf4..f3a6a2d0e 100644 +--- a/src/main/java/org/traccar/helper/PositionLogger.java ++++ b/src/main/java/org/traccar/helper/PositionLogger.java +@@ -65,6 +65,9 @@ public class PositionLogger { + case "course": + builder.append(", course: ").append(String.format("%.1f", position.getCourse())); + break; ++ case "altitude": ++ builder.append(", altitude: ").append(String.format("%.1f", position.getAltitude())); ++ break; + case "accuracy": + if (position.getAccuracy() > 0) { + builder.append(", accuracy: ").append(String.format("%.1f", position.getAccuracy())); +diff --git a/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java b/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java +index 2538c914d..426c10aec 100644 +--- a/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java +@@ -72,6 +72,22 @@ public class T55ProtocolDecoder extends BaseProtocolDecoder { + .expression("([NS]),") + .number("(d+)(dd.d+),") // longitude + .expression("([EW]),") ++ .number("(d+),") // fix quality 0..8 ++ .number("(d+),") // sat used 00..99 ++ .number("(d+.?d*),") // HDOP ++ .number("(-?d+.?d*),") // altitude ++ .any() ++ .compile(); ++ ++ private static final Pattern PATTERN_GPGLL = new PatternBuilder() ++ .text("$") ++ .expression("G[PLN]GLL,") ++ .number("(d+)(dd.d+),") // latitude ++ .expression("([NS]),") ++ .number("(d+)(dd.d+),") // longitude ++ .expression("([EW]),") ++ .number("(dd)(dd)(dd).?d*,") // time (hhmmss) ++ .expression("([AV]),") // validity + .any() + .compile(); + +@@ -244,9 +260,35 @@ public class T55ProtocolDecoder extends BaseProtocolDecoder { + .setTime(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0)); + position.setTime(dateBuilder.getDate()); + +- position.setValid(true); + position.setLatitude(parser.nextCoordinate()); + position.setLongitude(parser.nextCoordinate()); ++ position.setValid(parser.nextInt(0) > 0); ++ position.set(Position.KEY_SATELLITES, parser.nextInt()); ++ position.set(Position.KEY_HDOP, parser.nextDouble()); ++ position.setAltitude(parser.nextDouble()); ++ ++ return position; ++ } ++ ++ private Position decodeGpgll(DeviceSession deviceSession, String sentence) { ++ ++ Parser parser = new Parser(PATTERN_GPGLL, sentence); ++ if (!parser.matches()) { ++ return null; ++ } ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ position.setLatitude(parser.nextCoordinate()); ++ position.setLongitude(parser.nextCoordinate()); ++ ++ DateBuilder dateBuilder = new DateBuilder() ++ .setCurrentDate() ++ .setTime(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0)); ++ position.setTime(dateBuilder.getDate()); ++ ++ position.setValid(parser.next().equals("A")); + + return position; + } +@@ -449,6 +491,8 @@ public class T55ProtocolDecoder extends BaseProtocolDecoder { + return decodeGprmc(deviceSession, sentence, remoteAddress, channel); + } else if (sentence.startsWith("GGA", 3) && deviceSession != null) { + return decodeGpgga(deviceSession, sentence); ++ } else if (sentence.startsWith("GLL", 3) && deviceSession != null) { ++ return decodeGpgll(deviceSession, sentence); + } else if (sentence.startsWith("$GPRMA") && deviceSession != null) { + return decodeGprma(deviceSession, sentence); + } else if (sentence.startsWith("$TRCCR") && deviceSession != null) { +diff --git a/src/test/java/org/traccar/protocol/T55ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/T55ProtocolDecoderTest.java +index 91020714c..525e9737a 100644 +--- a/src/test/java/org/traccar/protocol/T55ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/T55ProtocolDecoderTest.java +@@ -23,7 +23,7 @@ public class T55ProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, text( + "$GNGGA,164414.90,4650.5156500,N,01246.1059604,E,1,12,0.84,740.729,M,44.804,M,,*4E")); + +- verifyNull(decoder, text( ++ verifyPosition(decoder, text( + "$GNGLL,4650.5156500,N,01246.1059604,E,164414.90,A,A*77")); + + verifyPosition(decoder, text( diff --git a/tasks/traccar__traccar-5663/tests/test.sh b/tasks/traccar__traccar-5663/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..248f8594a5beb9da25624e00bf8d9e6d373ac01b --- /dev/null +++ b/tasks/traccar__traccar-5663/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 f0c270f6f8bb9678003273159c3b5f464723335a > "$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/traccar__traccar-5663/tests/verifier.py b/tasks/traccar__traccar-5663/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5663/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/traccar__traccar-5692/environment/Dockerfile b/tasks/traccar__traccar-5692/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b8c6f1504a9610a1176062d33c25a15e646950d9 --- /dev/null +++ b/tasks/traccar__traccar-5692/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c42824acd4fc9bae224eece928c5d7bcb7b907ec 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c42824acd4fc9bae224eece928c5d7bcb7b907ec \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c42824acd4fc9bae224eece928c5d7bcb7b907ec \ + && 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/traccar__traccar-5692/instruction.md b/tasks/traccar__traccar-5692/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6a4f82716cc2b769ed715751e1da76217091b76 --- /dev/null +++ b/tasks/traccar__traccar-5692/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** feat: add junixsocket + +## Description + +Add support for JUnixSocket, allowing database connections via UNIX domain sockets without all the username and password fuzz. For a detailed description on how to configure this, see the following page: + +https://kohlschutter.github.io/junixsocket/dependency.html#jdbc + +Fixes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c42824acd4fc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5692/solution/patch.diff b/tasks/traccar__traccar-5692/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..84bf5862ef66c09a7f3a078491ecee9fd5e27504 --- /dev/null +++ b/tasks/traccar__traccar-5692/solution/patch.diff @@ -0,0 +1,21 @@ +diff --git a/build.gradle b/build.gradle +index c02da09e7..553f3ec99 100644 +--- a/build.gradle ++++ b/build.gradle +@@ -51,6 +51,7 @@ ext { + nettyVersion = "4.2.6.Final" + protobufVersion = "4.32.1" + jxlsVersion = "2.14.0" // version 3 has breaking changes ++ junixsocketVersion = "2.10.1" + } + + def resolveTransitiveVersion = { String root, String group, String name -> +@@ -85,6 +86,8 @@ dependencies { + implementation "com.mysql:mysql-connector-j:9.4.0" + implementation "org.mariadb.jdbc:mariadb-java-client:3.5.6" + implementation "org.postgresql:postgresql:42.7.8" ++ implementation "com.kohlschutter.junixsocket:junixsocket-core:$junixsocketVersion" ++ implementation "com.kohlschutter.junixsocket:junixsocket-mysql:$junixsocketVersion" + implementation "com.microsoft.sqlserver:mssql-jdbc:13.2.0.jre11" + implementation "com.zaxxer:HikariCP:7.0.2" + implementation "io.netty:netty-buffer:$nettyVersion" diff --git a/tasks/traccar__traccar-5692/solution/solve.sh b/tasks/traccar__traccar-5692/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5692/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/traccar__traccar-5692/task.toml b/tasks/traccar__traccar-5692/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e931c32750720a7edbe5e8c2baa29f345b0a9aaa --- /dev/null +++ b/tasks/traccar__traccar-5692/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5692" +description = "feat: add junixsocket" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "c42824acd4fc9bae224eece928c5d7bcb7b907ec" +reference = "https://github.com/traccar/traccar/pull/5692" +source_access = "auto" +built_at = "2026-11-16T16:09:42.613741+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b4c3c0ca3720b7472b73265e3e7e10475417257f0746180738843475ec6c15ce" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-10-27T13:12:57Z" +diff_format = "unified" +context_files = [ + "build.gradle", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.477064+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:74d9ac0165eedffbcf17fc38f90fba344045d48529ab8044769e2c64143bead4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5692/tests/capture.py b/tasks/traccar__traccar-5692/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5692/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/traccar__traccar-5692/tests/instruction.md b/tasks/traccar__traccar-5692/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6a4f82716cc2b769ed715751e1da76217091b76 --- /dev/null +++ b/tasks/traccar__traccar-5692/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** feat: add junixsocket + +## Description + +Add support for JUnixSocket, allowing database connections via UNIX domain sockets without all the username and password fuzz. For a detailed description on how to configure this, see the following page: + +https://kohlschutter.github.io/junixsocket/dependency.html#jdbc + +Fixes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c42824acd4fc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5692/tests/oracle.patch b/tasks/traccar__traccar-5692/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..84bf5862ef66c09a7f3a078491ecee9fd5e27504 --- /dev/null +++ b/tasks/traccar__traccar-5692/tests/oracle.patch @@ -0,0 +1,21 @@ +diff --git a/build.gradle b/build.gradle +index c02da09e7..553f3ec99 100644 +--- a/build.gradle ++++ b/build.gradle +@@ -51,6 +51,7 @@ ext { + nettyVersion = "4.2.6.Final" + protobufVersion = "4.32.1" + jxlsVersion = "2.14.0" // version 3 has breaking changes ++ junixsocketVersion = "2.10.1" + } + + def resolveTransitiveVersion = { String root, String group, String name -> +@@ -85,6 +86,8 @@ dependencies { + implementation "com.mysql:mysql-connector-j:9.4.0" + implementation "org.mariadb.jdbc:mariadb-java-client:3.5.6" + implementation "org.postgresql:postgresql:42.7.8" ++ implementation "com.kohlschutter.junixsocket:junixsocket-core:$junixsocketVersion" ++ implementation "com.kohlschutter.junixsocket:junixsocket-mysql:$junixsocketVersion" + implementation "com.microsoft.sqlserver:mssql-jdbc:13.2.0.jre11" + implementation "com.zaxxer:HikariCP:7.0.2" + implementation "io.netty:netty-buffer:$nettyVersion" diff --git a/tasks/traccar__traccar-5692/tests/test.sh b/tasks/traccar__traccar-5692/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..00c270cb5687cafd974538f5c6c0cbf6b1674f1d --- /dev/null +++ b/tasks/traccar__traccar-5692/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 c42824acd4fc9bae224eece928c5d7bcb7b907ec > "$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/traccar__traccar-5692/tests/verifier.py b/tasks/traccar__traccar-5692/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5692/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/traccar__traccar-5693/environment/Dockerfile b/tasks/traccar__traccar-5693/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4477e682cb23f03bf07b3fd14d81815e79028d9d --- /dev/null +++ b/tasks/traccar__traccar-5693/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f2ea1dd2a076696e0269e54c4f0e788708d4d60b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f2ea1dd2a076696e0269e54c4f0e788708d4d60b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f2ea1dd2a076696e0269e54c4f0e788708d4d60b \ + && 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/traccar__traccar-5693/instruction.md b/tasks/traccar__traccar-5693/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..686028ebe5db5ecfac90d2a2001d3dacdd21b747 --- /dev/null +++ b/tasks/traccar__traccar-5693/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Prevent creation of unnecessary sessions for unauthenticated requests… + +## Description + +Prevent creation of unnecessary sessions for unauthenticated requests and invalidate expired sessions before establishing the security context, ensuring expired logins cannot continue using the API. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f2ea1dd2a076`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5693/solution/patch.diff b/tasks/traccar__traccar-5693/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c186f92275f885e548732e0ddad5fd02bb62d14c --- /dev/null +++ b/tasks/traccar__traccar-5693/solution/patch.diff @@ -0,0 +1,44 @@ +diff --git a/src/main/java/org/traccar/api/security/SecurityRequestFilter.java b/src/main/java/org/traccar/api/security/SecurityRequestFilter.java +index 7faad3cfd..1ddb348a6 100644 +--- a/src/main/java/org/traccar/api/security/SecurityRequestFilter.java ++++ b/src/main/java/org/traccar/api/security/SecurityRequestFilter.java +@@ -26,6 +26,7 @@ import org.traccar.storage.StorageException; + import jakarta.annotation.security.PermitAll; + import jakarta.inject.Inject; + import jakarta.servlet.http.HttpServletRequest; ++import jakarta.servlet.http.HttpSession; + import jakarta.ws.rs.WebApplicationException; + import jakarta.ws.rs.container.ContainerRequestContext; + import jakarta.ws.rs.container.ContainerRequestFilter; +@@ -84,16 +85,21 @@ public class SecurityRequestFilter implements ContainerRequestFilter { + throw new WebApplicationException(e); + } + +- } else if (request.getSession() != null) { +- +- Long userId = (Long) request.getSession().getAttribute(SessionHelper.USER_ID_KEY); +- Date expiration = (Date) request.getSession().getAttribute(SessionHelper.EXPIRATION_KEY); +- if (userId != null) { +- User user = injector.getInstance(PermissionsService.class).getUser(userId); +- if (user != null) { +- user.checkDisabled(); +- statisticsManager.registerRequest(userId); +- securityContext = new UserSecurityContext(new UserPrincipal(userId, expiration)); ++ } else { ++ ++ HttpSession session = request.getSession(false); ++ if (session != null) { ++ Long userId = (Long) session.getAttribute(SessionHelper.USER_ID_KEY); ++ Date expiration = (Date) session.getAttribute(SessionHelper.EXPIRATION_KEY); ++ if (expiration != null && expiration.before(new Date())) { ++ session.invalidate(); ++ } else if (userId != null) { ++ User user = injector.getInstance(PermissionsService.class).getUser(userId); ++ if (user != null) { ++ user.checkDisabled(); ++ statisticsManager.registerRequest(userId); ++ securityContext = new UserSecurityContext(new UserPrincipal(userId, expiration)); ++ } + } + } + diff --git a/tasks/traccar__traccar-5693/solution/solve.sh b/tasks/traccar__traccar-5693/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5693/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/traccar__traccar-5693/task.toml b/tasks/traccar__traccar-5693/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3d4fc9f28aafce77ede4694f89a3ef8b98c53490 --- /dev/null +++ b/tasks/traccar__traccar-5693/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5693" +description = "Prevent creation of unnecessary sessions for unauthenticated requests…" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "f2ea1dd2a076696e0269e54c4f0e788708d4d60b" +reference = "https://github.com/traccar/traccar/pull/5693" +source_access = "auto" +built_at = "2026-11-16T16:09:42.612347+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:16993f7120a1524e4a28638fc54e0a461ca9f0f7ae998648805ea504c8764d58" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-10-28T13:45:13Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/api/security/SecurityRequestFilter.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 26 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.479232+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d101ba98799b59f719500e2f8abe8f6b61a84514cb2bc83b0ece158642148774" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5693/tests/capture.py b/tasks/traccar__traccar-5693/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5693/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/traccar__traccar-5693/tests/instruction.md b/tasks/traccar__traccar-5693/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..686028ebe5db5ecfac90d2a2001d3dacdd21b747 --- /dev/null +++ b/tasks/traccar__traccar-5693/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Prevent creation of unnecessary sessions for unauthenticated requests… + +## Description + +Prevent creation of unnecessary sessions for unauthenticated requests and invalidate expired sessions before establishing the security context, ensuring expired logins cannot continue using the API. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f2ea1dd2a076`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5693/tests/oracle.patch b/tasks/traccar__traccar-5693/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c186f92275f885e548732e0ddad5fd02bb62d14c --- /dev/null +++ b/tasks/traccar__traccar-5693/tests/oracle.patch @@ -0,0 +1,44 @@ +diff --git a/src/main/java/org/traccar/api/security/SecurityRequestFilter.java b/src/main/java/org/traccar/api/security/SecurityRequestFilter.java +index 7faad3cfd..1ddb348a6 100644 +--- a/src/main/java/org/traccar/api/security/SecurityRequestFilter.java ++++ b/src/main/java/org/traccar/api/security/SecurityRequestFilter.java +@@ -26,6 +26,7 @@ import org.traccar.storage.StorageException; + import jakarta.annotation.security.PermitAll; + import jakarta.inject.Inject; + import jakarta.servlet.http.HttpServletRequest; ++import jakarta.servlet.http.HttpSession; + import jakarta.ws.rs.WebApplicationException; + import jakarta.ws.rs.container.ContainerRequestContext; + import jakarta.ws.rs.container.ContainerRequestFilter; +@@ -84,16 +85,21 @@ public class SecurityRequestFilter implements ContainerRequestFilter { + throw new WebApplicationException(e); + } + +- } else if (request.getSession() != null) { +- +- Long userId = (Long) request.getSession().getAttribute(SessionHelper.USER_ID_KEY); +- Date expiration = (Date) request.getSession().getAttribute(SessionHelper.EXPIRATION_KEY); +- if (userId != null) { +- User user = injector.getInstance(PermissionsService.class).getUser(userId); +- if (user != null) { +- user.checkDisabled(); +- statisticsManager.registerRequest(userId); +- securityContext = new UserSecurityContext(new UserPrincipal(userId, expiration)); ++ } else { ++ ++ HttpSession session = request.getSession(false); ++ if (session != null) { ++ Long userId = (Long) session.getAttribute(SessionHelper.USER_ID_KEY); ++ Date expiration = (Date) session.getAttribute(SessionHelper.EXPIRATION_KEY); ++ if (expiration != null && expiration.before(new Date())) { ++ session.invalidate(); ++ } else if (userId != null) { ++ User user = injector.getInstance(PermissionsService.class).getUser(userId); ++ if (user != null) { ++ user.checkDisabled(); ++ statisticsManager.registerRequest(userId); ++ securityContext = new UserSecurityContext(new UserPrincipal(userId, expiration)); ++ } + } + } + diff --git a/tasks/traccar__traccar-5693/tests/test.sh b/tasks/traccar__traccar-5693/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a74123306720fe6d3150206876abffc5fb0c69c --- /dev/null +++ b/tasks/traccar__traccar-5693/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 f2ea1dd2a076696e0269e54c4f0e788708d4d60b > "$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/traccar__traccar-5693/tests/verifier.py b/tasks/traccar__traccar-5693/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5693/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/traccar__traccar-5708/environment/Dockerfile b/tasks/traccar__traccar-5708/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c890d9bfce42cb8234dbc024054251ec05d4bcc8 --- /dev/null +++ b/tasks/traccar__traccar-5708/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 26cf3c4eadb9ff95da1d595169ef7d6bf1096d88 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 26cf3c4eadb9ff95da1d595169ef7d6bf1096d88 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 26cf3c4eadb9ff95da1d595169ef7d6bf1096d88 \ + && 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/traccar__traccar-5708/instruction.md b/tasks/traccar__traccar-5708/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6daa4f72d5e5cc50528d4150489ed7525cc1114e --- /dev/null +++ b/tasks/traccar__traccar-5708/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** Add The Things Network Webhook Decoder + +## Description + +Hi, +The Things Network (TTN) provides a webhook to publish messages from LoRaWAN devices on their network, this PR will decode those messages for Traccar. + +The `decoded_payload` sent by TTN in the webhook must follow the format specified by TTN Mapper: +> Make sure you have a Payload decoder function enabled on the TTN Console that decodes the raw payload into a json object. The JSON object should contain the keys “latitude”, “longitude” and “altitude” and one of “hdop”, “accuracy” or “sats”. When using the Cayenne LPP data format, the GPS coordinates will be decoded into a different JSON format, but this format is also supported. + +`speed` and `heading`, while not apart of the TTN Mapper format, are also supported. All other keys will be added as a custom attribute in Traccar; if you are writing your own payload formatter, it is a good idea to use the keys specified in [`Position.java`](https://github.com/traccar/traccar/blob/master/src/main/java/org/traccar/model/Position.java), but that is not required. + +If using `speed`, a `ttnhttp.speed` entry should be added to your traccar.xml to configure your units, supported values are [listed here](https://github.com/traccar/traccar/blob/95151f242b3957e7e902c42e5a2b750e95897b28/src/main/java/org/traccar/BaseProtocolDecoder.java#L110-L117). + +TTN Console Webhook Config: +- Webhook format: `JSON` +- Base URL: `:5261` +- Enabled event types + - Uplink message (path can be left empty) + +Thanks, +Steve + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `26cf3c4eadb9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5708/solution/patch.diff b/tasks/traccar__traccar-5708/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8e9411a969f3393b3a25cc91767f80facaf07570 --- /dev/null +++ b/tasks/traccar__traccar-5708/solution/patch.diff @@ -0,0 +1,253 @@ +diff --git a/src/main/java/org/traccar/config/PortConfigSuffix.java b/src/main/java/org/traccar/config/PortConfigSuffix.java +index be7842ed5..40d38164e 100644 +--- a/src/main/java/org/traccar/config/PortConfigSuffix.java ++++ b/src/main/java/org/traccar/config/PortConfigSuffix.java +@@ -283,6 +283,7 @@ public class PortConfigSuffix extends ConfigSuffix { + PORTS.put("hyn600", 5258); + PORTS.put("jmak", 5259); + PORTS.put("bws", 5260); ++ PORTS.put("ttnhttp", 5261); + } + + PortConfigSuffix(String key, List types) { +diff --git a/src/main/java/org/traccar/protocol/TtnHttpProtocol.java b/src/main/java/org/traccar/protocol/TtnHttpProtocol.java +new file mode 100644 +index 000000000..668c22ad2 +--- /dev/null ++++ b/src/main/java/org/traccar/protocol/TtnHttpProtocol.java +@@ -0,0 +1,42 @@ ++/* ++ * Copyright 2025 Stephen Horvath (me@stevetech.au) ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.traccar.protocol; ++ ++import io.netty.handler.codec.http.HttpObjectAggregator; ++import io.netty.handler.codec.http.HttpRequestDecoder; ++import io.netty.handler.codec.http.HttpResponseEncoder; ++import jakarta.inject.Inject; ++import org.traccar.BaseProtocol; ++import org.traccar.PipelineBuilder; ++import org.traccar.TrackerServer; ++import org.traccar.config.Config; ++ ++public class TtnHttpProtocol extends BaseProtocol { ++ ++ @Inject ++ public TtnHttpProtocol(Config config) { ++ addServer(new TrackerServer(config, getName(), false) { ++ @Override ++ protected void addProtocolHandlers(PipelineBuilder pipeline, Config config) { ++ pipeline.addLast(new HttpResponseEncoder()); ++ pipeline.addLast(new HttpRequestDecoder()); ++ pipeline.addLast(new HttpObjectAggregator(16384)); ++ pipeline.addLast(new TtnHttpProtocolDecoder(TtnHttpProtocol.this)); ++ } ++ }); ++ } ++ ++} +diff --git a/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java b/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java +new file mode 100644 +index 000000000..2a004e78a +--- /dev/null ++++ b/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java +@@ -0,0 +1,158 @@ ++/* ++ * Copyright 2025 Stephen Horvath (me@stevetech.au) ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.traccar.protocol; ++ ++import io.netty.channel.Channel; ++import io.netty.handler.codec.http.FullHttpRequest; ++import io.netty.handler.codec.http.HttpHeaderNames; ++import io.netty.handler.codec.http.HttpHeaderValues; ++import io.netty.handler.codec.http.HttpResponseStatus; ++import jakarta.json.Json; ++import jakarta.json.JsonNumber; ++import jakarta.json.JsonObject; ++import jakarta.json.JsonString; ++import jakarta.json.JsonValue; ++import org.traccar.BaseHttpProtocolDecoder; ++import org.traccar.Protocol; ++import org.traccar.helper.DateUtil; ++import org.traccar.model.Position; ++import org.traccar.session.DeviceSession; ++ ++import java.io.StringReader; ++import java.net.SocketAddress; ++import java.nio.charset.StandardCharsets; ++ ++public class TtnHttpProtocolDecoder extends BaseHttpProtocolDecoder { ++ ++ public TtnHttpProtocolDecoder(Protocol protocol) { ++ super(protocol); ++ } ++ ++ @Override ++ protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { ++ ++ FullHttpRequest request = (FullHttpRequest) msg; ++ String contentType = request.headers().get(HttpHeaderNames.CONTENT_TYPE); ++ if (contentType == null || !contentType.startsWith(HttpHeaderValues.APPLICATION_JSON.toString())) { ++ sendResponse(channel, HttpResponseStatus.BAD_REQUEST); ++ return null; ++ } ++ ++ String content = request.content().toString(StandardCharsets.UTF_8); ++ JsonObject root = Json.createReader(new StringReader(content)).readObject(); ++ ++ DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, ++ root.getJsonObject("end_device_ids").getString("device_id")); ++ if (deviceSession == null) { ++ sendResponse(channel, HttpResponseStatus.NOT_FOUND); ++ return null; ++ } ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ JsonObject message = root.getJsonObject("uplink_message"); ++ if (message == null) { ++ sendResponse(channel, HttpResponseStatus.BAD_REQUEST); ++ return null; ++ } ++ ++ JsonObject payload = message.getJsonObject("decoded_payload"); ++ if (payload == null) { ++ sendResponse(channel, HttpResponseStatus.OK); ++ return null; ++ } ++ ++ if (message.getJsonArray("rx_metadata").getJsonObject(0).containsKey("time")) { ++ position.setTime(DateUtil.parseDate(message.getJsonArray("rx_metadata") ++ .getJsonObject(0).getString("time"))); ++ } else { ++ position.setTime(DateUtil.parseDate(message.getString("received_at"))); ++ } ++ ++ boolean foundGps = false; ++ ++ for (String jsonKey : payload.keySet()) { ++ if (jsonKey.startsWith("gps_")) { ++ JsonObject coordinates = payload.getJsonObject(jsonKey); ++ if (coordinates.getValueType() != JsonValue.ValueType.OBJECT) { ++ continue; ++ } ++ position.setLatitude(coordinates.getJsonNumber("latitude").doubleValue()); ++ position.setLongitude(coordinates.getJsonNumber("longitude").doubleValue()); ++ position.setAltitude(coordinates.getJsonNumber("altitude").doubleValue()); ++ foundGps = true; ++ } else { ++ switch (jsonKey) { ++ case "latitude": ++ position.setLatitude(payload.getJsonNumber(jsonKey).doubleValue()); ++ foundGps = true; ++ break; ++ case "longitude": ++ position.setLongitude(payload.getJsonNumber(jsonKey).doubleValue()); ++ foundGps = true; ++ break; ++ case "altitude": ++ position.setAltitude(payload.getJsonNumber(jsonKey).doubleValue()); ++ break; ++ case "accuracy": ++ position.setAccuracy(payload.getJsonNumber(jsonKey).doubleValue()); ++ break; ++ case "sats": ++ position.set(Position.KEY_SATELLITES, payload.getJsonNumber(jsonKey).intValue()); ++ break; ++ case "speed": ++ position.setSpeed(convertSpeed(payload.getJsonNumber(jsonKey).doubleValue(), "kn")); ++ break; ++ case "heading": ++ position.setCourse(payload.getJsonNumber(jsonKey).doubleValue()); ++ break; ++ default: ++ decodeJsonValue(position, jsonKey, payload.get(jsonKey)); ++ break; ++ } ++ } ++ } ++ ++ if (foundGps) { ++ position.setValid(true); ++ } else { ++ getLastLocation(position, null); ++ } ++ ++ sendResponse(channel, HttpResponseStatus.OK); ++ return position; ++ } ++ ++ private void decodeJsonValue(Position position, String key, JsonValue value) { ++ switch (value.getValueType()) { ++ case STRING: ++ position.set(key, ((JsonString) value).getString()); ++ break; ++ case NUMBER: ++ position.set(key, ((JsonNumber) value).doubleValue()); ++ break; ++ case TRUE: ++ position.set(key, true); ++ break; ++ case FALSE: ++ position.set(key, false); ++ break; ++ default: ++ break; ++ } ++ } ++} +diff --git a/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java +new file mode 100644 +index 000000000..e23d748ea +--- /dev/null ++++ b/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java +@@ -0,0 +1,23 @@ ++package org.traccar.protocol; ++ ++import io.netty.handler.codec.http.HttpMethod; ++import io.netty.handler.codec.http.ReadOnlyHttpHeaders; ++import org.junit.jupiter.api.Test; ++import org.traccar.ProtocolTest; ++ ++public class TtnHttpProtocolDecoderTest extends ProtocolTest { ++ ++ @Test ++ public void testDecodeJson() throws Exception { ++ ++ var decoder = inject(new TtnHttpProtocolDecoder(null)); ++ ++ verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( ++ "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIVpAyHNAIgFtcvtXxgAEWIAAAsAAgBaAIQAYwCCAAB7tQBnAS0AcyeRAGh5\",\"decoded_payload\":{\"altitude\":44.5,\"barometer_0\":1012.9,\"hdop\":0.9,\"heading\":99,\"humidity_0\":60.5,\"latitude\":37.4219,\"longitude\":-122.084,\"sats\":11,\"speed\":31.669,\"temperature_0\":30.1,\"time\":1762936141},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"location\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":47,\"source\":\"SOURCE_REGISTRY\"},\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); ++ ++ verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( ++ "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIgFxALtUoAAEWIAZwEQAWcA/w==\",\"decoded_payload\":{\"gps_0\":{\"altitude\": 44.5,\"latitude\": 37.7858,\"longitude\": -122.4064},\"temperature_0\": 27.2,\"temperature_1\":25.5},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.7858,\"longitude\":-122.4064,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); ++ ++ } ++ ++} diff --git a/tasks/traccar__traccar-5708/solution/solve.sh b/tasks/traccar__traccar-5708/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5708/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/traccar__traccar-5708/task.toml b/tasks/traccar__traccar-5708/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f787e9dea72b8be6065cad781bdf22c826f02976 --- /dev/null +++ b/tasks/traccar__traccar-5708/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5708" +description = "Add The Things Network Webhook Decoder" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "26cf3c4eadb9ff95da1d595169ef7d6bf1096d88" +reference = "https://github.com/traccar/traccar/pull/5708" +source_access = "auto" +built_at = "2026-11-16T16:09:42.610714+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:decaaea0af5ccb5515973b7fdd9ea61c0a3cc0d7a035215ed8eb60425468c18a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-11-22T14:29:48Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/config/PortConfigSuffix.java", + "src/main/java/org/traccar/protocol/TtnHttpProtocol.java", + "src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java", + "src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 224 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.479891+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6a4a8e839ca7fc45cac747132f22ba06de02a2651d958405fa60780827b727ec" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5708/tests/capture.py b/tasks/traccar__traccar-5708/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5708/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/traccar__traccar-5708/tests/instruction.md b/tasks/traccar__traccar-5708/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6daa4f72d5e5cc50528d4150489ed7525cc1114e --- /dev/null +++ b/tasks/traccar__traccar-5708/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** Add The Things Network Webhook Decoder + +## Description + +Hi, +The Things Network (TTN) provides a webhook to publish messages from LoRaWAN devices on their network, this PR will decode those messages for Traccar. + +The `decoded_payload` sent by TTN in the webhook must follow the format specified by TTN Mapper: +> Make sure you have a Payload decoder function enabled on the TTN Console that decodes the raw payload into a json object. The JSON object should contain the keys “latitude”, “longitude” and “altitude” and one of “hdop”, “accuracy” or “sats”. When using the Cayenne LPP data format, the GPS coordinates will be decoded into a different JSON format, but this format is also supported. + +`speed` and `heading`, while not apart of the TTN Mapper format, are also supported. All other keys will be added as a custom attribute in Traccar; if you are writing your own payload formatter, it is a good idea to use the keys specified in [`Position.java`](https://github.com/traccar/traccar/blob/master/src/main/java/org/traccar/model/Position.java), but that is not required. + +If using `speed`, a `ttnhttp.speed` entry should be added to your traccar.xml to configure your units, supported values are [listed here](https://github.com/traccar/traccar/blob/95151f242b3957e7e902c42e5a2b750e95897b28/src/main/java/org/traccar/BaseProtocolDecoder.java#L110-L117). + +TTN Console Webhook Config: +- Webhook format: `JSON` +- Base URL: `:5261` +- Enabled event types + - Uplink message (path can be left empty) + +Thanks, +Steve + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `26cf3c4eadb9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5708/tests/oracle.patch b/tasks/traccar__traccar-5708/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8e9411a969f3393b3a25cc91767f80facaf07570 --- /dev/null +++ b/tasks/traccar__traccar-5708/tests/oracle.patch @@ -0,0 +1,253 @@ +diff --git a/src/main/java/org/traccar/config/PortConfigSuffix.java b/src/main/java/org/traccar/config/PortConfigSuffix.java +index be7842ed5..40d38164e 100644 +--- a/src/main/java/org/traccar/config/PortConfigSuffix.java ++++ b/src/main/java/org/traccar/config/PortConfigSuffix.java +@@ -283,6 +283,7 @@ public class PortConfigSuffix extends ConfigSuffix { + PORTS.put("hyn600", 5258); + PORTS.put("jmak", 5259); + PORTS.put("bws", 5260); ++ PORTS.put("ttnhttp", 5261); + } + + PortConfigSuffix(String key, List types) { +diff --git a/src/main/java/org/traccar/protocol/TtnHttpProtocol.java b/src/main/java/org/traccar/protocol/TtnHttpProtocol.java +new file mode 100644 +index 000000000..668c22ad2 +--- /dev/null ++++ b/src/main/java/org/traccar/protocol/TtnHttpProtocol.java +@@ -0,0 +1,42 @@ ++/* ++ * Copyright 2025 Stephen Horvath (me@stevetech.au) ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.traccar.protocol; ++ ++import io.netty.handler.codec.http.HttpObjectAggregator; ++import io.netty.handler.codec.http.HttpRequestDecoder; ++import io.netty.handler.codec.http.HttpResponseEncoder; ++import jakarta.inject.Inject; ++import org.traccar.BaseProtocol; ++import org.traccar.PipelineBuilder; ++import org.traccar.TrackerServer; ++import org.traccar.config.Config; ++ ++public class TtnHttpProtocol extends BaseProtocol { ++ ++ @Inject ++ public TtnHttpProtocol(Config config) { ++ addServer(new TrackerServer(config, getName(), false) { ++ @Override ++ protected void addProtocolHandlers(PipelineBuilder pipeline, Config config) { ++ pipeline.addLast(new HttpResponseEncoder()); ++ pipeline.addLast(new HttpRequestDecoder()); ++ pipeline.addLast(new HttpObjectAggregator(16384)); ++ pipeline.addLast(new TtnHttpProtocolDecoder(TtnHttpProtocol.this)); ++ } ++ }); ++ } ++ ++} +diff --git a/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java b/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java +new file mode 100644 +index 000000000..2a004e78a +--- /dev/null ++++ b/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java +@@ -0,0 +1,158 @@ ++/* ++ * Copyright 2025 Stephen Horvath (me@stevetech.au) ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.traccar.protocol; ++ ++import io.netty.channel.Channel; ++import io.netty.handler.codec.http.FullHttpRequest; ++import io.netty.handler.codec.http.HttpHeaderNames; ++import io.netty.handler.codec.http.HttpHeaderValues; ++import io.netty.handler.codec.http.HttpResponseStatus; ++import jakarta.json.Json; ++import jakarta.json.JsonNumber; ++import jakarta.json.JsonObject; ++import jakarta.json.JsonString; ++import jakarta.json.JsonValue; ++import org.traccar.BaseHttpProtocolDecoder; ++import org.traccar.Protocol; ++import org.traccar.helper.DateUtil; ++import org.traccar.model.Position; ++import org.traccar.session.DeviceSession; ++ ++import java.io.StringReader; ++import java.net.SocketAddress; ++import java.nio.charset.StandardCharsets; ++ ++public class TtnHttpProtocolDecoder extends BaseHttpProtocolDecoder { ++ ++ public TtnHttpProtocolDecoder(Protocol protocol) { ++ super(protocol); ++ } ++ ++ @Override ++ protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { ++ ++ FullHttpRequest request = (FullHttpRequest) msg; ++ String contentType = request.headers().get(HttpHeaderNames.CONTENT_TYPE); ++ if (contentType == null || !contentType.startsWith(HttpHeaderValues.APPLICATION_JSON.toString())) { ++ sendResponse(channel, HttpResponseStatus.BAD_REQUEST); ++ return null; ++ } ++ ++ String content = request.content().toString(StandardCharsets.UTF_8); ++ JsonObject root = Json.createReader(new StringReader(content)).readObject(); ++ ++ DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, ++ root.getJsonObject("end_device_ids").getString("device_id")); ++ if (deviceSession == null) { ++ sendResponse(channel, HttpResponseStatus.NOT_FOUND); ++ return null; ++ } ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ JsonObject message = root.getJsonObject("uplink_message"); ++ if (message == null) { ++ sendResponse(channel, HttpResponseStatus.BAD_REQUEST); ++ return null; ++ } ++ ++ JsonObject payload = message.getJsonObject("decoded_payload"); ++ if (payload == null) { ++ sendResponse(channel, HttpResponseStatus.OK); ++ return null; ++ } ++ ++ if (message.getJsonArray("rx_metadata").getJsonObject(0).containsKey("time")) { ++ position.setTime(DateUtil.parseDate(message.getJsonArray("rx_metadata") ++ .getJsonObject(0).getString("time"))); ++ } else { ++ position.setTime(DateUtil.parseDate(message.getString("received_at"))); ++ } ++ ++ boolean foundGps = false; ++ ++ for (String jsonKey : payload.keySet()) { ++ if (jsonKey.startsWith("gps_")) { ++ JsonObject coordinates = payload.getJsonObject(jsonKey); ++ if (coordinates.getValueType() != JsonValue.ValueType.OBJECT) { ++ continue; ++ } ++ position.setLatitude(coordinates.getJsonNumber("latitude").doubleValue()); ++ position.setLongitude(coordinates.getJsonNumber("longitude").doubleValue()); ++ position.setAltitude(coordinates.getJsonNumber("altitude").doubleValue()); ++ foundGps = true; ++ } else { ++ switch (jsonKey) { ++ case "latitude": ++ position.setLatitude(payload.getJsonNumber(jsonKey).doubleValue()); ++ foundGps = true; ++ break; ++ case "longitude": ++ position.setLongitude(payload.getJsonNumber(jsonKey).doubleValue()); ++ foundGps = true; ++ break; ++ case "altitude": ++ position.setAltitude(payload.getJsonNumber(jsonKey).doubleValue()); ++ break; ++ case "accuracy": ++ position.setAccuracy(payload.getJsonNumber(jsonKey).doubleValue()); ++ break; ++ case "sats": ++ position.set(Position.KEY_SATELLITES, payload.getJsonNumber(jsonKey).intValue()); ++ break; ++ case "speed": ++ position.setSpeed(convertSpeed(payload.getJsonNumber(jsonKey).doubleValue(), "kn")); ++ break; ++ case "heading": ++ position.setCourse(payload.getJsonNumber(jsonKey).doubleValue()); ++ break; ++ default: ++ decodeJsonValue(position, jsonKey, payload.get(jsonKey)); ++ break; ++ } ++ } ++ } ++ ++ if (foundGps) { ++ position.setValid(true); ++ } else { ++ getLastLocation(position, null); ++ } ++ ++ sendResponse(channel, HttpResponseStatus.OK); ++ return position; ++ } ++ ++ private void decodeJsonValue(Position position, String key, JsonValue value) { ++ switch (value.getValueType()) { ++ case STRING: ++ position.set(key, ((JsonString) value).getString()); ++ break; ++ case NUMBER: ++ position.set(key, ((JsonNumber) value).doubleValue()); ++ break; ++ case TRUE: ++ position.set(key, true); ++ break; ++ case FALSE: ++ position.set(key, false); ++ break; ++ default: ++ break; ++ } ++ } ++} +diff --git a/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java +new file mode 100644 +index 000000000..e23d748ea +--- /dev/null ++++ b/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java +@@ -0,0 +1,23 @@ ++package org.traccar.protocol; ++ ++import io.netty.handler.codec.http.HttpMethod; ++import io.netty.handler.codec.http.ReadOnlyHttpHeaders; ++import org.junit.jupiter.api.Test; ++import org.traccar.ProtocolTest; ++ ++public class TtnHttpProtocolDecoderTest extends ProtocolTest { ++ ++ @Test ++ public void testDecodeJson() throws Exception { ++ ++ var decoder = inject(new TtnHttpProtocolDecoder(null)); ++ ++ verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( ++ "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIVpAyHNAIgFtcvtXxgAEWIAAAsAAgBaAIQAYwCCAAB7tQBnAS0AcyeRAGh5\",\"decoded_payload\":{\"altitude\":44.5,\"barometer_0\":1012.9,\"hdop\":0.9,\"heading\":99,\"humidity_0\":60.5,\"latitude\":37.4219,\"longitude\":-122.084,\"sats\":11,\"speed\":31.669,\"temperature_0\":30.1,\"time\":1762936141},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"location\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":47,\"source\":\"SOURCE_REGISTRY\"},\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); ++ ++ verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( ++ "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIgFxALtUoAAEWIAZwEQAWcA/w==\",\"decoded_payload\":{\"gps_0\":{\"altitude\": 44.5,\"latitude\": 37.7858,\"longitude\": -122.4064},\"temperature_0\": 27.2,\"temperature_1\":25.5},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.7858,\"longitude\":-122.4064,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); ++ ++ } ++ ++} diff --git a/tasks/traccar__traccar-5708/tests/test.sh b/tasks/traccar__traccar-5708/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..dac0a76cfbc8c52bf5176dbe573527b6e51fffd8 --- /dev/null +++ b/tasks/traccar__traccar-5708/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 26cf3c4eadb9ff95da1d595169ef7d6bf1096d88 > "$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/traccar__traccar-5708/tests/verifier.py b/tasks/traccar__traccar-5708/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5708/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/traccar__traccar-5719/environment/Dockerfile b/tasks/traccar__traccar-5719/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cec3b9fd53cb990306c4b47d976914aa5949d5cf --- /dev/null +++ b/tasks/traccar__traccar-5719/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5b60ffca5a6fc43e6f06571bf74eca6c72493c09 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5b60ffca5a6fc43e6f06571bf74eca6c72493c09 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5b60ffca5a6fc43e6f06571bf74eca6c72493c09 \ + && 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/traccar__traccar-5719/instruction.md b/tasks/traccar__traccar-5719/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d66cbc95c1d7ce87068acc40345010bedc55e48 --- /dev/null +++ b/tasks/traccar__traccar-5719/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix: Implemented user email in audit logs with batch fetching + +## Description + +### Changes +* Added `userEmail` field to the `Action` model. +* Annotated the new field with `@QueryIgnore` to prevent database persistence errors. +* Updated `AuditResource` to populate user emails. +* Implemented **batch fetching** for users to avoid the N+1 query problem (fetching all users in a single query instead of inside the loop). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5b60ffca5a6f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5719/solution/patch.diff b/tasks/traccar__traccar-5719/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d6628028773add0da694c0dfe8dc16f033818bd2 --- /dev/null +++ b/tasks/traccar__traccar-5719/solution/patch.diff @@ -0,0 +1,74 @@ +diff --git a/src/main/java/org/traccar/api/resource/AuditResource.java b/src/main/java/org/traccar/api/resource/AuditResource.java +index 229f30585..0e623d53e 100644 +--- a/src/main/java/org/traccar/api/resource/AuditResource.java ++++ b/src/main/java/org/traccar/api/resource/AuditResource.java +@@ -23,13 +23,16 @@ import jakarta.ws.rs.QueryParam; + import jakarta.ws.rs.core.MediaType; + import org.traccar.api.BaseResource; + import org.traccar.model.Action; ++import org.traccar.model.User; + import org.traccar.storage.StorageException; + import org.traccar.storage.query.Columns; + import org.traccar.storage.query.Condition; + import org.traccar.storage.query.Order; + import org.traccar.storage.query.Request; + ++import java.util.Map; + import java.util.Date; ++import java.util.stream.Collectors; + import java.util.stream.Stream; + + @Path("audit") +@@ -41,10 +44,22 @@ public class AuditResource extends BaseResource { + public Stream get( + @QueryParam("from") Date from, @QueryParam("to") Date to) throws StorageException { + permissionsService.checkAdmin(getUserId()); ++ ++ Map userEmailMap; ++ try (var stream = storage.getObjectsStream(User.class, new Request(new Columns.All()))) { ++ userEmailMap = stream ++ .filter(user -> user.getEmail() != null) ++ .collect(Collectors.toMap(User::getId, User::getEmail)); ++ } ++ + return storage.getObjectsStream(Action.class, new Request( +- new Columns.All(), +- new Condition.Between("actionTime", from, to), +- new Order("actionTime"))); ++ new Columns.All(), ++ new Condition.Between("actionTime", from, to), ++ new Order("actionTime"))) ++ .map(action -> { ++ action.setUserEmail(userEmailMap.get(action.getUserId())); ++ return action; ++ }); + } + + } +diff --git a/src/main/java/org/traccar/model/Action.java b/src/main/java/org/traccar/model/Action.java +index f7ec8baac..e3483e14d 100644 +--- a/src/main/java/org/traccar/model/Action.java ++++ b/src/main/java/org/traccar/model/Action.java +@@ -15,6 +15,7 @@ + */ + package org.traccar.model; + ++import org.traccar.storage.QueryIgnore; + import org.traccar.storage.StorageName; + + import java.util.Date; +@@ -82,4 +83,14 @@ public class Action extends ExtendedModel { + this.objectId = objectId; + } + ++ private String userEmail; ++ ++ @QueryIgnore ++ public String getUserEmail() { ++ return userEmail; ++ } ++ ++ public void setUserEmail(String userEmail) { ++ this.userEmail = userEmail; ++ } + } diff --git a/tasks/traccar__traccar-5719/solution/solve.sh b/tasks/traccar__traccar-5719/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5719/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/traccar__traccar-5719/task.toml b/tasks/traccar__traccar-5719/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7c2f0afcba81dde10b9c5c1c85327dc8936958e1 --- /dev/null +++ b/tasks/traccar__traccar-5719/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5719" +description = "fix: Implemented user email in audit logs with batch fetching (#5647)" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "5b60ffca5a6fc43e6f06571bf74eca6c72493c09" +reference = "https://github.com/traccar/traccar/pull/5719" +source_access = "auto" +built_at = "2026-11-16T16:09:42.609001+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0dbf21b2c7eeba4732e2142496dff2e03461ac60d7a4d099994856051843fef2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-12-08T14:22:31Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/api/resource/AuditResource.java", + "src/main/java/org/traccar/model/Action.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 32 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.480512+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:faa32aadf679be299dc64954e08b049b0a10e6d8c08e7f997d1b907a1ab1451d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5719/tests/capture.py b/tasks/traccar__traccar-5719/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5719/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/traccar__traccar-5719/tests/instruction.md b/tasks/traccar__traccar-5719/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d66cbc95c1d7ce87068acc40345010bedc55e48 --- /dev/null +++ b/tasks/traccar__traccar-5719/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix: Implemented user email in audit logs with batch fetching + +## Description + +### Changes +* Added `userEmail` field to the `Action` model. +* Annotated the new field with `@QueryIgnore` to prevent database persistence errors. +* Updated `AuditResource` to populate user emails. +* Implemented **batch fetching** for users to avoid the N+1 query problem (fetching all users in a single query instead of inside the loop). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5b60ffca5a6f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5719/tests/oracle.patch b/tasks/traccar__traccar-5719/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d6628028773add0da694c0dfe8dc16f033818bd2 --- /dev/null +++ b/tasks/traccar__traccar-5719/tests/oracle.patch @@ -0,0 +1,74 @@ +diff --git a/src/main/java/org/traccar/api/resource/AuditResource.java b/src/main/java/org/traccar/api/resource/AuditResource.java +index 229f30585..0e623d53e 100644 +--- a/src/main/java/org/traccar/api/resource/AuditResource.java ++++ b/src/main/java/org/traccar/api/resource/AuditResource.java +@@ -23,13 +23,16 @@ import jakarta.ws.rs.QueryParam; + import jakarta.ws.rs.core.MediaType; + import org.traccar.api.BaseResource; + import org.traccar.model.Action; ++import org.traccar.model.User; + import org.traccar.storage.StorageException; + import org.traccar.storage.query.Columns; + import org.traccar.storage.query.Condition; + import org.traccar.storage.query.Order; + import org.traccar.storage.query.Request; + ++import java.util.Map; + import java.util.Date; ++import java.util.stream.Collectors; + import java.util.stream.Stream; + + @Path("audit") +@@ -41,10 +44,22 @@ public class AuditResource extends BaseResource { + public Stream get( + @QueryParam("from") Date from, @QueryParam("to") Date to) throws StorageException { + permissionsService.checkAdmin(getUserId()); ++ ++ Map userEmailMap; ++ try (var stream = storage.getObjectsStream(User.class, new Request(new Columns.All()))) { ++ userEmailMap = stream ++ .filter(user -> user.getEmail() != null) ++ .collect(Collectors.toMap(User::getId, User::getEmail)); ++ } ++ + return storage.getObjectsStream(Action.class, new Request( +- new Columns.All(), +- new Condition.Between("actionTime", from, to), +- new Order("actionTime"))); ++ new Columns.All(), ++ new Condition.Between("actionTime", from, to), ++ new Order("actionTime"))) ++ .map(action -> { ++ action.setUserEmail(userEmailMap.get(action.getUserId())); ++ return action; ++ }); + } + + } +diff --git a/src/main/java/org/traccar/model/Action.java b/src/main/java/org/traccar/model/Action.java +index f7ec8baac..e3483e14d 100644 +--- a/src/main/java/org/traccar/model/Action.java ++++ b/src/main/java/org/traccar/model/Action.java +@@ -15,6 +15,7 @@ + */ + package org.traccar.model; + ++import org.traccar.storage.QueryIgnore; + import org.traccar.storage.StorageName; + + import java.util.Date; +@@ -82,4 +83,14 @@ public class Action extends ExtendedModel { + this.objectId = objectId; + } + ++ private String userEmail; ++ ++ @QueryIgnore ++ public String getUserEmail() { ++ return userEmail; ++ } ++ ++ public void setUserEmail(String userEmail) { ++ this.userEmail = userEmail; ++ } + } diff --git a/tasks/traccar__traccar-5719/tests/test.sh b/tasks/traccar__traccar-5719/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ac019f4828e2c2bf0f567f6747ae32e70b412fa --- /dev/null +++ b/tasks/traccar__traccar-5719/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 5b60ffca5a6fc43e6f06571bf74eca6c72493c09 > "$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/traccar__traccar-5719/tests/verifier.py b/tasks/traccar__traccar-5719/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5719/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/traccar__traccar-5790/environment/Dockerfile b/tasks/traccar__traccar-5790/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5c7e363dfad10fdc8db9d528da68d4a94342550d --- /dev/null +++ b/tasks/traccar__traccar-5790/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0436abf3bafbfa3bb7f7b489bdf47302124a6398 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0436abf3bafbfa3bb7f7b489bdf47302124a6398 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0436abf3bafbfa3bb7f7b489bdf47302124a6398 \ + && 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/traccar__traccar-5790/instruction.md b/tasks/traccar__traccar-5790/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b6bb377d9651b215a89711daa4cf0baf99b06836 --- /dev/null +++ b/tasks/traccar__traccar-5790/instruction.md @@ -0,0 +1,47 @@ +# Issue + +**Title:** Add missing Device, Position, Server and User API endpoints to openapi.yaml + +## Description + +While working on a [Laravel PHP Traccae API integration](https://traccar.thingstelemetry.com/introduction/getting-started.html) I noted that some endpoints were missing on `openapi.yaml` file. + +This PR expand `openapi.yaml` by adding several new endpoints that are in the source code. + +### Missing 'excludeAttributes' spec + +- Added a query parameter `excludeAttributes` that that lets clients omit the attributes map from responses. + +### Device-related endpoints: + +- Added `/devices/{id}/image` endpoint used for uploading or updating a device image. +- Added `/devices/share` endpoint that enable sharing a device's location. + +### Position export endpoints: + +- Added `/positions/kml`, `/positions/csv`, and `/positions/gpx` endpoints that wllows exporting device positions in KML, CSV, and GPX formats, respectively. +- See [PositionResource](https://github.com/traccar/traccar/blob/0436abf3bafbfa3bb7f7b489bdf47302124a6398/src/main/java/org/traccar/api/resource/PositionResource.java) + +### Server utility endpoints: + +- Added several missing server endpoints: + - `/server/geocode` for reverse geocoding coordinates. + - `/server/timezones` to fetch available timezones. + - `/server/file/{path}` for uploading files to the server. + - `/server/gc` to trigger garbage collection. + - `/server/cache` to fetch cache diagnostics. + - `/server/reboot` to reboot the server process. +- See [ServerResource](https://github.com/traccar/traccar/blob/0436abf3bafbfa3bb7f7b489bdf47302124a6398/src/main/java/org/traccar/api/resource/ServerResource.java) + +### User authentication: + +- Added `/users/totp` endpoint to generate a TOTP secret +- See [UserResource](https://github.com/traccar/traccar/blob/0436abf3bafbfa3bb7f7b489bdf47302124a6398/src/main/java/org/traccar/api/resource/UserResource.java) + +The goal is to ensure that the `openapi.yaml` API documentation reflects all available endpoints in the source code. + +I am assuming the the missing endpoints were not a deliberate omissions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0436abf3bafb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5790/solution/patch.diff b/tasks/traccar__traccar-5790/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..eda3449e917fef08b05c86fe04e78159dd5d8ef2 --- /dev/null +++ b/tasks/traccar__traccar-5790/solution/patch.diff @@ -0,0 +1,314 @@ +diff --git a/openapi.yaml b/openapi.yaml +index a8a67fbc3..ace69491a 100644 +--- a/openapi.yaml ++++ b/openapi.yaml +@@ -415,6 +415,11 @@ paths: + `uniqueId=333331&uniqieId=44442` + schema: + type: string ++ - name: excludeAttributes ++ in: query ++ description: Exclude attributes field from device payload ++ schema: ++ type: boolean + responses: + '200': + description: OK +@@ -506,6 +511,69 @@ paths: + description: No Content + content: {} + x-codegen-request-body-name: body ++ /devices/{id}/image: ++ post: ++ summary: Upload/Update Device image ++ tags: ++ - Devices ++ parameters: ++ - name: id ++ in: path ++ required: true ++ schema: ++ type: integer ++ requestBody: ++ required: true ++ content: ++ image/*: ++ schema: ++ type: string ++ format: binary ++ responses: ++ '200': ++ description: OK ++ content: ++ text/plain: ++ schema: ++ type: string ++ example: device.png ++ '400': ++ description: Invalid image type or size ++ content: {} ++ '404': ++ description: Device not found ++ content: {} ++ /devices/share: ++ post: ++ summary: Share device location ++ tags: ++ - Devices ++ requestBody: ++ required: true ++ content: ++ application/x-www-form-urlencoded: ++ schema: ++ type: object ++ required: ++ - deviceId ++ - expiration ++ properties: ++ deviceId: ++ type: integer ++ expiration: ++ type: string ++ format: date-time ++ responses: ++ '200': ++ description: OK ++ content: ++ text/plain: ++ schema: ++ type: string ++ example: eyJhbGciOi... ++ '403': ++ description: Sharing is disabled or temporary user ++ content: {} + /groups: + get: + summary: Fetch a list of Groups +@@ -734,6 +802,103 @@ paths: + '404': + description: Not Found + content: {} ++ /positions/kml: ++ get: ++ summary: Export Positions as KML ++ tags: ++ - Positions ++ parameters: ++ - name: deviceId ++ in: query ++ required: true ++ schema: ++ type: integer ++ - name: from ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ - name: to ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ responses: ++ '200': ++ description: OK ++ content: ++ application/vnd.google-earth.kml+xml: ++ schema: ++ type: string ++ format: binary ++ /positions/csv: ++ get: ++ summary: Export Positions as CSV ++ tags: ++ - Positions ++ parameters: ++ - name: deviceId ++ in: query ++ required: true ++ schema: ++ type: integer ++ - name: geofenceId ++ in: query ++ schema: ++ type: integer ++ - name: from ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ - name: to ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ responses: ++ '200': ++ description: OK ++ content: ++ text/csv: ++ schema: ++ type: string ++ format: binary ++ /positions/gpx: ++ get: ++ summary: Export Positions as GPX ++ tags: ++ - Positions ++ parameters: ++ - name: deviceId ++ in: query ++ required: true ++ schema: ++ type: integer ++ - name: from ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ - name: to ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ responses: ++ '200': ++ description: OK ++ content: ++ application/gpx+xml: ++ schema: ++ type: string ++ format: binary + /server: + get: + summary: Fetch Server information +@@ -765,6 +930,103 @@ paths: + schema: + $ref: '#/components/schemas/Server' + x-codegen-request-body-name: body ++ /server/geocode: ++ get: ++ summary: Reverse geocode coordinates ++ tags: ++ - Server ++ parameters: ++ - name: latitude ++ in: query ++ required: true ++ schema: ++ type: number ++ format: double ++ - name: longitude ++ in: query ++ required: true ++ schema: ++ type: number ++ format: double ++ responses: ++ '200': ++ description: OK ++ content: ++ text/plain: ++ schema: ++ type: string ++ '500': ++ description: Reverse geocoding is not enabled ++ content: {} ++ /server/timezones: ++ get: ++ summary: Fetch available timezones ++ tags: ++ - Server ++ responses: ++ '200': ++ description: OK ++ content: ++ application/json: ++ schema: ++ type: array ++ items: ++ type: string ++ /server/file/{path}: ++ post: ++ summary: Upload a server file ++ tags: ++ - Server ++ parameters: ++ - name: path ++ in: path ++ required: true ++ schema: ++ type: string ++ requestBody: ++ content: ++ application/octet-stream: ++ schema: ++ type: string ++ format: binary ++ required: true ++ responses: ++ '200': ++ description: OK ++ content: {} ++ '400': ++ description: Bad Request ++ content: {} ++ /server/gc: ++ get: ++ summary: Trigger garbage collection ++ tags: ++ - Server ++ responses: ++ '200': ++ description: OK ++ content: {} ++ /server/cache: ++ get: ++ summary: Fetch cache diagnostics ++ tags: ++ - Server ++ responses: ++ '200': ++ description: OK ++ content: ++ text/plain: ++ schema: ++ type: string ++ /server/reboot: ++ post: ++ summary: Reboot the server process ++ tags: ++ - Server ++ responses: ++ '200': ++ description: OK ++ content: {} + /session: + get: + summary: Fetch Session information +@@ -925,6 +1187,19 @@ paths: + schema: + $ref: '#/components/schemas/User' + x-codegen-request-body-name: body ++ /users/totp: ++ post: ++ summary: Generate TOTP secret ++ tags: ++ - Users ++ security: [] ++ responses: ++ '200': ++ description: OK ++ content: ++ text/plain: ++ schema: ++ type: string + /users/{id}: + put: + summary: Update a User diff --git a/tasks/traccar__traccar-5790/solution/solve.sh b/tasks/traccar__traccar-5790/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5790/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/traccar__traccar-5790/task.toml b/tasks/traccar__traccar-5790/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..39819eb5bd4c5a8b311bccc08ce1d6eefa8cee20 --- /dev/null +++ b/tasks/traccar__traccar-5790/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5790" +description = "Add missing Device, Position, Server and User API endpoints to openapi.yaml" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "0436abf3bafbfa3bb7f7b489bdf47302124a6398" +reference = "https://github.com/traccar/traccar/pull/5790" +source_access = "auto" +built_at = "2026-11-16T16:09:42.606969+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:eeaa1f0a6f48a2fc8947bf7ba796528b7056442313038f7dcd0a8cc37f51cc2b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-17T13:53:21Z" +diff_format = "unified" +context_files = [ + "openapi.yaml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 275 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.481107+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:102ff3c53420174b4b1ce35fedbae40246d8ba4c9acfdb2420aa836b74dba363" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5790/tests/capture.py b/tasks/traccar__traccar-5790/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5790/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/traccar__traccar-5790/tests/instruction.md b/tasks/traccar__traccar-5790/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b6bb377d9651b215a89711daa4cf0baf99b06836 --- /dev/null +++ b/tasks/traccar__traccar-5790/tests/instruction.md @@ -0,0 +1,47 @@ +# Issue + +**Title:** Add missing Device, Position, Server and User API endpoints to openapi.yaml + +## Description + +While working on a [Laravel PHP Traccae API integration](https://traccar.thingstelemetry.com/introduction/getting-started.html) I noted that some endpoints were missing on `openapi.yaml` file. + +This PR expand `openapi.yaml` by adding several new endpoints that are in the source code. + +### Missing 'excludeAttributes' spec + +- Added a query parameter `excludeAttributes` that that lets clients omit the attributes map from responses. + +### Device-related endpoints: + +- Added `/devices/{id}/image` endpoint used for uploading or updating a device image. +- Added `/devices/share` endpoint that enable sharing a device's location. + +### Position export endpoints: + +- Added `/positions/kml`, `/positions/csv`, and `/positions/gpx` endpoints that wllows exporting device positions in KML, CSV, and GPX formats, respectively. +- See [PositionResource](https://github.com/traccar/traccar/blob/0436abf3bafbfa3bb7f7b489bdf47302124a6398/src/main/java/org/traccar/api/resource/PositionResource.java) + +### Server utility endpoints: + +- Added several missing server endpoints: + - `/server/geocode` for reverse geocoding coordinates. + - `/server/timezones` to fetch available timezones. + - `/server/file/{path}` for uploading files to the server. + - `/server/gc` to trigger garbage collection. + - `/server/cache` to fetch cache diagnostics. + - `/server/reboot` to reboot the server process. +- See [ServerResource](https://github.com/traccar/traccar/blob/0436abf3bafbfa3bb7f7b489bdf47302124a6398/src/main/java/org/traccar/api/resource/ServerResource.java) + +### User authentication: + +- Added `/users/totp` endpoint to generate a TOTP secret +- See [UserResource](https://github.com/traccar/traccar/blob/0436abf3bafbfa3bb7f7b489bdf47302124a6398/src/main/java/org/traccar/api/resource/UserResource.java) + +The goal is to ensure that the `openapi.yaml` API documentation reflects all available endpoints in the source code. + +I am assuming the the missing endpoints were not a deliberate omissions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0436abf3bafb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5790/tests/oracle.patch b/tasks/traccar__traccar-5790/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..eda3449e917fef08b05c86fe04e78159dd5d8ef2 --- /dev/null +++ b/tasks/traccar__traccar-5790/tests/oracle.patch @@ -0,0 +1,314 @@ +diff --git a/openapi.yaml b/openapi.yaml +index a8a67fbc3..ace69491a 100644 +--- a/openapi.yaml ++++ b/openapi.yaml +@@ -415,6 +415,11 @@ paths: + `uniqueId=333331&uniqieId=44442` + schema: + type: string ++ - name: excludeAttributes ++ in: query ++ description: Exclude attributes field from device payload ++ schema: ++ type: boolean + responses: + '200': + description: OK +@@ -506,6 +511,69 @@ paths: + description: No Content + content: {} + x-codegen-request-body-name: body ++ /devices/{id}/image: ++ post: ++ summary: Upload/Update Device image ++ tags: ++ - Devices ++ parameters: ++ - name: id ++ in: path ++ required: true ++ schema: ++ type: integer ++ requestBody: ++ required: true ++ content: ++ image/*: ++ schema: ++ type: string ++ format: binary ++ responses: ++ '200': ++ description: OK ++ content: ++ text/plain: ++ schema: ++ type: string ++ example: device.png ++ '400': ++ description: Invalid image type or size ++ content: {} ++ '404': ++ description: Device not found ++ content: {} ++ /devices/share: ++ post: ++ summary: Share device location ++ tags: ++ - Devices ++ requestBody: ++ required: true ++ content: ++ application/x-www-form-urlencoded: ++ schema: ++ type: object ++ required: ++ - deviceId ++ - expiration ++ properties: ++ deviceId: ++ type: integer ++ expiration: ++ type: string ++ format: date-time ++ responses: ++ '200': ++ description: OK ++ content: ++ text/plain: ++ schema: ++ type: string ++ example: eyJhbGciOi... ++ '403': ++ description: Sharing is disabled or temporary user ++ content: {} + /groups: + get: + summary: Fetch a list of Groups +@@ -734,6 +802,103 @@ paths: + '404': + description: Not Found + content: {} ++ /positions/kml: ++ get: ++ summary: Export Positions as KML ++ tags: ++ - Positions ++ parameters: ++ - name: deviceId ++ in: query ++ required: true ++ schema: ++ type: integer ++ - name: from ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ - name: to ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ responses: ++ '200': ++ description: OK ++ content: ++ application/vnd.google-earth.kml+xml: ++ schema: ++ type: string ++ format: binary ++ /positions/csv: ++ get: ++ summary: Export Positions as CSV ++ tags: ++ - Positions ++ parameters: ++ - name: deviceId ++ in: query ++ required: true ++ schema: ++ type: integer ++ - name: geofenceId ++ in: query ++ schema: ++ type: integer ++ - name: from ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ - name: to ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ responses: ++ '200': ++ description: OK ++ content: ++ text/csv: ++ schema: ++ type: string ++ format: binary ++ /positions/gpx: ++ get: ++ summary: Export Positions as GPX ++ tags: ++ - Positions ++ parameters: ++ - name: deviceId ++ in: query ++ required: true ++ schema: ++ type: integer ++ - name: from ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ - name: to ++ in: query ++ required: true ++ schema: ++ type: string ++ format: date-time ++ responses: ++ '200': ++ description: OK ++ content: ++ application/gpx+xml: ++ schema: ++ type: string ++ format: binary + /server: + get: + summary: Fetch Server information +@@ -765,6 +930,103 @@ paths: + schema: + $ref: '#/components/schemas/Server' + x-codegen-request-body-name: body ++ /server/geocode: ++ get: ++ summary: Reverse geocode coordinates ++ tags: ++ - Server ++ parameters: ++ - name: latitude ++ in: query ++ required: true ++ schema: ++ type: number ++ format: double ++ - name: longitude ++ in: query ++ required: true ++ schema: ++ type: number ++ format: double ++ responses: ++ '200': ++ description: OK ++ content: ++ text/plain: ++ schema: ++ type: string ++ '500': ++ description: Reverse geocoding is not enabled ++ content: {} ++ /server/timezones: ++ get: ++ summary: Fetch available timezones ++ tags: ++ - Server ++ responses: ++ '200': ++ description: OK ++ content: ++ application/json: ++ schema: ++ type: array ++ items: ++ type: string ++ /server/file/{path}: ++ post: ++ summary: Upload a server file ++ tags: ++ - Server ++ parameters: ++ - name: path ++ in: path ++ required: true ++ schema: ++ type: string ++ requestBody: ++ content: ++ application/octet-stream: ++ schema: ++ type: string ++ format: binary ++ required: true ++ responses: ++ '200': ++ description: OK ++ content: {} ++ '400': ++ description: Bad Request ++ content: {} ++ /server/gc: ++ get: ++ summary: Trigger garbage collection ++ tags: ++ - Server ++ responses: ++ '200': ++ description: OK ++ content: {} ++ /server/cache: ++ get: ++ summary: Fetch cache diagnostics ++ tags: ++ - Server ++ responses: ++ '200': ++ description: OK ++ content: ++ text/plain: ++ schema: ++ type: string ++ /server/reboot: ++ post: ++ summary: Reboot the server process ++ tags: ++ - Server ++ responses: ++ '200': ++ description: OK ++ content: {} + /session: + get: + summary: Fetch Session information +@@ -925,6 +1187,19 @@ paths: + schema: + $ref: '#/components/schemas/User' + x-codegen-request-body-name: body ++ /users/totp: ++ post: ++ summary: Generate TOTP secret ++ tags: ++ - Users ++ security: [] ++ responses: ++ '200': ++ description: OK ++ content: ++ text/plain: ++ schema: ++ type: string + /users/{id}: + put: + summary: Update a User diff --git a/tasks/traccar__traccar-5790/tests/test.sh b/tasks/traccar__traccar-5790/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..26e27842d7c250b324c28403dafcea9734e00b33 --- /dev/null +++ b/tasks/traccar__traccar-5790/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 0436abf3bafbfa3bb7f7b489bdf47302124a6398 > "$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/traccar__traccar-5790/tests/verifier.py b/tasks/traccar__traccar-5790/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5790/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/traccar__traccar-5795/environment/Dockerfile b/tasks/traccar__traccar-5795/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a5ff89c494169d2f80890070224b6c2c490e2fc1 --- /dev/null +++ b/tasks/traccar__traccar-5795/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d07f1964336305bbe8decb49dbd802b09227d357 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d07f1964336305bbe8decb49dbd802b09227d357 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d07f1964336305bbe8decb49dbd802b09227d357 \ + && 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/traccar__traccar-5795/instruction.md b/tasks/traccar__traccar-5795/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cd58ae81f3332581289229e166a3dc8580164e48 --- /dev/null +++ b/tasks/traccar__traccar-5795/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Refactor ArnaviBinaryProtocolDecoder constants and methods + +## Description + +As previously recommended, I made it inline. +Fixed sendResponse, tags 5 and 9. +Fixed message handling — Arnavi can send multiple packets at once. +Added CAN and LLS tags. +Tested on real data. +Protocol description attached. +https://docs.google.com/spreadsheets/d/15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU/edit?pref=2&pli=1&gid=12#gid=12 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d07f19643363`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5795/solution/patch.diff b/tasks/traccar__traccar-5795/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6a18de113e2fc264951e82f3b550ac5356c74175 --- /dev/null +++ b/tasks/traccar__traccar-5795/solution/patch.diff @@ -0,0 +1,413 @@ +diff --git a/src/main/java/org/traccar/protocol/ArnaviBinaryProtocolDecoder.java b/src/main/java/org/traccar/protocol/ArnaviBinaryProtocolDecoder.java +index 8f983296f..6a5676610 100644 +--- a/src/main/java/org/traccar/protocol/ArnaviBinaryProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/ArnaviBinaryProtocolDecoder.java +@@ -25,6 +25,8 @@ import org.traccar.session.DeviceSession; + import org.traccar.NetworkMessage; + import org.traccar.Protocol; + import org.traccar.helper.Checksum; ++import org.traccar.model.CellTower; ++import org.traccar.model.Network; + import org.traccar.model.Position; + + import java.net.SocketAddress; +@@ -34,80 +36,225 @@ import java.util.List; + + public class ArnaviBinaryProtocolDecoder extends BaseProtocolDecoder { + +- private static final byte HEADER_START_SIGN = (byte) 0xff; +- private static final byte HEADER_VERSION_1 = 0x22; +- private static final byte HEADER_VERSION_2 = 0x23; ++ private static final int HEADER_START_SIGN = 0xFF; + +- private static final byte RECORD_PING = 0x00; +- private static final byte RECORD_DATA = 0x01; +- private static final byte RECORD_TEXT = 0x03; +- private static final byte RECORD_FILE = 0x04; +- private static final byte RECORD_BINARY = 0x06; ++ private static final int HEADER_VERSION_1 = 0x22; ++ private static final int HEADER_VERSION_2 = 0x23; ++ private static final int HEADER_VERSION_3 = 0x24; ++ ++ private static final int RECORD_PING = 0x00; ++ private static final int RECORD_DATA = 0x01; ++ private static final int RECORD_TEXT = 0x03; ++ private static final int RECORD_FILE = 0x04; ++ private static final int RECORD_BINARY = 0x06; + + public ArnaviBinaryProtocolDecoder(Protocol protocol) { + super(protocol); + } + +- private void sendResponse(Channel channel, byte version, int index) { ++ private void sendResponse(Channel channel, int version, int index) { + if (channel != null) { + ByteBuf response = Unpooled.buffer(); +- response.writeByte(0x7b); ++ response.writeByte(0x7B); ++ + if (version == HEADER_VERSION_1) { + response.writeByte(0x00); + response.writeByte((byte) index); + } else if (version == HEADER_VERSION_2) { + response.writeByte(0x04); + response.writeByte(0x00); +- ByteBuf time = Unpooled.buffer(); +- time.writeBytes(time); +- response.writeByte(Checksum.modulo256(time.nioBuffer())); +- response.writeBytes(time); +- time.release(); ++ ++ long unixTime = System.currentTimeMillis() / 1000; ++ ByteBuf timeBytes = Unpooled.buffer(4); ++ timeBytes.writeIntLE((int) unixTime); ++ ++ response.writeByte(Checksum.modulo256(timeBytes.nioBuffer())); ++ response.writeBytes(timeBytes); ++ timeBytes.release(); + } +- response.writeByte(0x7d); ++ response.writeByte(0x7D); + channel.writeAndFlush(new NetworkMessage(response, channel.remoteAddress())); + } ++ ++ + } + + private Position decodePosition(DeviceSession deviceSession, ByteBuf buf, int length, Date time) { + +- final Position position = new Position(); +- position.setProtocol(getProtocolName()); ++ Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); +- + position.setTime(time); + ++ int cid = 0, lac = 0, mnc = 0, mcc = 0, rssi = 0; ++ + int readBytes = 0; + while (readBytes < length) { +- short tag = buf.readUnsignedByte(); ++ ++ int tag = buf.readUnsignedByte(); ++ + switch (tag) { ++ + case 1: +- position.set(Position.KEY_POWER, buf.readUnsignedShortLE() / 1000.0); +- position.set(Position.KEY_BATTERY, buf.readUnsignedShortLE() / 1000.0); ++ int batMv = buf.readUnsignedShortLE(); ++ int extMv = buf.readUnsignedShortLE(); ++ if (extMv != 0x0000 && extMv != 0xFFFF) { ++ position.set(Position.KEY_POWER, extMv / 1000.0); ++ } ++ if (batMv != 0x0000 && batMv != 0xFFFF) { ++ position.set(Position.KEY_BATTERY, batMv / 1000.0); ++ } + break; + + case 3: + position.setLatitude(buf.readFloatLE()); +- position.setValid(true); + break; + + case 4: + position.setLongitude(buf.readFloatLE()); +- position.setValid(true); + break; + + case 5: +- position.setCourse(buf.readUnsignedByte() * 2); +- position.setAltitude(buf.readUnsignedByte() * 10); +- byte satellites = buf.readByte(); +- position.set(Position.KEY_SATELLITES, satellites & 0x0F + (satellites >> 4) & 0x0F); +- position.setSpeed(buf.readUnsignedByte()); ++ int course = buf.readUnsignedByte() * 2; ++ int altitude = buf.readUnsignedByte() * 10; ++ int satByte = buf.readUnsignedByte(); ++ int speed = buf.readUnsignedByte(); ++ if (satByte == 0xFE || satByte == 0xFF) { ++ position.setValid(false); ++ } else { ++ position.setCourse(course); ++ position.setAltitude(altitude); ++ position.setSpeed(speed); ++ position.set(Position.KEY_SATELLITES, ++ BitUtil.between(satByte, 0, 4) + BitUtil.between(satByte, 4, 8)); ++ position.setValid(true); ++ } ++ break; ++ ++ case 6: ++ switch (buf.readUnsignedByte()) { ++ case 0x01: ++ int virtualSensors = buf.readUnsignedByte(); ++ int physicalInputs = buf.readUnsignedShortLE(); ++ position.set("virtualIgnition", BitUtil.check(virtualSensors, 0)); ++ position.set("callButton", BitUtil.check(virtualSensors, 1)); ++ position.set(Position.KEY_INPUT, physicalInputs); ++ break; ++ ++ case 0x06: ++ position.set("pulses" + buf.readUnsignedByte(), buf.readUnsignedShortLE()); ++ break; ++ ++ case 0x07: ++ position.set("freq" + buf.readUnsignedByte(), buf.readUnsignedShortLE()); ++ break; ++ ++ case 0x08: ++ position.set(Position.PREFIX_ADC + buf.readUnsignedByte(), ++ buf.readUnsignedShortLE() / 1000.0); ++ break; ++ ++ default: ++ buf.skipBytes(3); ++ break; ++ } ++ break; ++ ++ case 7: ++ cid = buf.readUnsignedShortLE(); ++ lac = buf.readUnsignedShortLE(); ++ break; ++ ++ case 8: ++ rssi = buf.readUnsignedByte(); ++ mcc = buf.readUnsignedShortLE(); ++ mnc = buf.readUnsignedByte(); + break; + + case 9: +- long status = buf.readUnsignedIntLE(); +- position.set(Position.KEY_POWER, BitUtil.from(status, 24) * 150 / 1000.0); +- position.set(Position.KEY_STATUS, status); ++ position.set(Position.KEY_STATUS, (long) buf.readUnsignedIntLE()); ++ break; ++ ++ case 51: ++ position.set("canStatus", buf.readUnsignedIntLE()); ++ break; ++ ++ case 52: ++ position.set(Position.KEY_HOURS, (long) (buf.readUnsignedIntLE() / 100.0 * 3600 * 1000)); ++ break; ++ ++ case 53: ++ position.set(Position.KEY_ODOMETER, (long) (buf.readUnsignedIntLE() / 100.0 * 1000)); ++ break; ++ ++ case 54: ++ position.set(Position.KEY_FUEL_USED, buf.readUnsignedIntLE() / 10.0); ++ break; ++ ++ case 55: ++ position.set(Position.KEY_FUEL_LEVEL, buf.readUnsignedShortLE() / 10.0); ++ buf.skipBytes(2); ++ break; ++ ++ case 56: ++ position.set("fuelLitres", buf.readUnsignedIntLE()); ++ break; ++ ++ case 57: ++ position.set(Position.KEY_RPM, buf.readUnsignedShortLE()); ++ buf.skipBytes(2); ++ break; ++ ++ case 58: ++ position.set(Position.KEY_ENGINE_TEMP, buf.readUnsignedIntLE()); ++ break; ++ ++ case 59: ++ position.set(Position.KEY_OBD_SPEED, buf.readUnsignedIntLE()); ++ break; ++ ++ case 60: ++ case 61: ++ case 62: ++ case 63: ++ case 64: ++ int axleIndex = tag - 60 + 1; ++ if (axleIndex == 2) { ++ position.set(Position.KEY_AXLE_WEIGHT, buf.readUnsignedIntLE()); ++ } else { ++ position.set("axleLoad" + axleIndex, buf.readUnsignedIntLE()); ++ } ++ break; ++ ++ case 69: ++ position.set(Position.KEY_ENGINE_LOAD, buf.readUnsignedByte()); ++ position.set(Position.KEY_THROTTLE, buf.readUnsignedByte()); ++ int motionBits = buf.readUnsignedShortLE(); ++ if (motionBits != 0) { ++ position.set("motionState", motionBits); ++ } ++ break; ++ ++ case 71: ++ case 72: ++ case 73: ++ case 74: ++ case 75: ++ case 76: ++ case 77: ++ case 78: ++ case 79: ++ int idx = tag - 70; ++ int level = buf.readUnsignedShortLE(); ++ int tempRaw = buf.readUnsignedShortLE(); ++ if (level != 0x0000 && level != 0xFFFF) { ++ position.set("rawFuelLevel" + idx, level); ++ position.set("llsTemperture" + idx, (tempRaw - 100.0) / 10.0); ++ } ++ break; ++ ++ case 151: ++ position.set(Position.KEY_HDOP, buf.readUnsignedShortLE() / 100.0); ++ buf.skipBytes(2); + break; + + default: +@@ -115,9 +262,11 @@ public class ArnaviBinaryProtocolDecoder extends BaseProtocolDecoder { + break; + } + +- readBytes += 1 + 4; ++ readBytes += 5; ++ } ++ if (mcc != 0 || mnc != 0 || lac != 0 || cid != 0 || rssi != 0) { ++ position.setNetwork(new Network(CellTower.from(mcc, mnc, lac, cid, rssi))); + } +- + return position; + } + +@@ -126,19 +275,21 @@ public class ArnaviBinaryProtocolDecoder extends BaseProtocolDecoder { + + ByteBuf buf = (ByteBuf) msg; + +- byte startSign = buf.readByte(); ++ int startSign = buf.readUnsignedByte(); + + if (startSign == HEADER_START_SIGN) { + +- byte version = buf.readByte(); ++ int version = buf.readUnsignedByte(); ++ long imeiLong = buf.readLongLE(); + +- String imei = String.valueOf(buf.readLongLE()); +- DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei); ++ if (version == HEADER_VERSION_3 && buf.readableBytes() >= 8) { ++ buf.skipBytes(8); ++ } + ++ DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, String.valueOf(imeiLong)); + if (deviceSession != null) { + sendResponse(channel, version, 0); + } +- + return null; + } + +@@ -148,35 +299,32 @@ public class ArnaviBinaryProtocolDecoder extends BaseProtocolDecoder { + } + + List positions = new LinkedList<>(); +- + int index = buf.readUnsignedByte(); + +- byte recordType = buf.readByte(); +- while (buf.readableBytes() > 0) { ++ while (buf.readableBytes() > 1) { ++ ++ int recordType = buf.readUnsignedByte(); ++ + switch (recordType) { +- case RECORD_PING, RECORD_DATA, RECORD_TEXT, RECORD_FILE, RECORD_BINARY -> { ++ case RECORD_PING, RECORD_DATA, RECORD_TEXT, RECORD_FILE, RECORD_BINARY: + int length = buf.readUnsignedShortLE(); + Date time = new Date(buf.readUnsignedIntLE() * 1000); +- + if (recordType == RECORD_DATA) { + positions.add(decodePosition(deviceSession, buf, length, time)); + } else { +- buf.readBytes(length); ++ buf.skipBytes(length); + } ++ buf.readUnsignedByte(); ++ break; + +- buf.readUnsignedByte(); // checksum +- } +- default -> { +- return null; +- } ++ default: ++ return positions.isEmpty() ? null : positions; + } +- +- recordType = buf.readByte(); + } + + sendResponse(channel, HEADER_VERSION_1, index); + +- return positions; ++ return positions.isEmpty() ? null : positions; + } + + } +diff --git a/src/test/java/org/traccar/protocol/ArnaviBinaryProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/ArnaviBinaryProtocolDecoderTest.java +index e38e63755..db8f01c6c 100644 +--- a/src/test/java/org/traccar/protocol/ArnaviBinaryProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/ArnaviBinaryProtocolDecoderTest.java +@@ -2,6 +2,7 @@ package org.traccar.protocol; + + import org.junit.jupiter.api.Test; + import org.traccar.ProtocolTest; ++import org.traccar.model.Position; + + public class ArnaviBinaryProtocolDecoderTest extends ProtocolTest { + +@@ -31,4 +32,39 @@ public class ArnaviBinaryProtocolDecoderTest extends ProtocolTest { + position("2017-07-07 05:09:55.000", true, 45.05597, 39.03347)); + } + +-} ++ @Test ++ public void testHeader3Decode() throws Exception { ++ ++ var decoder = inject(new ArnaviBinaryProtocolDecoder(null)); ++ ++ verifyNull(decoder, binary("ff24f30c45f5c90f03000102030405060708")); ++ ++ verifyPositions(decoder, binary( ++ "5b01012800a3175f5903513934420447221c42055402781E0900f0c5215b4e0084005c00007c005d0000a300fa3701000029012800a3175f5903513934420447221c42055402781E0900f0c5215b4e0084005c00007c005d0000a300fa37010000295d"), ++ position("2017-07-07 05:09:55.000", true, 45.05597, 39.03347)); ++ } ++ ++ @Test ++ public void testDecode() throws Exception { ++ ++ var decoder = inject(new ArnaviBinaryProtocolDecoder(null)); ++ ++ verifyNull(decoder, binary("ff23ae52a969f30c45f5")); ++ ++ verifyPositions(decoder, binary( ++ "5bae0196008a52a9690373f35c42049746ac420574147529973e00000007ca325cb061ca3200000863fa001e96e553fe006353801a0201b50f5d6c0601010000474e0000005b4e0000005c000017005d000017003203000000330040110034d83b05003579b7200136700e090037c301000039ce0300003a4c0000003b4e0000003c8a0101003db8ab0000404c010000be1e4b00c045002d0000fa3b010000d75d"), ++ position("2026-03-05 09:53:14.000", true, 55.237743, 86.137871)); ++ ++ verifyAttribute(decoder, binary( ++ "5bae0196008a52a9690373f35c42049746ac420574147529973e00000007ca325cb061ca3200000863fa001e96e553fe006353801a0201b50f5d6c0601010000474e0000005b4e0000005c000017005d000017003203000000330040110034d83b05003579b7200136700e090037c301000039ce0300003a4c0000003b4e0000003c8a0101003db8ab0000404c010000be1e4b00c045002d0000fa3b010000d75d"), ++ Position.KEY_RPM, 974); ++ ++ verifyAttribute(decoder, binary( ++ "5bae0196008a52a9690373f35c42049746ac420574147529973e00000007ca325cb061ca3200000863fa001e96e553fe006353801a0201b50f5d6c0601010000474e0000005b4e0000005c000017005d000017003203000000330040110034d83b05003579b7200136700e090037c301000039ce0300003a4c0000003b4e0000003c8a0101003db8ab0000404c010000be1e4b00c045002d0000fa3b010000d75d"), ++ Position.KEY_HOURS, 12348000000L); ++ ++ verifyAttribute(decoder, binary( ++ "5bae0196008a52a9690373f35c42049746ac420574147529973e00000007ca325cb061ca3200000863fa001e96e553fe006353801a0201b50f5d6c0601010000474e0000005b4e0000005c000017005d000017003203000000330040110034d83b05003579b7200136700e090037c301000039ce0300003a4c0000003b4e0000003c8a0101003db8ab0000404c010000be1e4b00c045002d0000fa3b010000d75d"), ++ Position.KEY_ODOMETER, 189213370L); ++ } ++} +\ No newline at end of file diff --git a/tasks/traccar__traccar-5795/solution/solve.sh b/tasks/traccar__traccar-5795/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5795/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/traccar__traccar-5795/task.toml b/tasks/traccar__traccar-5795/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9f32389763a16b5f774664ed2b4e6e1ab2e6dab8 --- /dev/null +++ b/tasks/traccar__traccar-5795/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5795" +description = "Refactor ArnaviBinaryProtocolDecoder constants and methods" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "d07f1964336305bbe8decb49dbd802b09227d357" +reference = "https://github.com/traccar/traccar/pull/5795" +source_access = "auto" +built_at = "2026-11-16T16:09:42.596576+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:562e3e4cf8d0650a4839531963536c84f86512359895fdfc922e762c0ab3c0e0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-15T14:20:07Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/ArnaviBinaryProtocolDecoder.java", + "src/test/java/org/traccar/protocol/ArnaviBinaryProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 292 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.481722+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8350decf407e4c245fdec290fa0e0290babbdbc1976ec54c53e944f25e5c275a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5795/tests/capture.py b/tasks/traccar__traccar-5795/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5795/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/traccar__traccar-5795/tests/instruction.md b/tasks/traccar__traccar-5795/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cd58ae81f3332581289229e166a3dc8580164e48 --- /dev/null +++ b/tasks/traccar__traccar-5795/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Refactor ArnaviBinaryProtocolDecoder constants and methods + +## Description + +As previously recommended, I made it inline. +Fixed sendResponse, tags 5 and 9. +Fixed message handling — Arnavi can send multiple packets at once. +Added CAN and LLS tags. +Tested on real data. +Protocol description attached. +https://docs.google.com/spreadsheets/d/15s-2ZbqOQ1bZvAtFFm9sIEuKy3jbJzxdeynp72sjoYU/edit?pref=2&pli=1&gid=12#gid=12 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d07f19643363`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5795/tests/oracle.patch b/tasks/traccar__traccar-5795/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6a18de113e2fc264951e82f3b550ac5356c74175 --- /dev/null +++ b/tasks/traccar__traccar-5795/tests/oracle.patch @@ -0,0 +1,413 @@ +diff --git a/src/main/java/org/traccar/protocol/ArnaviBinaryProtocolDecoder.java b/src/main/java/org/traccar/protocol/ArnaviBinaryProtocolDecoder.java +index 8f983296f..6a5676610 100644 +--- a/src/main/java/org/traccar/protocol/ArnaviBinaryProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/ArnaviBinaryProtocolDecoder.java +@@ -25,6 +25,8 @@ import org.traccar.session.DeviceSession; + import org.traccar.NetworkMessage; + import org.traccar.Protocol; + import org.traccar.helper.Checksum; ++import org.traccar.model.CellTower; ++import org.traccar.model.Network; + import org.traccar.model.Position; + + import java.net.SocketAddress; +@@ -34,80 +36,225 @@ import java.util.List; + + public class ArnaviBinaryProtocolDecoder extends BaseProtocolDecoder { + +- private static final byte HEADER_START_SIGN = (byte) 0xff; +- private static final byte HEADER_VERSION_1 = 0x22; +- private static final byte HEADER_VERSION_2 = 0x23; ++ private static final int HEADER_START_SIGN = 0xFF; + +- private static final byte RECORD_PING = 0x00; +- private static final byte RECORD_DATA = 0x01; +- private static final byte RECORD_TEXT = 0x03; +- private static final byte RECORD_FILE = 0x04; +- private static final byte RECORD_BINARY = 0x06; ++ private static final int HEADER_VERSION_1 = 0x22; ++ private static final int HEADER_VERSION_2 = 0x23; ++ private static final int HEADER_VERSION_3 = 0x24; ++ ++ private static final int RECORD_PING = 0x00; ++ private static final int RECORD_DATA = 0x01; ++ private static final int RECORD_TEXT = 0x03; ++ private static final int RECORD_FILE = 0x04; ++ private static final int RECORD_BINARY = 0x06; + + public ArnaviBinaryProtocolDecoder(Protocol protocol) { + super(protocol); + } + +- private void sendResponse(Channel channel, byte version, int index) { ++ private void sendResponse(Channel channel, int version, int index) { + if (channel != null) { + ByteBuf response = Unpooled.buffer(); +- response.writeByte(0x7b); ++ response.writeByte(0x7B); ++ + if (version == HEADER_VERSION_1) { + response.writeByte(0x00); + response.writeByte((byte) index); + } else if (version == HEADER_VERSION_2) { + response.writeByte(0x04); + response.writeByte(0x00); +- ByteBuf time = Unpooled.buffer(); +- time.writeBytes(time); +- response.writeByte(Checksum.modulo256(time.nioBuffer())); +- response.writeBytes(time); +- time.release(); ++ ++ long unixTime = System.currentTimeMillis() / 1000; ++ ByteBuf timeBytes = Unpooled.buffer(4); ++ timeBytes.writeIntLE((int) unixTime); ++ ++ response.writeByte(Checksum.modulo256(timeBytes.nioBuffer())); ++ response.writeBytes(timeBytes); ++ timeBytes.release(); + } +- response.writeByte(0x7d); ++ response.writeByte(0x7D); + channel.writeAndFlush(new NetworkMessage(response, channel.remoteAddress())); + } ++ ++ + } + + private Position decodePosition(DeviceSession deviceSession, ByteBuf buf, int length, Date time) { + +- final Position position = new Position(); +- position.setProtocol(getProtocolName()); ++ Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); +- + position.setTime(time); + ++ int cid = 0, lac = 0, mnc = 0, mcc = 0, rssi = 0; ++ + int readBytes = 0; + while (readBytes < length) { +- short tag = buf.readUnsignedByte(); ++ ++ int tag = buf.readUnsignedByte(); ++ + switch (tag) { ++ + case 1: +- position.set(Position.KEY_POWER, buf.readUnsignedShortLE() / 1000.0); +- position.set(Position.KEY_BATTERY, buf.readUnsignedShortLE() / 1000.0); ++ int batMv = buf.readUnsignedShortLE(); ++ int extMv = buf.readUnsignedShortLE(); ++ if (extMv != 0x0000 && extMv != 0xFFFF) { ++ position.set(Position.KEY_POWER, extMv / 1000.0); ++ } ++ if (batMv != 0x0000 && batMv != 0xFFFF) { ++ position.set(Position.KEY_BATTERY, batMv / 1000.0); ++ } + break; + + case 3: + position.setLatitude(buf.readFloatLE()); +- position.setValid(true); + break; + + case 4: + position.setLongitude(buf.readFloatLE()); +- position.setValid(true); + break; + + case 5: +- position.setCourse(buf.readUnsignedByte() * 2); +- position.setAltitude(buf.readUnsignedByte() * 10); +- byte satellites = buf.readByte(); +- position.set(Position.KEY_SATELLITES, satellites & 0x0F + (satellites >> 4) & 0x0F); +- position.setSpeed(buf.readUnsignedByte()); ++ int course = buf.readUnsignedByte() * 2; ++ int altitude = buf.readUnsignedByte() * 10; ++ int satByte = buf.readUnsignedByte(); ++ int speed = buf.readUnsignedByte(); ++ if (satByte == 0xFE || satByte == 0xFF) { ++ position.setValid(false); ++ } else { ++ position.setCourse(course); ++ position.setAltitude(altitude); ++ position.setSpeed(speed); ++ position.set(Position.KEY_SATELLITES, ++ BitUtil.between(satByte, 0, 4) + BitUtil.between(satByte, 4, 8)); ++ position.setValid(true); ++ } ++ break; ++ ++ case 6: ++ switch (buf.readUnsignedByte()) { ++ case 0x01: ++ int virtualSensors = buf.readUnsignedByte(); ++ int physicalInputs = buf.readUnsignedShortLE(); ++ position.set("virtualIgnition", BitUtil.check(virtualSensors, 0)); ++ position.set("callButton", BitUtil.check(virtualSensors, 1)); ++ position.set(Position.KEY_INPUT, physicalInputs); ++ break; ++ ++ case 0x06: ++ position.set("pulses" + buf.readUnsignedByte(), buf.readUnsignedShortLE()); ++ break; ++ ++ case 0x07: ++ position.set("freq" + buf.readUnsignedByte(), buf.readUnsignedShortLE()); ++ break; ++ ++ case 0x08: ++ position.set(Position.PREFIX_ADC + buf.readUnsignedByte(), ++ buf.readUnsignedShortLE() / 1000.0); ++ break; ++ ++ default: ++ buf.skipBytes(3); ++ break; ++ } ++ break; ++ ++ case 7: ++ cid = buf.readUnsignedShortLE(); ++ lac = buf.readUnsignedShortLE(); ++ break; ++ ++ case 8: ++ rssi = buf.readUnsignedByte(); ++ mcc = buf.readUnsignedShortLE(); ++ mnc = buf.readUnsignedByte(); + break; + + case 9: +- long status = buf.readUnsignedIntLE(); +- position.set(Position.KEY_POWER, BitUtil.from(status, 24) * 150 / 1000.0); +- position.set(Position.KEY_STATUS, status); ++ position.set(Position.KEY_STATUS, (long) buf.readUnsignedIntLE()); ++ break; ++ ++ case 51: ++ position.set("canStatus", buf.readUnsignedIntLE()); ++ break; ++ ++ case 52: ++ position.set(Position.KEY_HOURS, (long) (buf.readUnsignedIntLE() / 100.0 * 3600 * 1000)); ++ break; ++ ++ case 53: ++ position.set(Position.KEY_ODOMETER, (long) (buf.readUnsignedIntLE() / 100.0 * 1000)); ++ break; ++ ++ case 54: ++ position.set(Position.KEY_FUEL_USED, buf.readUnsignedIntLE() / 10.0); ++ break; ++ ++ case 55: ++ position.set(Position.KEY_FUEL_LEVEL, buf.readUnsignedShortLE() / 10.0); ++ buf.skipBytes(2); ++ break; ++ ++ case 56: ++ position.set("fuelLitres", buf.readUnsignedIntLE()); ++ break; ++ ++ case 57: ++ position.set(Position.KEY_RPM, buf.readUnsignedShortLE()); ++ buf.skipBytes(2); ++ break; ++ ++ case 58: ++ position.set(Position.KEY_ENGINE_TEMP, buf.readUnsignedIntLE()); ++ break; ++ ++ case 59: ++ position.set(Position.KEY_OBD_SPEED, buf.readUnsignedIntLE()); ++ break; ++ ++ case 60: ++ case 61: ++ case 62: ++ case 63: ++ case 64: ++ int axleIndex = tag - 60 + 1; ++ if (axleIndex == 2) { ++ position.set(Position.KEY_AXLE_WEIGHT, buf.readUnsignedIntLE()); ++ } else { ++ position.set("axleLoad" + axleIndex, buf.readUnsignedIntLE()); ++ } ++ break; ++ ++ case 69: ++ position.set(Position.KEY_ENGINE_LOAD, buf.readUnsignedByte()); ++ position.set(Position.KEY_THROTTLE, buf.readUnsignedByte()); ++ int motionBits = buf.readUnsignedShortLE(); ++ if (motionBits != 0) { ++ position.set("motionState", motionBits); ++ } ++ break; ++ ++ case 71: ++ case 72: ++ case 73: ++ case 74: ++ case 75: ++ case 76: ++ case 77: ++ case 78: ++ case 79: ++ int idx = tag - 70; ++ int level = buf.readUnsignedShortLE(); ++ int tempRaw = buf.readUnsignedShortLE(); ++ if (level != 0x0000 && level != 0xFFFF) { ++ position.set("rawFuelLevel" + idx, level); ++ position.set("llsTemperture" + idx, (tempRaw - 100.0) / 10.0); ++ } ++ break; ++ ++ case 151: ++ position.set(Position.KEY_HDOP, buf.readUnsignedShortLE() / 100.0); ++ buf.skipBytes(2); + break; + + default: +@@ -115,9 +262,11 @@ public class ArnaviBinaryProtocolDecoder extends BaseProtocolDecoder { + break; + } + +- readBytes += 1 + 4; ++ readBytes += 5; ++ } ++ if (mcc != 0 || mnc != 0 || lac != 0 || cid != 0 || rssi != 0) { ++ position.setNetwork(new Network(CellTower.from(mcc, mnc, lac, cid, rssi))); + } +- + return position; + } + +@@ -126,19 +275,21 @@ public class ArnaviBinaryProtocolDecoder extends BaseProtocolDecoder { + + ByteBuf buf = (ByteBuf) msg; + +- byte startSign = buf.readByte(); ++ int startSign = buf.readUnsignedByte(); + + if (startSign == HEADER_START_SIGN) { + +- byte version = buf.readByte(); ++ int version = buf.readUnsignedByte(); ++ long imeiLong = buf.readLongLE(); + +- String imei = String.valueOf(buf.readLongLE()); +- DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei); ++ if (version == HEADER_VERSION_3 && buf.readableBytes() >= 8) { ++ buf.skipBytes(8); ++ } + ++ DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, String.valueOf(imeiLong)); + if (deviceSession != null) { + sendResponse(channel, version, 0); + } +- + return null; + } + +@@ -148,35 +299,32 @@ public class ArnaviBinaryProtocolDecoder extends BaseProtocolDecoder { + } + + List positions = new LinkedList<>(); +- + int index = buf.readUnsignedByte(); + +- byte recordType = buf.readByte(); +- while (buf.readableBytes() > 0) { ++ while (buf.readableBytes() > 1) { ++ ++ int recordType = buf.readUnsignedByte(); ++ + switch (recordType) { +- case RECORD_PING, RECORD_DATA, RECORD_TEXT, RECORD_FILE, RECORD_BINARY -> { ++ case RECORD_PING, RECORD_DATA, RECORD_TEXT, RECORD_FILE, RECORD_BINARY: + int length = buf.readUnsignedShortLE(); + Date time = new Date(buf.readUnsignedIntLE() * 1000); +- + if (recordType == RECORD_DATA) { + positions.add(decodePosition(deviceSession, buf, length, time)); + } else { +- buf.readBytes(length); ++ buf.skipBytes(length); + } ++ buf.readUnsignedByte(); ++ break; + +- buf.readUnsignedByte(); // checksum +- } +- default -> { +- return null; +- } ++ default: ++ return positions.isEmpty() ? null : positions; + } +- +- recordType = buf.readByte(); + } + + sendResponse(channel, HEADER_VERSION_1, index); + +- return positions; ++ return positions.isEmpty() ? null : positions; + } + + } +diff --git a/src/test/java/org/traccar/protocol/ArnaviBinaryProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/ArnaviBinaryProtocolDecoderTest.java +index e38e63755..db8f01c6c 100644 +--- a/src/test/java/org/traccar/protocol/ArnaviBinaryProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/ArnaviBinaryProtocolDecoderTest.java +@@ -2,6 +2,7 @@ package org.traccar.protocol; + + import org.junit.jupiter.api.Test; + import org.traccar.ProtocolTest; ++import org.traccar.model.Position; + + public class ArnaviBinaryProtocolDecoderTest extends ProtocolTest { + +@@ -31,4 +32,39 @@ public class ArnaviBinaryProtocolDecoderTest extends ProtocolTest { + position("2017-07-07 05:09:55.000", true, 45.05597, 39.03347)); + } + +-} ++ @Test ++ public void testHeader3Decode() throws Exception { ++ ++ var decoder = inject(new ArnaviBinaryProtocolDecoder(null)); ++ ++ verifyNull(decoder, binary("ff24f30c45f5c90f03000102030405060708")); ++ ++ verifyPositions(decoder, binary( ++ "5b01012800a3175f5903513934420447221c42055402781E0900f0c5215b4e0084005c00007c005d0000a300fa3701000029012800a3175f5903513934420447221c42055402781E0900f0c5215b4e0084005c00007c005d0000a300fa37010000295d"), ++ position("2017-07-07 05:09:55.000", true, 45.05597, 39.03347)); ++ } ++ ++ @Test ++ public void testDecode() throws Exception { ++ ++ var decoder = inject(new ArnaviBinaryProtocolDecoder(null)); ++ ++ verifyNull(decoder, binary("ff23ae52a969f30c45f5")); ++ ++ verifyPositions(decoder, binary( ++ "5bae0196008a52a9690373f35c42049746ac420574147529973e00000007ca325cb061ca3200000863fa001e96e553fe006353801a0201b50f5d6c0601010000474e0000005b4e0000005c000017005d000017003203000000330040110034d83b05003579b7200136700e090037c301000039ce0300003a4c0000003b4e0000003c8a0101003db8ab0000404c010000be1e4b00c045002d0000fa3b010000d75d"), ++ position("2026-03-05 09:53:14.000", true, 55.237743, 86.137871)); ++ ++ verifyAttribute(decoder, binary( ++ "5bae0196008a52a9690373f35c42049746ac420574147529973e00000007ca325cb061ca3200000863fa001e96e553fe006353801a0201b50f5d6c0601010000474e0000005b4e0000005c000017005d000017003203000000330040110034d83b05003579b7200136700e090037c301000039ce0300003a4c0000003b4e0000003c8a0101003db8ab0000404c010000be1e4b00c045002d0000fa3b010000d75d"), ++ Position.KEY_RPM, 974); ++ ++ verifyAttribute(decoder, binary( ++ "5bae0196008a52a9690373f35c42049746ac420574147529973e00000007ca325cb061ca3200000863fa001e96e553fe006353801a0201b50f5d6c0601010000474e0000005b4e0000005c000017005d000017003203000000330040110034d83b05003579b7200136700e090037c301000039ce0300003a4c0000003b4e0000003c8a0101003db8ab0000404c010000be1e4b00c045002d0000fa3b010000d75d"), ++ Position.KEY_HOURS, 12348000000L); ++ ++ verifyAttribute(decoder, binary( ++ "5bae0196008a52a9690373f35c42049746ac420574147529973e00000007ca325cb061ca3200000863fa001e96e553fe006353801a0201b50f5d6c0601010000474e0000005b4e0000005c000017005d000017003203000000330040110034d83b05003579b7200136700e090037c301000039ce0300003a4c0000003b4e0000003c8a0101003db8ab0000404c010000be1e4b00c045002d0000fa3b010000d75d"), ++ Position.KEY_ODOMETER, 189213370L); ++ } ++} +\ No newline at end of file diff --git a/tasks/traccar__traccar-5795/tests/test.sh b/tasks/traccar__traccar-5795/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f359db586ea54b1b9a2a2b9b8b4dd89ee48bc596 --- /dev/null +++ b/tasks/traccar__traccar-5795/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 d07f1964336305bbe8decb49dbd802b09227d357 > "$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/traccar__traccar-5795/tests/verifier.py b/tasks/traccar__traccar-5795/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5795/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/traccar__traccar-5801/environment/Dockerfile b/tasks/traccar__traccar-5801/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b7fbf48020bb50dda873da9e948792cc49e143e6 --- /dev/null +++ b/tasks/traccar__traccar-5801/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5288bee04d66c8fc9b37db9e4bd60dffa935bac6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5288bee04d66c8fc9b37db9e4bd60dffa935bac6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5288bee04d66c8fc9b37db9e4bd60dffa935bac6 \ + && 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/traccar__traccar-5801/instruction.md b/tasks/traccar__traccar-5801/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..574e584af7714211796a09008157c009256f503a --- /dev/null +++ b/tasks/traccar__traccar-5801/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Fix OpenID administrator flag not syncing for existing users + +## Description + +###Issue: + +When OpenID group membership changes, the administrator flag +is only set during initial user creation and is not updated +for existing users on subsequent logins. + +###Steps to reproduce: + +1. Login with a user in adminGroups (administrator = true) +2. Remove the user from adminGroups in the OpenID provider +3. Login again +4. Administrator flag remains unchanged + +###Fix: + +Synchronize the administrator flag on every OpenID login +by comparing and updating it if necessary. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5288bee04d66`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5801/solution/patch.diff b/tasks/traccar__traccar-5801/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d2956ad6e066e743a784a717d0a80f215ee31ded --- /dev/null +++ b/tasks/traccar__traccar-5801/solution/patch.diff @@ -0,0 +1,48 @@ +diff --git a/src/main/java/org/traccar/api/security/LoginService.java b/src/main/java/org/traccar/api/security/LoginService.java +index 507288c31..7e5b3b279 100644 +--- a/src/main/java/org/traccar/api/security/LoginService.java ++++ b/src/main/java/org/traccar/api/security/LoginService.java +@@ -35,6 +35,7 @@ import jakarta.inject.Singleton; + import java.io.IOException; + import java.nio.charset.StandardCharsets; + import java.security.GeneralSecurityException; ++import java.util.Objects; + + @Singleton + public class LoginService { +@@ -117,9 +118,10 @@ public class LoginService { + } + + public LoginResult login(String email, String name, boolean administrator) throws StorageException { ++ + User user = storage.getObject(User.class, new Request( +- new Columns.All(), +- new Condition.Equals("email", email))); ++ new Columns.All(), ++ new Condition.Equals("email", email))); + + if (user == null) { + user = new User(); +@@ -129,11 +131,21 @@ public class LoginService { + user.setFixedEmail(true); + user.setAdministrator(administrator); + user.setId(storage.addObject(user, new Request(new Columns.Exclude("id")))); ++ ++ } else if (!Objects.equals(name, user.getName()) ++ || user.getAdministrator() != administrator) { ++ ++ user.setName(name); ++ user.setAdministrator(administrator); ++ ++ storage.updateObject(user, new Request( ++ new Columns.Include("name", "administrator"), ++ new Condition.Equals("id", user.getId()))); + } ++ + checkUserEnabled(user); + return new LoginResult(user); + } +- + private void checkUserEnabled(User user) throws SecurityException { + if (user == null) { + throw new SecurityException("Unknown account"); diff --git a/tasks/traccar__traccar-5801/solution/solve.sh b/tasks/traccar__traccar-5801/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5801/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/traccar__traccar-5801/task.toml b/tasks/traccar__traccar-5801/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..678005802c645d8895c77098d51aa96257496763 --- /dev/null +++ b/tasks/traccar__traccar-5801/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5801" +description = "Fix OpenID administrator flag not syncing for existing users" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "5288bee04d66c8fc9b37db9e4bd60dffa935bac6" +reference = "https://github.com/traccar/traccar/pull/5801" +source_access = "auto" +built_at = "2026-11-16T16:09:42.605226+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3acfd49d77002686db9046431001b690135e909784a1624c9b36c39c6f840a22" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-25T14:30:51Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/api/security/LoginService.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.482306+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d3d8a235c1fb7a5c70bd48a6da587d3af6ffdfca92c5b90742467523723cd796" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5801/tests/capture.py b/tasks/traccar__traccar-5801/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5801/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/traccar__traccar-5801/tests/instruction.md b/tasks/traccar__traccar-5801/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..574e584af7714211796a09008157c009256f503a --- /dev/null +++ b/tasks/traccar__traccar-5801/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Fix OpenID administrator flag not syncing for existing users + +## Description + +###Issue: + +When OpenID group membership changes, the administrator flag +is only set during initial user creation and is not updated +for existing users on subsequent logins. + +###Steps to reproduce: + +1. Login with a user in adminGroups (administrator = true) +2. Remove the user from adminGroups in the OpenID provider +3. Login again +4. Administrator flag remains unchanged + +###Fix: + +Synchronize the administrator flag on every OpenID login +by comparing and updating it if necessary. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5288bee04d66`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5801/tests/oracle.patch b/tasks/traccar__traccar-5801/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d2956ad6e066e743a784a717d0a80f215ee31ded --- /dev/null +++ b/tasks/traccar__traccar-5801/tests/oracle.patch @@ -0,0 +1,48 @@ +diff --git a/src/main/java/org/traccar/api/security/LoginService.java b/src/main/java/org/traccar/api/security/LoginService.java +index 507288c31..7e5b3b279 100644 +--- a/src/main/java/org/traccar/api/security/LoginService.java ++++ b/src/main/java/org/traccar/api/security/LoginService.java +@@ -35,6 +35,7 @@ import jakarta.inject.Singleton; + import java.io.IOException; + import java.nio.charset.StandardCharsets; + import java.security.GeneralSecurityException; ++import java.util.Objects; + + @Singleton + public class LoginService { +@@ -117,9 +118,10 @@ public class LoginService { + } + + public LoginResult login(String email, String name, boolean administrator) throws StorageException { ++ + User user = storage.getObject(User.class, new Request( +- new Columns.All(), +- new Condition.Equals("email", email))); ++ new Columns.All(), ++ new Condition.Equals("email", email))); + + if (user == null) { + user = new User(); +@@ -129,11 +131,21 @@ public class LoginService { + user.setFixedEmail(true); + user.setAdministrator(administrator); + user.setId(storage.addObject(user, new Request(new Columns.Exclude("id")))); ++ ++ } else if (!Objects.equals(name, user.getName()) ++ || user.getAdministrator() != administrator) { ++ ++ user.setName(name); ++ user.setAdministrator(administrator); ++ ++ storage.updateObject(user, new Request( ++ new Columns.Include("name", "administrator"), ++ new Condition.Equals("id", user.getId()))); + } ++ + checkUserEnabled(user); + return new LoginResult(user); + } +- + private void checkUserEnabled(User user) throws SecurityException { + if (user == null) { + throw new SecurityException("Unknown account"); diff --git a/tasks/traccar__traccar-5801/tests/test.sh b/tasks/traccar__traccar-5801/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6f90277b22599ac72e711c2d9fb235dfa49b68c6 --- /dev/null +++ b/tasks/traccar__traccar-5801/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 5288bee04d66c8fc9b37db9e4bd60dffa935bac6 > "$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/traccar__traccar-5801/tests/verifier.py b/tasks/traccar__traccar-5801/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5801/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/traccar__traccar-5804/environment/Dockerfile b/tasks/traccar__traccar-5804/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..79c0e5b5de35e9f2586462328afcfabe2320365a --- /dev/null +++ b/tasks/traccar__traccar-5804/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 71a73dee6244231624fe78780bd309dd083011cf 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 71a73dee6244231624fe78780bd309dd083011cf \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 71a73dee6244231624fe78780bd309dd083011cf \ + && 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/traccar__traccar-5804/instruction.md b/tasks/traccar__traccar-5804/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73529e51f979fd2b28a3bdd257220d1b2b47582a --- /dev/null +++ b/tasks/traccar__traccar-5804/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** ttnhttp: Add `time` and `wifi` fields + +## Description + +Hi, my [Sensecap T1000](https://www.seeedstudio.com/sensecap-t1000-tracker) seems to be able to store positions while out of network range and then later upload them once reconnected to a LoRaWAN gateway, so a `time` field is mildly important. It also has the capability for scanning WiFi APs, so I've added a `wifi` field too. + +- The `time` field is just an ISO 8601 formatted string. +- The `wifi` field is an object containing BSSIDs as the keys, which each contains another object with the keys `rssi` and optionally `channel` (e.g. `"wifi":{"a1:b2:c3:d4:e5:f6":{"rssi":-84, "channel":1}}`). + +As I've very much strayed from the base TTN Mapper format, how would I go about adding a documentation page similar to [OsmAnd](https://www.traccar.org/osmand/)? Should I create an issue, or just create a post on the forum? + +Thanks, +Steve + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `71a73dee6244`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5804/solution/patch.diff b/tasks/traccar__traccar-5804/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6380a024d55fafc319f03172365c872a3a5f2caf --- /dev/null +++ b/tasks/traccar__traccar-5804/solution/patch.diff @@ -0,0 +1,73 @@ +diff --git a/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java b/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java +index 966c1482e..643333130 100644 +--- a/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java +@@ -28,7 +28,9 @@ import jakarta.json.JsonValue; + import org.traccar.BaseHttpProtocolDecoder; + import org.traccar.Protocol; + import org.traccar.helper.DateUtil; ++import org.traccar.model.Network; + import org.traccar.model.Position; ++import org.traccar.model.WifiAccessPoint; + import org.traccar.session.DeviceSession; + + import java.io.StringReader; +@@ -64,6 +66,8 @@ public class TtnHttpProtocolDecoder extends BaseHttpProtocolDecoder { + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + ++ Network network = new Network(); ++ + JsonObject message = root.getJsonObject("uplink_message"); + if (message == null) { + sendResponse(channel, HttpResponseStatus.BAD_REQUEST); +@@ -110,6 +114,18 @@ public class TtnHttpProtocolDecoder extends BaseHttpProtocolDecoder { + case "sats" -> position.set(Position.KEY_SATELLITES, payload.getJsonNumber(key).intValue()); + case "speed" -> position.setSpeed(convertSpeed(payload.getJsonNumber(key).doubleValue(), "kn")); + case "heading" -> position.setCourse(payload.getJsonNumber(key).doubleValue()); ++ case "time" -> position.setTime(DateUtil.parseDate(payload.getString(key))); ++ case "wifi" -> { ++ JsonObject networksObject = payload.getJsonObject(key); ++ for (String macAddress : networksObject.keySet()) { ++ JsonObject networkObject = networksObject.getJsonObject(macAddress); ++ WifiAccessPoint ap = WifiAccessPoint.from(macAddress, networkObject.getInt("rssi")); ++ if (networkObject.containsKey("channel")) { ++ ap.setChannel(networkObject.getInt("channel")); ++ } ++ network.addWifiAccessPoint(ap); ++ } ++ } + default -> decodeJsonValue(position, key, payload.get(key)); + } + } +@@ -121,6 +137,10 @@ public class TtnHttpProtocolDecoder extends BaseHttpProtocolDecoder { + getLastLocation(position, null); + } + ++ if (network.getWifiAccessPoints() != null) { ++ position.setNetwork(network); ++ } ++ + sendResponse(channel, HttpResponseStatus.OK); + return position; + } +diff --git a/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java +index e23d748ea..ff2b440e9 100644 +--- a/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java +@@ -13,11 +13,14 @@ public class TtnHttpProtocolDecoderTest extends ProtocolTest { + var decoder = inject(new TtnHttpProtocolDecoder(null)); + + verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( +- "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIVpAyHNAIgFtcvtXxgAEWIAAAsAAgBaAIQAYwCCAAB7tQBnAS0AcyeRAGh5\",\"decoded_payload\":{\"altitude\":44.5,\"barometer_0\":1012.9,\"hdop\":0.9,\"heading\":99,\"humidity_0\":60.5,\"latitude\":37.4219,\"longitude\":-122.084,\"sats\":11,\"speed\":31.669,\"temperature_0\":30.1,\"time\":1762936141},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"location\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":47,\"source\":\"SOURCE_REGISTRY\"},\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); ++ "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIVpAyHNAIgFtcvtXxgAEWIAAAsAAgBaAIQAYwCCAAB7tQBnAS0AcyeRAGh5\",\"decoded_payload\":{\"altitude\":44.5,\"barometer_0\":1012.9,\"hdop\":0.9,\"heading\":99,\"humidity_0\":60.5,\"latitude\":37.4219,\"longitude\":-122.084,\"sats\":11,\"speed\":31.669,\"temperature_0\":30.1,\"time\":\"2025-11-12T08:29:01.000Z\"},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"location\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":47,\"source\":\"SOURCE_REGISTRY\"},\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); + + verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( + "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIgFxALtUoAAEWIAZwEQAWcA/w==\",\"decoded_payload\":{\"gps_0\":{\"altitude\": 44.5,\"latitude\": 37.7858,\"longitude\": -122.4064},\"temperature_0\": 27.2,\"temperature_1\":25.5},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.7858,\"longitude\":-122.4064,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); + ++ verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( ++ "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIgFxALtUoAAEWIAZwEQAWcA/w==\",\"decoded_payload\":{\"latitude\": 37.7858,\"longitude\": -122.4064,\"temp1\": 27.2,\"time\":\"2025-11-12T02:59:23.000Z\",\"wifi\": {\"A1:B2:C3:D4:E5:F6\": {\"rssi\":-10, \"channel\": 1}}},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.7858,\"longitude\":-122.4064,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); ++ + } + + } diff --git a/tasks/traccar__traccar-5804/solution/solve.sh b/tasks/traccar__traccar-5804/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5804/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/traccar__traccar-5804/task.toml b/tasks/traccar__traccar-5804/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b840c5792b8cfa612f2e93f7631d387fe9172a32 --- /dev/null +++ b/tasks/traccar__traccar-5804/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5804" +description = "ttnhttp: Add `time` and `wifi` fields" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "71a73dee6244231624fe78780bd309dd083011cf" +reference = "https://github.com/traccar/traccar/pull/5804" +source_access = "auto" +built_at = "2026-11-16T16:09:42.603740+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9270677dabc6c4bea73c87a545a6896c806f2f72e209f6f4936ea807260f1f71" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-28T13:43:28Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java", + "src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 25 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.482906+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:21229cb06393473b72c93813910a3ad9f70d3a53a37fff537bcef8fdb108e1fa" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5804/tests/capture.py b/tasks/traccar__traccar-5804/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5804/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/traccar__traccar-5804/tests/instruction.md b/tasks/traccar__traccar-5804/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73529e51f979fd2b28a3bdd257220d1b2b47582a --- /dev/null +++ b/tasks/traccar__traccar-5804/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** ttnhttp: Add `time` and `wifi` fields + +## Description + +Hi, my [Sensecap T1000](https://www.seeedstudio.com/sensecap-t1000-tracker) seems to be able to store positions while out of network range and then later upload them once reconnected to a LoRaWAN gateway, so a `time` field is mildly important. It also has the capability for scanning WiFi APs, so I've added a `wifi` field too. + +- The `time` field is just an ISO 8601 formatted string. +- The `wifi` field is an object containing BSSIDs as the keys, which each contains another object with the keys `rssi` and optionally `channel` (e.g. `"wifi":{"a1:b2:c3:d4:e5:f6":{"rssi":-84, "channel":1}}`). + +As I've very much strayed from the base TTN Mapper format, how would I go about adding a documentation page similar to [OsmAnd](https://www.traccar.org/osmand/)? Should I create an issue, or just create a post on the forum? + +Thanks, +Steve + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `71a73dee6244`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5804/tests/oracle.patch b/tasks/traccar__traccar-5804/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6380a024d55fafc319f03172365c872a3a5f2caf --- /dev/null +++ b/tasks/traccar__traccar-5804/tests/oracle.patch @@ -0,0 +1,73 @@ +diff --git a/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java b/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java +index 966c1482e..643333130 100644 +--- a/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TtnHttpProtocolDecoder.java +@@ -28,7 +28,9 @@ import jakarta.json.JsonValue; + import org.traccar.BaseHttpProtocolDecoder; + import org.traccar.Protocol; + import org.traccar.helper.DateUtil; ++import org.traccar.model.Network; + import org.traccar.model.Position; ++import org.traccar.model.WifiAccessPoint; + import org.traccar.session.DeviceSession; + + import java.io.StringReader; +@@ -64,6 +66,8 @@ public class TtnHttpProtocolDecoder extends BaseHttpProtocolDecoder { + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + ++ Network network = new Network(); ++ + JsonObject message = root.getJsonObject("uplink_message"); + if (message == null) { + sendResponse(channel, HttpResponseStatus.BAD_REQUEST); +@@ -110,6 +114,18 @@ public class TtnHttpProtocolDecoder extends BaseHttpProtocolDecoder { + case "sats" -> position.set(Position.KEY_SATELLITES, payload.getJsonNumber(key).intValue()); + case "speed" -> position.setSpeed(convertSpeed(payload.getJsonNumber(key).doubleValue(), "kn")); + case "heading" -> position.setCourse(payload.getJsonNumber(key).doubleValue()); ++ case "time" -> position.setTime(DateUtil.parseDate(payload.getString(key))); ++ case "wifi" -> { ++ JsonObject networksObject = payload.getJsonObject(key); ++ for (String macAddress : networksObject.keySet()) { ++ JsonObject networkObject = networksObject.getJsonObject(macAddress); ++ WifiAccessPoint ap = WifiAccessPoint.from(macAddress, networkObject.getInt("rssi")); ++ if (networkObject.containsKey("channel")) { ++ ap.setChannel(networkObject.getInt("channel")); ++ } ++ network.addWifiAccessPoint(ap); ++ } ++ } + default -> decodeJsonValue(position, key, payload.get(key)); + } + } +@@ -121,6 +137,10 @@ public class TtnHttpProtocolDecoder extends BaseHttpProtocolDecoder { + getLastLocation(position, null); + } + ++ if (network.getWifiAccessPoints() != null) { ++ position.setNetwork(network); ++ } ++ + sendResponse(channel, HttpResponseStatus.OK); + return position; + } +diff --git a/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java +index e23d748ea..ff2b440e9 100644 +--- a/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/TtnHttpProtocolDecoderTest.java +@@ -13,11 +13,14 @@ public class TtnHttpProtocolDecoderTest extends ProtocolTest { + var decoder = inject(new TtnHttpProtocolDecoder(null)); + + verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( +- "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIVpAyHNAIgFtcvtXxgAEWIAAAsAAgBaAIQAYwCCAAB7tQBnAS0AcyeRAGh5\",\"decoded_payload\":{\"altitude\":44.5,\"barometer_0\":1012.9,\"hdop\":0.9,\"heading\":99,\"humidity_0\":60.5,\"latitude\":37.4219,\"longitude\":-122.084,\"sats\":11,\"speed\":31.669,\"temperature_0\":30.1,\"time\":1762936141},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"location\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":47,\"source\":\"SOURCE_REGISTRY\"},\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); ++ "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIVpAyHNAIgFtcvtXxgAEWIAAAsAAgBaAIQAYwCCAAB7tQBnAS0AcyeRAGh5\",\"decoded_payload\":{\"altitude\":44.5,\"barometer_0\":1012.9,\"hdop\":0.9,\"heading\":99,\"humidity_0\":60.5,\"latitude\":37.4219,\"longitude\":-122.084,\"sats\":11,\"speed\":31.669,\"temperature_0\":30.1,\"time\":\"2025-11-12T08:29:01.000Z\"},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"location\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":47,\"source\":\"SOURCE_REGISTRY\"},\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.4219,\"longitude\":-122.084,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); + + verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( + "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIgFxALtUoAAEWIAZwEQAWcA/w==\",\"decoded_payload\":{\"gps_0\":{\"altitude\": 44.5,\"latitude\": 37.7858,\"longitude\": -122.4064},\"temperature_0\": 27.2,\"temperature_1\":25.5},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.7858,\"longitude\":-122.4064,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); + ++ verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( ++ "{\"end_device_ids\":{\"device_id\":\"test-device\",\"application_ids\":{\"application_id\":\"test-app\"},\"dev_eui\":\"0000000000000000\",\"dev_addr\":\"00000000\"},\"received_at\":\"2025-11-12T08:29:01.954236764Z\",\"uplink_message\":{\"f_port\":1,\"f_cnt\":15,\"frm_payload\":\"AIgFxALtUoAAEWIAZwEQAWcA/w==\",\"decoded_payload\":{\"latitude\": 37.7858,\"longitude\": -122.4064,\"temp1\": 27.2,\"time\":\"2025-11-12T02:59:23.000Z\",\"wifi\": {\"A1:B2:C3:D4:E5:F6\": {\"rssi\":-10, \"channel\": 1}}},\"rx_metadata\":[{\"gateway_ids\":{\"gateway_id\":\"test-gateway\",\"eui\":\"0000000000000000\"},\"time\":\"2025-11-12T08:29:01.553412Z\",\"rssi\":-58,\"channel_rssi\":-58,\"snr\":12,\"received_at\":\"2025-11-12T08:23:02.467711084Z\"}],\"settings\":{\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7,\"coding_rate\":\"4/5\"}},\"frequency\":\"916800000\"},\"received_at\":\"2025-11-12T08:29:01.749842730Z\",\"consumed_airtime\":\"0.112896s\",\"packet_error_rate\":0.7777778,\"locations\":{\"frm-payload\":{\"latitude\":37.7858,\"longitude\":-122.4064,\"altitude\":44,\"source\":\"SOURCE_GPS\"}},\"network_ids\":{\"net_id\":\"000013\",\"ns_id\":\"EC656E0000000183\",\"tenant_id\":\"ttn\",\"cluster_id\":\"au1\",\"cluster_address\":\"au1.cloud.thethings.network\"}}}"))); ++ + } + + } diff --git a/tasks/traccar__traccar-5804/tests/test.sh b/tasks/traccar__traccar-5804/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..47cd52585a6b412d8113e66e1fb5af7ec70dcb7e --- /dev/null +++ b/tasks/traccar__traccar-5804/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 71a73dee6244231624fe78780bd309dd083011cf > "$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/traccar__traccar-5804/tests/verifier.py b/tasks/traccar__traccar-5804/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5804/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/traccar__traccar-5812/environment/Dockerfile b/tasks/traccar__traccar-5812/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..68ab168fa1bd0c2fdade24f8868bfb7a1ef2b002 --- /dev/null +++ b/tasks/traccar__traccar-5812/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2f5037701921c9e14b9c16608a75b68eea0b81fd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2f5037701921c9e14b9c16608a75b68eea0b81fd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2f5037701921c9e14b9c16608a75b68eea0b81fd \ + && 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/traccar__traccar-5812/instruction.md b/tasks/traccar__traccar-5812/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6da8ed82a61bd66ba7d2bbb511c4f36c30aba67a --- /dev/null +++ b/tasks/traccar__traccar-5812/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Implement daily summary scheduled report + +## Description + +**Purpose:** Scheduled summary report only supports type `Summary` and not type `Daily Summary`. + +**Solution:** This PR implements scheduled Summary report type `Daily Summary` in addition to type `Summary`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2f5037701921`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5812/solution/patch.diff b/tasks/traccar__traccar-5812/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..036d5cf143a1a154de2be2364abe0f3cc5bc8cb4 --- /dev/null +++ b/tasks/traccar__traccar-5812/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/src/main/java/org/traccar/schedule/TaskReports.java b/src/main/java/org/traccar/schedule/TaskReports.java +index bfe225267..d589bc630 100644 +--- a/src/main/java/org/traccar/schedule/TaskReports.java ++++ b/src/main/java/org/traccar/schedule/TaskReports.java +@@ -128,6 +128,9 @@ public class TaskReports extends SingleScheduleTask { + if (!groupIdsPart.isEmpty()) { + url.append(groupIdsPart).append('&'); + } ++ if (report.hasAttribute("daily")) { ++ url.append("daily=").append(report.getBoolean("daily")).append('&'); ++ } + url.append("from=").append(URLEncoder.encode(DateUtil.formatDate(from, true), StandardCharsets.UTF_8)); + url.append('&'); + url.append("to=").append(URLEncoder.encode(DateUtil.formatDate(to, true), StandardCharsets.UTF_8)); diff --git a/tasks/traccar__traccar-5812/solution/solve.sh b/tasks/traccar__traccar-5812/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5812/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/traccar__traccar-5812/task.toml b/tasks/traccar__traccar-5812/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b9fa9ddc2654ee57f3f1e0be32a8ae2a27e211f1 --- /dev/null +++ b/tasks/traccar__traccar-5812/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5812" +description = "Implement daily summary scheduled report" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "2f5037701921c9e14b9c16608a75b68eea0b81fd" +reference = "https://github.com/traccar/traccar/pull/5812" +source_access = "auto" +built_at = "2026-11-16T16:09:42.602203+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7907e3d7207962340f57f73641cc8dc55aa74f165cb95c7d9e8a138bc47aec01" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-12T13:57:14Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/schedule/TaskReports.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.483512+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a312e345300fb1e12a25c3067bd099d382869201d4d1441555e335d19013b3ea" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5812/tests/capture.py b/tasks/traccar__traccar-5812/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5812/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/traccar__traccar-5812/tests/instruction.md b/tasks/traccar__traccar-5812/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6da8ed82a61bd66ba7d2bbb511c4f36c30aba67a --- /dev/null +++ b/tasks/traccar__traccar-5812/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Implement daily summary scheduled report + +## Description + +**Purpose:** Scheduled summary report only supports type `Summary` and not type `Daily Summary`. + +**Solution:** This PR implements scheduled Summary report type `Daily Summary` in addition to type `Summary`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2f5037701921`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5812/tests/oracle.patch b/tasks/traccar__traccar-5812/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..036d5cf143a1a154de2be2364abe0f3cc5bc8cb4 --- /dev/null +++ b/tasks/traccar__traccar-5812/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/src/main/java/org/traccar/schedule/TaskReports.java b/src/main/java/org/traccar/schedule/TaskReports.java +index bfe225267..d589bc630 100644 +--- a/src/main/java/org/traccar/schedule/TaskReports.java ++++ b/src/main/java/org/traccar/schedule/TaskReports.java +@@ -128,6 +128,9 @@ public class TaskReports extends SingleScheduleTask { + if (!groupIdsPart.isEmpty()) { + url.append(groupIdsPart).append('&'); + } ++ if (report.hasAttribute("daily")) { ++ url.append("daily=").append(report.getBoolean("daily")).append('&'); ++ } + url.append("from=").append(URLEncoder.encode(DateUtil.formatDate(from, true), StandardCharsets.UTF_8)); + url.append('&'); + url.append("to=").append(URLEncoder.encode(DateUtil.formatDate(to, true), StandardCharsets.UTF_8)); diff --git a/tasks/traccar__traccar-5812/tests/test.sh b/tasks/traccar__traccar-5812/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0474f9ca8c74f4a00bdfe3b00343f27b3315efe2 --- /dev/null +++ b/tasks/traccar__traccar-5812/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 2f5037701921c9e14b9c16608a75b68eea0b81fd > "$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/traccar__traccar-5812/tests/verifier.py b/tasks/traccar__traccar-5812/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5812/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/traccar__traccar-5818/environment/Dockerfile b/tasks/traccar__traccar-5818/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..21956644d36f8126f474b06a5f129e584b804aa2 --- /dev/null +++ b/tasks/traccar__traccar-5818/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d2c27819328f2daff58cc1d9a5fe58b039582dc6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d2c27819328f2daff58cc1d9a5fe58b039582dc6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d2c27819328f2daff58cc1d9a5fe58b039582dc6 \ + && 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/traccar__traccar-5818/instruction.md b/tasks/traccar__traccar-5818/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5070e6c6f80292530660e996ed1302c27429a853 --- /dev/null +++ b/tasks/traccar__traccar-5818/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Xexun2 Protocol Correction + +## Description + +Corrects an issue where Xexun DDX14 plots about 1 degree east of reality. Math.floor produces the error where (int) corrects it. Test included. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d2c27819328f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5818/solution/patch.diff b/tasks/traccar__traccar-5818/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3f606b72d542d27d638106d3eecac26dcaa2e416 --- /dev/null +++ b/tasks/traccar__traccar-5818/solution/patch.diff @@ -0,0 +1,29 @@ +diff --git a/src/main/java/org/traccar/protocol/Xexun2ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun2ProtocolDecoder.java +index 99b5fedfb..fc24a8300 100644 +--- a/src/main/java/org/traccar/protocol/Xexun2ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Xexun2ProtocolDecoder.java +@@ -78,7 +78,7 @@ public class Xexun2ProtocolDecoder extends BaseProtocolDecoder { + } + + private double convertCoordinate(double value) { +- double degrees = Math.floor(value / 100); ++ double degrees = (int) (value / 100); + double minutes = value - degrees * 100; + return degrees + minutes / 60; + } +diff --git a/src/test/java/org/traccar/protocol/Xexun2ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Xexun2ProtocolDecoderTest.java +index b373c8283..c36b5acd5 100644 +--- a/src/test/java/org/traccar/protocol/Xexun2ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Xexun2ProtocolDecoderTest.java +@@ -29,6 +29,11 @@ public class Xexun2ProtocolDecoderTest extends ProtocolTest { + "FAAF0014000C8622050512345670002DF3A001002A0062D9047400005E0280001E47001B400D4BA732DF505E40B4153AAF78FEF00109000000000042B36666FAAF"), + position("2022-07-21 07:47:00.000", true, 51.68715, 0.06103)); + ++ // Negative longitude (West): DDMM.MMMM -12138.7186, 3705.8632 → -121.64531°, 37.09772° ++ verifyPositions(decoder, binary( ++ "FAAF0014000086220505123456700016F86F0100130065F0B2C200000002010Ac63daae045679dd0FAAF"), ++ position("2024-03-12 19:53:38.000", true, 37.09772, -121.64531)); ++ + } + + } diff --git a/tasks/traccar__traccar-5818/solution/solve.sh b/tasks/traccar__traccar-5818/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5818/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/traccar__traccar-5818/task.toml b/tasks/traccar__traccar-5818/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c38e4378b5aef6f2b424797eaa313c240217600c --- /dev/null +++ b/tasks/traccar__traccar-5818/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5818" +description = "Xexun2 Protocol Correction" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "d2c27819328f2daff58cc1d9a5fe58b039582dc6" +reference = "https://github.com/traccar/traccar/pull/5818" +source_access = "auto" +built_at = "2026-11-16T16:09:42.600740+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1f8c51b5174a48856d937d8d8a15a6d192a2f5457be12175e18c92cff5574738" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-14T14:47:41Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Xexun2ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Xexun2ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 7 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.484148+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2dd1e623377c7247328a72609449febe052eb6d50eee0aa21ae320f47f746b68" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5818/tests/capture.py b/tasks/traccar__traccar-5818/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5818/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/traccar__traccar-5818/tests/instruction.md b/tasks/traccar__traccar-5818/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5070e6c6f80292530660e996ed1302c27429a853 --- /dev/null +++ b/tasks/traccar__traccar-5818/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Xexun2 Protocol Correction + +## Description + +Corrects an issue where Xexun DDX14 plots about 1 degree east of reality. Math.floor produces the error where (int) corrects it. Test included. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d2c27819328f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5818/tests/oracle.patch b/tasks/traccar__traccar-5818/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3f606b72d542d27d638106d3eecac26dcaa2e416 --- /dev/null +++ b/tasks/traccar__traccar-5818/tests/oracle.patch @@ -0,0 +1,29 @@ +diff --git a/src/main/java/org/traccar/protocol/Xexun2ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun2ProtocolDecoder.java +index 99b5fedfb..fc24a8300 100644 +--- a/src/main/java/org/traccar/protocol/Xexun2ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Xexun2ProtocolDecoder.java +@@ -78,7 +78,7 @@ public class Xexun2ProtocolDecoder extends BaseProtocolDecoder { + } + + private double convertCoordinate(double value) { +- double degrees = Math.floor(value / 100); ++ double degrees = (int) (value / 100); + double minutes = value - degrees * 100; + return degrees + minutes / 60; + } +diff --git a/src/test/java/org/traccar/protocol/Xexun2ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Xexun2ProtocolDecoderTest.java +index b373c8283..c36b5acd5 100644 +--- a/src/test/java/org/traccar/protocol/Xexun2ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Xexun2ProtocolDecoderTest.java +@@ -29,6 +29,11 @@ public class Xexun2ProtocolDecoderTest extends ProtocolTest { + "FAAF0014000C8622050512345670002DF3A001002A0062D9047400005E0280001E47001B400D4BA732DF505E40B4153AAF78FEF00109000000000042B36666FAAF"), + position("2022-07-21 07:47:00.000", true, 51.68715, 0.06103)); + ++ // Negative longitude (West): DDMM.MMMM -12138.7186, 3705.8632 → -121.64531°, 37.09772° ++ verifyPositions(decoder, binary( ++ "FAAF0014000086220505123456700016F86F0100130065F0B2C200000002010Ac63daae045679dd0FAAF"), ++ position("2024-03-12 19:53:38.000", true, 37.09772, -121.64531)); ++ + } + + } diff --git a/tasks/traccar__traccar-5818/tests/test.sh b/tasks/traccar__traccar-5818/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6b9b4bd8b949712e026c7d7f11c231ad21b5be8b --- /dev/null +++ b/tasks/traccar__traccar-5818/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 d2c27819328f2daff58cc1d9a5fe58b039582dc6 > "$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/traccar__traccar-5818/tests/verifier.py b/tasks/traccar__traccar-5818/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5818/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/traccar__traccar-5831/environment/Dockerfile b/tasks/traccar__traccar-5831/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8acbd64ad6f7a5cbaae1af6fa0f1345275eb3790 --- /dev/null +++ b/tasks/traccar__traccar-5831/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fd2e58874517a2ac9770dd65dd01771d9d0f4d8e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fd2e58874517a2ac9770dd65dd01771d9d0f4d8e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fd2e58874517a2ac9770dd65dd01771d9d0f4d8e \ + && 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/traccar__traccar-5831/instruction.md b/tasks/traccar__traccar-5831/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1d1a5ded09f4e82e43cc7c8c7604531f0b92ca0c --- /dev/null +++ b/tasks/traccar__traccar-5831/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Support proxy configuration for Telegram notifications + +## Description + +## Summary + +Add optional proxy configuration for Telegram notifications. + +This allows Telegram requests to work in deployments where outbound access to `api.telegram.org` is restricted. + +## Changes + +- add Telegram proxy host, port, type, username, and password settings +- support optional HTTP and SOCKS5 proxies for Telegram notifications +- keep existing behavior unchanged when proxy is not configured + +## Verification + +- `./gradlew compileJava` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fd2e58874517`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5831/solution/patch.diff b/tasks/traccar__traccar-5831/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5422abbe8c8ef0b27338be4df3251ffd09aace34 --- /dev/null +++ b/tasks/traccar__traccar-5831/solution/patch.diff @@ -0,0 +1,79 @@ +diff --git a/src/main/java/org/traccar/config/Keys.java b/src/main/java/org/traccar/config/Keys.java +index fb8a066eb..ab6c8f47b 100644 +--- a/src/main/java/org/traccar/config/Keys.java ++++ b/src/main/java/org/traccar/config/Keys.java +@@ -1301,6 +1301,13 @@ public final class Keys { + "notificator.telegram.sendLocation", + List.of(KeyType.CONFIG)); + ++ /** ++ * Telegram notification proxy URL. ++ */ ++ public static final ConfigKey NOTIFICATOR_TELEGRAM_PROXY_URL = new StringConfigKey( ++ "notificator.telegram.proxy.url", ++ List.of(KeyType.CONFIG)); ++ + /** + * WhatsApp Cloud API permanent access token. + */ +diff --git a/src/main/java/org/traccar/notificators/NotificatorTelegram.java b/src/main/java/org/traccar/notificators/NotificatorTelegram.java +index 021bbe074..54ad59a28 100644 +--- a/src/main/java/org/traccar/notificators/NotificatorTelegram.java ++++ b/src/main/java/org/traccar/notificators/NotificatorTelegram.java +@@ -20,15 +20,20 @@ import com.fasterxml.jackson.annotation.JsonProperty; + import jakarta.inject.Inject; + import jakarta.inject.Singleton; + import jakarta.ws.rs.client.Client; ++import jakarta.ws.rs.client.ClientBuilder; + import jakarta.ws.rs.client.Entity; ++import org.glassfish.jersey.client.ClientProperties; + import org.traccar.config.Config; + import org.traccar.config.Keys; ++import org.traccar.helper.ObjectMapperContextResolver; + import org.traccar.model.Event; + import org.traccar.model.Position; + import org.traccar.model.User; + import org.traccar.notification.NotificationFormatter; + import org.traccar.notification.NotificationMessage; + ++import java.net.URI; ++ + @Singleton + public class NotificatorTelegram extends Notificator { + +@@ -62,15 +67,33 @@ public class NotificatorTelegram extends Notificator { + } + + @Inject +- public NotificatorTelegram(Config config, NotificationFormatter notificationFormatter, Client client) { ++ public NotificatorTelegram(Config config, NotificationFormatter notificationFormatter, ++ Client client, ObjectMapperContextResolver objectMapperContextResolver) { + super(notificationFormatter); +- this.client = client; + urlSendText = String.format( + "https://api.telegram.org/bot%s/sendMessage", config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); + urlSendLocation = String.format( + "https://api.telegram.org/bot%s/sendLocation", config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); + chatId = config.getString(Keys.NOTIFICATOR_TELEGRAM_CHAT_ID); + sendLocation = config.getBoolean(Keys.NOTIFICATOR_TELEGRAM_SEND_LOCATION); ++ ++ String proxyUrl = config.getString(Keys.NOTIFICATOR_TELEGRAM_PROXY_URL); ++ if (proxyUrl != null) { ++ ClientBuilder clientBuilder = ClientBuilder.newBuilder() ++ .register(objectMapperContextResolver) ++ .property(ClientProperties.PROXY_URI, proxyUrl); ++ String userInfo = URI.create(proxyUrl).getUserInfo(); ++ if (userInfo != null) { ++ String[] credentials = userInfo.split(":", 2); ++ clientBuilder.property(ClientProperties.PROXY_USERNAME, credentials[0]); ++ if (credentials.length > 1) { ++ clientBuilder.property(ClientProperties.PROXY_PASSWORD, credentials[1]); ++ } ++ } ++ this.client = clientBuilder.build(); ++ } else { ++ this.client = client; ++ } + } + + private LocationMessage createLocationMessage(String messageChatId, Position position) { diff --git a/tasks/traccar__traccar-5831/solution/solve.sh b/tasks/traccar__traccar-5831/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5831/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/traccar__traccar-5831/task.toml b/tasks/traccar__traccar-5831/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c433af25c29f84df326324c3d942ca1971ef58c1 --- /dev/null +++ b/tasks/traccar__traccar-5831/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5831" +description = "Support proxy configuration for Telegram notifications" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "fd2e58874517a2ac9770dd65dd01771d9d0f4d8e" +reference = "https://github.com/traccar/traccar/pull/5831" +source_access = "auto" +built_at = "2026-11-16T16:09:42.599313+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a5946ce2bb39ad5aa49b9282dcbbe0aa19190ac30b0cc68eb45935e803e8be3e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-23T17:18:13Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/config/Keys.java", + "src/main/java/org/traccar/notificators/NotificatorTelegram.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 34 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.484713+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:40ab811c1ba7a4e873ff7fe884353235ada37cb70a0b2463698783c17553b054" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5831/tests/capture.py b/tasks/traccar__traccar-5831/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5831/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/traccar__traccar-5831/tests/instruction.md b/tasks/traccar__traccar-5831/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1d1a5ded09f4e82e43cc7c8c7604531f0b92ca0c --- /dev/null +++ b/tasks/traccar__traccar-5831/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Support proxy configuration for Telegram notifications + +## Description + +## Summary + +Add optional proxy configuration for Telegram notifications. + +This allows Telegram requests to work in deployments where outbound access to `api.telegram.org` is restricted. + +## Changes + +- add Telegram proxy host, port, type, username, and password settings +- support optional HTTP and SOCKS5 proxies for Telegram notifications +- keep existing behavior unchanged when proxy is not configured + +## Verification + +- `./gradlew compileJava` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fd2e58874517`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5831/tests/oracle.patch b/tasks/traccar__traccar-5831/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5422abbe8c8ef0b27338be4df3251ffd09aace34 --- /dev/null +++ b/tasks/traccar__traccar-5831/tests/oracle.patch @@ -0,0 +1,79 @@ +diff --git a/src/main/java/org/traccar/config/Keys.java b/src/main/java/org/traccar/config/Keys.java +index fb8a066eb..ab6c8f47b 100644 +--- a/src/main/java/org/traccar/config/Keys.java ++++ b/src/main/java/org/traccar/config/Keys.java +@@ -1301,6 +1301,13 @@ public final class Keys { + "notificator.telegram.sendLocation", + List.of(KeyType.CONFIG)); + ++ /** ++ * Telegram notification proxy URL. ++ */ ++ public static final ConfigKey NOTIFICATOR_TELEGRAM_PROXY_URL = new StringConfigKey( ++ "notificator.telegram.proxy.url", ++ List.of(KeyType.CONFIG)); ++ + /** + * WhatsApp Cloud API permanent access token. + */ +diff --git a/src/main/java/org/traccar/notificators/NotificatorTelegram.java b/src/main/java/org/traccar/notificators/NotificatorTelegram.java +index 021bbe074..54ad59a28 100644 +--- a/src/main/java/org/traccar/notificators/NotificatorTelegram.java ++++ b/src/main/java/org/traccar/notificators/NotificatorTelegram.java +@@ -20,15 +20,20 @@ import com.fasterxml.jackson.annotation.JsonProperty; + import jakarta.inject.Inject; + import jakarta.inject.Singleton; + import jakarta.ws.rs.client.Client; ++import jakarta.ws.rs.client.ClientBuilder; + import jakarta.ws.rs.client.Entity; ++import org.glassfish.jersey.client.ClientProperties; + import org.traccar.config.Config; + import org.traccar.config.Keys; ++import org.traccar.helper.ObjectMapperContextResolver; + import org.traccar.model.Event; + import org.traccar.model.Position; + import org.traccar.model.User; + import org.traccar.notification.NotificationFormatter; + import org.traccar.notification.NotificationMessage; + ++import java.net.URI; ++ + @Singleton + public class NotificatorTelegram extends Notificator { + +@@ -62,15 +67,33 @@ public class NotificatorTelegram extends Notificator { + } + + @Inject +- public NotificatorTelegram(Config config, NotificationFormatter notificationFormatter, Client client) { ++ public NotificatorTelegram(Config config, NotificationFormatter notificationFormatter, ++ Client client, ObjectMapperContextResolver objectMapperContextResolver) { + super(notificationFormatter); +- this.client = client; + urlSendText = String.format( + "https://api.telegram.org/bot%s/sendMessage", config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); + urlSendLocation = String.format( + "https://api.telegram.org/bot%s/sendLocation", config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); + chatId = config.getString(Keys.NOTIFICATOR_TELEGRAM_CHAT_ID); + sendLocation = config.getBoolean(Keys.NOTIFICATOR_TELEGRAM_SEND_LOCATION); ++ ++ String proxyUrl = config.getString(Keys.NOTIFICATOR_TELEGRAM_PROXY_URL); ++ if (proxyUrl != null) { ++ ClientBuilder clientBuilder = ClientBuilder.newBuilder() ++ .register(objectMapperContextResolver) ++ .property(ClientProperties.PROXY_URI, proxyUrl); ++ String userInfo = URI.create(proxyUrl).getUserInfo(); ++ if (userInfo != null) { ++ String[] credentials = userInfo.split(":", 2); ++ clientBuilder.property(ClientProperties.PROXY_USERNAME, credentials[0]); ++ if (credentials.length > 1) { ++ clientBuilder.property(ClientProperties.PROXY_PASSWORD, credentials[1]); ++ } ++ } ++ this.client = clientBuilder.build(); ++ } else { ++ this.client = client; ++ } + } + + private LocationMessage createLocationMessage(String messageChatId, Position position) { diff --git a/tasks/traccar__traccar-5831/tests/test.sh b/tasks/traccar__traccar-5831/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8d362871e89b22eb906f900dd61dcda1bcafc155 --- /dev/null +++ b/tasks/traccar__traccar-5831/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 fd2e58874517a2ac9770dd65dd01771d9d0f4d8e > "$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/traccar__traccar-5831/tests/verifier.py b/tasks/traccar__traccar-5831/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5831/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/traccar__traccar-5834/environment/Dockerfile b/tasks/traccar__traccar-5834/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fbabbe9c9cf5010d567e8dc78aef9ef6c5e84506 --- /dev/null +++ b/tasks/traccar__traccar-5834/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin bd631d5e28d0cf368978289377d1b6b6c199aa58 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard bd631d5e28d0cf368978289377d1b6b6c199aa58 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base bd631d5e28d0cf368978289377d1b6b6c199aa58 \ + && 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/traccar__traccar-5834/instruction.md b/tasks/traccar__traccar-5834/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e73b9b9a49b8a122ad62a26a0a106252266fcb7f --- /dev/null +++ b/tasks/traccar__traccar-5834/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** GT06 NT20 protocol correction, hours should be long and odometer shou… + +## Description + +…ld be read as unsigned + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bd631d5e28d0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5834/solution/patch.diff b/tasks/traccar__traccar-5834/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ffd5b27fbbb912a464e8d42ef2b1fc8a9a194dfe --- /dev/null +++ b/tasks/traccar__traccar-5834/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +index c5c9a72ea..b46cbab45 100644 +--- a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +@@ -1027,8 +1027,8 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + + if (modelNT20 && type == MSG_GPS_LBS_2) { +- position.set(Position.KEY_ODOMETER, buf.readMedium()); +- position.set(Position.KEY_HOURS, buf.readMedium() * 60 * 1000); ++ position.set(Position.KEY_ODOMETER, buf.readUnsignedMedium()); ++ position.set(Position.KEY_HOURS, buf.readUnsignedMedium() * 60 * 1000L); + } + + if (buf.readableBytes() == 3 + 6 || buf.readableBytes() == 3 + 4 + 6) { +diff --git a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +index 92aff2387..2dc16cf87 100644 +--- a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +@@ -584,7 +584,7 @@ public class Gt06ProtocolDecoderTest extends ProtocolTest { + + verifyAttribute(decoder, binary( + "78783c22010357789648774484180c06142038180c06142038cb03313ee4061fe98300185e090000000000000000460984284c000200000000017101d6f35d0d0a"), +- Position.KEY_HOURS, 22140000); ++ Position.KEY_HOURS, 22140000L); + + decoder.setModelOverride("G18"); + diff --git a/tasks/traccar__traccar-5834/solution/solve.sh b/tasks/traccar__traccar-5834/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5834/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/traccar__traccar-5834/task.toml b/tasks/traccar__traccar-5834/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..29b9ceeba9c0381ac955cd17550c5ada952a40f8 --- /dev/null +++ b/tasks/traccar__traccar-5834/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5834" +description = "GT06 NT20 protocol correction, hours should be long and odometer shou…" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "bd631d5e28d0cf368978289377d1b6b6c199aa58" +reference = "https://github.com/traccar/traccar/pull/5834" +source_access = "auto" +built_at = "2026-11-16T16:09:42.598065+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5ac5466f519a7f829c33ad6bd19168e3b254cfa37ad2ff0e857f70c0fe4fd168" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-24T18:26:44Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.485286+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8467f52e007a6c5e0844d1c1d77ea00321deaf4649c8d5bade63739203d7473a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5834/tests/capture.py b/tasks/traccar__traccar-5834/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5834/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/traccar__traccar-5834/tests/instruction.md b/tasks/traccar__traccar-5834/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e73b9b9a49b8a122ad62a26a0a106252266fcb7f --- /dev/null +++ b/tasks/traccar__traccar-5834/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** GT06 NT20 protocol correction, hours should be long and odometer shou… + +## Description + +…ld be read as unsigned + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bd631d5e28d0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5834/tests/oracle.patch b/tasks/traccar__traccar-5834/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ffd5b27fbbb912a464e8d42ef2b1fc8a9a194dfe --- /dev/null +++ b/tasks/traccar__traccar-5834/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +index c5c9a72ea..b46cbab45 100644 +--- a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +@@ -1027,8 +1027,8 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + + if (modelNT20 && type == MSG_GPS_LBS_2) { +- position.set(Position.KEY_ODOMETER, buf.readMedium()); +- position.set(Position.KEY_HOURS, buf.readMedium() * 60 * 1000); ++ position.set(Position.KEY_ODOMETER, buf.readUnsignedMedium()); ++ position.set(Position.KEY_HOURS, buf.readUnsignedMedium() * 60 * 1000L); + } + + if (buf.readableBytes() == 3 + 6 || buf.readableBytes() == 3 + 4 + 6) { +diff --git a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +index 92aff2387..2dc16cf87 100644 +--- a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +@@ -584,7 +584,7 @@ public class Gt06ProtocolDecoderTest extends ProtocolTest { + + verifyAttribute(decoder, binary( + "78783c22010357789648774484180c06142038180c06142038cb03313ee4061fe98300185e090000000000000000460984284c000200000000017101d6f35d0d0a"), +- Position.KEY_HOURS, 22140000); ++ Position.KEY_HOURS, 22140000L); + + decoder.setModelOverride("G18"); + diff --git a/tasks/traccar__traccar-5834/tests/test.sh b/tasks/traccar__traccar-5834/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..84d7ab5e9759cadeac071be4045961e10c474b95 --- /dev/null +++ b/tasks/traccar__traccar-5834/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 bd631d5e28d0cf368978289377d1b6b6c199aa58 > "$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/traccar__traccar-5834/tests/verifier.py b/tasks/traccar__traccar-5834/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5834/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/traccar__traccar-5837/environment/Dockerfile b/tasks/traccar__traccar-5837/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0d3cc5ba4223c9cee3471bf13884bd5910ddcd46 --- /dev/null +++ b/tasks/traccar__traccar-5837/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0a88cf3f9c8152f7437e4a9c5641b0d41cb41bfd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0a88cf3f9c8152f7437e4a9c5641b0d41cb41bfd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0a88cf3f9c8152f7437e4a9c5641b0d41cb41bfd \ + && 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/traccar__traccar-5837/instruction.md b/tasks/traccar__traccar-5837/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d7bf42a3b60b3efc213afadbf623fc5bfcf5e6ba --- /dev/null +++ b/tasks/traccar__traccar-5837/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add support for AOVX VL100 model + +## Description + +[AOVX VL100 Protocol.pdf](https://github.com/user-attachments/files/26362944/AOVX.VL100.Protocol.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0a88cf3f9c81`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5837/solution/patch.diff b/tasks/traccar__traccar-5837/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a0f4ae3ece2eb3678456b9ff2b49860387a7e9be --- /dev/null +++ b/tasks/traccar__traccar-5837/solution/patch.diff @@ -0,0 +1,75 @@ +diff --git a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +index fdcd02e31..157949fcc 100644 +--- a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +@@ -237,7 +237,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + case MSG_LBS_ALARM: + return true; + case MSG_GPS_LBS_2: +- return "NT20".equalsIgnoreCase(model); ++ return model != null && Set.of("NT20", "VL100").contains(model.toUpperCase()); + case 0xA3: // MSG_FENCE_SINGLE / MSG_STATUS_3 + return variant == Variant.SEEWORLD; + default: +@@ -479,7 +479,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + String model = deviceSession != null ? getDeviceModel(deviceSession) : null; + boolean modelLW = model != null && model.toUpperCase().startsWith("LW"); + boolean modelSW = "SEEWORLD".equalsIgnoreCase(model); +- boolean modelNT20 = "NT20".equalsIgnoreCase(model); ++ boolean modelNT = model != null && Set.of("NT20", "VL100").contains(model.toUpperCase()); + boolean modelVL = model != null && Set.of("VL103", "LL303", "VL512", "G18").contains(model); + + if (type == MSG_LOGIN) { +@@ -827,7 +827,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + if (type == MSG_GPS_LBS_1 && "QH302R".equals(model)) { + buf.skipBytes(8); // imei + } +- if (type == MSG_GPS_LBS_2 && modelNT20) { ++ if (type == MSG_GPS_LBS_2 && modelNT) { + buf.readUnsignedByte(); // location source type + buf.skipBytes(8); // imei + position.setDeviceTime(decodeDate(buf, deviceSession)); +@@ -869,14 +869,14 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.PREFIX_TEMP + 1, buf.readShort() / 10.0); + } + } else { +- if (type == MSG_GPS_LBS_STATUS_5 || (modelNT20 && type == MSG_GPS_LBS_2)) { ++ if (type == MSG_GPS_LBS_STATUS_5 || (modelNT && type == MSG_GPS_LBS_2)) { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); + } + if (type == MSG_STATUS && "R11".equals(model)) { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); + } else { + int battery = buf.readUnsignedByte(); +- if (modelNT20 && type == MSG_GPS_LBS_2) { ++ if (modelNT && type == MSG_GPS_LBS_2) { + battery = battery / 10; + } + if (battery <= 6) { +@@ -903,7 +903,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + + if (type == MSG_STATUS_2 || type == MSG_GPS_LBS_STATUS_5 || type == MSG_GPS_LBS_STATUS_3 +- || type == MSG_FENCE_MULTI || modelNT20 && type == MSG_GPS_LBS_2) { ++ || type == MSG_FENCE_MULTI || modelNT && type == MSG_GPS_LBS_2) { + buf.readUnsignedByte(); // language + } + +@@ -998,7 +998,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + + if ((type == MSG_GPS_LBS_2 || type == MSG_GPS_LBS_3 || type == MSG_GPS_LBS_4 || type == MSG_GPS_LBS_5) +- && buf.readableBytes() >= 3 + 6 && !modelNT20) { ++ && buf.readableBytes() >= 3 + 6 && !modelNT) { + position.set(Position.KEY_IGNITION, buf.readUnsignedByte() > 0); + position.set(Position.KEY_EVENT, buf.readUnsignedByte()); // reason + position.set(Position.KEY_ARCHIVE, buf.readUnsignedByte() > 0); +@@ -1026,7 +1026,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + buf.readUnsignedByte(); // validity + } + +- if (modelNT20 && type == MSG_GPS_LBS_2) { ++ if (modelNT && type == MSG_GPS_LBS_2) { + position.set(Position.KEY_ODOMETER, buf.readUnsignedMedium()); + position.set(Position.KEY_HOURS, buf.readUnsignedMedium() * 60 * 1000L); + } diff --git a/tasks/traccar__traccar-5837/solution/solve.sh b/tasks/traccar__traccar-5837/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5837/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/traccar__traccar-5837/task.toml b/tasks/traccar__traccar-5837/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..079279eb0fbbca3c16cae5402e47975188de27a6 --- /dev/null +++ b/tasks/traccar__traccar-5837/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5837" +description = "Add support for AOVX VL100 model" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "0a88cf3f9c8152f7437e4a9c5641b0d41cb41bfd" +reference = "https://github.com/traccar/traccar/pull/5837" +source_access = "auto" +built_at = "2026-11-16T16:09:42.587078+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:abcf9e2c42c64ebd782838aa47829b1e0122aa6ef8a3e769c6f68459a62e930e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-01T00:40:02Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 16 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.485880+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fcccbab20b345898044564fa075282b5342e63720b19f9790974f4503c632efa" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5837/tests/capture.py b/tasks/traccar__traccar-5837/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5837/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/traccar__traccar-5837/tests/instruction.md b/tasks/traccar__traccar-5837/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d7bf42a3b60b3efc213afadbf623fc5bfcf5e6ba --- /dev/null +++ b/tasks/traccar__traccar-5837/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add support for AOVX VL100 model + +## Description + +[AOVX VL100 Protocol.pdf](https://github.com/user-attachments/files/26362944/AOVX.VL100.Protocol.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0a88cf3f9c81`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5837/tests/oracle.patch b/tasks/traccar__traccar-5837/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a0f4ae3ece2eb3678456b9ff2b49860387a7e9be --- /dev/null +++ b/tasks/traccar__traccar-5837/tests/oracle.patch @@ -0,0 +1,75 @@ +diff --git a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +index fdcd02e31..157949fcc 100644 +--- a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +@@ -237,7 +237,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + case MSG_LBS_ALARM: + return true; + case MSG_GPS_LBS_2: +- return "NT20".equalsIgnoreCase(model); ++ return model != null && Set.of("NT20", "VL100").contains(model.toUpperCase()); + case 0xA3: // MSG_FENCE_SINGLE / MSG_STATUS_3 + return variant == Variant.SEEWORLD; + default: +@@ -479,7 +479,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + String model = deviceSession != null ? getDeviceModel(deviceSession) : null; + boolean modelLW = model != null && model.toUpperCase().startsWith("LW"); + boolean modelSW = "SEEWORLD".equalsIgnoreCase(model); +- boolean modelNT20 = "NT20".equalsIgnoreCase(model); ++ boolean modelNT = model != null && Set.of("NT20", "VL100").contains(model.toUpperCase()); + boolean modelVL = model != null && Set.of("VL103", "LL303", "VL512", "G18").contains(model); + + if (type == MSG_LOGIN) { +@@ -827,7 +827,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + if (type == MSG_GPS_LBS_1 && "QH302R".equals(model)) { + buf.skipBytes(8); // imei + } +- if (type == MSG_GPS_LBS_2 && modelNT20) { ++ if (type == MSG_GPS_LBS_2 && modelNT) { + buf.readUnsignedByte(); // location source type + buf.skipBytes(8); // imei + position.setDeviceTime(decodeDate(buf, deviceSession)); +@@ -869,14 +869,14 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.PREFIX_TEMP + 1, buf.readShort() / 10.0); + } + } else { +- if (type == MSG_GPS_LBS_STATUS_5 || (modelNT20 && type == MSG_GPS_LBS_2)) { ++ if (type == MSG_GPS_LBS_STATUS_5 || (modelNT && type == MSG_GPS_LBS_2)) { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); + } + if (type == MSG_STATUS && "R11".equals(model)) { + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); + } else { + int battery = buf.readUnsignedByte(); +- if (modelNT20 && type == MSG_GPS_LBS_2) { ++ if (modelNT && type == MSG_GPS_LBS_2) { + battery = battery / 10; + } + if (battery <= 6) { +@@ -903,7 +903,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + + if (type == MSG_STATUS_2 || type == MSG_GPS_LBS_STATUS_5 || type == MSG_GPS_LBS_STATUS_3 +- || type == MSG_FENCE_MULTI || modelNT20 && type == MSG_GPS_LBS_2) { ++ || type == MSG_FENCE_MULTI || modelNT && type == MSG_GPS_LBS_2) { + buf.readUnsignedByte(); // language + } + +@@ -998,7 +998,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } + + if ((type == MSG_GPS_LBS_2 || type == MSG_GPS_LBS_3 || type == MSG_GPS_LBS_4 || type == MSG_GPS_LBS_5) +- && buf.readableBytes() >= 3 + 6 && !modelNT20) { ++ && buf.readableBytes() >= 3 + 6 && !modelNT) { + position.set(Position.KEY_IGNITION, buf.readUnsignedByte() > 0); + position.set(Position.KEY_EVENT, buf.readUnsignedByte()); // reason + position.set(Position.KEY_ARCHIVE, buf.readUnsignedByte() > 0); +@@ -1026,7 +1026,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + buf.readUnsignedByte(); // validity + } + +- if (modelNT20 && type == MSG_GPS_LBS_2) { ++ if (modelNT && type == MSG_GPS_LBS_2) { + position.set(Position.KEY_ODOMETER, buf.readUnsignedMedium()); + position.set(Position.KEY_HOURS, buf.readUnsignedMedium() * 60 * 1000L); + } diff --git a/tasks/traccar__traccar-5837/tests/test.sh b/tasks/traccar__traccar-5837/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f7133eacf61d1711ce9734adcfbe69772a9cfd1b --- /dev/null +++ b/tasks/traccar__traccar-5837/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 0a88cf3f9c8152f7437e4a9c5641b0d41cb41bfd > "$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/traccar__traccar-5837/tests/verifier.py b/tasks/traccar__traccar-5837/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5837/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/traccar__traccar-5845/environment/Dockerfile b/tasks/traccar__traccar-5845/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0be14cf741c2d45c7d5216d2806d37ace55cf65f --- /dev/null +++ b/tasks/traccar__traccar-5845/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin af3df62ce82402213fff801723d1d7ddaeef02e1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard af3df62ce82402213fff801723d1d7ddaeef02e1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base af3df62ce82402213fff801723d1d7ddaeef02e1 \ + && 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/traccar__traccar-5845/instruction.md b/tasks/traccar__traccar-5845/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..502acaca7427f7dd549a05d9dfdde80e627e0dfd --- /dev/null +++ b/tasks/traccar__traccar-5845/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Update Jt808ProtocolDecoder: Handle WiFi additional info ID 0xEC + +## Description + +## Description + +Some Huabao JT808 devices send WiFi access point data with additional info ID `0xEC` instead of the standard `0xF4`. + +This PR adds `0xEC` as a valid ID for WiFi data in `HuabaoProtocolDecoder`. + +## Evidence + +Example frame from a Huabao device: +7e02000072...EC23b286255f68fec4...7e + +text +- `0xEC` = WiFi data ID +- `0x23` = 35 bytes (5 MACs + 5 signals) + +## Current behavior + +WiFi data with ID `0xEC` is ignored → no network-based positioning. + +## New behavior + +`0xEC` is processed identically to `0xF4` → WiFi data is extracted and sent to geolocation provider. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `af3df62ce824`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5845/solution/patch.diff b/tasks/traccar__traccar-5845/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c5a82381b699d1558831deb46b1e666f0f435a5b --- /dev/null +++ b/tasks/traccar__traccar-5845/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 370617306..72362a3c1 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -1132,6 +1132,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + } + } + break; ++ case 0xEC: + case 0xF4: + while (buf.readerIndex() < endIndex) { + String mac = ByteBufUtil.hexDump(buf.readSlice(6)).replaceAll("(..)", "$1:"); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index a759683fb..a0db92482 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -339,6 +339,9 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7e0200003601911111000000d2000000000000004202b71a72008dbba000000000000025070208082901040000000030011731010e5708000000000000000082020082367e"), + Position.KEY_POWER, 13.0); + ++ verifyPositions(decoder, binary( ++ "7e0704011204545009154600a4000301004200000000004c000a0236d9f9008126ba00280001000026052318421301040000003d30010031010de4020159e50101e60100e7080000000400000000f50101fb0100006700000000004c00000236d9f9008126ba00280000000026052318451301040000003d300100310100e4020158e50101e60100e7080000000400000000ec155091e3194157ae8c86dd750382a69e86dd750382a4e10c010c000600bbe4001ada2900f50101fb0100006000000000004c00000236d9f9008126ba00280000000026052318481201040000003d300100310100e4020157e50101e60100e7080000000400000000ec0e5091e3194157b09e86dd750382afe10c010c000600bbe4001b1c2900f50101fb0100a57e")); ++ + decoder.setModelOverride("MV710G"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5845/solution/solve.sh b/tasks/traccar__traccar-5845/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5845/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/traccar__traccar-5845/task.toml b/tasks/traccar__traccar-5845/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..989f954c0ead0c33968c4a6dc74a017f367194ed --- /dev/null +++ b/tasks/traccar__traccar-5845/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5845" +description = "Update Jt808ProtocolDecoder: Handle WiFi additional info ID 0xEC" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "af3df62ce82402213fff801723d1d7ddaeef02e1" +reference = "https://github.com/traccar/traccar/pull/5845" +source_access = "auto" +built_at = "2026-11-16T16:09:42.585740+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b69b7f26a8824a4f17db9cdca0f1034adb27d5479eaa5c31af506bec4fde5cc1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-29T00:40:45Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.486481+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:eefd18d68b55f16c5794cae7bd246155942a3b05f23817dc2155a59d45861a24" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5845/tests/capture.py b/tasks/traccar__traccar-5845/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5845/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/traccar__traccar-5845/tests/instruction.md b/tasks/traccar__traccar-5845/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..502acaca7427f7dd549a05d9dfdde80e627e0dfd --- /dev/null +++ b/tasks/traccar__traccar-5845/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Update Jt808ProtocolDecoder: Handle WiFi additional info ID 0xEC + +## Description + +## Description + +Some Huabao JT808 devices send WiFi access point data with additional info ID `0xEC` instead of the standard `0xF4`. + +This PR adds `0xEC` as a valid ID for WiFi data in `HuabaoProtocolDecoder`. + +## Evidence + +Example frame from a Huabao device: +7e02000072...EC23b286255f68fec4...7e + +text +- `0xEC` = WiFi data ID +- `0x23` = 35 bytes (5 MACs + 5 signals) + +## Current behavior + +WiFi data with ID `0xEC` is ignored → no network-based positioning. + +## New behavior + +`0xEC` is processed identically to `0xF4` → WiFi data is extracted and sent to geolocation provider. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `af3df62ce824`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5845/tests/oracle.patch b/tasks/traccar__traccar-5845/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c5a82381b699d1558831deb46b1e666f0f435a5b --- /dev/null +++ b/tasks/traccar__traccar-5845/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 370617306..72362a3c1 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -1132,6 +1132,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + } + } + break; ++ case 0xEC: + case 0xF4: + while (buf.readerIndex() < endIndex) { + String mac = ByteBufUtil.hexDump(buf.readSlice(6)).replaceAll("(..)", "$1:"); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index a759683fb..a0db92482 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -339,6 +339,9 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7e0200003601911111000000d2000000000000004202b71a72008dbba000000000000025070208082901040000000030011731010e5708000000000000000082020082367e"), + Position.KEY_POWER, 13.0); + ++ verifyPositions(decoder, binary( ++ "7e0704011204545009154600a4000301004200000000004c000a0236d9f9008126ba00280001000026052318421301040000003d30010031010de4020159e50101e60100e7080000000400000000f50101fb0100006700000000004c00000236d9f9008126ba00280000000026052318451301040000003d300100310100e4020158e50101e60100e7080000000400000000ec155091e3194157ae8c86dd750382a69e86dd750382a4e10c010c000600bbe4001ada2900f50101fb0100006000000000004c00000236d9f9008126ba00280000000026052318481201040000003d300100310100e4020157e50101e60100e7080000000400000000ec0e5091e3194157b09e86dd750382afe10c010c000600bbe4001b1c2900f50101fb0100a57e")); ++ + decoder.setModelOverride("MV710G"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5845/tests/test.sh b/tasks/traccar__traccar-5845/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1f462ae73fd9c97b2b96667521f3884def9ffe5b --- /dev/null +++ b/tasks/traccar__traccar-5845/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 af3df62ce82402213fff801723d1d7ddaeef02e1 > "$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/traccar__traccar-5845/tests/verifier.py b/tasks/traccar__traccar-5845/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5845/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/traccar__traccar-5848/environment/Dockerfile b/tasks/traccar__traccar-5848/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..68d798978dfc81bdf86d0aecff7e20da329712f5 --- /dev/null +++ b/tasks/traccar__traccar-5848/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8febe0c7a1e0f4ab1a0709e2c03e90169c7a6dbc 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8febe0c7a1e0f4ab1a0709e2c03e90169c7a6dbc \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8febe0c7a1e0f4ab1a0709e2c03e90169c7a6dbc \ + && 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/traccar__traccar-5848/instruction.md b/tasks/traccar__traccar-5848/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..359b5c614c5d8b278775143ba63dc32b64be799d --- /dev/null +++ b/tasks/traccar__traccar-5848/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** Add SeeWorld W15L support to JT808 protocol + +## Description + +Adds SeeWorld W15L device support to the JT/T 808 protocol decoder/encoder. + +Spec reference: JT/T 808-2013, "GNSS system for operating vehicles — General specifications for the communication protocol and data format of BD compatible vehicle terminal" (W15L vendor doc: [W15L_808 protocol 20221117.docx](https://github.com/user-attachments/files/26769797/W15L_808.protocol.20221117.docx)). + +## Changes + +- Decode `0xEB` sub-extension `0x0089` (extended alarm status, §8.18 Table 27 custom area): + - bit 0 active-low → `ALARM_POWER_OFF` (matches std alarm-sign bit 8) + - bit 12 active-low → `ALARM_REMOVING` +- Decode `0xEB` sub-extension `0x00C5` (extended alarm status 2): + - bit 6 active-low → `ALARM_VIBRATION` + - bits 23-24 → `KEY_MOTION` (0 = moving, 1 = stopped) +- Handle terminal logout `0x0003` (§8.7) with platform general response `0x8001` (§8.2). Standard, not vendor-gated — uses the existing `sendGeneralResponse` path alongside `MSG_TERMINAL_AUTH` / `MSG_HEARTBEAT_2` / `MSG_PHOTO`. +- Encoder: W15L engine stop/resume via `0x8105` (§8.13) with vendor command bytes `0x64` / `0x65`, alongside the existing `VL300` branch. + +## Test plan + +- [x] `./gradlew checkstyleMain checkstyleTest` +- [x] `./gradlew test --tests org.traccar.protocol.Jt808ProtocolDecoderTest --tests org.traccar.protocol.Jt808ProtocolEncoderTest` +- [x] New decoder tests cover each added 0xEB sub-extension branch (POWER_OFF, REMOVING, VIBRATION, MOTION) and the dedupe between standard + extended alarm bits. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8febe0c7a1e0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5848/solution/patch.diff b/tasks/traccar__traccar-5848/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..66a084eda6d7ee08d337fbd4b8f33219d8517fe3 --- /dev/null +++ b/tasks/traccar__traccar-5848/solution/patch.diff @@ -0,0 +1,102 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 760698cd3..57c082099 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -57,6 +57,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_GENERAL_RESPONSE = 0x8001; + public static final int MSG_GENERAL_RESPONSE_2 = 0x4401; + public static final int MSG_HEARTBEAT = 0x0002; ++ public static final int MSG_TERMINAL_LOGOUT = 0x0003; + public static final int MSG_HEARTBEAT_2 = 0x0506; + public static final int MSG_TERMINAL_REGISTER = 0x0100; + public static final int MSG_TERMINAL_REGISTER_RESPONSE = 0x8100; +@@ -350,7 +351,8 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + return position; + } + +- } else if (type == MSG_TERMINAL_AUTH || type == MSG_HEARTBEAT_2 || type == MSG_PHOTO) { ++ } else if (type == MSG_TERMINAL_AUTH || type == MSG_HEARTBEAT_2 ++ || type == MSG_PHOTO || type == MSG_TERMINAL_LOGOUT) { + + sendGeneralResponse(channel, remoteAddress, id, type, index); + +@@ -908,6 +910,15 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + case 0x002D: + position.set(Position.KEY_BATTERY, buf.readUnsignedShort() / 1000.0); + break; ++ case 0x0089: ++ long extAlarm = buf.readUnsignedInt(); ++ if (!BitUtil.check(extAlarm, 0)) { ++ position.addAlarm(Position.ALARM_POWER_OFF); ++ } ++ if (!BitUtil.check(extAlarm, 12)) { ++ position.addAlarm(Position.ALARM_REMOVING); ++ } ++ break; + case 0x00B2: + position.set(Position.KEY_ICCID, ByteBufUtil.hexDump( + buf.readSlice(10)).replaceAll("f", "")); +@@ -921,6 +932,18 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + WifiAccessPoint.from(wifi[i * 2], Integer.parseInt(wifi[i * 2 + 1]))); + } + break; ++ case 0x00C5: ++ long extStatus = buf.readUnsignedInt(); ++ if (!BitUtil.check(extStatus, 6)) { ++ position.addAlarm(Position.ALARM_VIBRATION); ++ } ++ long motionState = BitUtil.between(extStatus, 23, 25); ++ if (motionState == 0) { ++ position.set(Position.KEY_MOTION, true); ++ } else if (motionState == 1) { ++ position.set(Position.KEY_MOTION, false); ++ } ++ break; + case 0x00C6: + int batteryAlarm = buf.readUnsignedByte(); + if (batteryAlarm == 0x03 || batteryAlarm == 0x04) { +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +index 5e5474bab..1f2f8ffc0 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +@@ -104,6 +104,8 @@ public class Jt808ProtocolEncoder extends BaseProtocolEncoder { + if ("VL300".equals(getDeviceModel(command.getDeviceId()))) { + data.writeCharSequence(command.getType().equals(Command.TYPE_ENGINE_STOP) ? "#0;1" : "#0;0", + StandardCharsets.US_ASCII); ++ } else if ("W15L".equals(getDeviceModel(command.getDeviceId()))) { ++ data.writeByte(command.getType().equals(Command.TYPE_ENGINE_STOP) ? 0x64 : 0x65); + } else { + data.writeByte(command.getType().equals(Command.TYPE_ENGINE_STOP) ? 0xf0 : 0xf1); + } +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index b9d17be4a..b3aee4b60 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -23,6 +23,18 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7e020000530095900689830016000000000000000b00a2394803a925f800000000000025112411514701040000003e300115310113eb29000c00b28988228066613427450900060089ffffffff000600c5ffffffef0004002d0fa5000300a85c657e"), + Position.KEY_BATTERY, 4.005); + ++ verifyAttribute(decoder, binary( ++ "7e020000530095900689830016000000000000000b00a2394803a925f800000000000025112411514701040000003e300115310113eb29000c00b28988228066613427450900060089ffffefff000600c5ffffffef0004002d0fa5000300a85c757e"), ++ Position.KEY_ALARM, Position.ALARM_REMOVING); ++ ++ verifyAttribute(decoder, binary( ++ "7e020000530095900689830016000000000000000b00a2394803a925f800000000000025112411514701040000003e300115310113eb29000c00b28988228066613427450900060089ffffffff000600c5ffffffaf0004002d0fa5000300a85c257e"), ++ Position.KEY_ALARM, Position.ALARM_VIBRATION); ++ ++ verifyAttribute(decoder, binary( ++ "7e020000530095900689830016000000000000000b00a2394803a925f800000000000025112411514701040000003e300115310113eb29000c00b28988228066613427450900060089ffffffff000600c5fe7fffef0004002d0fa5000300a85ce47e"), ++ Position.KEY_MOTION, true); ++ + verifyAttribute(decoder, binary( + "7e070401654eb6fb4afd9e485b000601003900000000000c000301f5a58700ca24c5000d0000004925111215454501040000000025040000000030011731010aeb095554432b30383a3030003900000000000c000301f5a58e00ca24cd000d0000002825111215454701040000000025040000000030011731010aeb095554432b30383a3030003900000000000c000301f5a5ad00ca24de000e0000011025111215455901040000000025040000000030011931010aeb095554432b30383a3030003900000000000c000301f5a5b100ca24ed000e0000004625111215461401040000000025040000000030011931010aeb095554432b30383a3030003900000000000c000301f5a5a900ca24f5000e000000a125111215461701040000000025040000000030011931010aeb095554432b30383a3030003900000000000c000301f5a5af00ca24fb000e000000dd25111215463201040000000025040000000030011731010beb095554432b30383a3030537e"), + "timezone", "UTC+08:00"); +@@ -184,7 +196,7 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + + verifyAttribute(decoder, binary( + "7E020000480123456789010013000000800000000301597BC506CBFF6600EB00000155210726203531010400000000EB24000C00B28986047701207027150200060089FFFFEFFF0004002D0E10000600C5FFFFFFEF697E"), +- Position.KEY_ALARM, Position.ALARM_LOW_BATTERY); ++ Position.KEY_ALARM, Position.ALARM_LOW_BATTERY + "," + Position.ALARM_REMOVING); + + verifyAttribute(decoder, binary( + "7e0200008e01917159043700b300000000800000030158990606ca0fd7000400000000211129111705010400000000cc14383938363037423831303230393031363239363830010d8001aa81021388820200858301148401aa8502189b8601338702007e8801338901148a0200998b1131323334353637383941424344454647488c04000200a88d0200828e0114a00b50353338662c5530323966037e"), diff --git a/tasks/traccar__traccar-5848/solution/solve.sh b/tasks/traccar__traccar-5848/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5848/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/traccar__traccar-5848/task.toml b/tasks/traccar__traccar-5848/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6900f9f64480184d53893ef9202dee49d492fddd --- /dev/null +++ b/tasks/traccar__traccar-5848/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5848" +description = "Add SeeWorld W15L support to JT808 protocol" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "8febe0c7a1e0f4ab1a0709e2c03e90169c7a6dbc" +reference = "https://github.com/traccar/traccar/pull/5848" +source_access = "auto" +built_at = "2026-11-16T16:09:42.593123+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b230fcc95267c11d70316425979a9cab947f3d9f48b1879d1f3f495e9c53a580" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-26T01:59:03Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 41 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.487138+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:23db6317c979d108f0c29b93da84f5ac539aae920f0b12170ae773eec415237b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5848/tests/capture.py b/tasks/traccar__traccar-5848/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5848/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/traccar__traccar-5848/tests/instruction.md b/tasks/traccar__traccar-5848/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..359b5c614c5d8b278775143ba63dc32b64be799d --- /dev/null +++ b/tasks/traccar__traccar-5848/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** Add SeeWorld W15L support to JT808 protocol + +## Description + +Adds SeeWorld W15L device support to the JT/T 808 protocol decoder/encoder. + +Spec reference: JT/T 808-2013, "GNSS system for operating vehicles — General specifications for the communication protocol and data format of BD compatible vehicle terminal" (W15L vendor doc: [W15L_808 protocol 20221117.docx](https://github.com/user-attachments/files/26769797/W15L_808.protocol.20221117.docx)). + +## Changes + +- Decode `0xEB` sub-extension `0x0089` (extended alarm status, §8.18 Table 27 custom area): + - bit 0 active-low → `ALARM_POWER_OFF` (matches std alarm-sign bit 8) + - bit 12 active-low → `ALARM_REMOVING` +- Decode `0xEB` sub-extension `0x00C5` (extended alarm status 2): + - bit 6 active-low → `ALARM_VIBRATION` + - bits 23-24 → `KEY_MOTION` (0 = moving, 1 = stopped) +- Handle terminal logout `0x0003` (§8.7) with platform general response `0x8001` (§8.2). Standard, not vendor-gated — uses the existing `sendGeneralResponse` path alongside `MSG_TERMINAL_AUTH` / `MSG_HEARTBEAT_2` / `MSG_PHOTO`. +- Encoder: W15L engine stop/resume via `0x8105` (§8.13) with vendor command bytes `0x64` / `0x65`, alongside the existing `VL300` branch. + +## Test plan + +- [x] `./gradlew checkstyleMain checkstyleTest` +- [x] `./gradlew test --tests org.traccar.protocol.Jt808ProtocolDecoderTest --tests org.traccar.protocol.Jt808ProtocolEncoderTest` +- [x] New decoder tests cover each added 0xEB sub-extension branch (POWER_OFF, REMOVING, VIBRATION, MOTION) and the dedupe between standard + extended alarm bits. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8febe0c7a1e0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5848/tests/oracle.patch b/tasks/traccar__traccar-5848/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..66a084eda6d7ee08d337fbd4b8f33219d8517fe3 --- /dev/null +++ b/tasks/traccar__traccar-5848/tests/oracle.patch @@ -0,0 +1,102 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 760698cd3..57c082099 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -57,6 +57,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_GENERAL_RESPONSE = 0x8001; + public static final int MSG_GENERAL_RESPONSE_2 = 0x4401; + public static final int MSG_HEARTBEAT = 0x0002; ++ public static final int MSG_TERMINAL_LOGOUT = 0x0003; + public static final int MSG_HEARTBEAT_2 = 0x0506; + public static final int MSG_TERMINAL_REGISTER = 0x0100; + public static final int MSG_TERMINAL_REGISTER_RESPONSE = 0x8100; +@@ -350,7 +351,8 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + return position; + } + +- } else if (type == MSG_TERMINAL_AUTH || type == MSG_HEARTBEAT_2 || type == MSG_PHOTO) { ++ } else if (type == MSG_TERMINAL_AUTH || type == MSG_HEARTBEAT_2 ++ || type == MSG_PHOTO || type == MSG_TERMINAL_LOGOUT) { + + sendGeneralResponse(channel, remoteAddress, id, type, index); + +@@ -908,6 +910,15 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + case 0x002D: + position.set(Position.KEY_BATTERY, buf.readUnsignedShort() / 1000.0); + break; ++ case 0x0089: ++ long extAlarm = buf.readUnsignedInt(); ++ if (!BitUtil.check(extAlarm, 0)) { ++ position.addAlarm(Position.ALARM_POWER_OFF); ++ } ++ if (!BitUtil.check(extAlarm, 12)) { ++ position.addAlarm(Position.ALARM_REMOVING); ++ } ++ break; + case 0x00B2: + position.set(Position.KEY_ICCID, ByteBufUtil.hexDump( + buf.readSlice(10)).replaceAll("f", "")); +@@ -921,6 +932,18 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + WifiAccessPoint.from(wifi[i * 2], Integer.parseInt(wifi[i * 2 + 1]))); + } + break; ++ case 0x00C5: ++ long extStatus = buf.readUnsignedInt(); ++ if (!BitUtil.check(extStatus, 6)) { ++ position.addAlarm(Position.ALARM_VIBRATION); ++ } ++ long motionState = BitUtil.between(extStatus, 23, 25); ++ if (motionState == 0) { ++ position.set(Position.KEY_MOTION, true); ++ } else if (motionState == 1) { ++ position.set(Position.KEY_MOTION, false); ++ } ++ break; + case 0x00C6: + int batteryAlarm = buf.readUnsignedByte(); + if (batteryAlarm == 0x03 || batteryAlarm == 0x04) { +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +index 5e5474bab..1f2f8ffc0 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +@@ -104,6 +104,8 @@ public class Jt808ProtocolEncoder extends BaseProtocolEncoder { + if ("VL300".equals(getDeviceModel(command.getDeviceId()))) { + data.writeCharSequence(command.getType().equals(Command.TYPE_ENGINE_STOP) ? "#0;1" : "#0;0", + StandardCharsets.US_ASCII); ++ } else if ("W15L".equals(getDeviceModel(command.getDeviceId()))) { ++ data.writeByte(command.getType().equals(Command.TYPE_ENGINE_STOP) ? 0x64 : 0x65); + } else { + data.writeByte(command.getType().equals(Command.TYPE_ENGINE_STOP) ? 0xf0 : 0xf1); + } +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index b9d17be4a..b3aee4b60 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -23,6 +23,18 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7e020000530095900689830016000000000000000b00a2394803a925f800000000000025112411514701040000003e300115310113eb29000c00b28988228066613427450900060089ffffffff000600c5ffffffef0004002d0fa5000300a85c657e"), + Position.KEY_BATTERY, 4.005); + ++ verifyAttribute(decoder, binary( ++ "7e020000530095900689830016000000000000000b00a2394803a925f800000000000025112411514701040000003e300115310113eb29000c00b28988228066613427450900060089ffffefff000600c5ffffffef0004002d0fa5000300a85c757e"), ++ Position.KEY_ALARM, Position.ALARM_REMOVING); ++ ++ verifyAttribute(decoder, binary( ++ "7e020000530095900689830016000000000000000b00a2394803a925f800000000000025112411514701040000003e300115310113eb29000c00b28988228066613427450900060089ffffffff000600c5ffffffaf0004002d0fa5000300a85c257e"), ++ Position.KEY_ALARM, Position.ALARM_VIBRATION); ++ ++ verifyAttribute(decoder, binary( ++ "7e020000530095900689830016000000000000000b00a2394803a925f800000000000025112411514701040000003e300115310113eb29000c00b28988228066613427450900060089ffffffff000600c5fe7fffef0004002d0fa5000300a85ce47e"), ++ Position.KEY_MOTION, true); ++ + verifyAttribute(decoder, binary( + "7e070401654eb6fb4afd9e485b000601003900000000000c000301f5a58700ca24c5000d0000004925111215454501040000000025040000000030011731010aeb095554432b30383a3030003900000000000c000301f5a58e00ca24cd000d0000002825111215454701040000000025040000000030011731010aeb095554432b30383a3030003900000000000c000301f5a5ad00ca24de000e0000011025111215455901040000000025040000000030011931010aeb095554432b30383a3030003900000000000c000301f5a5b100ca24ed000e0000004625111215461401040000000025040000000030011931010aeb095554432b30383a3030003900000000000c000301f5a5a900ca24f5000e000000a125111215461701040000000025040000000030011931010aeb095554432b30383a3030003900000000000c000301f5a5af00ca24fb000e000000dd25111215463201040000000025040000000030011731010beb095554432b30383a3030537e"), + "timezone", "UTC+08:00"); +@@ -184,7 +196,7 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + + verifyAttribute(decoder, binary( + "7E020000480123456789010013000000800000000301597BC506CBFF6600EB00000155210726203531010400000000EB24000C00B28986047701207027150200060089FFFFEFFF0004002D0E10000600C5FFFFFFEF697E"), +- Position.KEY_ALARM, Position.ALARM_LOW_BATTERY); ++ Position.KEY_ALARM, Position.ALARM_LOW_BATTERY + "," + Position.ALARM_REMOVING); + + verifyAttribute(decoder, binary( + "7e0200008e01917159043700b300000000800000030158990606ca0fd7000400000000211129111705010400000000cc14383938363037423831303230393031363239363830010d8001aa81021388820200858301148401aa8502189b8601338702007e8801338901148a0200998b1131323334353637383941424344454647488c04000200a88d0200828e0114a00b50353338662c5530323966037e"), diff --git a/tasks/traccar__traccar-5848/tests/test.sh b/tasks/traccar__traccar-5848/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2db97ea4025bd59df8702d73b97db06491ae58ba --- /dev/null +++ b/tasks/traccar__traccar-5848/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 8febe0c7a1e0f4ab1a0709e2c03e90169c7a6dbc > "$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/traccar__traccar-5848/tests/verifier.py b/tasks/traccar__traccar-5848/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5848/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/traccar__traccar-5861/environment/Dockerfile b/tasks/traccar__traccar-5861/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6795d5f1279db7fd067335ad4f5c19a792206b04 --- /dev/null +++ b/tasks/traccar__traccar-5861/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 16099380b3396abb829278cfebe23a6381dcf61a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 16099380b3396abb829278cfebe23a6381dcf61a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 16099380b3396abb829278cfebe23a6381dcf61a \ + && 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/traccar__traccar-5861/instruction.md b/tasks/traccar__traccar-5861/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d625bc138b73915ddf3b83ce3c9ba58898cfd2a2 --- /dev/null +++ b/tasks/traccar__traccar-5861/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Fix NPE in OpenID login when user has no groups + +## Description + +Fixes a NullPointerException when authenticating via OpenID if the user has no group memberships in their token. + +## Changes + +- Add null check for userGroups before calling contains() in admin group check +- Add null check for userGroups before calling contains() in allow group check + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `16099380b339`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5861/solution/patch.diff b/tasks/traccar__traccar-5861/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b02aca711bf6c07353b7135c148591388d7033e8 --- /dev/null +++ b/tasks/traccar__traccar-5861/solution/patch.diff @@ -0,0 +1,19 @@ +diff --git a/src/main/java/org/traccar/database/OpenIdProvider.java b/src/main/java/org/traccar/database/OpenIdProvider.java +index 130884b04..96c9f8834 100644 +--- a/src/main/java/org/traccar/database/OpenIdProvider.java ++++ b/src/main/java/org/traccar/database/OpenIdProvider.java +@@ -174,9 +174,12 @@ public class OpenIdProvider { + UserInfo userInfo = getUserInfo(bearerToken); + + List userGroups = userInfo.getStringListClaim(groupsClaimName); +- Boolean administrator = adminGroup != null ? userGroups.contains(adminGroup) : null; ++ Boolean administrator = adminGroup != null && userGroups != null ? userGroups.contains(adminGroup) : null; + +- if (!(Boolean.TRUE.equals(administrator) || allowGroup == null || userGroups.contains(allowGroup))) { ++ boolean authorized = Boolean.TRUE.equals(administrator) ++ || allowGroup == null ++ || (userGroups != null && userGroups.contains(allowGroup)); ++ if (!authorized) { + throw new GeneralSecurityException("Your OpenID Groups do not permit access"); + } + diff --git a/tasks/traccar__traccar-5861/solution/solve.sh b/tasks/traccar__traccar-5861/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5861/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/traccar__traccar-5861/task.toml b/tasks/traccar__traccar-5861/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..20fb5b4b072d98db38ce903dc751d0cce99e51ed --- /dev/null +++ b/tasks/traccar__traccar-5861/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5861" +description = "Fix NPE in OpenID login when user has no groups" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "16099380b3396abb829278cfebe23a6381dcf61a" +reference = "https://github.com/traccar/traccar/pull/5861" +source_access = "auto" +built_at = "2026-11-16T16:09:42.594838+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6a2a25b893409cb0360b740ac6b9c72b66a034fdb67fca5dba52144f5d0faeef" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-25T05:22:00Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/database/OpenIdProvider.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 7 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.487715+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8a5636b27a1feada07406b77a1c89401756ecc84a8ff1d9dde3e86c48f260be0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5861/tests/capture.py b/tasks/traccar__traccar-5861/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5861/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/traccar__traccar-5861/tests/instruction.md b/tasks/traccar__traccar-5861/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d625bc138b73915ddf3b83ce3c9ba58898cfd2a2 --- /dev/null +++ b/tasks/traccar__traccar-5861/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Fix NPE in OpenID login when user has no groups + +## Description + +Fixes a NullPointerException when authenticating via OpenID if the user has no group memberships in their token. + +## Changes + +- Add null check for userGroups before calling contains() in admin group check +- Add null check for userGroups before calling contains() in allow group check + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `16099380b339`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5861/tests/oracle.patch b/tasks/traccar__traccar-5861/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b02aca711bf6c07353b7135c148591388d7033e8 --- /dev/null +++ b/tasks/traccar__traccar-5861/tests/oracle.patch @@ -0,0 +1,19 @@ +diff --git a/src/main/java/org/traccar/database/OpenIdProvider.java b/src/main/java/org/traccar/database/OpenIdProvider.java +index 130884b04..96c9f8834 100644 +--- a/src/main/java/org/traccar/database/OpenIdProvider.java ++++ b/src/main/java/org/traccar/database/OpenIdProvider.java +@@ -174,9 +174,12 @@ public class OpenIdProvider { + UserInfo userInfo = getUserInfo(bearerToken); + + List userGroups = userInfo.getStringListClaim(groupsClaimName); +- Boolean administrator = adminGroup != null ? userGroups.contains(adminGroup) : null; ++ Boolean administrator = adminGroup != null && userGroups != null ? userGroups.contains(adminGroup) : null; + +- if (!(Boolean.TRUE.equals(administrator) || allowGroup == null || userGroups.contains(allowGroup))) { ++ boolean authorized = Boolean.TRUE.equals(administrator) ++ || allowGroup == null ++ || (userGroups != null && userGroups.contains(allowGroup)); ++ if (!authorized) { + throw new GeneralSecurityException("Your OpenID Groups do not permit access"); + } + diff --git a/tasks/traccar__traccar-5861/tests/test.sh b/tasks/traccar__traccar-5861/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c527742a74bda12074909c8abf2bea9e5b9ed2ef --- /dev/null +++ b/tasks/traccar__traccar-5861/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 16099380b3396abb829278cfebe23a6381dcf61a > "$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/traccar__traccar-5861/tests/verifier.py b/tasks/traccar__traccar-5861/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5861/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/traccar__traccar-5862/environment/Dockerfile b/tasks/traccar__traccar-5862/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..098898265da35fcb635e88053b141c5c9ee1a434 --- /dev/null +++ b/tasks/traccar__traccar-5862/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a9d0c7f17be87b8050e612dc14cc65ec5268496f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a9d0c7f17be87b8050e612dc14cc65ec5268496f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a9d0c7f17be87b8050e612dc14cc65ec5268496f \ + && 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/traccar__traccar-5862/instruction.md b/tasks/traccar__traccar-5862/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73c2a63214ef3d0ed339127cc435f8482a68fbf9 --- /dev/null +++ b/tasks/traccar__traccar-5862/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** correct battery voltage decoding for gt06 nt devices and add more device models + +## Description + +This PR replaces original idea of creating a separate support for XT40 + +this makes a breaking change for NT devices protocol removing KEY_BATTERY_LEVEL and adding KEY_BATTERY with received battery voltage. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a9d0c7f17be8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5862/solution/patch.diff b/tasks/traccar__traccar-5862/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3fd8895daa3521a3356f26559d9f54758b0b0767 --- /dev/null +++ b/tasks/traccar__traccar-5862/solution/patch.diff @@ -0,0 +1,60 @@ +diff --git a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +index 9a54062e1..8381fe685 100644 +--- a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +@@ -137,6 +137,8 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + LW4G, + } + ++ private static final Set NT_MODELS = Set.of("NT11", "NT20", "NT26", "NT40", "NT46", "VL100", "XT40"); ++ + private Variant variant; + + private static final Pattern PATTERN_FUEL = new PatternBuilder() +@@ -237,7 +239,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + case MSG_LBS_ALARM: + return true; + case MSG_GPS_LBS_2: +- return model != null && Set.of("NT20", "VL100").contains(model.toUpperCase()); ++ return model != null && NT_MODELS.contains(model.toUpperCase()); + case 0xA3: // MSG_FENCE_SINGLE / MSG_STATUS_3 + return variant == Variant.SEEWORLD; + default: +@@ -479,7 +481,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + String model = deviceSession != null ? getDeviceModel(deviceSession) : null; + boolean modelLW = model != null && model.toUpperCase().startsWith("LW"); + boolean modelSW = "SEEWORLD".equalsIgnoreCase(model); +- boolean modelNT = model != null && Set.of("NT20", "VL100").contains(model.toUpperCase()); ++ boolean modelNT = model != null && NT_MODELS.contains(model.toUpperCase()); + boolean modelVL = model != null && Set.of("VL103", "LL303", "VL512", "G18").contains(model.toUpperCase()); + + if (type == MSG_LOGIN) { +@@ -877,9 +879,8 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } else { + int battery = buf.readUnsignedByte(); + if (modelNT && type == MSG_GPS_LBS_2) { +- battery = battery / 10; +- } +- if (battery <= 6) { ++ position.set(Position.KEY_BATTERY, battery / 10.0); ++ } else if (battery <= 6) { + position.set(Position.KEY_BATTERY_LEVEL, battery * 100 / 6); + } else if (battery <= 100) { + position.set(Position.KEY_BATTERY_LEVEL, battery); +diff --git a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +index 2dc16cf87..a7edc3003 100644 +--- a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +@@ -585,6 +585,12 @@ public class Gt06ProtocolDecoderTest extends ProtocolTest { + verifyAttribute(decoder, binary( + "78783c22010357789648774484180c06142038180c06142038cb03313ee4061fe98300185e090000000000000000460984284c000200000000017101d6f35d0d0a"), + Position.KEY_HOURS, 22140000L); ++ verifyAttribute(decoder, binary( ++ "78783c22010357789648774484180c06142038180c06142038cb03313ee4061fe98300185e090000000000000000460984284c000200000000017101d6f35d0d0a"), ++ Position.KEY_BATTERY, 4.0); ++ verifyAttribute(decoder, binary( ++ "78783c22010357789648774484180c06142038180c06142038cb03313ee4061fe98300185e090000000000000000460984284c000200000000017101d6f35d0d0a"), ++ Position.KEY_BATTERY_LEVEL, null); + + decoder.setModelOverride("G18"); + diff --git a/tasks/traccar__traccar-5862/solution/solve.sh b/tasks/traccar__traccar-5862/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5862/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/traccar__traccar-5862/task.toml b/tasks/traccar__traccar-5862/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b9e8f1a864b1ee767e3904d47c9d01e8e7fe207e --- /dev/null +++ b/tasks/traccar__traccar-5862/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5862" +description = "correct battery voltage decoding for gt06 nt devices and add more device models" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "a9d0c7f17be87b8050e612dc14cc65ec5268496f" +reference = "https://github.com/traccar/traccar/pull/5862" +source_access = "auto" +built_at = "2026-11-16T16:09:42.591672+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a3695c0c19007c116f3573aa02414bfcdb649a147c5ca4cc7493e450bc87d84b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-26T21:55:43Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java", +] +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:03.488340+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fb9396123f640b675f3d48e2425b825f698fc33141788c312626d2596ea8b239" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5862/tests/capture.py b/tasks/traccar__traccar-5862/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5862/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/traccar__traccar-5862/tests/instruction.md b/tasks/traccar__traccar-5862/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73c2a63214ef3d0ed339127cc435f8482a68fbf9 --- /dev/null +++ b/tasks/traccar__traccar-5862/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** correct battery voltage decoding for gt06 nt devices and add more device models + +## Description + +This PR replaces original idea of creating a separate support for XT40 + +this makes a breaking change for NT devices protocol removing KEY_BATTERY_LEVEL and adding KEY_BATTERY with received battery voltage. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a9d0c7f17be8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5862/tests/oracle.patch b/tasks/traccar__traccar-5862/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3fd8895daa3521a3356f26559d9f54758b0b0767 --- /dev/null +++ b/tasks/traccar__traccar-5862/tests/oracle.patch @@ -0,0 +1,60 @@ +diff --git a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +index 9a54062e1..8381fe685 100644 +--- a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +@@ -137,6 +137,8 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + LW4G, + } + ++ private static final Set NT_MODELS = Set.of("NT11", "NT20", "NT26", "NT40", "NT46", "VL100", "XT40"); ++ + private Variant variant; + + private static final Pattern PATTERN_FUEL = new PatternBuilder() +@@ -237,7 +239,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + case MSG_LBS_ALARM: + return true; + case MSG_GPS_LBS_2: +- return model != null && Set.of("NT20", "VL100").contains(model.toUpperCase()); ++ return model != null && NT_MODELS.contains(model.toUpperCase()); + case 0xA3: // MSG_FENCE_SINGLE / MSG_STATUS_3 + return variant == Variant.SEEWORLD; + default: +@@ -479,7 +481,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + String model = deviceSession != null ? getDeviceModel(deviceSession) : null; + boolean modelLW = model != null && model.toUpperCase().startsWith("LW"); + boolean modelSW = "SEEWORLD".equalsIgnoreCase(model); +- boolean modelNT = model != null && Set.of("NT20", "VL100").contains(model.toUpperCase()); ++ boolean modelNT = model != null && NT_MODELS.contains(model.toUpperCase()); + boolean modelVL = model != null && Set.of("VL103", "LL303", "VL512", "G18").contains(model.toUpperCase()); + + if (type == MSG_LOGIN) { +@@ -877,9 +879,8 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { + } else { + int battery = buf.readUnsignedByte(); + if (modelNT && type == MSG_GPS_LBS_2) { +- battery = battery / 10; +- } +- if (battery <= 6) { ++ position.set(Position.KEY_BATTERY, battery / 10.0); ++ } else if (battery <= 6) { + position.set(Position.KEY_BATTERY_LEVEL, battery * 100 / 6); + } else if (battery <= 100) { + position.set(Position.KEY_BATTERY_LEVEL, battery); +diff --git a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +index 2dc16cf87..a7edc3003 100644 +--- a/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gt06ProtocolDecoderTest.java +@@ -585,6 +585,12 @@ public class Gt06ProtocolDecoderTest extends ProtocolTest { + verifyAttribute(decoder, binary( + "78783c22010357789648774484180c06142038180c06142038cb03313ee4061fe98300185e090000000000000000460984284c000200000000017101d6f35d0d0a"), + Position.KEY_HOURS, 22140000L); ++ verifyAttribute(decoder, binary( ++ "78783c22010357789648774484180c06142038180c06142038cb03313ee4061fe98300185e090000000000000000460984284c000200000000017101d6f35d0d0a"), ++ Position.KEY_BATTERY, 4.0); ++ verifyAttribute(decoder, binary( ++ "78783c22010357789648774484180c06142038180c06142038cb03313ee4061fe98300185e090000000000000000460984284c000200000000017101d6f35d0d0a"), ++ Position.KEY_BATTERY_LEVEL, null); + + decoder.setModelOverride("G18"); + diff --git a/tasks/traccar__traccar-5862/tests/test.sh b/tasks/traccar__traccar-5862/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6bfbbacda0d40f7a3368e5fd63de2eff464a902d --- /dev/null +++ b/tasks/traccar__traccar-5862/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 a9d0c7f17be87b8050e612dc14cc65ec5268496f > "$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/traccar__traccar-5862/tests/verifier.py b/tasks/traccar__traccar-5862/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5862/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/traccar__traccar-5864/environment/Dockerfile b/tasks/traccar__traccar-5864/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..85c4340648b85d463cc4bd6cd7bc83dba061a76e --- /dev/null +++ b/tasks/traccar__traccar-5864/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6f30f4898420fbf41c6c017540a85fcdc59e375d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6f30f4898420fbf41c6c017540a85fcdc59e375d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6f30f4898420fbf41c6c017540a85fcdc59e375d \ + && 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/traccar__traccar-5864/instruction.md b/tasks/traccar__traccar-5864/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7b0fcaf2c11061946c12c2a1ffd2c436b2ec070b --- /dev/null +++ b/tasks/traccar__traccar-5864/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** Add Jimi JC371/JC181/JC182/JC450/JC451 dashcam support to JT808 protocol + +## Description + +Adds support for the Jimi IoT JC371/JC181/JC182/JC450/JC451 dashcam family. These devices speak **JT/T 808-2019 + JT/T 1078-2016** with Jimi-specific extensions to the 0x0200 location report — they are NOT the proprietary Gt06-family protocol used by older Jimi trackers (JC400 etc., handled by `Gt06ProtocolDecoder`). + +Spec reference: Jimi IoT JC371 Communication Protocol and Data Format V1.5.2 (2026-02-24), which also documents JC181/JC182/JC450/JC451. + +## Changes (all in `Jt808ProtocolDecoder`) + +- **0xE8 model-gated dual handler.** The existing 3-byte `lockStatus` path for non-Jimi devices is preserved; the Jimi branch (when `model` is one of `JC371`/`JC181`/`JC182`/`JC450`/`JC451`) parses two formats by inspecting the leading WORD: + - **Custom extension data** (0x2000-0x2FFF, spec §7.3): `0x2002` upload mode + buffered, `0x2003` charging/battery/signal/external voltage, `0x2005` nested status (internal battery voltage, daily data usage, battery level, charging, ICCID, HDOP, external voltage). + - **Extended alarm** (0x0001-0x0FFF, spec §7.2 Table 7-8): video alarms (camera failure/obstructed → `ALARM_FAULT`), location/driving alarms (harsh accel/brake/cornering, overspeed, fatigue, accident, vibration, tow, geofence enter/exit, door, lane change), basic alarms (SOS → `ALARM_SOS`, low power, ACC on/off → `KEY_IGNITION`, theft, power cut, low battery, power off, tamper). +- **0x14 video-related alarm** (spec Table 6-6): decode bits 0-3 (signal loss, signal block, memory failure, device failure) into `ALARM_FAULT`. Raw value still stored as `videoAlarm` attribute for back-compat. +- **`decodeAlarm` default branch**: extend with JT/T 808-2019 standard bits not previously decoded — bit 2 (fatigue → `ALARM_FATIGUE_DRIVING`), bit 6 (GPS antenna shorted → `ALARM_GPS_ANTENNA_CUT`), bit 19 (parking overtime → `ALARM_PARKING`), bit 21 (route entry/exit → `ALARM_GEOFENCE`), bit 26 (vehicle stolen → `ALARM_GENERAL`). These are the JT808-2019 standard, beneficial for all conforming devices, not just Jimi. + +## Notes + +- **Device model must be set manually** to one of `JC371`/`JC181`/`JC182`/`JC450`/`JC451` in the device profile for Jimi-specific decoding to activate. Same pattern as existing JT808 vendor variants (W15L, AL300, GL100, VL300, MV810G, etc.). +- **No live-device validation has been done** — tests are derived from the spec's Appendix II packet examples and synthetic fixtures that exercise each decoder branch. Happy to iterate based on field reports. +- **Live video streaming** for these dashcams works today via the existing `Jt1078Protocol` + `videoStart`/`videoStop` commands — no change needed. +- **Image/video upload HTTP server** (spec §8) is intentionally out of scope; that's a separate HTTPS endpoint with MD5-signed multipart POSTs and would belong in a follow-up PR if there's demand. + +## Test plan + +- [x] `./gradlew checkstyleMain checkstyleTest` +- [x] `./gradlew test --tests org.traccar.protocol.Jt808ProtocolDecoderTest --tests org.traccar.protocol.Jt808ProtocolEncoderTest --tests org.traccar.protocol.Jt808FrameDecoderTest --tests org.traccar.protocol.Jt808FrameEncoderTest` +- [x] `./gradlew assemble` +- [x] Confirmed no regression on the existing 0xE8 `lockStatus` decoding for non-Jimi devices. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6f30f4898420`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5864/solution/patch.diff b/tasks/traccar__traccar-5864/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..49b9528025279c348580b83cc7e5c9c9e33e1f02 --- /dev/null +++ b/tasks/traccar__traccar-5864/solution/patch.diff @@ -0,0 +1,135 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 279c4bb41..732450893 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -151,7 +151,10 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + if (BitUtil.check(value, 1)) { + position.addAlarm(Position.ALARM_OVERSPEED); + } +- if (BitUtil.check(value, 5)) { ++ if (BitUtil.check(value, 2)) { ++ position.addAlarm(Position.ALARM_FATIGUE_DRIVING); ++ } ++ if (BitUtil.check(value, 5) || BitUtil.check(value, 6)) { + position.addAlarm(Position.ALARM_GPS_ANTENNA_CUT); + } + if (BitUtil.check(value, 4) || BitUtil.check(value, 9) +@@ -170,9 +173,15 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + if (BitUtil.check(value, 16) || BitUtil.check(value, 17)) { + position.addAlarm(Position.ALARM_TAMPERING); + } ++ if (BitUtil.check(value, 19)) { ++ position.addAlarm(Position.ALARM_PARKING); ++ } + if (BitUtil.check(value, 20)) { + position.addAlarm(Position.ALARM_GEOFENCE); + } ++ if (BitUtil.check(value, 26)) { ++ position.addAlarm(Position.ALARM_GENERAL); ++ } + if (BitUtil.check(value, 28)) { + position.addAlarm(Position.ALARM_MOVEMENT); + } +@@ -847,7 +856,76 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + } + break; + case 0xE8: +- position.set("lockStatus", buf.readUnsignedMedium()); ++ if (model != null ++ && Set.of("JC371", "JC181", "JC182", "JC450", "JC451").contains(model)) { ++ int extendedType = buf.readUnsignedShort(); ++ switch (extendedType) { ++ case 0x2002 -> { ++ buf.readUnsignedByte(); // packet length ++ position.set("uploadMode", buf.readUnsignedByte()); ++ position.set("buffered", buf.readUnsignedByte() == 1); ++ } ++ case 0x2003 -> { ++ buf.readUnsignedByte(); // packet length ++ position.set(Position.KEY_CHARGE, buf.readUnsignedByte() == 1); ++ int batteryStatus = buf.readUnsignedByte(); ++ if (batteryStatus >= 1 && batteryStatus <= 6) { ++ position.set(Position.KEY_BATTERY_LEVEL, batteryStatus * 100 / 6); ++ } ++ position.set(Position.KEY_BATTERY, buf.readUnsignedShort() / 100.0); ++ position.set(Position.KEY_RSSI, buf.readUnsignedByte()); ++ position.set(Position.KEY_POWER, buf.readUnsignedShort() / 100.0); ++ } ++ case 0x2005 -> { ++ buf.readUnsignedByte(); // packet length ++ while (buf.readerIndex() < endIndex) { ++ int statusId = buf.readUnsignedShort(); ++ int statusLength = buf.readUnsignedByte(); ++ int statusEndIndex = buf.readerIndex() + statusLength; ++ switch (statusId) { ++ case 0x0001 -> position.set( ++ Position.KEY_BATTERY, buf.readUnsignedShort() / 100.0); ++ case 0x0002 -> position.set("dataUsage", buf.readUnsignedInt()); ++ case 0x0003 -> position.set( ++ Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); ++ case 0x0004 -> position.set( ++ Position.KEY_CHARGE, buf.readUnsignedByte() == 0); ++ case 0x0005 -> position.set(Position.KEY_ICCID, ++ ByteBufUtil.hexDump(buf.readSlice(10)).substring(0, 19)); ++ case 0x0007 -> position.set( ++ Position.KEY_HDOP, buf.readUnsignedShort() / 10.0); ++ case 0x2001 -> position.set( ++ Position.KEY_POWER, buf.readUnsignedShort() / 10.0); ++ } ++ buf.readerIndex(statusEndIndex); ++ } ++ } ++ case 0x0001 -> position.addAlarm(Position.ALARM_FAULT); ++ case 0x0400, 0x0412 -> position.addAlarm(Position.ALARM_ACCELERATION); ++ case 0x0401, 0x0413 -> position.addAlarm(Position.ALARM_BRAKING); ++ case 0x0402, 0x0414 -> position.addAlarm(Position.ALARM_CORNERING); ++ case 0x0403 -> position.addAlarm(Position.ALARM_OVERSPEED); ++ case 0x0405, 0x0416, 0x0417 -> position.addAlarm(Position.ALARM_ACCIDENT); ++ case 0x0406 -> position.addAlarm(Position.ALARM_VIBRATION); ++ case 0x0407 -> position.addAlarm(Position.ALARM_TOW); ++ case 0x0408 -> position.addAlarm(Position.ALARM_GEOFENCE_ENTER); ++ case 0x0409 -> position.addAlarm(Position.ALARM_GEOFENCE_EXIT); ++ case 0x040C -> position.addAlarm(Position.ALARM_DOOR); ++ case 0x0415 -> position.addAlarm(Position.ALARM_LANE_CHANGE); ++ case 0x0C01 -> position.addAlarm(Position.ALARM_SOS); ++ case 0x0C02 -> position.addAlarm(Position.ALARM_LOW_POWER); ++ case 0x0C03 -> position.set(Position.KEY_IGNITION, true); ++ case 0x0C04 -> position.set(Position.KEY_IGNITION, false); ++ case 0x0C05 -> position.addAlarm(Position.ALARM_GENERAL); ++ case 0x0C0E -> position.addAlarm(Position.ALARM_POWER_CUT); ++ case 0x0C0F -> position.addAlarm(Position.ALARM_LOW_BATTERY); ++ case 0x0C10 -> position.addAlarm(Position.ALARM_POWER_OFF); ++ case 0x0C12 -> position.addAlarm(Position.ALARM_TAMPERING); ++ } ++ buf.readerIndex(endIndex); ++ } else { ++ position.set("lockStatus", buf.readUnsignedMedium()); ++ } + break; + case 0xEA: + if (length > 2) { +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index b3aee4b60..55ba4643e 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -340,6 +340,20 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7e020000ec6710704387730579000100009058000e015baf2c029bb433001200000129250310035204300111310108f03402d400020f720e0f00007d8b8e02d400020f720e0b00007d8b8c02d400020f720d0b00007d8b8a02d4000b092bf3030000c9a588f231414f56585f414c3330302d4c415f48322e305f4547393135554c4141425230334130344d30385f56322e312e303a763031f40e18ef3a6ae1c6be00bb252515d3b5f614021901cb006d0099052005dc002800000032000af70600000d6f003cf81d04086967107043877389550327001051953711414c3330302d4c410000f912000f0000000100000000000b2503100352322a7e"), + Position.KEY_ALARM, Position.ALARM_MOVEMENT); + ++ decoder.setModelOverride("JC371"); ++ ++ verifyAttribute(decoder, binary( ++ "7E020000344EB6FB4AD6280001000000000000000301587D0106CBFF6600000000000026010112000001040000007B30011831010AE80A2003070105019F030190657E"), ++ Position.KEY_BATTERY, 4.15); ++ ++ verifyAttribute(decoder, binary( ++ "7E0200003E4EB6FB4AD6280002000000000000000301587D0106CBFF6600000000000026010112000001040000007B30011831010AE8140C01103131313131313126010112000000000000467E"), ++ Position.KEY_ALARM, Position.ALARM_SOS); ++ ++ verifyAttribute(decoder, binary( ++ "7E0200003E4EB6FB4AD6280003000000000000000301587D0106CBFF6600000000000026010112000001040000007B30011831010AE8140406103131313131313126010112000000000000487E"), ++ Position.KEY_ALARM, Position.ALARM_VIBRATION); ++ + } + + } diff --git a/tasks/traccar__traccar-5864/solution/solve.sh b/tasks/traccar__traccar-5864/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5864/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/traccar__traccar-5864/task.toml b/tasks/traccar__traccar-5864/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d9a8693d4fd14ad6b7010f138e3c759097d4b212 --- /dev/null +++ b/tasks/traccar__traccar-5864/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5864" +description = "Add Jimi JC371/JC181/JC182/JC450/JC451 dashcam support to JT808 protocol" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "6f30f4898420fbf41c6c017540a85fcdc59e375d" +reference = "https://github.com/traccar/traccar/pull/5864" +source_access = "auto" +built_at = "2026-11-16T16:09:42.590020+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5832fe8eaa74744104a97815c71e366f71a18c4fe81279e5f3f9db7282603b33" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-30T00:32:30Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 96 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.488941+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ed8120b73d2b8d05d62f802c264cffc5d23071dd36f25fba5dbd727da4bec650" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5864/tests/capture.py b/tasks/traccar__traccar-5864/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5864/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/traccar__traccar-5864/tests/instruction.md b/tasks/traccar__traccar-5864/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7b0fcaf2c11061946c12c2a1ffd2c436b2ec070b --- /dev/null +++ b/tasks/traccar__traccar-5864/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** Add Jimi JC371/JC181/JC182/JC450/JC451 dashcam support to JT808 protocol + +## Description + +Adds support for the Jimi IoT JC371/JC181/JC182/JC450/JC451 dashcam family. These devices speak **JT/T 808-2019 + JT/T 1078-2016** with Jimi-specific extensions to the 0x0200 location report — they are NOT the proprietary Gt06-family protocol used by older Jimi trackers (JC400 etc., handled by `Gt06ProtocolDecoder`). + +Spec reference: Jimi IoT JC371 Communication Protocol and Data Format V1.5.2 (2026-02-24), which also documents JC181/JC182/JC450/JC451. + +## Changes (all in `Jt808ProtocolDecoder`) + +- **0xE8 model-gated dual handler.** The existing 3-byte `lockStatus` path for non-Jimi devices is preserved; the Jimi branch (when `model` is one of `JC371`/`JC181`/`JC182`/`JC450`/`JC451`) parses two formats by inspecting the leading WORD: + - **Custom extension data** (0x2000-0x2FFF, spec §7.3): `0x2002` upload mode + buffered, `0x2003` charging/battery/signal/external voltage, `0x2005` nested status (internal battery voltage, daily data usage, battery level, charging, ICCID, HDOP, external voltage). + - **Extended alarm** (0x0001-0x0FFF, spec §7.2 Table 7-8): video alarms (camera failure/obstructed → `ALARM_FAULT`), location/driving alarms (harsh accel/brake/cornering, overspeed, fatigue, accident, vibration, tow, geofence enter/exit, door, lane change), basic alarms (SOS → `ALARM_SOS`, low power, ACC on/off → `KEY_IGNITION`, theft, power cut, low battery, power off, tamper). +- **0x14 video-related alarm** (spec Table 6-6): decode bits 0-3 (signal loss, signal block, memory failure, device failure) into `ALARM_FAULT`. Raw value still stored as `videoAlarm` attribute for back-compat. +- **`decodeAlarm` default branch**: extend with JT/T 808-2019 standard bits not previously decoded — bit 2 (fatigue → `ALARM_FATIGUE_DRIVING`), bit 6 (GPS antenna shorted → `ALARM_GPS_ANTENNA_CUT`), bit 19 (parking overtime → `ALARM_PARKING`), bit 21 (route entry/exit → `ALARM_GEOFENCE`), bit 26 (vehicle stolen → `ALARM_GENERAL`). These are the JT808-2019 standard, beneficial for all conforming devices, not just Jimi. + +## Notes + +- **Device model must be set manually** to one of `JC371`/`JC181`/`JC182`/`JC450`/`JC451` in the device profile for Jimi-specific decoding to activate. Same pattern as existing JT808 vendor variants (W15L, AL300, GL100, VL300, MV810G, etc.). +- **No live-device validation has been done** — tests are derived from the spec's Appendix II packet examples and synthetic fixtures that exercise each decoder branch. Happy to iterate based on field reports. +- **Live video streaming** for these dashcams works today via the existing `Jt1078Protocol` + `videoStart`/`videoStop` commands — no change needed. +- **Image/video upload HTTP server** (spec §8) is intentionally out of scope; that's a separate HTTPS endpoint with MD5-signed multipart POSTs and would belong in a follow-up PR if there's demand. + +## Test plan + +- [x] `./gradlew checkstyleMain checkstyleTest` +- [x] `./gradlew test --tests org.traccar.protocol.Jt808ProtocolDecoderTest --tests org.traccar.protocol.Jt808ProtocolEncoderTest --tests org.traccar.protocol.Jt808FrameDecoderTest --tests org.traccar.protocol.Jt808FrameEncoderTest` +- [x] `./gradlew assemble` +- [x] Confirmed no regression on the existing 0xE8 `lockStatus` decoding for non-Jimi devices. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6f30f4898420`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5864/tests/oracle.patch b/tasks/traccar__traccar-5864/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..49b9528025279c348580b83cc7e5c9c9e33e1f02 --- /dev/null +++ b/tasks/traccar__traccar-5864/tests/oracle.patch @@ -0,0 +1,135 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 279c4bb41..732450893 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -151,7 +151,10 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + if (BitUtil.check(value, 1)) { + position.addAlarm(Position.ALARM_OVERSPEED); + } +- if (BitUtil.check(value, 5)) { ++ if (BitUtil.check(value, 2)) { ++ position.addAlarm(Position.ALARM_FATIGUE_DRIVING); ++ } ++ if (BitUtil.check(value, 5) || BitUtil.check(value, 6)) { + position.addAlarm(Position.ALARM_GPS_ANTENNA_CUT); + } + if (BitUtil.check(value, 4) || BitUtil.check(value, 9) +@@ -170,9 +173,15 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + if (BitUtil.check(value, 16) || BitUtil.check(value, 17)) { + position.addAlarm(Position.ALARM_TAMPERING); + } ++ if (BitUtil.check(value, 19)) { ++ position.addAlarm(Position.ALARM_PARKING); ++ } + if (BitUtil.check(value, 20)) { + position.addAlarm(Position.ALARM_GEOFENCE); + } ++ if (BitUtil.check(value, 26)) { ++ position.addAlarm(Position.ALARM_GENERAL); ++ } + if (BitUtil.check(value, 28)) { + position.addAlarm(Position.ALARM_MOVEMENT); + } +@@ -847,7 +856,76 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + } + break; + case 0xE8: +- position.set("lockStatus", buf.readUnsignedMedium()); ++ if (model != null ++ && Set.of("JC371", "JC181", "JC182", "JC450", "JC451").contains(model)) { ++ int extendedType = buf.readUnsignedShort(); ++ switch (extendedType) { ++ case 0x2002 -> { ++ buf.readUnsignedByte(); // packet length ++ position.set("uploadMode", buf.readUnsignedByte()); ++ position.set("buffered", buf.readUnsignedByte() == 1); ++ } ++ case 0x2003 -> { ++ buf.readUnsignedByte(); // packet length ++ position.set(Position.KEY_CHARGE, buf.readUnsignedByte() == 1); ++ int batteryStatus = buf.readUnsignedByte(); ++ if (batteryStatus >= 1 && batteryStatus <= 6) { ++ position.set(Position.KEY_BATTERY_LEVEL, batteryStatus * 100 / 6); ++ } ++ position.set(Position.KEY_BATTERY, buf.readUnsignedShort() / 100.0); ++ position.set(Position.KEY_RSSI, buf.readUnsignedByte()); ++ position.set(Position.KEY_POWER, buf.readUnsignedShort() / 100.0); ++ } ++ case 0x2005 -> { ++ buf.readUnsignedByte(); // packet length ++ while (buf.readerIndex() < endIndex) { ++ int statusId = buf.readUnsignedShort(); ++ int statusLength = buf.readUnsignedByte(); ++ int statusEndIndex = buf.readerIndex() + statusLength; ++ switch (statusId) { ++ case 0x0001 -> position.set( ++ Position.KEY_BATTERY, buf.readUnsignedShort() / 100.0); ++ case 0x0002 -> position.set("dataUsage", buf.readUnsignedInt()); ++ case 0x0003 -> position.set( ++ Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); ++ case 0x0004 -> position.set( ++ Position.KEY_CHARGE, buf.readUnsignedByte() == 0); ++ case 0x0005 -> position.set(Position.KEY_ICCID, ++ ByteBufUtil.hexDump(buf.readSlice(10)).substring(0, 19)); ++ case 0x0007 -> position.set( ++ Position.KEY_HDOP, buf.readUnsignedShort() / 10.0); ++ case 0x2001 -> position.set( ++ Position.KEY_POWER, buf.readUnsignedShort() / 10.0); ++ } ++ buf.readerIndex(statusEndIndex); ++ } ++ } ++ case 0x0001 -> position.addAlarm(Position.ALARM_FAULT); ++ case 0x0400, 0x0412 -> position.addAlarm(Position.ALARM_ACCELERATION); ++ case 0x0401, 0x0413 -> position.addAlarm(Position.ALARM_BRAKING); ++ case 0x0402, 0x0414 -> position.addAlarm(Position.ALARM_CORNERING); ++ case 0x0403 -> position.addAlarm(Position.ALARM_OVERSPEED); ++ case 0x0405, 0x0416, 0x0417 -> position.addAlarm(Position.ALARM_ACCIDENT); ++ case 0x0406 -> position.addAlarm(Position.ALARM_VIBRATION); ++ case 0x0407 -> position.addAlarm(Position.ALARM_TOW); ++ case 0x0408 -> position.addAlarm(Position.ALARM_GEOFENCE_ENTER); ++ case 0x0409 -> position.addAlarm(Position.ALARM_GEOFENCE_EXIT); ++ case 0x040C -> position.addAlarm(Position.ALARM_DOOR); ++ case 0x0415 -> position.addAlarm(Position.ALARM_LANE_CHANGE); ++ case 0x0C01 -> position.addAlarm(Position.ALARM_SOS); ++ case 0x0C02 -> position.addAlarm(Position.ALARM_LOW_POWER); ++ case 0x0C03 -> position.set(Position.KEY_IGNITION, true); ++ case 0x0C04 -> position.set(Position.KEY_IGNITION, false); ++ case 0x0C05 -> position.addAlarm(Position.ALARM_GENERAL); ++ case 0x0C0E -> position.addAlarm(Position.ALARM_POWER_CUT); ++ case 0x0C0F -> position.addAlarm(Position.ALARM_LOW_BATTERY); ++ case 0x0C10 -> position.addAlarm(Position.ALARM_POWER_OFF); ++ case 0x0C12 -> position.addAlarm(Position.ALARM_TAMPERING); ++ } ++ buf.readerIndex(endIndex); ++ } else { ++ position.set("lockStatus", buf.readUnsignedMedium()); ++ } + break; + case 0xEA: + if (length > 2) { +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index b3aee4b60..55ba4643e 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -340,6 +340,20 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7e020000ec6710704387730579000100009058000e015baf2c029bb433001200000129250310035204300111310108f03402d400020f720e0f00007d8b8e02d400020f720e0b00007d8b8c02d400020f720d0b00007d8b8a02d4000b092bf3030000c9a588f231414f56585f414c3330302d4c415f48322e305f4547393135554c4141425230334130344d30385f56322e312e303a763031f40e18ef3a6ae1c6be00bb252515d3b5f614021901cb006d0099052005dc002800000032000af70600000d6f003cf81d04086967107043877389550327001051953711414c3330302d4c410000f912000f0000000100000000000b2503100352322a7e"), + Position.KEY_ALARM, Position.ALARM_MOVEMENT); + ++ decoder.setModelOverride("JC371"); ++ ++ verifyAttribute(decoder, binary( ++ "7E020000344EB6FB4AD6280001000000000000000301587D0106CBFF6600000000000026010112000001040000007B30011831010AE80A2003070105019F030190657E"), ++ Position.KEY_BATTERY, 4.15); ++ ++ verifyAttribute(decoder, binary( ++ "7E0200003E4EB6FB4AD6280002000000000000000301587D0106CBFF6600000000000026010112000001040000007B30011831010AE8140C01103131313131313126010112000000000000467E"), ++ Position.KEY_ALARM, Position.ALARM_SOS); ++ ++ verifyAttribute(decoder, binary( ++ "7E0200003E4EB6FB4AD6280003000000000000000301587D0106CBFF6600000000000026010112000001040000007B30011831010AE8140406103131313131313126010112000000000000487E"), ++ Position.KEY_ALARM, Position.ALARM_VIBRATION); ++ + } + + } diff --git a/tasks/traccar__traccar-5864/tests/test.sh b/tasks/traccar__traccar-5864/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..22867292d03363d8440b255a846fd94717d66f86 --- /dev/null +++ b/tasks/traccar__traccar-5864/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 6f30f4898420fbf41c6c017540a85fcdc59e375d > "$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/traccar__traccar-5864/tests/verifier.py b/tasks/traccar__traccar-5864/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5864/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/traccar__traccar-5866/environment/Dockerfile b/tasks/traccar__traccar-5866/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a705fa892d013c33848a3b45e1e16ff217f22e71 --- /dev/null +++ b/tasks/traccar__traccar-5866/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 663e31bd6a806d9a92fadc72f276d7e00149b2f8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 663e31bd6a806d9a92fadc72f276d7e00149b2f8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 663e31bd6a806d9a92fadc72f276d7e00149b2f8 \ + && 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/traccar__traccar-5866/instruction.md b/tasks/traccar__traccar-5866/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..288c4c07f9f84d02ab680bbd2890e2ff5a61f5cb --- /dev/null +++ b/tasks/traccar__traccar-5866/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Fix MiniFinder WiFi position decoding + +## Description + +## Summary +- Handle MiniFinder2/Eview WiFi position records without embedded coordinates. +- Only decode latitude and longitude for key `0x2A` when the flags indicate coordinates are present. +- Add a regression sample for a WiFi description-only packet. + +## Testing +- `./gradlew test --tests org.traccar.protocol.Minifinder2ProtocolDecoderTest` +- `./gradlew checkstyleMain checkstyleTest` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `663e31bd6a80`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5866/solution/patch.diff b/tasks/traccar__traccar-5866/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0aa14720f6134b5f493d58ba00818fe141517a1f --- /dev/null +++ b/tasks/traccar__traccar-5866/solution/patch.diff @@ -0,0 +1,38 @@ +diff --git a/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java +index 6f4889d8d..7b230bc50 100644 +--- a/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java +@@ -331,12 +331,14 @@ public class Minifinder2ProtocolDecoder extends BaseProtocolDecoder { + } + break; + case 0x2A: +- buf.readUnsignedByte(); // flags ++ int wifiFlags = buf.readUnsignedByte(); + buf.skipBytes(6); // mac + buf.readUnsignedByte(); // rssi +- position.setLatitude(buf.readIntLE() / 10000000.0); +- position.setLongitude(buf.readIntLE() / 10000000.0); +- position.setValid(true); ++ if (BitUtil.check(wifiFlags, 7)) { ++ position.setLatitude(buf.readIntLE() / 10000000.0); ++ position.setLongitude(buf.readIntLE() / 10000000.0); ++ position.setValid(true); ++ } + if (endIndex > buf.readerIndex()) { + position.set("description", buf.readCharSequence( + endIndex - buf.readerIndex(), StandardCharsets.US_ASCII).toString()); +diff --git a/src/test/java/org/traccar/protocol/Minifinder2ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Minifinder2ProtocolDecoderTest.java +index 265fdb0b4..5c5864a2f 100644 +--- a/src/test/java/org/traccar/protocol/Minifinder2ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Minifinder2ProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Minifinder2ProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Minifinder2ProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "ab102c0039aac6020110013836313632393035303632353039380924dc37f36900427e5b0f2a404a8cba41a770ba506c61636531"), ++ "description", "Place1"); ++ + verifyPositions(decoder, binary( + "ab104b00cab208010110013836323232313038373738303438310d24d0b71d6a0800f864000000000d0200100000d0b71d6a000000001c23c69b531448e06ed4e621e254cf084d696e6946696e646572204851")); + diff --git a/tasks/traccar__traccar-5866/solution/solve.sh b/tasks/traccar__traccar-5866/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5866/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/traccar__traccar-5866/task.toml b/tasks/traccar__traccar-5866/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b78873d07377fd1528cafe84267eaa2b607cef6a --- /dev/null +++ b/tasks/traccar__traccar-5866/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5866" +description = "Fix MiniFinder WiFi position decoding" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "663e31bd6a806d9a92fadc72f276d7e00149b2f8" +reference = "https://github.com/traccar/traccar/pull/5866" +source_access = "auto" +built_at = "2026-11-16T16:09:42.555232+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:20d17288bbe6b4f95c90f8e0c6430ec012142aed716ac60e95db03cfd116dd00" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-30T14:22:23Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Minifinder2ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.489530+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:56d557820ac25133bae0dfa23eb3de48d16ed23af2357d6bab29acd907c71234" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5866/tests/capture.py b/tasks/traccar__traccar-5866/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5866/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/traccar__traccar-5866/tests/instruction.md b/tasks/traccar__traccar-5866/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..288c4c07f9f84d02ab680bbd2890e2ff5a61f5cb --- /dev/null +++ b/tasks/traccar__traccar-5866/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Fix MiniFinder WiFi position decoding + +## Description + +## Summary +- Handle MiniFinder2/Eview WiFi position records without embedded coordinates. +- Only decode latitude and longitude for key `0x2A` when the flags indicate coordinates are present. +- Add a regression sample for a WiFi description-only packet. + +## Testing +- `./gradlew test --tests org.traccar.protocol.Minifinder2ProtocolDecoderTest` +- `./gradlew checkstyleMain checkstyleTest` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `663e31bd6a80`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5866/tests/oracle.patch b/tasks/traccar__traccar-5866/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0aa14720f6134b5f493d58ba00818fe141517a1f --- /dev/null +++ b/tasks/traccar__traccar-5866/tests/oracle.patch @@ -0,0 +1,38 @@ +diff --git a/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java +index 6f4889d8d..7b230bc50 100644 +--- a/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Minifinder2ProtocolDecoder.java +@@ -331,12 +331,14 @@ public class Minifinder2ProtocolDecoder extends BaseProtocolDecoder { + } + break; + case 0x2A: +- buf.readUnsignedByte(); // flags ++ int wifiFlags = buf.readUnsignedByte(); + buf.skipBytes(6); // mac + buf.readUnsignedByte(); // rssi +- position.setLatitude(buf.readIntLE() / 10000000.0); +- position.setLongitude(buf.readIntLE() / 10000000.0); +- position.setValid(true); ++ if (BitUtil.check(wifiFlags, 7)) { ++ position.setLatitude(buf.readIntLE() / 10000000.0); ++ position.setLongitude(buf.readIntLE() / 10000000.0); ++ position.setValid(true); ++ } + if (endIndex > buf.readerIndex()) { + position.set("description", buf.readCharSequence( + endIndex - buf.readerIndex(), StandardCharsets.US_ASCII).toString()); +diff --git a/src/test/java/org/traccar/protocol/Minifinder2ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Minifinder2ProtocolDecoderTest.java +index 265fdb0b4..5c5864a2f 100644 +--- a/src/test/java/org/traccar/protocol/Minifinder2ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Minifinder2ProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Minifinder2ProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Minifinder2ProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "ab102c0039aac6020110013836313632393035303632353039380924dc37f36900427e5b0f2a404a8cba41a770ba506c61636531"), ++ "description", "Place1"); ++ + verifyPositions(decoder, binary( + "ab104b00cab208010110013836323232313038373738303438310d24d0b71d6a0800f864000000000d0200100000d0b71d6a000000001c23c69b531448e06ed4e621e254cf084d696e6946696e646572204851")); + diff --git a/tasks/traccar__traccar-5866/tests/test.sh b/tasks/traccar__traccar-5866/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5e45bac8fbae4931c6188445818610a36c6bc763 --- /dev/null +++ b/tasks/traccar__traccar-5866/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 663e31bd6a806d9a92fadc72f276d7e00149b2f8 > "$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/traccar__traccar-5866/tests/verifier.py b/tasks/traccar__traccar-5866/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5866/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/traccar__traccar-5884/environment/Dockerfile b/tasks/traccar__traccar-5884/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3cf86fafc13aaf1b6b8ea0feedd88d419b6e7560 --- /dev/null +++ b/tasks/traccar__traccar-5884/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6918e9f8f5d44920a34569b514cb6c7e6e2966c1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6918e9f8f5d44920a34569b514cb6c7e6e2966c1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6918e9f8f5d44920a34569b514cb6c7e6e2966c1 \ + && 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/traccar__traccar-5884/instruction.md b/tasks/traccar__traccar-5884/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa517029ecaf01275ee5cea616593bc47662e131 --- /dev/null +++ b/tasks/traccar__traccar-5884/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Add basic .editorconfig + +## Description + +My code editor has other defaults, this would help to easily have defaults consistent with the codebase. + +Is this something you want to add? + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6918e9f8f5d4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5884/solution/patch.diff b/tasks/traccar__traccar-5884/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..25e468d76f2989a25c1878c7fe1c59097a7d404d --- /dev/null +++ b/tasks/traccar__traccar-5884/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/.editorconfig b/.editorconfig +new file mode 100644 +index 000000000..10b0c576d +--- /dev/null ++++ b/.editorconfig +@@ -0,0 +1,11 @@ ++root = true ++ ++[*] ++charset = utf-8 ++end_of_line = lf ++insert_final_newline = true ++trim_trailing_whitespace = true ++ ++[*.java] ++indent_style = space ++indent_size = 4 diff --git a/tasks/traccar__traccar-5884/solution/solve.sh b/tasks/traccar__traccar-5884/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5884/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/traccar__traccar-5884/task.toml b/tasks/traccar__traccar-5884/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4f3b6dfddda6d893428efed920f7fcf1ae87c893 --- /dev/null +++ b/tasks/traccar__traccar-5884/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5884" +description = "Add basic .editorconfig" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "6918e9f8f5d44920a34569b514cb6c7e6e2966c1" +reference = "https://github.com/traccar/traccar/pull/5884" +source_access = "auto" +built_at = "2026-11-16T16:09:42.584215+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d8ae0f9778823c36abb5cf1acea2065c2374d04e7d34698b5e1c718ebed7c1a7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-21T16:48:55Z" +diff_format = "unified" +context_files = [ + ".editorconfig", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 11 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.490091+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d2b7c9c73d645c66d59c23ed2a73c035081c967fd3133766f7225f7be2ee2bc7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5884/tests/capture.py b/tasks/traccar__traccar-5884/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5884/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/traccar__traccar-5884/tests/instruction.md b/tasks/traccar__traccar-5884/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa517029ecaf01275ee5cea616593bc47662e131 --- /dev/null +++ b/tasks/traccar__traccar-5884/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Add basic .editorconfig + +## Description + +My code editor has other defaults, this would help to easily have defaults consistent with the codebase. + +Is this something you want to add? + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6918e9f8f5d4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5884/tests/oracle.patch b/tasks/traccar__traccar-5884/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..25e468d76f2989a25c1878c7fe1c59097a7d404d --- /dev/null +++ b/tasks/traccar__traccar-5884/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/.editorconfig b/.editorconfig +new file mode 100644 +index 000000000..10b0c576d +--- /dev/null ++++ b/.editorconfig +@@ -0,0 +1,11 @@ ++root = true ++ ++[*] ++charset = utf-8 ++end_of_line = lf ++insert_final_newline = true ++trim_trailing_whitespace = true ++ ++[*.java] ++indent_style = space ++indent_size = 4 diff --git a/tasks/traccar__traccar-5884/tests/test.sh b/tasks/traccar__traccar-5884/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f117aa95bcc0b94788db045e91b06a5907240e0d --- /dev/null +++ b/tasks/traccar__traccar-5884/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 6918e9f8f5d44920a34569b514cb6c7e6e2966c1 > "$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/traccar__traccar-5884/tests/verifier.py b/tasks/traccar__traccar-5884/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5884/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/traccar__traccar-5888/environment/Dockerfile b/tasks/traccar__traccar-5888/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f6655c4a0660770a90e851ee2a13eb999075850c --- /dev/null +++ b/tasks/traccar__traccar-5888/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fb1ef0cfbf6ee0f0983678c9c290e242acd9a216 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fb1ef0cfbf6ee0f0983678c9c290e242acd9a216 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fb1ef0cfbf6ee0f0983678c9c290e242acd9a216 \ + && 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/traccar__traccar-5888/instruction.md b/tasks/traccar__traccar-5888/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c73da7451af951346204690d8d4c253b91cf2151 --- /dev/null +++ b/tasks/traccar__traccar-5888/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** Add support for JT808 SMS response message (0x1300) + +## Description + +This change adds support for JT808 message type 0x1300 (SMS Response Transparent Transmission Protocol). + +Some JT808-compatible devices reply to text commands (0x8300) using message 0x1300 instead of the existing response types currently handled by the decoder. As a result, command responses such as: + +- Set OK! +- Set FAIL! +- Invalid sms cmd! + +were ignored and not forwarded by Traccar because message 0x1300 was not decoded. + +**Changes:** +- Added JT808 message constant MSG_TEXT_MESSAGE_RESPONSE (0x1300) +- Added decoder handling for 0x1300 messages +- Decoded text payloads and stored them in Position.KEY_RESULT +- Added unit test coverage for a real-world device response + +This allows command execution results returned through 0x1300 to appear in Traccar in the same way as other supported command response messages and so allows command result forwarding. + +**Evidence:** + +Message ID 0x1300 is explained in the protocol documentation: +File: [Xchinchun JT808.docx](https://github.com/user-attachments/files/28387344/Xchinchun.JT808.docx) + +It can be found on page 43 in the section: +SMS Response Transparent Transmission Protocol (0x1300) 3.27 + +Field | Meaning +-- | -- +Message ID | 0x1300 +Name | SMS Response Transparent Transmission Protocol +Start byte 0 | Response Serial Number, WORD +Start byte 2 | Text information, STRING +Encoding | Unicode +Purpose | Device response to SMS/text commands sent via 0x8300 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fb1ef0cfbf6e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5888/solution/patch.diff b/tasks/traccar__traccar-5888/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e2ab751188079314ea32516e034c34dec8479f41 --- /dev/null +++ b/tasks/traccar__traccar-5888/solution/patch.diff @@ -0,0 +1,50 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 72362a3c1..99db8c4c2 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -83,6 +83,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_REPORT_TEXT_MESSAGE = 0x6006; + public static final int MSG_CONFIGURATION_PARAMETERS = 0x8103; + public static final int MSG_COMMAND_RESPONSE = 0x0701; ++ public static final int MSG_TEXT_MESSAGE_RESPONSE = 0x1300; + public static final int MSG_DRIVER_IDENTITY = 0x0702; + public static final int MSG_VIDEO_REQUEST = 0x9101; + public static final int MSG_VIDEO_CONTROL = 0x9102; +@@ -364,6 +365,22 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + + return position; + ++ } else if (type == MSG_TEXT_MESSAGE_RESPONSE) { ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ getLastLocation(position, null); ++ ++ int bodyLength = BitUtil.to(attribute, 10); ++ ++ buf.readUnsignedShort(); // response serial number ++ ++ String result = buf.readCharSequence(bodyLength - 2, StandardCharsets.UTF_16BE).toString().trim(); ++ position.set(Position.KEY_RESULT, result); ++ ++ return position; ++ + } else if (type == MSG_HEARTBEAT) { + + sendGeneralResponse(channel, remoteAddress, id, type, index); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index a0db92482..9e47aaea4 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -252,6 +252,10 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "283734303139303331313138352c312c3030312c454c4f434b2c332c35323934333929"), + Position.KEY_RESULT, "(740190311185,1,001,ELOCK,3,529439)"); + ++ verifyAttribute(decoder, binary( ++ "7e13000012045450091546010900000053006500740020004f004b0021000d197e"), ++ Position.KEY_RESULT, "Set OK!"); ++ + verifyPosition(decoder, binary( + "7e55028436740190311185091607200239270613212607536108630000170a000000014600005ded05e203000000000b010d0c06005b003e00ab0a0302dc65100100a37e")); + diff --git a/tasks/traccar__traccar-5888/solution/solve.sh b/tasks/traccar__traccar-5888/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5888/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/traccar__traccar-5888/task.toml b/tasks/traccar__traccar-5888/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..94a34620a4f88bc0cd49a326057575b444d368b9 --- /dev/null +++ b/tasks/traccar__traccar-5888/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5888" +description = "Add support for JT808 SMS response message (0x1300)" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "fb1ef0cfbf6ee0f0983678c9c290e242acd9a216" +reference = "https://github.com/traccar/traccar/pull/5888" +source_access = "auto" +built_at = "2026-11-16T16:09:42.575038+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:424211ef13e0e982fcd3b9d77541842c3bd47ffd3d1ae066c657526d691a492c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-29T16:27:12Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 21 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.490703+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0d2697a7d3e47bb6283fcfc4257a7d2284a1a813efb0a0ee885d91bfdfcef378" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5888/tests/capture.py b/tasks/traccar__traccar-5888/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5888/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/traccar__traccar-5888/tests/instruction.md b/tasks/traccar__traccar-5888/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c73da7451af951346204690d8d4c253b91cf2151 --- /dev/null +++ b/tasks/traccar__traccar-5888/tests/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** Add support for JT808 SMS response message (0x1300) + +## Description + +This change adds support for JT808 message type 0x1300 (SMS Response Transparent Transmission Protocol). + +Some JT808-compatible devices reply to text commands (0x8300) using message 0x1300 instead of the existing response types currently handled by the decoder. As a result, command responses such as: + +- Set OK! +- Set FAIL! +- Invalid sms cmd! + +were ignored and not forwarded by Traccar because message 0x1300 was not decoded. + +**Changes:** +- Added JT808 message constant MSG_TEXT_MESSAGE_RESPONSE (0x1300) +- Added decoder handling for 0x1300 messages +- Decoded text payloads and stored them in Position.KEY_RESULT +- Added unit test coverage for a real-world device response + +This allows command execution results returned through 0x1300 to appear in Traccar in the same way as other supported command response messages and so allows command result forwarding. + +**Evidence:** + +Message ID 0x1300 is explained in the protocol documentation: +File: [Xchinchun JT808.docx](https://github.com/user-attachments/files/28387344/Xchinchun.JT808.docx) + +It can be found on page 43 in the section: +SMS Response Transparent Transmission Protocol (0x1300) 3.27 + +Field | Meaning +-- | -- +Message ID | 0x1300 +Name | SMS Response Transparent Transmission Protocol +Start byte 0 | Response Serial Number, WORD +Start byte 2 | Text information, STRING +Encoding | Unicode +Purpose | Device response to SMS/text commands sent via 0x8300 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fb1ef0cfbf6e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5888/tests/oracle.patch b/tasks/traccar__traccar-5888/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e2ab751188079314ea32516e034c34dec8479f41 --- /dev/null +++ b/tasks/traccar__traccar-5888/tests/oracle.patch @@ -0,0 +1,50 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 72362a3c1..99db8c4c2 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -83,6 +83,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_REPORT_TEXT_MESSAGE = 0x6006; + public static final int MSG_CONFIGURATION_PARAMETERS = 0x8103; + public static final int MSG_COMMAND_RESPONSE = 0x0701; ++ public static final int MSG_TEXT_MESSAGE_RESPONSE = 0x1300; + public static final int MSG_DRIVER_IDENTITY = 0x0702; + public static final int MSG_VIDEO_REQUEST = 0x9101; + public static final int MSG_VIDEO_CONTROL = 0x9102; +@@ -364,6 +365,22 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + + return position; + ++ } else if (type == MSG_TEXT_MESSAGE_RESPONSE) { ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ getLastLocation(position, null); ++ ++ int bodyLength = BitUtil.to(attribute, 10); ++ ++ buf.readUnsignedShort(); // response serial number ++ ++ String result = buf.readCharSequence(bodyLength - 2, StandardCharsets.UTF_16BE).toString().trim(); ++ position.set(Position.KEY_RESULT, result); ++ ++ return position; ++ + } else if (type == MSG_HEARTBEAT) { + + sendGeneralResponse(channel, remoteAddress, id, type, index); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index a0db92482..9e47aaea4 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -252,6 +252,10 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "283734303139303331313138352c312c3030312c454c4f434b2c332c35323934333929"), + Position.KEY_RESULT, "(740190311185,1,001,ELOCK,3,529439)"); + ++ verifyAttribute(decoder, binary( ++ "7e13000012045450091546010900000053006500740020004f004b0021000d197e"), ++ Position.KEY_RESULT, "Set OK!"); ++ + verifyPosition(decoder, binary( + "7e55028436740190311185091607200239270613212607536108630000170a000000014600005ded05e203000000000b010d0c06005b003e00ab0a0302dc65100100a37e")); + diff --git a/tasks/traccar__traccar-5888/tests/test.sh b/tasks/traccar__traccar-5888/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..25f5053b079cbaed4f2e304fba4ad09d1b8ca31a --- /dev/null +++ b/tasks/traccar__traccar-5888/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 fb1ef0cfbf6ee0f0983678c9c290e242acd9a216 > "$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/traccar__traccar-5888/tests/verifier.py b/tasks/traccar__traccar-5888/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5888/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/traccar__traccar-5889/environment/Dockerfile b/tasks/traccar__traccar-5889/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..962b3f4ad4e086eacab07646d34337015b26dfdc --- /dev/null +++ b/tasks/traccar__traccar-5889/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6316843e84b51a618bb58824ae7a990dc7b50682 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6316843e84b51a618bb58824ae7a990dc7b50682 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6316843e84b51a618bb58824ae7a990dc7b50682 \ + && 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/traccar__traccar-5889/instruction.md b/tasks/traccar__traccar-5889/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8fe4fa0b2d5b05cebd2be94303a167341362dc2d --- /dev/null +++ b/tasks/traccar__traccar-5889/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Lazy AMQP connection and forwarding error logging + +## Description + +AMQP is the only forwarder that connects synchronously in its constructor. If the broker is unavailable, `factory.newConnection()` throws and the `RuntimeException` propagates through Guice provisioning, causing `System.exit(1)` — Traccar fails to start entirely. + +Kafka, MQTT and JSON forwarders don't have this issue because they connect lazily or asynchronously. + +This change defers the AMQP connection to the first `publishMessage()` call and adds `channel.isOpen()` checks so forwarding resumes automatically if the broker restarts. Follows the same lazy-connect pattern used in `NetworkForwarder`. + +Also adds `LOGGER.warn` to `EventForwarderAmqp` and `PositionForwarderAmqp` for forwarding errors, matching existing logging in `NetworkForwarder` and `PositionForwardingHandler`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6316843e84b5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5889/solution/patch.diff b/tasks/traccar__traccar-5889/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7ec1af91bf1907f7c8b59f7316a70ce72dd826ad --- /dev/null +++ b/tasks/traccar__traccar-5889/solution/patch.diff @@ -0,0 +1,149 @@ +diff --git a/src/main/java/org/traccar/forward/AmqpClient.java b/src/main/java/org/traccar/forward/AmqpClient.java +index 7892805df..6b2a1fd19 100644 +--- a/src/main/java/org/traccar/forward/AmqpClient.java ++++ b/src/main/java/org/traccar/forward/AmqpClient.java +@@ -21,6 +21,9 @@ import com.rabbitmq.client.Connection; + import com.rabbitmq.client.ConnectionFactory; + import com.rabbitmq.client.MessageProperties; + ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; ++ + import java.io.IOException; + import java.net.URISyntaxException; + import java.nio.charset.StandardCharsets; +@@ -29,32 +32,63 @@ import java.security.NoSuchAlgorithmException; + import java.util.concurrent.TimeoutException; + + public class AmqpClient { +- private final Channel channel; ++ ++ private static final Logger LOGGER = LoggerFactory.getLogger(AmqpClient.class); ++ ++ private final ConnectionFactory factory; + private final String exchange; + private final String topic; + ++ private Connection connection; ++ private Channel channel; ++ + AmqpClient(String connectionUrl, String exchange, String topic) { + this.exchange = exchange; + this.topic = topic; + +- ConnectionFactory factory = new ConnectionFactory(); ++ factory = new ConnectionFactory(); + try { + factory.setUri(connectionUrl); + } catch (NoSuchAlgorithmException | URISyntaxException | KeyManagementException e) { + throw new RuntimeException("Error while setting URI for RabbitMQ connection factory", e); + } ++ } + +- try { +- Connection connection = factory.newConnection(); +- channel = connection.createChannel(); +- channel.exchangeDeclare(exchange, BuiltinExchangeType.TOPIC, true); +- } catch (IOException | TimeoutException e) { +- throw new RuntimeException("Error while creating and configuring RabbitMQ channel", e); ++ private static void closeQuietly(AutoCloseable resource) { ++ if (resource != null) { ++ try { ++ resource.close(); ++ } catch (Exception e) { ++ LOGGER.warn("AMQP close error", e); ++ } + } + } + +- public void publishMessage(String message) throws IOException { +- channel.basicPublish( +- exchange, topic, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8)); ++ private void disconnect() { ++ closeQuietly(channel); ++ channel = null; ++ closeQuietly(connection); ++ connection = null; ++ } ++ ++ private void connect() throws IOException, TimeoutException { ++ disconnect(); ++ connection = factory.newConnection(); ++ channel = connection.createChannel(); ++ channel.exchangeDeclare(exchange, BuiltinExchangeType.TOPIC, true); ++ } ++ ++ public synchronized void publishMessage(String message) throws IOException { ++ try { ++ if (channel == null || !channel.isOpen()) { ++ connect(); ++ } ++ channel.basicPublish( ++ exchange, topic, MessageProperties.PERSISTENT_TEXT_PLAIN, ++ message.getBytes(StandardCharsets.UTF_8)); ++ } catch (IOException | TimeoutException e) { ++ disconnect(); ++ throw new IOException("AMQP publish failed", e); ++ } + } + } +diff --git a/src/main/java/org/traccar/forward/EventForwarderAmqp.java b/src/main/java/org/traccar/forward/EventForwarderAmqp.java +index 5c38a4459..4bb56ef25 100644 +--- a/src/main/java/org/traccar/forward/EventForwarderAmqp.java ++++ b/src/main/java/org/traccar/forward/EventForwarderAmqp.java +@@ -17,6 +17,8 @@ package org.traccar.forward; + + import com.fasterxml.jackson.databind.ObjectMapper; + ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + import org.traccar.config.Config; + import org.traccar.config.Keys; + +@@ -24,6 +26,8 @@ import java.io.IOException; + + public class EventForwarderAmqp implements EventForwarder { + ++ private static final Logger LOGGER = LoggerFactory.getLogger(EventForwarderAmqp.class); ++ + private final AmqpClient amqpClient; + private final ObjectMapper objectMapper; + +@@ -42,6 +46,7 @@ public class EventForwarderAmqp implements EventForwarder { + amqpClient.publishMessage(value); + resultHandler.onResult(true, null); + } catch (IOException e) { ++ LOGGER.warn("Event forwarding error", e); + resultHandler.onResult(false, e); + } + } +diff --git a/src/main/java/org/traccar/forward/PositionForwarderAmqp.java b/src/main/java/org/traccar/forward/PositionForwarderAmqp.java +index 3996bda15..972f44e10 100644 +--- a/src/main/java/org/traccar/forward/PositionForwarderAmqp.java ++++ b/src/main/java/org/traccar/forward/PositionForwarderAmqp.java +@@ -17,6 +17,8 @@ package org.traccar.forward; + + import com.fasterxml.jackson.databind.ObjectMapper; + ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + import org.traccar.config.Config; + import org.traccar.config.Keys; + +@@ -24,6 +26,8 @@ import java.io.IOException; + + public class PositionForwarderAmqp implements PositionForwarder { + ++ private static final Logger LOGGER = LoggerFactory.getLogger(PositionForwarderAmqp.class); ++ + private final AmqpClient amqpClient; + private final ObjectMapper objectMapper; + +@@ -42,6 +46,7 @@ public class PositionForwarderAmqp implements PositionForwarder { + amqpClient.publishMessage(value); + resultHandler.onResult(true, null); + } catch (IOException e) { ++ LOGGER.warn("Position forwarding error", e); + resultHandler.onResult(false, e); + } + } diff --git a/tasks/traccar__traccar-5889/solution/solve.sh b/tasks/traccar__traccar-5889/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5889/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/traccar__traccar-5889/task.toml b/tasks/traccar__traccar-5889/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1bc950631e9ab301b606f53d1eb768f487e69aca --- /dev/null +++ b/tasks/traccar__traccar-5889/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5889" +description = "Lazy AMQP connection and forwarding error logging" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "6316843e84b51a618bb58824ae7a990dc7b50682" +reference = "https://github.com/traccar/traccar/pull/5889" +source_access = "auto" +built_at = "2026-11-16T16:09:42.556857+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:07f63cde5553bef33aabdafd95a9001b64887e24d97a26bb8be79a255f1a356f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-29T01:23:07Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/forward/AmqpClient.java", + "src/main/java/org/traccar/forward/EventForwarderAmqp.java", + "src/main/java/org/traccar/forward/PositionForwarderAmqp.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 66 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.491300+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0dded24a9caae87280e182943631ec7d09c19dffee98c98fa66956995d0b8551" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5889/tests/capture.py b/tasks/traccar__traccar-5889/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5889/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/traccar__traccar-5889/tests/instruction.md b/tasks/traccar__traccar-5889/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8fe4fa0b2d5b05cebd2be94303a167341362dc2d --- /dev/null +++ b/tasks/traccar__traccar-5889/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Lazy AMQP connection and forwarding error logging + +## Description + +AMQP is the only forwarder that connects synchronously in its constructor. If the broker is unavailable, `factory.newConnection()` throws and the `RuntimeException` propagates through Guice provisioning, causing `System.exit(1)` — Traccar fails to start entirely. + +Kafka, MQTT and JSON forwarders don't have this issue because they connect lazily or asynchronously. + +This change defers the AMQP connection to the first `publishMessage()` call and adds `channel.isOpen()` checks so forwarding resumes automatically if the broker restarts. Follows the same lazy-connect pattern used in `NetworkForwarder`. + +Also adds `LOGGER.warn` to `EventForwarderAmqp` and `PositionForwarderAmqp` for forwarding errors, matching existing logging in `NetworkForwarder` and `PositionForwardingHandler`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6316843e84b5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5889/tests/oracle.patch b/tasks/traccar__traccar-5889/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7ec1af91bf1907f7c8b59f7316a70ce72dd826ad --- /dev/null +++ b/tasks/traccar__traccar-5889/tests/oracle.patch @@ -0,0 +1,149 @@ +diff --git a/src/main/java/org/traccar/forward/AmqpClient.java b/src/main/java/org/traccar/forward/AmqpClient.java +index 7892805df..6b2a1fd19 100644 +--- a/src/main/java/org/traccar/forward/AmqpClient.java ++++ b/src/main/java/org/traccar/forward/AmqpClient.java +@@ -21,6 +21,9 @@ import com.rabbitmq.client.Connection; + import com.rabbitmq.client.ConnectionFactory; + import com.rabbitmq.client.MessageProperties; + ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; ++ + import java.io.IOException; + import java.net.URISyntaxException; + import java.nio.charset.StandardCharsets; +@@ -29,32 +32,63 @@ import java.security.NoSuchAlgorithmException; + import java.util.concurrent.TimeoutException; + + public class AmqpClient { +- private final Channel channel; ++ ++ private static final Logger LOGGER = LoggerFactory.getLogger(AmqpClient.class); ++ ++ private final ConnectionFactory factory; + private final String exchange; + private final String topic; + ++ private Connection connection; ++ private Channel channel; ++ + AmqpClient(String connectionUrl, String exchange, String topic) { + this.exchange = exchange; + this.topic = topic; + +- ConnectionFactory factory = new ConnectionFactory(); ++ factory = new ConnectionFactory(); + try { + factory.setUri(connectionUrl); + } catch (NoSuchAlgorithmException | URISyntaxException | KeyManagementException e) { + throw new RuntimeException("Error while setting URI for RabbitMQ connection factory", e); + } ++ } + +- try { +- Connection connection = factory.newConnection(); +- channel = connection.createChannel(); +- channel.exchangeDeclare(exchange, BuiltinExchangeType.TOPIC, true); +- } catch (IOException | TimeoutException e) { +- throw new RuntimeException("Error while creating and configuring RabbitMQ channel", e); ++ private static void closeQuietly(AutoCloseable resource) { ++ if (resource != null) { ++ try { ++ resource.close(); ++ } catch (Exception e) { ++ LOGGER.warn("AMQP close error", e); ++ } + } + } + +- public void publishMessage(String message) throws IOException { +- channel.basicPublish( +- exchange, topic, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8)); ++ private void disconnect() { ++ closeQuietly(channel); ++ channel = null; ++ closeQuietly(connection); ++ connection = null; ++ } ++ ++ private void connect() throws IOException, TimeoutException { ++ disconnect(); ++ connection = factory.newConnection(); ++ channel = connection.createChannel(); ++ channel.exchangeDeclare(exchange, BuiltinExchangeType.TOPIC, true); ++ } ++ ++ public synchronized void publishMessage(String message) throws IOException { ++ try { ++ if (channel == null || !channel.isOpen()) { ++ connect(); ++ } ++ channel.basicPublish( ++ exchange, topic, MessageProperties.PERSISTENT_TEXT_PLAIN, ++ message.getBytes(StandardCharsets.UTF_8)); ++ } catch (IOException | TimeoutException e) { ++ disconnect(); ++ throw new IOException("AMQP publish failed", e); ++ } + } + } +diff --git a/src/main/java/org/traccar/forward/EventForwarderAmqp.java b/src/main/java/org/traccar/forward/EventForwarderAmqp.java +index 5c38a4459..4bb56ef25 100644 +--- a/src/main/java/org/traccar/forward/EventForwarderAmqp.java ++++ b/src/main/java/org/traccar/forward/EventForwarderAmqp.java +@@ -17,6 +17,8 @@ package org.traccar.forward; + + import com.fasterxml.jackson.databind.ObjectMapper; + ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + import org.traccar.config.Config; + import org.traccar.config.Keys; + +@@ -24,6 +26,8 @@ import java.io.IOException; + + public class EventForwarderAmqp implements EventForwarder { + ++ private static final Logger LOGGER = LoggerFactory.getLogger(EventForwarderAmqp.class); ++ + private final AmqpClient amqpClient; + private final ObjectMapper objectMapper; + +@@ -42,6 +46,7 @@ public class EventForwarderAmqp implements EventForwarder { + amqpClient.publishMessage(value); + resultHandler.onResult(true, null); + } catch (IOException e) { ++ LOGGER.warn("Event forwarding error", e); + resultHandler.onResult(false, e); + } + } +diff --git a/src/main/java/org/traccar/forward/PositionForwarderAmqp.java b/src/main/java/org/traccar/forward/PositionForwarderAmqp.java +index 3996bda15..972f44e10 100644 +--- a/src/main/java/org/traccar/forward/PositionForwarderAmqp.java ++++ b/src/main/java/org/traccar/forward/PositionForwarderAmqp.java +@@ -17,6 +17,8 @@ package org.traccar.forward; + + import com.fasterxml.jackson.databind.ObjectMapper; + ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + import org.traccar.config.Config; + import org.traccar.config.Keys; + +@@ -24,6 +26,8 @@ import java.io.IOException; + + public class PositionForwarderAmqp implements PositionForwarder { + ++ private static final Logger LOGGER = LoggerFactory.getLogger(PositionForwarderAmqp.class); ++ + private final AmqpClient amqpClient; + private final ObjectMapper objectMapper; + +@@ -42,6 +46,7 @@ public class PositionForwarderAmqp implements PositionForwarder { + amqpClient.publishMessage(value); + resultHandler.onResult(true, null); + } catch (IOException e) { ++ LOGGER.warn("Position forwarding error", e); + resultHandler.onResult(false, e); + } + } diff --git a/tasks/traccar__traccar-5889/tests/test.sh b/tasks/traccar__traccar-5889/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8882c74e2e343ded6ed2621732e011eba2ad46fe --- /dev/null +++ b/tasks/traccar__traccar-5889/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 6316843e84b51a618bb58824ae7a990dc7b50682 > "$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/traccar__traccar-5889/tests/verifier.py b/tasks/traccar__traccar-5889/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5889/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/traccar__traccar-5890/environment/Dockerfile b/tasks/traccar__traccar-5890/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5154eb6a6283266f0b14546848d76a33c38e34af --- /dev/null +++ b/tasks/traccar__traccar-5890/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1a32c1bc453277d331179b0b280fc9f4ec022617 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1a32c1bc453277d331179b0b280fc9f4ec022617 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1a32c1bc453277d331179b0b280fc9f4ec022617 \ + && 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/traccar__traccar-5890/instruction.md b/tasks/traccar__traccar-5890/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2765c9dc1f8c8f82df4bf221d883e1d0d4744dec --- /dev/null +++ b/tasks/traccar__traccar-5890/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** Added C5 and C5L model specific handling + +## Description + +## Summary + +Extend JT808 custom command support for C5 and C5L devices. + +Previously, text-based custom commands were only encoded as JT808 text messages (`0x8300`) for the BSJ model. This change adds support for C5 and C5L devices, which use the same command transport mechanism. + +## Changes + +* Added `C5` and `C5L` to the JT808 encoder text message model list. +* Custom commands for `BSJ`, `C5`, and `C5L` are now encoded using JT808 message type `0x8300` (Send Text Message). +* Added a unit test covering all three models to ensure they follow the same encoding path. + +## Test Coverage + +Added a test that verifies: + +* `BSJ`, `C5`, and `C5L` use the same encoder branch. +* Custom commands are encoded as JT808 text messages (`0x8300`). +* The command payload is prefixed with the required flag byte (`0x01`). +* The command text is correctly included in the encoded message. + +Example command used in the test: + +`Test, Command, 123#` + +## Motivation + +C5 and C5L devices accept SMS-style text commands through the JT808 text message mechanism, matching the existing BSJ implementation. This change enables command delivery without requiring raw hexadecimal payloads and keeps behavior consistent across supported device models. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1a32c1bc4532`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5890/solution/patch.diff b/tasks/traccar__traccar-5890/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..74ad418c56a46e5184e9aa8289383b594cebba79 --- /dev/null +++ b/tasks/traccar__traccar-5890/solution/patch.diff @@ -0,0 +1,44 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +index 744f7367e..765204646 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +@@ -70,7 +70,7 @@ public class Jt808ProtocolEncoder extends BaseProtocolEncoder { + data.writeCharSequence(command.getString(Command.KEY_DATA), StandardCharsets.US_ASCII); + return decoder.formatMessage( + Jt808ProtocolDecoder.MSG_CONFIGURATION_PARAMETERS, id, false, data); +- } else if ("BSJ".equals(model)) { ++ } else if (model != null && Set.of("BSJ", "C5", "C5L").contains(model)) { + data.writeByte(1); // flag + var charset = Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII; + data.writeCharSequence(command.getString(Command.KEY_DATA), charset); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java +index f7e2cd21f..b38cd3507 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java +@@ -14,12 +14,25 @@ public class Jt808ProtocolEncoderTest extends ProtocolTest { + + Command command = new Command(); + command.setDeviceId(1); +- command.setType(Command.TYPE_ENGINE_STOP); + ++ command.setType(Command.TYPE_ENGINE_STOP); + verifyFrame( + binary("7e810500010b3a73ce2ff20000f0247e"), + encodeCommand(encoder, decoder, command)); + ++ command.setType(Command.TYPE_CUSTOM); ++ ++ command.set(Command.KEY_DATA, "7e830000140b3a73ce2ff2000001546573742c20436f6d6d616e642c2031323323a57e"); ++ verifyFrame( ++ binary("7e830000140b3a73ce2ff2000001546573742c20436f6d6d616e642c2031323323a57e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ encoder.setModelOverride("BSJ"); ++ command.set(Command.KEY_DATA, "Test, Command, 123#"); ++ verifyFrame( ++ binary("7e830000140b3a73ce2ff2000001546573742c20436f6d6d616e642c2031323323a57e"), ++ encodeCommand(encoder, decoder, command)); ++ + } + + } diff --git a/tasks/traccar__traccar-5890/solution/solve.sh b/tasks/traccar__traccar-5890/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5890/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/traccar__traccar-5890/task.toml b/tasks/traccar__traccar-5890/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..642f44581fc97f7ef570b02f12a44c2a3e1600f7 --- /dev/null +++ b/tasks/traccar__traccar-5890/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5890" +description = "Added C5 and C5L model specific handling" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "1a32c1bc453277d331179b0b280fc9f4ec022617" +reference = "https://github.com/traccar/traccar/pull/5890" +source_access = "auto" +built_at = "2026-11-16T16:09:42.576708+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5bacdee08c0be3fe47ccb70002e9998f739e357cd59f2d25f3412c2ca4592ba7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-03T14:22:18Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java", +] +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:03.491899+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6d7ec75e86b5b5c86d73cb4f4db4fac34bfb556162c785cfddc45c5bb442b4c1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5890/tests/capture.py b/tasks/traccar__traccar-5890/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5890/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/traccar__traccar-5890/tests/instruction.md b/tasks/traccar__traccar-5890/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2765c9dc1f8c8f82df4bf221d883e1d0d4744dec --- /dev/null +++ b/tasks/traccar__traccar-5890/tests/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** Added C5 and C5L model specific handling + +## Description + +## Summary + +Extend JT808 custom command support for C5 and C5L devices. + +Previously, text-based custom commands were only encoded as JT808 text messages (`0x8300`) for the BSJ model. This change adds support for C5 and C5L devices, which use the same command transport mechanism. + +## Changes + +* Added `C5` and `C5L` to the JT808 encoder text message model list. +* Custom commands for `BSJ`, `C5`, and `C5L` are now encoded using JT808 message type `0x8300` (Send Text Message). +* Added a unit test covering all three models to ensure they follow the same encoding path. + +## Test Coverage + +Added a test that verifies: + +* `BSJ`, `C5`, and `C5L` use the same encoder branch. +* Custom commands are encoded as JT808 text messages (`0x8300`). +* The command payload is prefixed with the required flag byte (`0x01`). +* The command text is correctly included in the encoded message. + +Example command used in the test: + +`Test, Command, 123#` + +## Motivation + +C5 and C5L devices accept SMS-style text commands through the JT808 text message mechanism, matching the existing BSJ implementation. This change enables command delivery without requiring raw hexadecimal payloads and keeps behavior consistent across supported device models. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1a32c1bc4532`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5890/tests/oracle.patch b/tasks/traccar__traccar-5890/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..74ad418c56a46e5184e9aa8289383b594cebba79 --- /dev/null +++ b/tasks/traccar__traccar-5890/tests/oracle.patch @@ -0,0 +1,44 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +index 744f7367e..765204646 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +@@ -70,7 +70,7 @@ public class Jt808ProtocolEncoder extends BaseProtocolEncoder { + data.writeCharSequence(command.getString(Command.KEY_DATA), StandardCharsets.US_ASCII); + return decoder.formatMessage( + Jt808ProtocolDecoder.MSG_CONFIGURATION_PARAMETERS, id, false, data); +- } else if ("BSJ".equals(model)) { ++ } else if (model != null && Set.of("BSJ", "C5", "C5L").contains(model)) { + data.writeByte(1); // flag + var charset = Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII; + data.writeCharSequence(command.getString(Command.KEY_DATA), charset); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java +index f7e2cd21f..b38cd3507 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java +@@ -14,12 +14,25 @@ public class Jt808ProtocolEncoderTest extends ProtocolTest { + + Command command = new Command(); + command.setDeviceId(1); +- command.setType(Command.TYPE_ENGINE_STOP); + ++ command.setType(Command.TYPE_ENGINE_STOP); + verifyFrame( + binary("7e810500010b3a73ce2ff20000f0247e"), + encodeCommand(encoder, decoder, command)); + ++ command.setType(Command.TYPE_CUSTOM); ++ ++ command.set(Command.KEY_DATA, "7e830000140b3a73ce2ff2000001546573742c20436f6d6d616e642c2031323323a57e"); ++ verifyFrame( ++ binary("7e830000140b3a73ce2ff2000001546573742c20436f6d6d616e642c2031323323a57e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ encoder.setModelOverride("BSJ"); ++ command.set(Command.KEY_DATA, "Test, Command, 123#"); ++ verifyFrame( ++ binary("7e830000140b3a73ce2ff2000001546573742c20436f6d6d616e642c2031323323a57e"), ++ encodeCommand(encoder, decoder, command)); ++ + } + + } diff --git a/tasks/traccar__traccar-5890/tests/test.sh b/tasks/traccar__traccar-5890/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..80e7ab77f7484f6d657b21b46b7eb0fc2596d06a --- /dev/null +++ b/tasks/traccar__traccar-5890/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 1a32c1bc453277d331179b0b280fc9f4ec022617 > "$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/traccar__traccar-5890/tests/verifier.py b/tasks/traccar__traccar-5890/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5890/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/traccar__traccar-5895/environment/Dockerfile b/tasks/traccar__traccar-5895/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5154eb6a6283266f0b14546848d76a33c38e34af --- /dev/null +++ b/tasks/traccar__traccar-5895/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1a32c1bc453277d331179b0b280fc9f4ec022617 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1a32c1bc453277d331179b0b280fc9f4ec022617 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1a32c1bc453277d331179b0b280fc9f4ec022617 \ + && 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/traccar__traccar-5895/instruction.md b/tasks/traccar__traccar-5895/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..254d3d6d710cace62b1fbdda9b719c306bfe77ed --- /dev/null +++ b/tasks/traccar__traccar-5895/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Decode Xchinchun 0xE1 cell tower data + +## Description + +This pull request adds support for decoding Xinchun-specific 0xE1 location extension data as cell tower information. + +When the 0xE1 payload matches the Xinchun base station format, the decoder now extracts MCC, MNC, LAC, Cell ID, and RSSI and adds them to the position network. + +The existing fallback behavior for other 0xE1 payload formats is preserved. + +Evidence can be found in the Xchinchun protocol documentation [Xchinchun JT808.docx](https://github.com/user-attachments/files/28529600/Xchinchun.JT808.docx) on page 24. + +image + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1a32c1bc4532`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5895/solution/patch.diff b/tasks/traccar__traccar-5895/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..254ddb265d2d3969d66306a59f951fcdc58dd7c3 --- /dev/null +++ b/tasks/traccar__traccar-5895/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 99db8c4c2..af313cb06 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -838,6 +838,17 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + } else { + position.set(Position.KEY_BATTERY_LEVEL, batteryLevel); + } ++ } else if (subtype == 0xE1 && length >= 12 && (length - 4) % 8 == 0) { ++ int mcc = buf.readUnsignedShort(); ++ int mnc = buf.readUnsignedShort(); ++ ++ while (buf.readerIndex() < endIndex) { ++ int lac = buf.readUnsignedMedium(); ++ long cid = buf.readUnsignedInt(); ++ int rssi = buf.readUnsignedByte(); ++ ++ network.addCellTower(CellTower.from(mcc, mnc, lac, cid, rssi)); ++ } + } else { + position.set(Position.KEY_DRIVER_UNIQUE_ID, String.valueOf(buf.readUnsignedInt())); + } +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 9e47aaea4..49301fd55 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -346,6 +346,9 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + verifyPositions(decoder, binary( + "7e0704011204545009154600a4000301004200000000004c000a0236d9f9008126ba00280001000026052318421301040000003d30010031010de4020159e50101e60100e7080000000400000000f50101fb0100006700000000004c00000236d9f9008126ba00280000000026052318451301040000003d300100310100e4020158e50101e60100e7080000000400000000ec155091e3194157ae8c86dd750382a69e86dd750382a4e10c010c000600bbe4001ada2900f50101fb0100006000000000004c00000236d9f9008126ba00280000000026052318481201040000003d300100310100e4020157e50101e60100e7080000000400000000ec0e5091e3194157b09e86dd750382afe10c010c000600bbe4001b1c2900f50101fb0100a57e")); + ++ verifyPosition(decoder, binary( ++ "7e02000072045460005635007300000000000000000236d51c00823f19000000000000260602220701010400000000300111310100e4020064e50100e60100e7080000000600000000e10c010c000600bbe4001ada1500ec23f0090dba115abb5091e3194157b9ce20bd25d93fb5ce20bd85d93fb57e9cd82cadd5b1f50101717e")); ++ + decoder.setModelOverride("MV710G"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5895/solution/solve.sh b/tasks/traccar__traccar-5895/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5895/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/traccar__traccar-5895/task.toml b/tasks/traccar__traccar-5895/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d285f29cdc9eed5513e558c650fb080f4147d007 --- /dev/null +++ b/tasks/traccar__traccar-5895/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5895" +description = "Decode Xchinchun 0xE1 cell tower data" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "1a32c1bc453277d331179b0b280fc9f4ec022617" +reference = "https://github.com/traccar/traccar/pull/5895" +source_access = "auto" +built_at = "2026-11-16T16:09:42.582632+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7fa83c2a50feaaab99d2d1ad046839429d05bac20a682e20dad9c941c19cf299" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-03T13:13:11Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.492470+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6d7ec75e86b5b5c86d73cb4f4db4fac34bfb556162c785cfddc45c5bb442b4c1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5895/tests/capture.py b/tasks/traccar__traccar-5895/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5895/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/traccar__traccar-5895/tests/instruction.md b/tasks/traccar__traccar-5895/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..254d3d6d710cace62b1fbdda9b719c306bfe77ed --- /dev/null +++ b/tasks/traccar__traccar-5895/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Decode Xchinchun 0xE1 cell tower data + +## Description + +This pull request adds support for decoding Xinchun-specific 0xE1 location extension data as cell tower information. + +When the 0xE1 payload matches the Xinchun base station format, the decoder now extracts MCC, MNC, LAC, Cell ID, and RSSI and adds them to the position network. + +The existing fallback behavior for other 0xE1 payload formats is preserved. + +Evidence can be found in the Xchinchun protocol documentation [Xchinchun JT808.docx](https://github.com/user-attachments/files/28529600/Xchinchun.JT808.docx) on page 24. + +image + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1a32c1bc4532`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5895/tests/oracle.patch b/tasks/traccar__traccar-5895/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..254ddb265d2d3969d66306a59f951fcdc58dd7c3 --- /dev/null +++ b/tasks/traccar__traccar-5895/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 99db8c4c2..af313cb06 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -838,6 +838,17 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + } else { + position.set(Position.KEY_BATTERY_LEVEL, batteryLevel); + } ++ } else if (subtype == 0xE1 && length >= 12 && (length - 4) % 8 == 0) { ++ int mcc = buf.readUnsignedShort(); ++ int mnc = buf.readUnsignedShort(); ++ ++ while (buf.readerIndex() < endIndex) { ++ int lac = buf.readUnsignedMedium(); ++ long cid = buf.readUnsignedInt(); ++ int rssi = buf.readUnsignedByte(); ++ ++ network.addCellTower(CellTower.from(mcc, mnc, lac, cid, rssi)); ++ } + } else { + position.set(Position.KEY_DRIVER_UNIQUE_ID, String.valueOf(buf.readUnsignedInt())); + } +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 9e47aaea4..49301fd55 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -346,6 +346,9 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + verifyPositions(decoder, binary( + "7e0704011204545009154600a4000301004200000000004c000a0236d9f9008126ba00280001000026052318421301040000003d30010031010de4020159e50101e60100e7080000000400000000f50101fb0100006700000000004c00000236d9f9008126ba00280000000026052318451301040000003d300100310100e4020158e50101e60100e7080000000400000000ec155091e3194157ae8c86dd750382a69e86dd750382a4e10c010c000600bbe4001ada2900f50101fb0100006000000000004c00000236d9f9008126ba00280000000026052318481201040000003d300100310100e4020157e50101e60100e7080000000400000000ec0e5091e3194157b09e86dd750382afe10c010c000600bbe4001b1c2900f50101fb0100a57e")); + ++ verifyPosition(decoder, binary( ++ "7e02000072045460005635007300000000000000000236d51c00823f19000000000000260602220701010400000000300111310100e4020064e50100e60100e7080000000600000000e10c010c000600bbe4001ada1500ec23f0090dba115abb5091e3194157b9ce20bd25d93fb5ce20bd85d93fb57e9cd82cadd5b1f50101717e")); ++ + decoder.setModelOverride("MV710G"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5895/tests/test.sh b/tasks/traccar__traccar-5895/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..80e7ab77f7484f6d657b21b46b7eb0fc2596d06a --- /dev/null +++ b/tasks/traccar__traccar-5895/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 1a32c1bc453277d331179b0b280fc9f4ec022617 > "$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/traccar__traccar-5895/tests/verifier.py b/tasks/traccar__traccar-5895/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5895/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/traccar__traccar-5900/environment/Dockerfile b/tasks/traccar__traccar-5900/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2c92fb1e56dde277f7340d503b2b98a35251ae1 --- /dev/null +++ b/tasks/traccar__traccar-5900/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1b7927b90eb638fa056d273dbcbc2ef0e56fd672 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1b7927b90eb638fa056d273dbcbc2ef0e56fd672 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1b7927b90eb638fa056d273dbcbc2ef0e56fd672 \ + && 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/traccar__traccar-5900/instruction.md b/tasks/traccar__traccar-5900/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..689479ef66c359aaad91083ba0a71fd120800146 --- /dev/null +++ b/tasks/traccar__traccar-5900/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** feat(notification): add custom base URL support for Telegram + +## Description + +Introduce a new configuration key 'notificator.telegram.base.url' to allow overriding the default Telegram Bot API endpoint. + +This is highly useful for environments or countries where the official Telegram API (api.telegram.org) is blocked or restricted, enabling the use of reverse proxies or self-hosted Telegram Bot API servers. + +- Added NOTIFICATOR_TELEGRAM_BASE_URL to Keys.java +- Updated NotificatorTelegram.java to fallback to default URL if not specified + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1b7927b90eb6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5900/solution/patch.diff b/tasks/traccar__traccar-5900/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3f022fbf523c5f829e19a4393ca9241cca46617f --- /dev/null +++ b/tasks/traccar__traccar-5900/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/src/main/java/org/traccar/config/Keys.java b/src/main/java/org/traccar/config/Keys.java +index 3adb27646..91e69e897 100644 +--- a/src/main/java/org/traccar/config/Keys.java ++++ b/src/main/java/org/traccar/config/Keys.java +@@ -1489,6 +1489,13 @@ public final class Keys { + "notificator.telegram.proxy.url", + List.of(KeyType.CONFIG)); + ++ /** ++ * Telegram notification base URL. ++ */ ++ public static final ConfigKey NOTIFICATOR_TELEGRAM_BASE_URL = new StringConfigKey( ++ "notificator.telegram.base.url", ++ List.of(KeyType.CONFIG)); ++ + /** + * WhatsApp Cloud API permanent access token. + */ +diff --git a/src/main/java/org/traccar/notificators/NotificatorTelegram.java b/src/main/java/org/traccar/notificators/NotificatorTelegram.java +index df9bf5e28..f732cc263 100644 +--- a/src/main/java/org/traccar/notificators/NotificatorTelegram.java ++++ b/src/main/java/org/traccar/notificators/NotificatorTelegram.java +@@ -70,10 +70,16 @@ public class NotificatorTelegram extends Notificator { + public NotificatorTelegram(Config config, NotificationFormatter notificationFormatter, + Client client, Provider clientBuilderProvider) { + super(notificationFormatter); ++ ++ String baseUrl = config.getString(Keys.NOTIFICATOR_TELEGRAM_BASE_URL); ++ if (baseUrl == null) { ++ baseUrl = "https://api.telegram.org/bot"; ++ } ++ + urlSendText = String.format( +- "https://api.telegram.org/bot%s/sendMessage", config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); ++ "%s%s/sendMessage", baseUrl, config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); + urlSendLocation = String.format( +- "https://api.telegram.org/bot%s/sendLocation", config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); ++ "%s%s/sendLocation", baseUrl, config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); + chatId = config.getString(Keys.NOTIFICATOR_TELEGRAM_CHAT_ID); + sendLocation = config.getBoolean(Keys.NOTIFICATOR_TELEGRAM_SEND_LOCATION); + diff --git a/tasks/traccar__traccar-5900/solution/solve.sh b/tasks/traccar__traccar-5900/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5900/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/traccar__traccar-5900/task.toml b/tasks/traccar__traccar-5900/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6415e67ead868d1adb5c1304e94517ef2796efb9 --- /dev/null +++ b/tasks/traccar__traccar-5900/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5900" +description = "feat(notification): add custom base URL support for Telegram" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "1b7927b90eb638fa056d273dbcbc2ef0e56fd672" +reference = "https://github.com/traccar/traccar/pull/5900" +source_access = "auto" +built_at = "2026-11-16T16:09:42.548801+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:df375a2a88ddf261d0bf5626ab9dc032e280e71a5744a6e447e2367e26dc21b0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-26T04:34:50Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/config/Keys.java", + "src/main/java/org/traccar/notificators/NotificatorTelegram.java", +] +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:03.493081+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6b928216c553cb3fea7f1c28a35eb1a041742c2ac888ff82a904e01a7e5d386d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5900/tests/capture.py b/tasks/traccar__traccar-5900/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5900/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/traccar__traccar-5900/tests/instruction.md b/tasks/traccar__traccar-5900/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..689479ef66c359aaad91083ba0a71fd120800146 --- /dev/null +++ b/tasks/traccar__traccar-5900/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** feat(notification): add custom base URL support for Telegram + +## Description + +Introduce a new configuration key 'notificator.telegram.base.url' to allow overriding the default Telegram Bot API endpoint. + +This is highly useful for environments or countries where the official Telegram API (api.telegram.org) is blocked or restricted, enabling the use of reverse proxies or self-hosted Telegram Bot API servers. + +- Added NOTIFICATOR_TELEGRAM_BASE_URL to Keys.java +- Updated NotificatorTelegram.java to fallback to default URL if not specified + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1b7927b90eb6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5900/tests/oracle.patch b/tasks/traccar__traccar-5900/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3f022fbf523c5f829e19a4393ca9241cca46617f --- /dev/null +++ b/tasks/traccar__traccar-5900/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/src/main/java/org/traccar/config/Keys.java b/src/main/java/org/traccar/config/Keys.java +index 3adb27646..91e69e897 100644 +--- a/src/main/java/org/traccar/config/Keys.java ++++ b/src/main/java/org/traccar/config/Keys.java +@@ -1489,6 +1489,13 @@ public final class Keys { + "notificator.telegram.proxy.url", + List.of(KeyType.CONFIG)); + ++ /** ++ * Telegram notification base URL. ++ */ ++ public static final ConfigKey NOTIFICATOR_TELEGRAM_BASE_URL = new StringConfigKey( ++ "notificator.telegram.base.url", ++ List.of(KeyType.CONFIG)); ++ + /** + * WhatsApp Cloud API permanent access token. + */ +diff --git a/src/main/java/org/traccar/notificators/NotificatorTelegram.java b/src/main/java/org/traccar/notificators/NotificatorTelegram.java +index df9bf5e28..f732cc263 100644 +--- a/src/main/java/org/traccar/notificators/NotificatorTelegram.java ++++ b/src/main/java/org/traccar/notificators/NotificatorTelegram.java +@@ -70,10 +70,16 @@ public class NotificatorTelegram extends Notificator { + public NotificatorTelegram(Config config, NotificationFormatter notificationFormatter, + Client client, Provider clientBuilderProvider) { + super(notificationFormatter); ++ ++ String baseUrl = config.getString(Keys.NOTIFICATOR_TELEGRAM_BASE_URL); ++ if (baseUrl == null) { ++ baseUrl = "https://api.telegram.org/bot"; ++ } ++ + urlSendText = String.format( +- "https://api.telegram.org/bot%s/sendMessage", config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); ++ "%s%s/sendMessage", baseUrl, config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); + urlSendLocation = String.format( +- "https://api.telegram.org/bot%s/sendLocation", config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); ++ "%s%s/sendLocation", baseUrl, config.getString(Keys.NOTIFICATOR_TELEGRAM_KEY)); + chatId = config.getString(Keys.NOTIFICATOR_TELEGRAM_CHAT_ID); + sendLocation = config.getBoolean(Keys.NOTIFICATOR_TELEGRAM_SEND_LOCATION); + diff --git a/tasks/traccar__traccar-5900/tests/test.sh b/tasks/traccar__traccar-5900/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..241ff35a09ace3f118a0397fd261631072e8ffad --- /dev/null +++ b/tasks/traccar__traccar-5900/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 1b7927b90eb638fa056d273dbcbc2ef0e56fd672 > "$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/traccar__traccar-5900/tests/verifier.py b/tasks/traccar__traccar-5900/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5900/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/traccar__traccar-5907/environment/Dockerfile b/tasks/traccar__traccar-5907/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b14e53f00776bf3e62bbb4f83c306f747fb8086c --- /dev/null +++ b/tasks/traccar__traccar-5907/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0417a9264981e9ca5fde52d80cf338a197c03bc9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0417a9264981e9ca5fde52d80cf338a197c03bc9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0417a9264981e9ca5fde52d80cf338a197c03bc9 \ + && 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/traccar__traccar-5907/instruction.md b/tasks/traccar__traccar-5907/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e53888a81e6fb30a6e1dd4f92ae45009dd8aa14e --- /dev/null +++ b/tasks/traccar__traccar-5907/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Decode power voltage for BSJ and JH119 trackers + +## Description + +Two JT808 variants report the vehicle supply voltage in fields that are currently dropped or misread: + +- BSJ-KG-12A: extended block `0xEB` sub-id `0x002D` carries a 4-byte value in mV. The existing 2-byte case (a backup battery) is kept; the 4-byte variant is decoded as `power`, discriminated by length. +- JH119: additional id `0xE1` with length 2 carries a 0.1 V value, decoded as `power`. + +Tests included for both fields. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0417a9264981`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5907/solution/patch.diff b/tasks/traccar__traccar-5907/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6d7de47553a30e7e7806648c023d3e3e5f7bf02d --- /dev/null +++ b/tasks/traccar__traccar-5907/solution/patch.diff @@ -0,0 +1,45 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 5374207eb..5b00c78de 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -870,6 +870,8 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + network.addCellTower(CellTower.from( + mcc, mnc, buf.readUnsignedMedium(), buf.readUnsignedInt(), buf.readUnsignedByte())); + } ++ } else if (subtype == 0xE1 && length == 2) { ++ position.set(Position.KEY_POWER, buf.readUnsignedShort() / 10.0); + } else { + position.set(Position.KEY_DRIVER_UNIQUE_ID, String.valueOf(buf.readUnsignedInt())); + } +@@ -1068,7 +1070,11 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + buf.readCharSequence(6, StandardCharsets.US_ASCII).toString())); + break; + case 0x002D: +- position.set(Position.KEY_BATTERY, buf.readUnsignedShort() / 1000.0); ++ if (extendedLength == 6) { ++ position.set(Position.KEY_POWER, buf.readUnsignedInt() / 1000.0); ++ } else { ++ position.set(Position.KEY_BATTERY, buf.readUnsignedShort() / 1000.0); ++ } + break; + case 0x0089: + alarm = buf.readUnsignedInt(); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 6fce3f0de..d1f88856d 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -11,6 +11,14 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Jt808ProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "7e0200006300000000000008f50000000000000000000000000000000000c7000000cc260615100115010400000001300114310108eb39000c00b20000000000000000000000060089fffffffe000600c5ffffffef0006002d00002db4001100d5303030303030303030303030303030c87e"), ++ Position.KEY_POWER, 11.7); ++ ++ verifyAttribute(decoder, binary( ++ "7e02000032000000000000022500000000000c0002000000000000000000710000014626061510572501040000006430011f31010ce10200722b04ab560000487e"), ++ Position.KEY_POWER, 11.4); ++ + verifyAttribute(decoder, binary( + "7e02000048051160004464000d00000000000c00020159885e06cbf34400000000000020080718072201040000000130011c310109e4020063e50100e60100e7080000000000000000ee0a01cc01262c009a6743001e7e"), + Position.KEY_BATTERY_LEVEL, 99); diff --git a/tasks/traccar__traccar-5907/solution/solve.sh b/tasks/traccar__traccar-5907/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5907/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/traccar__traccar-5907/task.toml b/tasks/traccar__traccar-5907/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ba9e2e8a1c6d715a7223ae315df94cb7b8702e91 --- /dev/null +++ b/tasks/traccar__traccar-5907/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5907" +description = "Decode power voltage for BSJ and JH119 trackers" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "0417a9264981e9ca5fde52d80cf338a197c03bc9" +reference = "https://github.com/traccar/traccar/pull/5907" +source_access = "auto" +built_at = "2026-11-16T16:09:42.581131+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3ce0a138106c00b6e7fdc86a49d6659a80cc0868aaa4b8d4f7e8df87f653efc2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-15T03:57:02Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 16 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.493719+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:feca7fcae8113ad84905b572943d324ae92d8c1501d7e63a02ce228764d0dc5f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5907/tests/capture.py b/tasks/traccar__traccar-5907/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5907/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/traccar__traccar-5907/tests/instruction.md b/tasks/traccar__traccar-5907/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e53888a81e6fb30a6e1dd4f92ae45009dd8aa14e --- /dev/null +++ b/tasks/traccar__traccar-5907/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Decode power voltage for BSJ and JH119 trackers + +## Description + +Two JT808 variants report the vehicle supply voltage in fields that are currently dropped or misread: + +- BSJ-KG-12A: extended block `0xEB` sub-id `0x002D` carries a 4-byte value in mV. The existing 2-byte case (a backup battery) is kept; the 4-byte variant is decoded as `power`, discriminated by length. +- JH119: additional id `0xE1` with length 2 carries a 0.1 V value, decoded as `power`. + +Tests included for both fields. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0417a9264981`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5907/tests/oracle.patch b/tasks/traccar__traccar-5907/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6d7de47553a30e7e7806648c023d3e3e5f7bf02d --- /dev/null +++ b/tasks/traccar__traccar-5907/tests/oracle.patch @@ -0,0 +1,45 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 5374207eb..5b00c78de 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -870,6 +870,8 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + network.addCellTower(CellTower.from( + mcc, mnc, buf.readUnsignedMedium(), buf.readUnsignedInt(), buf.readUnsignedByte())); + } ++ } else if (subtype == 0xE1 && length == 2) { ++ position.set(Position.KEY_POWER, buf.readUnsignedShort() / 10.0); + } else { + position.set(Position.KEY_DRIVER_UNIQUE_ID, String.valueOf(buf.readUnsignedInt())); + } +@@ -1068,7 +1070,11 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + buf.readCharSequence(6, StandardCharsets.US_ASCII).toString())); + break; + case 0x002D: +- position.set(Position.KEY_BATTERY, buf.readUnsignedShort() / 1000.0); ++ if (extendedLength == 6) { ++ position.set(Position.KEY_POWER, buf.readUnsignedInt() / 1000.0); ++ } else { ++ position.set(Position.KEY_BATTERY, buf.readUnsignedShort() / 1000.0); ++ } + break; + case 0x0089: + alarm = buf.readUnsignedInt(); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 6fce3f0de..d1f88856d 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -11,6 +11,14 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Jt808ProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "7e0200006300000000000008f50000000000000000000000000000000000c7000000cc260615100115010400000001300114310108eb39000c00b20000000000000000000000060089fffffffe000600c5ffffffef0006002d00002db4001100d5303030303030303030303030303030c87e"), ++ Position.KEY_POWER, 11.7); ++ ++ verifyAttribute(decoder, binary( ++ "7e02000032000000000000022500000000000c0002000000000000000000710000014626061510572501040000006430011f31010ce10200722b04ab560000487e"), ++ Position.KEY_POWER, 11.4); ++ + verifyAttribute(decoder, binary( + "7e02000048051160004464000d00000000000c00020159885e06cbf34400000000000020080718072201040000000130011c310109e4020063e50100e60100e7080000000000000000ee0a01cc01262c009a6743001e7e"), + Position.KEY_BATTERY_LEVEL, 99); diff --git a/tasks/traccar__traccar-5907/tests/test.sh b/tasks/traccar__traccar-5907/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41cc56cac56d8ea45cd0fcec83d756aafa607706 --- /dev/null +++ b/tasks/traccar__traccar-5907/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 0417a9264981e9ca5fde52d80cf338a197c03bc9 > "$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/traccar__traccar-5907/tests/verifier.py b/tasks/traccar__traccar-5907/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5907/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/traccar__traccar-5910/environment/Dockerfile b/tasks/traccar__traccar-5910/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..33a330ed13e43ff0a71f214efbfd1bc4e2fe6259 --- /dev/null +++ b/tasks/traccar__traccar-5910/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 \ + && 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/traccar__traccar-5910/instruction.md b/tasks/traccar__traccar-5910/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7718d4aaa6ace05b04389eac472d5a4e6034881b --- /dev/null +++ b/tasks/traccar__traccar-5910/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Decode JT808 0x0210 hibernation battery reports + +## Description + +Add handling for JT808 0x0210 hibernation battery level updates. + +Some devices use message 0x0210 with a 7-byte body to report battery level during sleep: +- 1 byte battery percentage +- 6 byte BCD timestamp + +The existing decoder treated all 0x0210 messages as batch location uploads. This caused 7-byte sleep battery reports to be parsed incorrectly. + +This change adds a length-based special case for 0x0210 messages with a 7-byte body, decodes the battery level and timestamp into a Position object, and keeps existing batch upload handling unchanged for other 0x0210 payloads. + +A regression test is included using a real device frame: 7e0210000704546000231900884f2606180229579c7e + +**Evidence** can be found in the [Xchinchun JT808.docx](https://github.com/user-attachments/files/29068497/Xchinchun.JT808.docx) on page 41, section **3.20 Hibernation Battery Level Update (0x 0210)** + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8b605bf7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5910/solution/patch.diff b/tasks/traccar__traccar-5910/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f5527e9d514ea378e280f6879f0839da5376a266 --- /dev/null +++ b/tasks/traccar__traccar-5910/solution/patch.diff @@ -0,0 +1,56 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 5b00c78de..83ea838ff 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -342,6 +342,8 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + int type = buf.readUnsignedShort(); + int attribute = buf.readUnsignedShort(); + ++ int bodyLength = BitUtil.to(attribute, 10); ++ + protocolVersion = BitUtil.check(attribute, 14) ? (int) buf.readUnsignedByte() : null; + ByteBuf id = buf.readSlice(protocolVersion != null ? 10 : (delimiter == 0xe7 ? 7 : 6)); + +@@ -395,8 +397,6 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + + getLastLocation(position, null); + +- int bodyLength = BitUtil.to(attribute, 10); +- + buf.readUnsignedShort(); // response serial number + + String result = buf.readCharSequence(bodyLength - 2, StandardCharsets.UTF_16BE).toString().trim(); +@@ -442,6 +442,18 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + + return decodeLocation2(deviceSession, buf, type); + ++ } else if (type == MSG_LOCATION_BATCH_2 && bodyLength == 7) { ++ ++ sendGeneralResponse(channel, remoteAddress, id, type, index); ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); ++ getLastLocation(position, readDate(buf, deviceSession.get(DeviceSession.KEY_TIMEZONE))); ++ ++ return position; ++ + } else if (type == MSG_LOCATION_BATCH || type == MSG_LOCATION_BATCH_2) { + + sendGeneralResponse(channel, remoteAddress, id, type, index); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index d1f88856d..baa31cee5 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -357,6 +357,10 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, binary( + "7e02000072045460005635007300000000000000000236d51c00823f19000000000000260602220701010400000000300111310100e4020064e50100e60100e7080000000600000000e10c010c000600bbe4001ada1500ec23f0090dba115abb5091e3194157b9ce20bd25d93fb5ce20bd85d93fb57e9cd82cadd5b1f50101717e")); + ++ verifyAttribute(decoder, binary( ++ "7e0210000704546000231900884f2606180229579c7e"), ++ Position.KEY_BATTERY_LEVEL, 79); ++ + decoder.setModelOverride("MV710G"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5910/solution/solve.sh b/tasks/traccar__traccar-5910/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5910/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/traccar__traccar-5910/task.toml b/tasks/traccar__traccar-5910/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bf716ab3461ffabe933992d30f158c813da632b3 --- /dev/null +++ b/tasks/traccar__traccar-5910/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5910" +description = "Decode JT808 0x0210 hibernation battery reports" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "4e8b605bf7d7c4584491b1095b3a87186ee0a9c7" +reference = "https://github.com/traccar/traccar/pull/5910" +source_access = "auto" +built_at = "2026-11-16T16:09:42.578379+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a47086d4f7259c97ffa36d9c3c46d56fd4fc4faca68f763df7eeae3327087b80" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-18T14:40:11Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +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:03.494306+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e1103824365c018166cf80d7697e463ed461e1906eb57c762b5d02ae1b0acc02" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5910/tests/capture.py b/tasks/traccar__traccar-5910/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5910/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/traccar__traccar-5910/tests/instruction.md b/tasks/traccar__traccar-5910/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7718d4aaa6ace05b04389eac472d5a4e6034881b --- /dev/null +++ b/tasks/traccar__traccar-5910/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Decode JT808 0x0210 hibernation battery reports + +## Description + +Add handling for JT808 0x0210 hibernation battery level updates. + +Some devices use message 0x0210 with a 7-byte body to report battery level during sleep: +- 1 byte battery percentage +- 6 byte BCD timestamp + +The existing decoder treated all 0x0210 messages as batch location uploads. This caused 7-byte sleep battery reports to be parsed incorrectly. + +This change adds a length-based special case for 0x0210 messages with a 7-byte body, decodes the battery level and timestamp into a Position object, and keeps existing batch upload handling unchanged for other 0x0210 payloads. + +A regression test is included using a real device frame: 7e0210000704546000231900884f2606180229579c7e + +**Evidence** can be found in the [Xchinchun JT808.docx](https://github.com/user-attachments/files/29068497/Xchinchun.JT808.docx) on page 41, section **3.20 Hibernation Battery Level Update (0x 0210)** + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8b605bf7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5910/tests/oracle.patch b/tasks/traccar__traccar-5910/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f5527e9d514ea378e280f6879f0839da5376a266 --- /dev/null +++ b/tasks/traccar__traccar-5910/tests/oracle.patch @@ -0,0 +1,56 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 5b00c78de..83ea838ff 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -342,6 +342,8 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + int type = buf.readUnsignedShort(); + int attribute = buf.readUnsignedShort(); + ++ int bodyLength = BitUtil.to(attribute, 10); ++ + protocolVersion = BitUtil.check(attribute, 14) ? (int) buf.readUnsignedByte() : null; + ByteBuf id = buf.readSlice(protocolVersion != null ? 10 : (delimiter == 0xe7 ? 7 : 6)); + +@@ -395,8 +397,6 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + + getLastLocation(position, null); + +- int bodyLength = BitUtil.to(attribute, 10); +- + buf.readUnsignedShort(); // response serial number + + String result = buf.readCharSequence(bodyLength - 2, StandardCharsets.UTF_16BE).toString().trim(); +@@ -442,6 +442,18 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + + return decodeLocation2(deviceSession, buf, type); + ++ } else if (type == MSG_LOCATION_BATCH_2 && bodyLength == 7) { ++ ++ sendGeneralResponse(channel, remoteAddress, id, type, index); ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte()); ++ getLastLocation(position, readDate(buf, deviceSession.get(DeviceSession.KEY_TIMEZONE))); ++ ++ return position; ++ + } else if (type == MSG_LOCATION_BATCH || type == MSG_LOCATION_BATCH_2) { + + sendGeneralResponse(channel, remoteAddress, id, type, index); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index d1f88856d..baa31cee5 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -357,6 +357,10 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, binary( + "7e02000072045460005635007300000000000000000236d51c00823f19000000000000260602220701010400000000300111310100e4020064e50100e60100e7080000000600000000e10c010c000600bbe4001ada1500ec23f0090dba115abb5091e3194157b9ce20bd25d93fb5ce20bd85d93fb57e9cd82cadd5b1f50101717e")); + ++ verifyAttribute(decoder, binary( ++ "7e0210000704546000231900884f2606180229579c7e"), ++ Position.KEY_BATTERY_LEVEL, 79); ++ + decoder.setModelOverride("MV710G"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5910/tests/test.sh b/tasks/traccar__traccar-5910/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9cf5aebb54701bc4bc61ae36a2ee9d3ce3cdbfbd --- /dev/null +++ b/tasks/traccar__traccar-5910/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 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 > "$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/traccar__traccar-5910/tests/verifier.py b/tasks/traccar__traccar-5910/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5910/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/traccar__traccar-5912/environment/Dockerfile b/tasks/traccar__traccar-5912/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6f98c3a2b6535cbbcd563cbcc2c107abd0ea1119 --- /dev/null +++ b/tasks/traccar__traccar-5912/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7c00b1c837304756464b136fe90231664a22c2dd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7c00b1c837304756464b136fe90231664a22c2dd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7c00b1c837304756464b136fe90231664a22c2dd \ + && 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/traccar__traccar-5912/instruction.md b/tasks/traccar__traccar-5912/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1fa870404d978bf4fbd6ad2a1b11cf471f2206b0 --- /dev/null +++ b/tasks/traccar__traccar-5912/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** Add JT808 0xF6 IMEI decoding + +## Description + +### Summary + +Adds support for decoding the Xinchun-specific JT808 `0x0200` additional information field `0xF6` as an IMEI upload field. + +### Details + +According to the Xinchun JT808 protocol documentation, additional field `0xF6` with length `8` contains the device IMEI encoded as BCD. The decoder previously handled `0xF6` only as air pressure or as a generic event/sensor field, so Xinchun IMEI uploads were not exposed. + +This change adds explicit handling for `0xF6` when the field length is `8`: + +* reads the 8-byte BCD value +* removes the leading BCD padding zero +* stores the decoded value as `imei` +* keeps the existing `0xF6` handling for other lengths unchanged + +### Test + +Adds a decoder test using a minimal `0x0200` position report with: + +`f6 08 08 67 56 70 41 10 07 69` + +Expected decoded value: + +`imei = 867567041100769` + +### Evidence + +Evidence can be found in the [Xchinchun JT808.docx](https://github.com/user-attachments/files/29069443/Xchinchun.JT808.docx) page 27, 0xF6 IMEI Upload. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7c00b1c83730`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5912/solution/patch.diff b/tasks/traccar__traccar-5912/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..06d24a83b55667b52a6d8642781a9e28c5d72502 --- /dev/null +++ b/tasks/traccar__traccar-5912/solution/patch.diff @@ -0,0 +1,32 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 83ea838ff..0f5e91d59 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -1215,6 +1215,8 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + case 0xF6: + if (length == 2) { + position.set("airPressure", buf.readUnsignedShort()); ++ } else if (length == 8) { ++ position.set("imei", ByteBufUtil.hexDump(buf.readSlice(length)).substring(1)); + } else { + event = buf.readUnsignedByte(); + position.set(Position.KEY_EVENT, event); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index baa31cee5..d35fb697a 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -357,9 +357,13 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, binary( + "7e02000072045460005635007300000000000000000236d51c00823f19000000000000260602220701010400000000300111310100e4020064e50100e60100e7080000000600000000e10c010c000600bbe4001ada1500ec23f0090dba115abb5091e3194157b9ce20bd25d93fb5ce20bd85d93fb57e9cd82cadd5b1f50101717e")); + ++ verifyAttribute(decoder, binary( ++ "7e02000026000000000000000100000000000000020000000000000000000000000000260618001512f6080867567041100769907e"), ++ "imei", "867567041100769"); ++ + verifyAttribute(decoder, binary( + "7e0210000704546000231900884f2606180229579c7e"), +- Position.KEY_BATTERY_LEVEL, 79); ++ Position.KEY_BATTERY_LEVEL, 79); + + decoder.setModelOverride("MV710G"); + diff --git a/tasks/traccar__traccar-5912/solution/solve.sh b/tasks/traccar__traccar-5912/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5912/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/traccar__traccar-5912/task.toml b/tasks/traccar__traccar-5912/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..83483ad947e56bcee7c3dd841478cf9de00c407e --- /dev/null +++ b/tasks/traccar__traccar-5912/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5912" +description = "Add JT808 0xF6 IMEI decoding" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "7c00b1c837304756464b136fe90231664a22c2dd" +reference = "https://github.com/traccar/traccar/pull/5912" +source_access = "auto" +built_at = "2026-11-16T16:09:42.570889+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6600b7fa0fe8ba62a56a94fb6c08c8227aa002a49d6e2aadb391464ef22b1a93" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-23T12:49:45Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.494873+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:93b72d9c18972ce56275dd6347468994d070c382a71e666e94b09702eaab5325" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5912/tests/capture.py b/tasks/traccar__traccar-5912/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5912/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/traccar__traccar-5912/tests/instruction.md b/tasks/traccar__traccar-5912/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1fa870404d978bf4fbd6ad2a1b11cf471f2206b0 --- /dev/null +++ b/tasks/traccar__traccar-5912/tests/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** Add JT808 0xF6 IMEI decoding + +## Description + +### Summary + +Adds support for decoding the Xinchun-specific JT808 `0x0200` additional information field `0xF6` as an IMEI upload field. + +### Details + +According to the Xinchun JT808 protocol documentation, additional field `0xF6` with length `8` contains the device IMEI encoded as BCD. The decoder previously handled `0xF6` only as air pressure or as a generic event/sensor field, so Xinchun IMEI uploads were not exposed. + +This change adds explicit handling for `0xF6` when the field length is `8`: + +* reads the 8-byte BCD value +* removes the leading BCD padding zero +* stores the decoded value as `imei` +* keeps the existing `0xF6` handling for other lengths unchanged + +### Test + +Adds a decoder test using a minimal `0x0200` position report with: + +`f6 08 08 67 56 70 41 10 07 69` + +Expected decoded value: + +`imei = 867567041100769` + +### Evidence + +Evidence can be found in the [Xchinchun JT808.docx](https://github.com/user-attachments/files/29069443/Xchinchun.JT808.docx) page 27, 0xF6 IMEI Upload. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7c00b1c83730`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5912/tests/oracle.patch b/tasks/traccar__traccar-5912/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..06d24a83b55667b52a6d8642781a9e28c5d72502 --- /dev/null +++ b/tasks/traccar__traccar-5912/tests/oracle.patch @@ -0,0 +1,32 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 83ea838ff..0f5e91d59 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -1215,6 +1215,8 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + case 0xF6: + if (length == 2) { + position.set("airPressure", buf.readUnsignedShort()); ++ } else if (length == 8) { ++ position.set("imei", ByteBufUtil.hexDump(buf.readSlice(length)).substring(1)); + } else { + event = buf.readUnsignedByte(); + position.set(Position.KEY_EVENT, event); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index baa31cee5..d35fb697a 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -357,9 +357,13 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, binary( + "7e02000072045460005635007300000000000000000236d51c00823f19000000000000260602220701010400000000300111310100e4020064e50100e60100e7080000000600000000e10c010c000600bbe4001ada1500ec23f0090dba115abb5091e3194157b9ce20bd25d93fb5ce20bd85d93fb57e9cd82cadd5b1f50101717e")); + ++ verifyAttribute(decoder, binary( ++ "7e02000026000000000000000100000000000000020000000000000000000000000000260618001512f6080867567041100769907e"), ++ "imei", "867567041100769"); ++ + verifyAttribute(decoder, binary( + "7e0210000704546000231900884f2606180229579c7e"), +- Position.KEY_BATTERY_LEVEL, 79); ++ Position.KEY_BATTERY_LEVEL, 79); + + decoder.setModelOverride("MV710G"); + diff --git a/tasks/traccar__traccar-5912/tests/test.sh b/tasks/traccar__traccar-5912/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..97bbcf6e8baf07cf5e41f2fb2e712fbc0c6390d5 --- /dev/null +++ b/tasks/traccar__traccar-5912/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 7c00b1c837304756464b136fe90231664a22c2dd > "$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/traccar__traccar-5912/tests/verifier.py b/tasks/traccar__traccar-5912/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5912/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/traccar__traccar-5915/environment/Dockerfile b/tasks/traccar__traccar-5915/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..33a330ed13e43ff0a71f214efbfd1bc4e2fe6259 --- /dev/null +++ b/tasks/traccar__traccar-5915/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 \ + && 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/traccar__traccar-5915/instruction.md b/tasks/traccar__traccar-5915/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a0a2784a2b0303aea3c57cabe533188270328d90 --- /dev/null +++ b/tasks/traccar__traccar-5915/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** #5909: Support dynamic extra keys in OsmAnd json requests + +## Description + +this + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8b605bf7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5915/solution/patch.diff b/tasks/traccar__traccar-5915/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..84831469c0dbcc3a4e597a76a627265af7cf217f --- /dev/null +++ b/tasks/traccar__traccar-5915/solution/patch.diff @@ -0,0 +1,81 @@ +diff --git a/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java b/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java +index 7517c5040..ee9b770bc 100644 +--- a/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java +@@ -23,7 +23,10 @@ import io.netty.handler.codec.http.HttpHeaderValues; + import io.netty.handler.codec.http.HttpResponseStatus; + import io.netty.handler.codec.http.QueryStringDecoder; + import jakarta.json.Json; ++import jakarta.json.JsonNumber; + import jakarta.json.JsonObject; ++import jakarta.json.JsonString; ++import jakarta.json.JsonValue; + import org.traccar.BaseHttpProtocolDecoder; + import org.traccar.config.Keys; + import org.traccar.helper.UnitsConverter; +@@ -291,13 +294,29 @@ public class OsmAndProtocolDecoder extends BaseHttpProtocolDecoder { + position.set(Position.KEY_CHARGE, true); + } + } +- + if (location.containsKey("alarm")) { + position.set(Position.KEY_ALARM, location.getString("alarm")); +- } else if (location.containsKey("extras")) { ++ } ++ if (location.containsKey("extras")) { + JsonObject extras = location.getJsonObject("extras"); +- if (extras.containsKey("alarm")) { +- position.set(Position.KEY_ALARM, extras.getString("alarm")); ++ for (Map.Entry extraEntry : extras.entrySet()) { ++ if (extraEntry.getKey().equals("alarm") && location.containsKey("alarm")) { ++ continue; ++ } ++ switch (extraEntry.getValue().getValueType()) { ++ case NUMBER -> { ++ JsonNumber jsonNumber = (JsonNumber) extraEntry.getValue(); ++ if (jsonNumber.isIntegral()) { ++ position.set(extraEntry.getKey(), jsonNumber.longValue()); ++ } else { ++ position.set(extraEntry.getKey(), jsonNumber.doubleValue()); ++ } ++ } ++ case TRUE -> position.set(extraEntry.getKey(), true); ++ case FALSE -> position.set(extraEntry.getKey(), false); ++ case STRING -> position.set(extraEntry.getKey(), ((JsonString) extraEntry.getValue()).getString()); ++ default -> {} ++ } + } + } + +diff --git a/src/test/java/org/traccar/protocol/OsmAndProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/OsmAndProtocolDecoderTest.java +index b3d35eb19..1adcfe0b7 100644 +--- a/src/test/java/org/traccar/protocol/OsmAndProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/OsmAndProtocolDecoderTest.java +@@ -15,6 +15,10 @@ public class OsmAndProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( + "{\"location\":{\"timestamp\":\"2025-06-15T13:45:12.862Z\",\"coords\":{\"latitude\":37.4219983,\"longitude\":-122.084,\"accuracy\":5,\"speed\":0,\"heading\":-1,\"altitude\":5},\"is_moving\":false,\"odometer\":0,\"event\":\"motionchange\",\"battery\":{\"level\":1,\"is_charging\":false},\"activity\":{\"type\":\"still\"},\"extras\":{},\"_\":\"&id=48241179&lat=37.4219983&lon=-122.084×tamp=2025-06-15T13:45:12.862Z&\"},\"device_id\":\"48241179\"}"))); + ++ verifyAttribute(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( ++ "{\"location\":{\"timestamp\":\"2025-06-15T13:45:12.862Z\",\"coords\":{\"latitude\":37.4219983,\"longitude\":-122.084,\"accuracy\":5,\"speed\":0,\"heading\":-1,\"altitude\":5},\"is_moving\":false,\"odometer\":0,\"event\":\"motionchange\",\"battery\":{\"level\":1,\"is_charging\":false},\"activity\":{\"type\":\"still\"},\"extras\":{\"device_string_test\":\"long_device_id\",\"device_bool_test\":true,\"device_bool_false_test\":false,\"device_integer_test\":1,\"device_integer_twelve_test\":12,\"device_double_test\":1.345,\"device_very_long_double_test\":1763636.3442},\"_\":\"&id=48241179&lat=37.4219983&lon=-122.084×tamp=2025-06-15T13:45:12.862Z&\"},\"device_id\":\"48241179\"}")), ++ "device_integer_twelve_test", 12L); ++ + verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( + "{\"location\":{\"extras\":{},\"mock\":true,\"coords\":{\"speed_accuracy\":-1,\"speed\":-1,\"longitude\":-122.406417,\"ellipsoidal_altitude\":0,\"floor\":null,\"heading_accuracy\":-1,\"latitude\":37.785834000000001,\"accuracy\":5,\"altitude_accuracy\":-1,\"altitude\":0,\"heading\":-1},\"is_moving\":false,\"age\":188,\"odometer\":0,\"uuid\":\"2FB04C65-99CF-42AB-8DD3-EBCB4B108BF8\",\"event\":\"motionchange\",\"battery\":{\"level\":-1,\"is_charging\":false},\"activity\":{\"type\":\"unknown\",\"confidence\":100},\"timestamp\":\"2025-05-09T04:11:30.579Z\"},\"device_id\":\"658765\"}"))); + +@@ -42,13 +46,13 @@ public class OsmAndProtocolDecoderTest extends ProtocolTest { + + verifyPosition(decoder, request( + "/?lat=49.60688&lon=6.15788×tamp=2014-06-04+09%3A10%3A11&altitude=384.7&speed=0.0&id=353861053849681")); +- ++ + verifyPosition(decoder, request( + "/?id=123456×tamp=1377177267&lat=60.0&lon=30.0&speed=0.0&bearing=0.0&altitude=0&hdop=0.0")); +- ++ + verifyPosition(decoder, request( + "/?id=123456×tamp=1377177267&lat=60.0&lon=30.0")); +- ++ + verifyPosition(decoder, request( + "/?lat=60.0&lon=30.0&speed=0.0&heading=0.0&vacc=0&hacc=0&altitude=0&deviceid=123456")); + diff --git a/tasks/traccar__traccar-5915/solution/solve.sh b/tasks/traccar__traccar-5915/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5915/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/traccar__traccar-5915/task.toml b/tasks/traccar__traccar-5915/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a24d29c4190539cd3a307ccdf4f073390fc80218 --- /dev/null +++ b/tasks/traccar__traccar-5915/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5915" +description = "#5909: Support dynamic extra keys in OsmAnd json requests" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "4e8b605bf7d7c4584491b1095b3a87186ee0a9c7" +reference = "https://github.com/traccar/traccar/pull/5915" +source_access = "auto" +built_at = "2026-11-16T16:09:42.573685+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5823c84647ca7d980ef4c9f8fa1dde9a1a1a075326fe73829ff2a73ce0e72cde" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-21T00:32:21Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java", + "src/test/java/org/traccar/protocol/OsmAndProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 37 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.495465+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e1103824365c018166cf80d7697e463ed461e1906eb57c762b5d02ae1b0acc02" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5915/tests/capture.py b/tasks/traccar__traccar-5915/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5915/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/traccar__traccar-5915/tests/instruction.md b/tasks/traccar__traccar-5915/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a0a2784a2b0303aea3c57cabe533188270328d90 --- /dev/null +++ b/tasks/traccar__traccar-5915/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** #5909: Support dynamic extra keys in OsmAnd json requests + +## Description + +this + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8b605bf7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5915/tests/oracle.patch b/tasks/traccar__traccar-5915/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..84831469c0dbcc3a4e597a76a627265af7cf217f --- /dev/null +++ b/tasks/traccar__traccar-5915/tests/oracle.patch @@ -0,0 +1,81 @@ +diff --git a/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java b/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java +index 7517c5040..ee9b770bc 100644 +--- a/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java +@@ -23,7 +23,10 @@ import io.netty.handler.codec.http.HttpHeaderValues; + import io.netty.handler.codec.http.HttpResponseStatus; + import io.netty.handler.codec.http.QueryStringDecoder; + import jakarta.json.Json; ++import jakarta.json.JsonNumber; + import jakarta.json.JsonObject; ++import jakarta.json.JsonString; ++import jakarta.json.JsonValue; + import org.traccar.BaseHttpProtocolDecoder; + import org.traccar.config.Keys; + import org.traccar.helper.UnitsConverter; +@@ -291,13 +294,29 @@ public class OsmAndProtocolDecoder extends BaseHttpProtocolDecoder { + position.set(Position.KEY_CHARGE, true); + } + } +- + if (location.containsKey("alarm")) { + position.set(Position.KEY_ALARM, location.getString("alarm")); +- } else if (location.containsKey("extras")) { ++ } ++ if (location.containsKey("extras")) { + JsonObject extras = location.getJsonObject("extras"); +- if (extras.containsKey("alarm")) { +- position.set(Position.KEY_ALARM, extras.getString("alarm")); ++ for (Map.Entry extraEntry : extras.entrySet()) { ++ if (extraEntry.getKey().equals("alarm") && location.containsKey("alarm")) { ++ continue; ++ } ++ switch (extraEntry.getValue().getValueType()) { ++ case NUMBER -> { ++ JsonNumber jsonNumber = (JsonNumber) extraEntry.getValue(); ++ if (jsonNumber.isIntegral()) { ++ position.set(extraEntry.getKey(), jsonNumber.longValue()); ++ } else { ++ position.set(extraEntry.getKey(), jsonNumber.doubleValue()); ++ } ++ } ++ case TRUE -> position.set(extraEntry.getKey(), true); ++ case FALSE -> position.set(extraEntry.getKey(), false); ++ case STRING -> position.set(extraEntry.getKey(), ((JsonString) extraEntry.getValue()).getString()); ++ default -> {} ++ } + } + } + +diff --git a/src/test/java/org/traccar/protocol/OsmAndProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/OsmAndProtocolDecoderTest.java +index b3d35eb19..1adcfe0b7 100644 +--- a/src/test/java/org/traccar/protocol/OsmAndProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/OsmAndProtocolDecoderTest.java +@@ -15,6 +15,10 @@ public class OsmAndProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( + "{\"location\":{\"timestamp\":\"2025-06-15T13:45:12.862Z\",\"coords\":{\"latitude\":37.4219983,\"longitude\":-122.084,\"accuracy\":5,\"speed\":0,\"heading\":-1,\"altitude\":5},\"is_moving\":false,\"odometer\":0,\"event\":\"motionchange\",\"battery\":{\"level\":1,\"is_charging\":false},\"activity\":{\"type\":\"still\"},\"extras\":{},\"_\":\"&id=48241179&lat=37.4219983&lon=-122.084×tamp=2025-06-15T13:45:12.862Z&\"},\"device_id\":\"48241179\"}"))); + ++ verifyAttribute(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( ++ "{\"location\":{\"timestamp\":\"2025-06-15T13:45:12.862Z\",\"coords\":{\"latitude\":37.4219983,\"longitude\":-122.084,\"accuracy\":5,\"speed\":0,\"heading\":-1,\"altitude\":5},\"is_moving\":false,\"odometer\":0,\"event\":\"motionchange\",\"battery\":{\"level\":1,\"is_charging\":false},\"activity\":{\"type\":\"still\"},\"extras\":{\"device_string_test\":\"long_device_id\",\"device_bool_test\":true,\"device_bool_false_test\":false,\"device_integer_test\":1,\"device_integer_twelve_test\":12,\"device_double_test\":1.345,\"device_very_long_double_test\":1763636.3442},\"_\":\"&id=48241179&lat=37.4219983&lon=-122.084×tamp=2025-06-15T13:45:12.862Z&\"},\"device_id\":\"48241179\"}")), ++ "device_integer_twelve_test", 12L); ++ + verifyPosition(decoder, request(HttpMethod.POST, "/", new ReadOnlyHttpHeaders(true, "Content-Type", "application/json"), buffer( + "{\"location\":{\"extras\":{},\"mock\":true,\"coords\":{\"speed_accuracy\":-1,\"speed\":-1,\"longitude\":-122.406417,\"ellipsoidal_altitude\":0,\"floor\":null,\"heading_accuracy\":-1,\"latitude\":37.785834000000001,\"accuracy\":5,\"altitude_accuracy\":-1,\"altitude\":0,\"heading\":-1},\"is_moving\":false,\"age\":188,\"odometer\":0,\"uuid\":\"2FB04C65-99CF-42AB-8DD3-EBCB4B108BF8\",\"event\":\"motionchange\",\"battery\":{\"level\":-1,\"is_charging\":false},\"activity\":{\"type\":\"unknown\",\"confidence\":100},\"timestamp\":\"2025-05-09T04:11:30.579Z\"},\"device_id\":\"658765\"}"))); + +@@ -42,13 +46,13 @@ public class OsmAndProtocolDecoderTest extends ProtocolTest { + + verifyPosition(decoder, request( + "/?lat=49.60688&lon=6.15788×tamp=2014-06-04+09%3A10%3A11&altitude=384.7&speed=0.0&id=353861053849681")); +- ++ + verifyPosition(decoder, request( + "/?id=123456×tamp=1377177267&lat=60.0&lon=30.0&speed=0.0&bearing=0.0&altitude=0&hdop=0.0")); +- ++ + verifyPosition(decoder, request( + "/?id=123456×tamp=1377177267&lat=60.0&lon=30.0")); +- ++ + verifyPosition(decoder, request( + "/?lat=60.0&lon=30.0&speed=0.0&heading=0.0&vacc=0&hacc=0&altitude=0&deviceid=123456")); + diff --git a/tasks/traccar__traccar-5915/tests/test.sh b/tasks/traccar__traccar-5915/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9cf5aebb54701bc4bc61ae36a2ee9d3ce3cdbfbd --- /dev/null +++ b/tasks/traccar__traccar-5915/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 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 > "$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/traccar__traccar-5915/tests/verifier.py b/tasks/traccar__traccar-5915/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5915/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/traccar__traccar-5916/environment/Dockerfile b/tasks/traccar__traccar-5916/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..33a330ed13e43ff0a71f214efbfd1bc4e2fe6259 --- /dev/null +++ b/tasks/traccar__traccar-5916/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 \ + && 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/traccar__traccar-5916/instruction.md b/tasks/traccar__traccar-5916/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9d1a1dafff4e1631b2f1cfc4b83de79032744fef --- /dev/null +++ b/tasks/traccar__traccar-5916/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** converted old switch to new format and added test + +## Description + +Using the new switch syntax seems to be a preference. So I converted the rest of the file + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8b605bf7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5916/solution/patch.diff b/tasks/traccar__traccar-5916/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3db27745ae954c5175f8c2f974095444ff54a3e9 --- /dev/null +++ b/tasks/traccar__traccar-5916/solution/patch.diff @@ -0,0 +1,121 @@ +diff --git a/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java b/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java +index 7517c5040..260e9e941 100644 +--- a/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java +@@ -93,24 +93,21 @@ public class OsmAndProtocolDecoder extends BaseHttpProtocolDecoder { + for (Map.Entry> entry : params.entrySet()) { + for (String value : entry.getValue()) { + switch (entry.getKey()) { +- case "id": +- case "deviceid": ++ case "id", "deviceid" -> { + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, value); + if (deviceSession == null) { + sendResponse(channel, HttpResponseStatus.BAD_REQUEST); + return null; + } + position.setDeviceId(deviceSession.getDeviceId()); +- break; +- case "notificationToken": ++ } ++ case "notificationToken" -> { + if (position.getDeviceId() > 0) { + getCommandsManager().updateNotificationToken(position.getDeviceId(), value); + } +- break; +- case "valid": +- position.setValid(Boolean.parseBoolean(value) || "1".equals(value)); +- break; +- case "timestamp": ++ } ++ case "valid" -> position.setValid(Boolean.parseBoolean(value) || "1".equals(value)); ++ case "timestamp" -> { + try { + long timestamp = Long.parseLong(value); + if (timestamp < Integer.MAX_VALUE) { +@@ -124,19 +121,15 @@ public class OsmAndProtocolDecoder extends BaseHttpProtocolDecoder { + position.setTime(DateUtil.parse(DATE_FORMAT, value)); + } + } +- break; +- case "lat": +- latitude = Double.parseDouble(value); +- break; +- case "lon": +- longitude = Double.parseDouble(value); +- break; +- case "location": ++ } ++ case "lat" -> latitude = Double.parseDouble(value); ++ case "lon" -> longitude = Double.parseDouble(value); ++ case "location" -> { + String[] location = value.split(","); + latitude = Double.parseDouble(location[0]); + longitude = Double.parseDouble(location[1]); +- break; +- case "cell": ++ } ++ case "cell" -> { + String[] cell = value.split(","); + if (cell.length > 4) { + network.addCellTower(CellTower.from( +@@ -147,38 +140,21 @@ public class OsmAndProtocolDecoder extends BaseHttpProtocolDecoder { + Integer.parseInt(cell[0]), Integer.parseInt(cell[1]), + Integer.parseInt(cell[2]), Integer.parseInt(cell[3]))); + } +- break; +- case "wifi": ++ } ++ case "wifi" -> { + String[] wifi = value.split(","); + network.addWifiAccessPoint(WifiAccessPoint.from( + wifi[0].replace('-', ':'), Integer.parseInt(wifi[1]))); +- break; +- case "speed": +- position.setSpeed(convertSpeed(Double.parseDouble(value), "kn")); +- break; +- case "bearing": +- case "heading": +- position.setCourse(Double.parseDouble(value)); +- break; +- case "altitude": +- position.setAltitude(Double.parseDouble(value)); +- break; +- case "accuracy": +- position.setAccuracy(Double.parseDouble(value)); +- break; +- case "hdop": +- position.set(Position.KEY_HDOP, Double.parseDouble(value)); +- break; +- case "batt": +- position.set(Position.KEY_BATTERY_LEVEL, Double.parseDouble(value)); +- break; +- case "driverUniqueId": +- position.set(Position.KEY_DRIVER_UNIQUE_ID, value); +- break; +- case "charge": +- position.set(Position.KEY_CHARGE, Boolean.parseBoolean(value)); +- break; +- default: ++ } ++ case "speed" -> position.setSpeed(convertSpeed(Double.parseDouble(value), "kn")); ++ case "bearing", "heading" -> position.setCourse(Double.parseDouble(value)); ++ case "altitude" -> position.setAltitude(Double.parseDouble(value)); ++ case "accuracy" -> position.setAccuracy(Double.parseDouble(value)); ++ case "hdop" -> position.set(Position.KEY_HDOP, Double.parseDouble(value)); ++ case "batt" -> position.set(Position.KEY_BATTERY_LEVEL, Double.parseDouble(value)); ++ case "driverUniqueId" -> position.set(Position.KEY_DRIVER_UNIQUE_ID, value); ++ case "charge" -> position.set(Position.KEY_CHARGE, Boolean.parseBoolean(value)); ++ default -> { + try { + position.set(entry.getKey(), Double.parseDouble(value)); + } catch (NumberFormatException e) { +@@ -188,7 +164,7 @@ public class OsmAndProtocolDecoder extends BaseHttpProtocolDecoder { + default -> position.set(entry.getKey(), value); + } + } +- break; ++ } + } + } + } diff --git a/tasks/traccar__traccar-5916/solution/solve.sh b/tasks/traccar__traccar-5916/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5916/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/traccar__traccar-5916/task.toml b/tasks/traccar__traccar-5916/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..439d1f98133a6bada04f28c739c45e6dcaa364cf --- /dev/null +++ b/tasks/traccar__traccar-5916/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5916" +description = "converted old switch to new format and added test" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "4e8b605bf7d7c4584491b1095b3a87186ee0a9c7" +reference = "https://github.com/traccar/traccar/pull/5916" +source_access = "auto" +built_at = "2026-11-16T16:09:42.579814+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:10a581246df0886c1f2dec3f2363505b3f10db29b761c625ef0c3d6800011310" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-18T13:12:40Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 74 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.496037+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e1103824365c018166cf80d7697e463ed461e1906eb57c762b5d02ae1b0acc02" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5916/tests/capture.py b/tasks/traccar__traccar-5916/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5916/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/traccar__traccar-5916/tests/instruction.md b/tasks/traccar__traccar-5916/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9d1a1dafff4e1631b2f1cfc4b83de79032744fef --- /dev/null +++ b/tasks/traccar__traccar-5916/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** converted old switch to new format and added test + +## Description + +Using the new switch syntax seems to be a preference. So I converted the rest of the file + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8b605bf7d7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5916/tests/oracle.patch b/tasks/traccar__traccar-5916/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3db27745ae954c5175f8c2f974095444ff54a3e9 --- /dev/null +++ b/tasks/traccar__traccar-5916/tests/oracle.patch @@ -0,0 +1,121 @@ +diff --git a/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java b/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java +index 7517c5040..260e9e941 100644 +--- a/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/OsmAndProtocolDecoder.java +@@ -93,24 +93,21 @@ public class OsmAndProtocolDecoder extends BaseHttpProtocolDecoder { + for (Map.Entry> entry : params.entrySet()) { + for (String value : entry.getValue()) { + switch (entry.getKey()) { +- case "id": +- case "deviceid": ++ case "id", "deviceid" -> { + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, value); + if (deviceSession == null) { + sendResponse(channel, HttpResponseStatus.BAD_REQUEST); + return null; + } + position.setDeviceId(deviceSession.getDeviceId()); +- break; +- case "notificationToken": ++ } ++ case "notificationToken" -> { + if (position.getDeviceId() > 0) { + getCommandsManager().updateNotificationToken(position.getDeviceId(), value); + } +- break; +- case "valid": +- position.setValid(Boolean.parseBoolean(value) || "1".equals(value)); +- break; +- case "timestamp": ++ } ++ case "valid" -> position.setValid(Boolean.parseBoolean(value) || "1".equals(value)); ++ case "timestamp" -> { + try { + long timestamp = Long.parseLong(value); + if (timestamp < Integer.MAX_VALUE) { +@@ -124,19 +121,15 @@ public class OsmAndProtocolDecoder extends BaseHttpProtocolDecoder { + position.setTime(DateUtil.parse(DATE_FORMAT, value)); + } + } +- break; +- case "lat": +- latitude = Double.parseDouble(value); +- break; +- case "lon": +- longitude = Double.parseDouble(value); +- break; +- case "location": ++ } ++ case "lat" -> latitude = Double.parseDouble(value); ++ case "lon" -> longitude = Double.parseDouble(value); ++ case "location" -> { + String[] location = value.split(","); + latitude = Double.parseDouble(location[0]); + longitude = Double.parseDouble(location[1]); +- break; +- case "cell": ++ } ++ case "cell" -> { + String[] cell = value.split(","); + if (cell.length > 4) { + network.addCellTower(CellTower.from( +@@ -147,38 +140,21 @@ public class OsmAndProtocolDecoder extends BaseHttpProtocolDecoder { + Integer.parseInt(cell[0]), Integer.parseInt(cell[1]), + Integer.parseInt(cell[2]), Integer.parseInt(cell[3]))); + } +- break; +- case "wifi": ++ } ++ case "wifi" -> { + String[] wifi = value.split(","); + network.addWifiAccessPoint(WifiAccessPoint.from( + wifi[0].replace('-', ':'), Integer.parseInt(wifi[1]))); +- break; +- case "speed": +- position.setSpeed(convertSpeed(Double.parseDouble(value), "kn")); +- break; +- case "bearing": +- case "heading": +- position.setCourse(Double.parseDouble(value)); +- break; +- case "altitude": +- position.setAltitude(Double.parseDouble(value)); +- break; +- case "accuracy": +- position.setAccuracy(Double.parseDouble(value)); +- break; +- case "hdop": +- position.set(Position.KEY_HDOP, Double.parseDouble(value)); +- break; +- case "batt": +- position.set(Position.KEY_BATTERY_LEVEL, Double.parseDouble(value)); +- break; +- case "driverUniqueId": +- position.set(Position.KEY_DRIVER_UNIQUE_ID, value); +- break; +- case "charge": +- position.set(Position.KEY_CHARGE, Boolean.parseBoolean(value)); +- break; +- default: ++ } ++ case "speed" -> position.setSpeed(convertSpeed(Double.parseDouble(value), "kn")); ++ case "bearing", "heading" -> position.setCourse(Double.parseDouble(value)); ++ case "altitude" -> position.setAltitude(Double.parseDouble(value)); ++ case "accuracy" -> position.setAccuracy(Double.parseDouble(value)); ++ case "hdop" -> position.set(Position.KEY_HDOP, Double.parseDouble(value)); ++ case "batt" -> position.set(Position.KEY_BATTERY_LEVEL, Double.parseDouble(value)); ++ case "driverUniqueId" -> position.set(Position.KEY_DRIVER_UNIQUE_ID, value); ++ case "charge" -> position.set(Position.KEY_CHARGE, Boolean.parseBoolean(value)); ++ default -> { + try { + position.set(entry.getKey(), Double.parseDouble(value)); + } catch (NumberFormatException e) { +@@ -188,7 +164,7 @@ public class OsmAndProtocolDecoder extends BaseHttpProtocolDecoder { + default -> position.set(entry.getKey(), value); + } + } +- break; ++ } + } + } + } diff --git a/tasks/traccar__traccar-5916/tests/test.sh b/tasks/traccar__traccar-5916/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9cf5aebb54701bc4bc61ae36a2ee9d3ce3cdbfbd --- /dev/null +++ b/tasks/traccar__traccar-5916/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 4e8b605bf7d7c4584491b1095b3a87186ee0a9c7 > "$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/traccar__traccar-5916/tests/verifier.py b/tasks/traccar__traccar-5916/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5916/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/traccar__traccar-5923/environment/Dockerfile b/tasks/traccar__traccar-5923/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6f98c3a2b6535cbbcd563cbcc2c107abd0ea1119 --- /dev/null +++ b/tasks/traccar__traccar-5923/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7c00b1c837304756464b136fe90231664a22c2dd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7c00b1c837304756464b136fe90231664a22c2dd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7c00b1c837304756464b136fe90231664a22c2dd \ + && 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/traccar__traccar-5923/instruction.md b/tasks/traccar__traccar-5923/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..949c4d649aa23fe2ab749212916bf3d6cabb1974 --- /dev/null +++ b/tasks/traccar__traccar-5923/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** Add support for JT808 terminal attribute report (0x0107) ICCID decoding + +## Description + +## Summary + +Add support for decoding ICCID information from JT808 terminal attribute report messages (0x0107). + +## Details + +Some devices report terminal information using message ID 0x0107 immediately after connection. The message contains device metadata including terminal model, terminal ID, ICCID, hardware version, and firmware version. + +The current decoder ignores 0x0107 messages, causing ICCID information to be unavailable until a vendor-specific (e.g. 0x1107) message is received. This change adds support for extracting the ICCID from the standard JT808 terminal attribute report. + +## Protocol Reference + +[Xchinchun JT808.docx](https://github.com/user-attachments/files/29208352/Xchinchun.JT808.docx) + +- Page 33 +- Section 2.22: Query Terminal Attribute Reporting (0x0107) + +The specification defines the following fields in the 0x0107 message: + +- Terminal Type +- Manufacturer ID +- Terminal Model +- Terminal ID +- Terminal SIM Card ICCID (BCD[10]) +- Hardware Version +- Firmware Version + +This change decodes the standard ICCID field from the terminal attribute report and stores it in `Position.KEY_ICCID`. + +## Testing + +Added a unit test using a real C5L terminal attribute report frame containing: + +- Model: C5L +- ICCID: 89883030000131882455 +- Firmware Version: C5L_V2.6 2026/06/04 15:31 + +The test verifies that the decoder correctly extracts and stores the ICCID from the 0x0107 message. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7c00b1c83730`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5923/solution/patch.diff b/tasks/traccar__traccar-5923/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..89d28b4d538b3d7b8a928777140fcf88c64f75e2 --- /dev/null +++ b/tasks/traccar__traccar-5923/solution/patch.diff @@ -0,0 +1,52 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 83ea838ff..2736cc141 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -70,6 +70,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_TERMINAL_REGISTER_RESPONSE = 0x8100; + public static final int MSG_TERMINAL_CONTROL = 0x8105; + public static final int MSG_TERMINAL_AUTH = 0x0102; ++ public static final int MSG_TERMINAL_ATTRIBUTES = 0x0107; + public static final int MSG_LOCATION_REPORT = 0x0200; + public static final int MSG_LOCATION_BATCH_2 = 0x0210; + public static final int MSG_ACCELERATION = 0x2070; +@@ -426,6 +427,24 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + + sendGeneralResponse(channel, remoteAddress, id, type, index); + ++ } else if (type == MSG_TERMINAL_ATTRIBUTES) { ++ ++ sendGeneralResponse(channel, remoteAddress, id, type, index); ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ getLastLocation(position, null); ++ ++ buf.readUnsignedShort(); // terminal type ++ buf.skipBytes(5); // manufacturer id ++ buf.skipBytes(20); // terminal model ++ buf.skipBytes(7); // terminal id ++ ++ position.set(Position.KEY_ICCID, ByteBufUtil.hexDump(buf.readSlice(10))); ++ ++ return position; ++ + } else if (type == MSG_LOCATION_REPORT) { + + sendGeneralResponse(channel, remoteAddress, id, type, index); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index baa31cee5..49f65b65d 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -361,6 +361,10 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7e0210000704546000231900884f2606180229579c7e"), + Position.KEY_BATTERY_LEVEL, 79); + ++ verifyAttribute(decoder, binary( ++ "7e0107004904546000563500030000584300000043354c00000000000000000000000000000000003938383731323589883030000131882455001943354c5f56322e3620323032362f30362f30342031353a33310301f47e"), ++ Position.KEY_ICCID, "89883030000131882455"); ++ + decoder.setModelOverride("MV710G"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5923/solution/solve.sh b/tasks/traccar__traccar-5923/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5923/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/traccar__traccar-5923/task.toml b/tasks/traccar__traccar-5923/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5a3a7d8bc9b29dbd1998caa0b18e8d1781a30cdb --- /dev/null +++ b/tasks/traccar__traccar-5923/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5923" +description = "Add support for JT808 terminal attribute report (0x0107) ICCID decoding" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "7c00b1c837304756464b136fe90231664a22c2dd" +reference = "https://github.com/traccar/traccar/pull/5923" +source_access = "auto" +built_at = "2026-11-16T16:09:42.572334+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b259923671f2ab1fa8116dfd81bbe86b9bb3ea51dc34661b6406d758cdc165f0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-23T00:29:46Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 23 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.496635+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:93b72d9c18972ce56275dd6347468994d070c382a71e666e94b09702eaab5325" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5923/tests/capture.py b/tasks/traccar__traccar-5923/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5923/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/traccar__traccar-5923/tests/instruction.md b/tasks/traccar__traccar-5923/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..949c4d649aa23fe2ab749212916bf3d6cabb1974 --- /dev/null +++ b/tasks/traccar__traccar-5923/tests/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** Add support for JT808 terminal attribute report (0x0107) ICCID decoding + +## Description + +## Summary + +Add support for decoding ICCID information from JT808 terminal attribute report messages (0x0107). + +## Details + +Some devices report terminal information using message ID 0x0107 immediately after connection. The message contains device metadata including terminal model, terminal ID, ICCID, hardware version, and firmware version. + +The current decoder ignores 0x0107 messages, causing ICCID information to be unavailable until a vendor-specific (e.g. 0x1107) message is received. This change adds support for extracting the ICCID from the standard JT808 terminal attribute report. + +## Protocol Reference + +[Xchinchun JT808.docx](https://github.com/user-attachments/files/29208352/Xchinchun.JT808.docx) + +- Page 33 +- Section 2.22: Query Terminal Attribute Reporting (0x0107) + +The specification defines the following fields in the 0x0107 message: + +- Terminal Type +- Manufacturer ID +- Terminal Model +- Terminal ID +- Terminal SIM Card ICCID (BCD[10]) +- Hardware Version +- Firmware Version + +This change decodes the standard ICCID field from the terminal attribute report and stores it in `Position.KEY_ICCID`. + +## Testing + +Added a unit test using a real C5L terminal attribute report frame containing: + +- Model: C5L +- ICCID: 89883030000131882455 +- Firmware Version: C5L_V2.6 2026/06/04 15:31 + +The test verifies that the decoder correctly extracts and stores the ICCID from the 0x0107 message. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7c00b1c83730`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5923/tests/oracle.patch b/tasks/traccar__traccar-5923/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..89d28b4d538b3d7b8a928777140fcf88c64f75e2 --- /dev/null +++ b/tasks/traccar__traccar-5923/tests/oracle.patch @@ -0,0 +1,52 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index 83ea838ff..2736cc141 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -70,6 +70,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_TERMINAL_REGISTER_RESPONSE = 0x8100; + public static final int MSG_TERMINAL_CONTROL = 0x8105; + public static final int MSG_TERMINAL_AUTH = 0x0102; ++ public static final int MSG_TERMINAL_ATTRIBUTES = 0x0107; + public static final int MSG_LOCATION_REPORT = 0x0200; + public static final int MSG_LOCATION_BATCH_2 = 0x0210; + public static final int MSG_ACCELERATION = 0x2070; +@@ -426,6 +427,24 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + + sendGeneralResponse(channel, remoteAddress, id, type, index); + ++ } else if (type == MSG_TERMINAL_ATTRIBUTES) { ++ ++ sendGeneralResponse(channel, remoteAddress, id, type, index); ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ getLastLocation(position, null); ++ ++ buf.readUnsignedShort(); // terminal type ++ buf.skipBytes(5); // manufacturer id ++ buf.skipBytes(20); // terminal model ++ buf.skipBytes(7); // terminal id ++ ++ position.set(Position.KEY_ICCID, ByteBufUtil.hexDump(buf.readSlice(10))); ++ ++ return position; ++ + } else if (type == MSG_LOCATION_REPORT) { + + sendGeneralResponse(channel, remoteAddress, id, type, index); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index baa31cee5..49f65b65d 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -361,6 +361,10 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7e0210000704546000231900884f2606180229579c7e"), + Position.KEY_BATTERY_LEVEL, 79); + ++ verifyAttribute(decoder, binary( ++ "7e0107004904546000563500030000584300000043354c00000000000000000000000000000000003938383731323589883030000131882455001943354c5f56322e3620323032362f30362f30342031353a33310301f47e"), ++ Position.KEY_ICCID, "89883030000131882455"); ++ + decoder.setModelOverride("MV710G"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5923/tests/test.sh b/tasks/traccar__traccar-5923/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..97bbcf6e8baf07cf5e41f2fb2e712fbc0c6390d5 --- /dev/null +++ b/tasks/traccar__traccar-5923/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 7c00b1c837304756464b136fe90231664a22c2dd > "$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/traccar__traccar-5923/tests/verifier.py b/tasks/traccar__traccar-5923/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5923/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/traccar__traccar-5926/environment/Dockerfile b/tasks/traccar__traccar-5926/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9dc6aa0842b13df7a49a496651ec6538093ac042 --- /dev/null +++ b/tasks/traccar__traccar-5926/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 13c49d928a106585d13ee40de63f01fc3cefd6f2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 13c49d928a106585d13ee40de63f01fc3cefd6f2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 13c49d928a106585d13ee40de63f01fc3cefd6f2 \ + && 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/traccar__traccar-5926/instruction.md b/tasks/traccar__traccar-5926/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..896a2ffff8c86f706081cda7f213f6235fff4b72 --- /dev/null +++ b/tasks/traccar__traccar-5926/instruction.md @@ -0,0 +1,60 @@ +# Issue + +**Title:** Add support for the Xinchun time zone synchronization command (0x1007) by sending a general response (0x8001) + +## Description + +## Details + +Some devices send message ID 0x1007 after authentication and before the first location report. The current decoder does not explicitly handle this message and does not send a response. + +This change adds support for 0x1007 and acknowledges the message with a standard JT808 general response (0x8001). + +No position data is contained in this message and no device attributes are currently updated. + +## Protocol Reference + +[Xchinchun JT808.docx](https://github.com/user-attachments/files/29297571/Xchinchun.JT808.docx) + +* Page 41 +* Section 3.7: Time Zone Synchronization Command (0x1007) + +The protocol defines a 4-byte payload containing time zone information. + +Example frame observed from a C5L device: + +```text +7e10070004045460002319090640000000567e +``` + +Payload: + +```text +40 00 00 00 +``` + +According to the protocol specification, the first byte represents the configured time zone. In this example, the value corresponds to GMT+8. + +## Future Improvements + +The time zone value is currently not stored or applied by the decoder. + +While the protocol provides time zone information, this change intentionally limits the implementation to acknowledging the message. The observed devices report GMT+8, which matches the existing default behavior and does not currently provide any additional information required by the decoder. + +Future work could include: + +* Decoding the reported time zone value into a human-readable UTC offset +* Storing the reported device time zone as a device attribute +* Applying the reported time zone to device-specific date parsing where appropriate + +These enhancements can be implemented later if devices are observed reporting different time zone values or if additional use cases require access to the reported configuration. + +## Testing + +Added a unit test using a real device frame to verify that the decoder accepts and processes the 0x1007 message without generating a position. + +The message has been observed consistently on C5L devices immediately after authentication and before the first location report following a reconnect. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `13c49d928a10`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5926/solution/patch.diff b/tasks/traccar__traccar-5926/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..44f6b0a19084eb3aa85a2b7d847e5c2525ed543f --- /dev/null +++ b/tasks/traccar__traccar-5926/solution/patch.diff @@ -0,0 +1,35 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index cbca76762..ead0415e6 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -80,6 +80,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_OIL_CONTROL = 0XA006; + public static final int MSG_TIME_SYNC_REQUEST = 0x0109; + public static final int MSG_TIME_SYNC_RESPONSE = 0x8109; ++ public static final int MSG_TIMEZONE_SYNC = 0x1007; + public static final int MSG_PHOTO = 0x8888; + public static final int MSG_TRANSPARENT = 0x0900; + public static final int MSG_TRANSPARENT_DOWNLINK = 0x8900; +@@ -423,7 +424,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + } + + } else if (type == MSG_TERMINAL_AUTH || type == MSG_HEARTBEAT_2 +- || type == MSG_PHOTO || type == MSG_TERMINAL_LOGOUT) { ++ || type == MSG_PHOTO || type == MSG_TERMINAL_LOGOUT || type == MSG_TIMEZONE_SYNC) { + + sendGeneralResponse(channel, remoteAddress, id, type, index); + +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 8be1e1f9a..98bca52df 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -369,6 +369,9 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7e0107004904546000563500030000584300000043354c00000000000000000000000000000000003938383731323589883030000131882455001943354c5f56322e3620323032362f30362f30342031353a33310301f47e"), + Position.KEY_ICCID, "89883030000131882455"); + ++ verifyNull(decoder, binary( ++ "7e10070004045460002319090640000000567e")); ++ + decoder.setModelOverride("MV710G"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5926/solution/solve.sh b/tasks/traccar__traccar-5926/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5926/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/traccar__traccar-5926/task.toml b/tasks/traccar__traccar-5926/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b8c9c24281bc170b4dbc680d2b7ba08a1f3a0409 --- /dev/null +++ b/tasks/traccar__traccar-5926/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5926" +description = "Add support for the Xinchun time zone synchronization command (0x1007) by sending a general response (0x8001)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "13c49d928a106585d13ee40de63f01fc3cefd6f2" +reference = "https://github.com/traccar/traccar/pull/5926" +source_access = "auto" +built_at = "2026-11-16T16:09:42.569111+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4e07b70da999d2693cbd146a5a9e3a8838d11012935b7664ef6acfc21d8ff3cf" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-24T16:58:08Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.497211+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:dadeccc73f20430bb984e12d80076e72d3e03985de563778e34403daa8de39e6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5926/tests/capture.py b/tasks/traccar__traccar-5926/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5926/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/traccar__traccar-5926/tests/instruction.md b/tasks/traccar__traccar-5926/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..896a2ffff8c86f706081cda7f213f6235fff4b72 --- /dev/null +++ b/tasks/traccar__traccar-5926/tests/instruction.md @@ -0,0 +1,60 @@ +# Issue + +**Title:** Add support for the Xinchun time zone synchronization command (0x1007) by sending a general response (0x8001) + +## Description + +## Details + +Some devices send message ID 0x1007 after authentication and before the first location report. The current decoder does not explicitly handle this message and does not send a response. + +This change adds support for 0x1007 and acknowledges the message with a standard JT808 general response (0x8001). + +No position data is contained in this message and no device attributes are currently updated. + +## Protocol Reference + +[Xchinchun JT808.docx](https://github.com/user-attachments/files/29297571/Xchinchun.JT808.docx) + +* Page 41 +* Section 3.7: Time Zone Synchronization Command (0x1007) + +The protocol defines a 4-byte payload containing time zone information. + +Example frame observed from a C5L device: + +```text +7e10070004045460002319090640000000567e +``` + +Payload: + +```text +40 00 00 00 +``` + +According to the protocol specification, the first byte represents the configured time zone. In this example, the value corresponds to GMT+8. + +## Future Improvements + +The time zone value is currently not stored or applied by the decoder. + +While the protocol provides time zone information, this change intentionally limits the implementation to acknowledging the message. The observed devices report GMT+8, which matches the existing default behavior and does not currently provide any additional information required by the decoder. + +Future work could include: + +* Decoding the reported time zone value into a human-readable UTC offset +* Storing the reported device time zone as a device attribute +* Applying the reported time zone to device-specific date parsing where appropriate + +These enhancements can be implemented later if devices are observed reporting different time zone values or if additional use cases require access to the reported configuration. + +## Testing + +Added a unit test using a real device frame to verify that the decoder accepts and processes the 0x1007 message without generating a position. + +The message has been observed consistently on C5L devices immediately after authentication and before the first location report following a reconnect. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `13c49d928a10`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5926/tests/oracle.patch b/tasks/traccar__traccar-5926/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..44f6b0a19084eb3aa85a2b7d847e5c2525ed543f --- /dev/null +++ b/tasks/traccar__traccar-5926/tests/oracle.patch @@ -0,0 +1,35 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index cbca76762..ead0415e6 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -80,6 +80,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_OIL_CONTROL = 0XA006; + public static final int MSG_TIME_SYNC_REQUEST = 0x0109; + public static final int MSG_TIME_SYNC_RESPONSE = 0x8109; ++ public static final int MSG_TIMEZONE_SYNC = 0x1007; + public static final int MSG_PHOTO = 0x8888; + public static final int MSG_TRANSPARENT = 0x0900; + public static final int MSG_TRANSPARENT_DOWNLINK = 0x8900; +@@ -423,7 +424,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + } + + } else if (type == MSG_TERMINAL_AUTH || type == MSG_HEARTBEAT_2 +- || type == MSG_PHOTO || type == MSG_TERMINAL_LOGOUT) { ++ || type == MSG_PHOTO || type == MSG_TERMINAL_LOGOUT || type == MSG_TIMEZONE_SYNC) { + + sendGeneralResponse(channel, remoteAddress, id, type, index); + +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 8be1e1f9a..98bca52df 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -369,6 +369,9 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7e0107004904546000563500030000584300000043354c00000000000000000000000000000000003938383731323589883030000131882455001943354c5f56322e3620323032362f30362f30342031353a33310301f47e"), + Position.KEY_ICCID, "89883030000131882455"); + ++ verifyNull(decoder, binary( ++ "7e10070004045460002319090640000000567e")); ++ + decoder.setModelOverride("MV710G"); + + verifyAttribute(decoder, binary( diff --git a/tasks/traccar__traccar-5926/tests/test.sh b/tasks/traccar__traccar-5926/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4de6450722195a9235bdfae5ff4f0ccc38f0a842 --- /dev/null +++ b/tasks/traccar__traccar-5926/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 13c49d928a106585d13ee40de63f01fc3cefd6f2 > "$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/traccar__traccar-5926/tests/verifier.py b/tasks/traccar__traccar-5926/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5926/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/traccar__traccar-5927/environment/Dockerfile b/tasks/traccar__traccar-5927/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc63f128cab943c10db8bdf202f42513231772a3 --- /dev/null +++ b/tasks/traccar__traccar-5927/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8b0aae0e1916b59a8e3a3cd2321955a856ddbc23 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8b0aae0e1916b59a8e3a3cd2321955a856ddbc23 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8b0aae0e1916b59a8e3a3cd2321955a856ddbc23 \ + && 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/traccar__traccar-5927/instruction.md b/tasks/traccar__traccar-5927/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d34ed53690d0ef0df4c9fb99f4127f1715c4d0ab --- /dev/null +++ b/tasks/traccar__traccar-5927/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** Fix JT808 0x0109 Time Synchronization Response + +## Description + +### Description + +This PR corrects the response generated for JT808 **0x0109 (Time Synchronization Request)**. + +### Changes + +* Respond with **0x8109 (Time Synchronization Response)** instead of **0x8100 (Terminal Register Response)**. +* Include the **result/status byte (0x00 = Success)** in the response payload. + +### Motivation + +The decoder already defines both message IDs (`0x0109` and `0x8109`), but the current implementation replies using the terminal registration response (`0x8100`). Returning the dedicated time synchronization response improves protocol compliance and interoperability with devices that expect the standard reply. + +### Evidence + +See the [Xchinchun JT808.docx](https://github.com/user-attachments/files/29335613/Xchinchun.JT808.docx): + +* **Section:** Time Synchronization +* **Message IDs:** `0x0109` (Time Synchronization Request) / `0x8109` (Time Synchronization Response) +* **Page:** 13 (Time Synchronization section) *(according to the Xchinchun JT808 protocol documentation provided with this project).* + +### Test + +I did not add a dedicated unit test for this small change because the fix only corrects the response message type used for an already handled message. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8b0aae0e1916`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5927/solution/patch.diff b/tasks/traccar__traccar-5927/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2ebf6a48b707aafbaea6c7706f254a3940e5e18a --- /dev/null +++ b/tasks/traccar__traccar-5927/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index ead0415e6..71af89457 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -491,8 +491,9 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + response.writeByte(calendar.get(Calendar.HOUR_OF_DAY)); + response.writeByte(calendar.get(Calendar.MINUTE)); + response.writeByte(calendar.get(Calendar.SECOND)); ++ response.writeByte(RESULT_SUCCESS); + channel.writeAndFlush(new NetworkMessage( +- formatMessage(MSG_TERMINAL_REGISTER_RESPONSE, id, false, response), remoteAddress)); ++ formatMessage(MSG_TIME_SYNC_RESPONSE, id, false, response), remoteAddress)); + } + + } else if (type == MSG_ACCELERATION) { diff --git a/tasks/traccar__traccar-5927/solution/solve.sh b/tasks/traccar__traccar-5927/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5927/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/traccar__traccar-5927/task.toml b/tasks/traccar__traccar-5927/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..638fa9cf24642716d13bc096602d006eb2cfcf75 --- /dev/null +++ b/tasks/traccar__traccar-5927/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5927" +description = "Fix JT808 0x0109 Time Synchronization Response" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "8b0aae0e1916b59a8e3a3cd2321955a856ddbc23" +reference = "https://github.com/traccar/traccar/pull/5927" +source_access = "auto" +built_at = "2026-11-16T16:09:42.565933+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c45c6ebf505ce550b9a23629c3f3ee85c119478acf16290a4959650d9fba80a9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-25T12:35:20Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.497761+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:eda3df9617d903cfa03e1fd2823d42a659cb4455b08061074687c13bc286e216" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5927/tests/capture.py b/tasks/traccar__traccar-5927/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5927/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/traccar__traccar-5927/tests/instruction.md b/tasks/traccar__traccar-5927/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d34ed53690d0ef0df4c9fb99f4127f1715c4d0ab --- /dev/null +++ b/tasks/traccar__traccar-5927/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** Fix JT808 0x0109 Time Synchronization Response + +## Description + +### Description + +This PR corrects the response generated for JT808 **0x0109 (Time Synchronization Request)**. + +### Changes + +* Respond with **0x8109 (Time Synchronization Response)** instead of **0x8100 (Terminal Register Response)**. +* Include the **result/status byte (0x00 = Success)** in the response payload. + +### Motivation + +The decoder already defines both message IDs (`0x0109` and `0x8109`), but the current implementation replies using the terminal registration response (`0x8100`). Returning the dedicated time synchronization response improves protocol compliance and interoperability with devices that expect the standard reply. + +### Evidence + +See the [Xchinchun JT808.docx](https://github.com/user-attachments/files/29335613/Xchinchun.JT808.docx): + +* **Section:** Time Synchronization +* **Message IDs:** `0x0109` (Time Synchronization Request) / `0x8109` (Time Synchronization Response) +* **Page:** 13 (Time Synchronization section) *(according to the Xchinchun JT808 protocol documentation provided with this project).* + +### Test + +I did not add a dedicated unit test for this small change because the fix only corrects the response message type used for an already handled message. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8b0aae0e1916`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5927/tests/oracle.patch b/tasks/traccar__traccar-5927/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2ebf6a48b707aafbaea6c7706f254a3940e5e18a --- /dev/null +++ b/tasks/traccar__traccar-5927/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index ead0415e6..71af89457 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -491,8 +491,9 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + response.writeByte(calendar.get(Calendar.HOUR_OF_DAY)); + response.writeByte(calendar.get(Calendar.MINUTE)); + response.writeByte(calendar.get(Calendar.SECOND)); ++ response.writeByte(RESULT_SUCCESS); + channel.writeAndFlush(new NetworkMessage( +- formatMessage(MSG_TERMINAL_REGISTER_RESPONSE, id, false, response), remoteAddress)); ++ formatMessage(MSG_TIME_SYNC_RESPONSE, id, false, response), remoteAddress)); + } + + } else if (type == MSG_ACCELERATION) { diff --git a/tasks/traccar__traccar-5927/tests/test.sh b/tasks/traccar__traccar-5927/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..abc562bb7ffffa2f2db803bb0aa3cb9cb5de88c3 --- /dev/null +++ b/tasks/traccar__traccar-5927/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 8b0aae0e1916b59a8e3a3cd2321955a856ddbc23 > "$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/traccar__traccar-5927/tests/verifier.py b/tasks/traccar__traccar-5927/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5927/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/traccar__traccar-5928/environment/Dockerfile b/tasks/traccar__traccar-5928/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc63f128cab943c10db8bdf202f42513231772a3 --- /dev/null +++ b/tasks/traccar__traccar-5928/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8b0aae0e1916b59a8e3a3cd2321955a856ddbc23 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8b0aae0e1916b59a8e3a3cd2321955a856ddbc23 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8b0aae0e1916b59a8e3a3cd2321955a856ddbc23 \ + && 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/traccar__traccar-5928/instruction.md b/tasks/traccar__traccar-5928/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a54bfc15d9fe88a48fb608ce5084e59464a0b485 --- /dev/null +++ b/tasks/traccar__traccar-5928/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** Decode Xinchun 0xF8 Extension as Step Count for C5/C5L Devices + +## Description + +### Description + +This PR adds model-specific decoding for the proprietary Xinchun extension **`0xF8`**. + +### Changes + +* Decode extension **`0xF8`** as **step count** (`steps`) for **C5** and **C5L** devices. +* Preserve the existing behavior for all other JT808 models, where `0xF8` continues to be decoded as the second external temperature sensor. +* Keep the implementation fully backward compatible by applying the new interpretation only to the affected device models. + +### Motivation + +The Xinchun protocol assigns a different meaning to extension `0xF8` than the current JT808 implementation. According to the vendor documentation, `0xF8` contains the device's **step count** for C5/C5L pet trackers, while the current decoder interprets it as an external temperature value. + +Restricting the change to the relevant models preserves compatibility with existing devices while allowing C5/C5L trackers to expose the correct data. + +### Evidence + +See the [Xchinchun JT808.docx](https://github.com/user-attachments/files/29336626/Xchinchun.JT808.docx): + +* **Section:** Location Report – Extended Information Items +* **Extension ID:** `0xF8` +* **Definition:** Step Count (WORD, 2 bytes) +* **Page:** 10 (Extended Information Items section) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8b0aae0e1916`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5928/solution/patch.diff b/tasks/traccar__traccar-5928/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..85ff6c80be156d08e6a8a01d360e441e89bed213 --- /dev/null +++ b/tasks/traccar__traccar-5928/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index ead0415e6..e637e2dfb 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -1272,7 +1272,11 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + } + break; + case 0xF8: +- position.set(Position.PREFIX_TEMP + 2, buf.readUnsignedShort() / 10.0 - 50); ++ if (model != null && Set.of("C5", "C5L").contains(model)) { ++ position.set("steps", buf.readUnsignedShort()); ++ } else { ++ position.set(Position.PREFIX_TEMP + 2, buf.readUnsignedShort() / 10.0 - 50); ++ } + break; + case 0xFB: + position.set("container", buf.readCharSequence(length, StandardCharsets.US_ASCII).toString()); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 98bca52df..7f9e9b1ec 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -406,6 +406,12 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7E020000834EB6FB4AF2C1010F00000800000C000B01AAB48204EA7E57000801AD00B626032715524501040000045130011F310112EB095554432D30343A3030140400000001150400000004642F0000000B00040100000000002A000801AAB33804EA7E542603271552450400303037343234322603271552450B0500E81120050E200102008C0006010400070200069B7E"), + "alarmLabel", "303037343234322603271552450b0500"); + ++ decoder.setModelOverride("C5L"); ++ ++ verifyAttribute(decoder, binary( ++ "7e020000760454600047450f2a0000000000000002030fed58006d0e02008f000000002606250712430104000004cc300110310100e4020163e50100e60100e7080000000600000000e10c010600030091c400ce542100ec23b286252f68fecdb286258f68fecdb286255f68fecce0d362e7acaec1e0d362b519ceb0f8024936f50101ef7e"), ++ "steps", 18742); ++ + } + + } diff --git a/tasks/traccar__traccar-5928/solution/solve.sh b/tasks/traccar__traccar-5928/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5928/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/traccar__traccar-5928/task.toml b/tasks/traccar__traccar-5928/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..081b0dae5571b0add52c4a0ba1a92cdf2156a6ff --- /dev/null +++ b/tasks/traccar__traccar-5928/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5928" +description = "Decode Xinchun 0xF8 Extension as Step Count for C5/C5L Devices" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "8b0aae0e1916b59a8e3a3cd2321955a856ddbc23" +reference = "https://github.com/traccar/traccar/pull/5928" +source_access = "auto" +built_at = "2026-11-16T16:09:42.567323+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:992f65b968164950a49e000575064982a3aee79c31016618b0c47c080532f6b3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-25T14:16:52Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.498399+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:eda3df9617d903cfa03e1fd2823d42a659cb4455b08061074687c13bc286e216" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5928/tests/capture.py b/tasks/traccar__traccar-5928/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5928/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/traccar__traccar-5928/tests/instruction.md b/tasks/traccar__traccar-5928/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a54bfc15d9fe88a48fb608ce5084e59464a0b485 --- /dev/null +++ b/tasks/traccar__traccar-5928/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** Decode Xinchun 0xF8 Extension as Step Count for C5/C5L Devices + +## Description + +### Description + +This PR adds model-specific decoding for the proprietary Xinchun extension **`0xF8`**. + +### Changes + +* Decode extension **`0xF8`** as **step count** (`steps`) for **C5** and **C5L** devices. +* Preserve the existing behavior for all other JT808 models, where `0xF8` continues to be decoded as the second external temperature sensor. +* Keep the implementation fully backward compatible by applying the new interpretation only to the affected device models. + +### Motivation + +The Xinchun protocol assigns a different meaning to extension `0xF8` than the current JT808 implementation. According to the vendor documentation, `0xF8` contains the device's **step count** for C5/C5L pet trackers, while the current decoder interprets it as an external temperature value. + +Restricting the change to the relevant models preserves compatibility with existing devices while allowing C5/C5L trackers to expose the correct data. + +### Evidence + +See the [Xchinchun JT808.docx](https://github.com/user-attachments/files/29336626/Xchinchun.JT808.docx): + +* **Section:** Location Report – Extended Information Items +* **Extension ID:** `0xF8` +* **Definition:** Step Count (WORD, 2 bytes) +* **Page:** 10 (Extended Information Items section) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8b0aae0e1916`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5928/tests/oracle.patch b/tasks/traccar__traccar-5928/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..85ff6c80be156d08e6a8a01d360e441e89bed213 --- /dev/null +++ b/tasks/traccar__traccar-5928/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index ead0415e6..e637e2dfb 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -1272,7 +1272,11 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + } + break; + case 0xF8: +- position.set(Position.PREFIX_TEMP + 2, buf.readUnsignedShort() / 10.0 - 50); ++ if (model != null && Set.of("C5", "C5L").contains(model)) { ++ position.set("steps", buf.readUnsignedShort()); ++ } else { ++ position.set(Position.PREFIX_TEMP + 2, buf.readUnsignedShort() / 10.0 - 50); ++ } + break; + case 0xFB: + position.set("container", buf.readCharSequence(length, StandardCharsets.US_ASCII).toString()); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 98bca52df..7f9e9b1ec 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -406,6 +406,12 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7E020000834EB6FB4AF2C1010F00000800000C000B01AAB48204EA7E57000801AD00B626032715524501040000045130011F310112EB095554432D30343A3030140400000001150400000004642F0000000B00040100000000002A000801AAB33804EA7E542603271552450400303037343234322603271552450B0500E81120050E200102008C0006010400070200069B7E"), + "alarmLabel", "303037343234322603271552450b0500"); + ++ decoder.setModelOverride("C5L"); ++ ++ verifyAttribute(decoder, binary( ++ "7e020000760454600047450f2a0000000000000002030fed58006d0e02008f000000002606250712430104000004cc300110310100e4020163e50100e60100e7080000000600000000e10c010600030091c400ce542100ec23b286252f68fecdb286258f68fecdb286255f68fecce0d362e7acaec1e0d362b519ceb0f8024936f50101ef7e"), ++ "steps", 18742); ++ + } + + } diff --git a/tasks/traccar__traccar-5928/tests/test.sh b/tasks/traccar__traccar-5928/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..abc562bb7ffffa2f2db803bb0aa3cb9cb5de88c3 --- /dev/null +++ b/tasks/traccar__traccar-5928/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 8b0aae0e1916b59a8e3a3cd2321955a856ddbc23 > "$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/traccar__traccar-5928/tests/verifier.py b/tasks/traccar__traccar-5928/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5928/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/traccar__traccar-5929/environment/Dockerfile b/tasks/traccar__traccar-5929/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..deed15e242199bab24f5d4ff756de6f4df2fe80b --- /dev/null +++ b/tasks/traccar__traccar-5929/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2e3c087a240986aac10f01fc02d10db10af0216b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2e3c087a240986aac10f01fc02d10db10af0216b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2e3c087a240986aac10f01fc02d10db10af0216b \ + && 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/traccar__traccar-5929/instruction.md b/tasks/traccar__traccar-5929/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e885120064e320ff8b64175b9ba8361c7e8b86ff --- /dev/null +++ b/tasks/traccar__traccar-5929/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Use of Position.KEY_STEPS + +## Description + +Use of Position.KEY_STEPS instead of custom "steps" attribute. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2e3c087a2409`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5929/solution/patch.diff b/tasks/traccar__traccar-5929/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7986bce239c35aae55a90d13bfc2029f5753318e --- /dev/null +++ b/tasks/traccar__traccar-5929/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index f74a0de77..aae2cc7f8 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -1274,7 +1274,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + break; + case 0xF8: + if (model != null && Set.of("C5", "C5L").contains(model)) { +- position.set("steps", buf.readUnsignedShort()); ++ position.set(Position.KEY_STEPS, buf.readUnsignedShort()); + } else { + position.set(Position.PREFIX_TEMP + 2, buf.readUnsignedShort() / 10.0 - 50); + } +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 7f9e9b1ec..a388b0451 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -410,7 +410,7 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + + verifyAttribute(decoder, binary( + "7e020000760454600047450f2a0000000000000002030fed58006d0e02008f000000002606250712430104000004cc300110310100e4020163e50100e60100e7080000000600000000e10c010600030091c400ce542100ec23b286252f68fecdb286258f68fecdb286255f68fecce0d362e7acaec1e0d362b519ceb0f8024936f50101ef7e"), +- "steps", 18742); ++ Position.KEY_STEPS, 18742); + + } + diff --git a/tasks/traccar__traccar-5929/solution/solve.sh b/tasks/traccar__traccar-5929/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5929/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/traccar__traccar-5929/task.toml b/tasks/traccar__traccar-5929/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3bb802869769a40766cbc53a43b1f18e1ee316c6 --- /dev/null +++ b/tasks/traccar__traccar-5929/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5929" +description = "Use of Position.KEY_STEPS" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "2e3c087a240986aac10f01fc02d10db10af0216b" +reference = "https://github.com/traccar/traccar/pull/5929" +source_access = "auto" +built_at = "2026-11-16T16:09:42.563267+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:370921dc118b78aabe359ee8d044978f2c78280fc215b99b6463047c49541dcc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-25T14:34:09Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.498990+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d7c2e7f667a2a4be7e6176d76883c16005a9c89b7d04060a15f14870d28b5bdd" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5929/tests/capture.py b/tasks/traccar__traccar-5929/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5929/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/traccar__traccar-5929/tests/instruction.md b/tasks/traccar__traccar-5929/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e885120064e320ff8b64175b9ba8361c7e8b86ff --- /dev/null +++ b/tasks/traccar__traccar-5929/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Use of Position.KEY_STEPS + +## Description + +Use of Position.KEY_STEPS instead of custom "steps" attribute. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2e3c087a2409`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5929/tests/oracle.patch b/tasks/traccar__traccar-5929/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7986bce239c35aae55a90d13bfc2029f5753318e --- /dev/null +++ b/tasks/traccar__traccar-5929/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index f74a0de77..aae2cc7f8 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -1274,7 +1274,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + break; + case 0xF8: + if (model != null && Set.of("C5", "C5L").contains(model)) { +- position.set("steps", buf.readUnsignedShort()); ++ position.set(Position.KEY_STEPS, buf.readUnsignedShort()); + } else { + position.set(Position.PREFIX_TEMP + 2, buf.readUnsignedShort() / 10.0 - 50); + } +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 7f9e9b1ec..a388b0451 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -410,7 +410,7 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + + verifyAttribute(decoder, binary( + "7e020000760454600047450f2a0000000000000002030fed58006d0e02008f000000002606250712430104000004cc300110310100e4020163e50100e60100e7080000000600000000e10c010600030091c400ce542100ec23b286252f68fecdb286258f68fecdb286255f68fecce0d362e7acaec1e0d362b519ceb0f8024936f50101ef7e"), +- "steps", 18742); ++ Position.KEY_STEPS, 18742); + + } + diff --git a/tasks/traccar__traccar-5929/tests/test.sh b/tasks/traccar__traccar-5929/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d0ae03fb3354dd70c514b84a3d32fb09e738e860 --- /dev/null +++ b/tasks/traccar__traccar-5929/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 2e3c087a240986aac10f01fc02d10db10af0216b > "$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/traccar__traccar-5929/tests/verifier.py b/tasks/traccar__traccar-5929/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5929/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/traccar__traccar-5931/environment/Dockerfile b/tasks/traccar__traccar-5931/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d4192a10c40753fec1fe6e14c57a3d7911bfd456 --- /dev/null +++ b/tasks/traccar__traccar-5931/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 35555d03ecb50cf46b1c376dfd9ea2132edd092b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 35555d03ecb50cf46b1c376dfd9ea2132edd092b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 35555d03ecb50cf46b1c376dfd9ea2132edd092b \ + && 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/traccar__traccar-5931/instruction.md b/tasks/traccar__traccar-5931/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..973a30b8acd5c70a0d7476dfb80259680b9d1054 --- /dev/null +++ b/tasks/traccar__traccar-5931/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Make memory storage concurrent-safe + +## Description + +Update `MemoryStorage` to use concurrent collections for shared in-memory object and permission maps. + +The previous implementation used regular `HashMap` instances and exposed lazy streams over `values()`. With `database.memory=true` and `database.registerUnknown=true`, concurrent device logins can read from `getObjectsStream()` while another thread registers or updates an object, which can trigger `ConcurrentModificationException`. + +This change replaces the shared maps with `ConcurrentHashMap`, centralizes object-map creation through `getObjectMap()`, and uses concurrent permission sets. This keeps the in-memory storage behavior unchanged while making concurrent access from decoder/session threads safer. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `35555d03ecb5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5931/solution/patch.diff b/tasks/traccar__traccar-5931/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..76c69ebbb0dd8122a8a175219ba59108ad3cb73b --- /dev/null +++ b/tasks/traccar__traccar-5931/solution/patch.diff @@ -0,0 +1,90 @@ +diff --git a/src/main/java/org/traccar/storage/MemoryStorage.java b/src/main/java/org/traccar/storage/MemoryStorage.java +index 75c2058b8..48046e4da 100644 +--- a/src/main/java/org/traccar/storage/MemoryStorage.java ++++ b/src/main/java/org/traccar/storage/MemoryStorage.java +@@ -29,19 +29,19 @@ import org.traccar.storage.query.Request; + + import java.lang.invoke.MethodHandle; + import java.util.Collection; +-import java.util.HashMap; + import java.util.HashSet; + import java.util.List; + import java.util.Locale; + import java.util.Map; + import java.util.Set; ++import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.atomic.AtomicLong; + import java.util.stream.Stream; + + public class MemoryStorage extends Storage { + +- private final Map, Map> objects = new HashMap<>(); +- private final Map, Class>, Set>> permissions = new HashMap<>(); ++ private final Map, Map> objects = new ConcurrentHashMap<>(); ++ private final Map, Class>, Set>> permissions = new ConcurrentHashMap<>(); + + private final AtomicLong increment = new AtomicLong(); + +@@ -61,7 +61,7 @@ public class MemoryStorage extends Storage { + + @Override + public Stream getObjectsStream(Class clazz, Request request) { +- var stream = objects.computeIfAbsent(clazz, key -> new HashMap<>()).values().stream() ++ var stream = objects.computeIfAbsent(clazz, key -> new ConcurrentHashMap<>()).values().stream() + .filter(object -> checkCondition(request.getCondition(), object)); + Order order = request.getOrder(); + if (order != null) { +@@ -128,7 +128,7 @@ public class MemoryStorage extends Storage { + if (condition.getDeviceId() > 0 && positionDeviceId != condition.getDeviceId()) { + yield false; + } +- yield objects.computeIfAbsent(Device.class, key -> new HashMap<>()).values().stream() ++ yield objects.computeIfAbsent(Device.class, key -> new ConcurrentHashMap<>()).values().stream() + .anyMatch(device -> (Long) retrieveValue(device, "positionId") == positionId); + } + default -> false; +@@ -179,7 +179,7 @@ public class MemoryStorage extends Storage { + if (!result.add(groupId)) { + break; + } +- Object group = objects.computeIfAbsent(Group.class, key -> new HashMap<>()).get(groupId); ++ Object group = objects.computeIfAbsent(Group.class, key -> new ConcurrentHashMap<>()).get(groupId); + if (group instanceof GroupedModel parent) { + groupId = parent.getGroupId(); + } else { +@@ -200,7 +200,7 @@ public class MemoryStorage extends Storage { + @Override + public long addObject(T entity, Request request) { + long id = increment.incrementAndGet(); +- objects.computeIfAbsent(entity.getClass(), key -> new HashMap<>()).put(id, entity); ++ objects.computeIfAbsent(entity.getClass(), key -> new ConcurrentHashMap<>()).put(id, entity); + return id; + } + +@@ -209,9 +209,10 @@ public class MemoryStorage extends Storage { + Collection items; + if (request.getCondition() != null) { + long id = (Long) ((Condition.Equals) request.getCondition()).getValue(); +- items = List.of(objects.computeIfAbsent(entity.getClass(), key -> new HashMap<>()).get(id)); ++ Object item = objects.computeIfAbsent(entity.getClass(), key -> new ConcurrentHashMap<>()).get(id); ++ items = item != null ? List.of(item) : List.of(); + } else { +- items = objects.computeIfAbsent(entity.getClass(), key -> new HashMap<>()).values(); ++ items = objects.computeIfAbsent(entity.getClass(), key -> new ConcurrentHashMap<>()).values(); + } + var getters = ReflectionCache.getProperties(entity.getClass(), "get"); + var setters = ReflectionCache.getProperties(entity.getClass(), "set"); +@@ -232,11 +233,11 @@ public class MemoryStorage extends Storage { + @Override + public void removeObject(Class clazz, Request request) { + long id = (Long) ((Condition.Equals) request.getCondition()).getValue(); +- objects.computeIfAbsent(clazz, key -> new HashMap<>()).remove(id); ++ objects.computeIfAbsent(clazz, key -> new ConcurrentHashMap<>()).remove(id); + } + + private Set> getPermissionsSet(Class ownerClass, Class propertyClass) { +- return permissions.computeIfAbsent(new Pair<>(ownerClass, propertyClass), k -> new HashSet<>()); ++ return permissions.computeIfAbsent(new Pair<>(ownerClass, propertyClass), k -> ConcurrentHashMap.newKeySet()); + } + + @Override diff --git a/tasks/traccar__traccar-5931/solution/solve.sh b/tasks/traccar__traccar-5931/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5931/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/traccar__traccar-5931/task.toml b/tasks/traccar__traccar-5931/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e878c031033034b6e5e53c24106a8fc87d7f1891 --- /dev/null +++ b/tasks/traccar__traccar-5931/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5931" +description = "Make memory storage concurrent-safe" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "35555d03ecb50cf46b1c376dfd9ea2132edd092b" +reference = "https://github.com/traccar/traccar/pull/5931" +source_access = "auto" +built_at = "2026-11-16T16:09:42.564570+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:180a45d5f1426eae01aa39c75668f2f91672032a9f0a2cde551c1f7637ff19a8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-27T21:39:44Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/storage/MemoryStorage.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 23 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.499575+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:14faf2eb15f6d7a7df6b2ce0f8a272395a95285de18a582859421e79cf3215f1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5931/tests/capture.py b/tasks/traccar__traccar-5931/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5931/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/traccar__traccar-5931/tests/instruction.md b/tasks/traccar__traccar-5931/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..973a30b8acd5c70a0d7476dfb80259680b9d1054 --- /dev/null +++ b/tasks/traccar__traccar-5931/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Make memory storage concurrent-safe + +## Description + +Update `MemoryStorage` to use concurrent collections for shared in-memory object and permission maps. + +The previous implementation used regular `HashMap` instances and exposed lazy streams over `values()`. With `database.memory=true` and `database.registerUnknown=true`, concurrent device logins can read from `getObjectsStream()` while another thread registers or updates an object, which can trigger `ConcurrentModificationException`. + +This change replaces the shared maps with `ConcurrentHashMap`, centralizes object-map creation through `getObjectMap()`, and uses concurrent permission sets. This keeps the in-memory storage behavior unchanged while making concurrent access from decoder/session threads safer. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `35555d03ecb5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5931/tests/oracle.patch b/tasks/traccar__traccar-5931/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..76c69ebbb0dd8122a8a175219ba59108ad3cb73b --- /dev/null +++ b/tasks/traccar__traccar-5931/tests/oracle.patch @@ -0,0 +1,90 @@ +diff --git a/src/main/java/org/traccar/storage/MemoryStorage.java b/src/main/java/org/traccar/storage/MemoryStorage.java +index 75c2058b8..48046e4da 100644 +--- a/src/main/java/org/traccar/storage/MemoryStorage.java ++++ b/src/main/java/org/traccar/storage/MemoryStorage.java +@@ -29,19 +29,19 @@ import org.traccar.storage.query.Request; + + import java.lang.invoke.MethodHandle; + import java.util.Collection; +-import java.util.HashMap; + import java.util.HashSet; + import java.util.List; + import java.util.Locale; + import java.util.Map; + import java.util.Set; ++import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.atomic.AtomicLong; + import java.util.stream.Stream; + + public class MemoryStorage extends Storage { + +- private final Map, Map> objects = new HashMap<>(); +- private final Map, Class>, Set>> permissions = new HashMap<>(); ++ private final Map, Map> objects = new ConcurrentHashMap<>(); ++ private final Map, Class>, Set>> permissions = new ConcurrentHashMap<>(); + + private final AtomicLong increment = new AtomicLong(); + +@@ -61,7 +61,7 @@ public class MemoryStorage extends Storage { + + @Override + public Stream getObjectsStream(Class clazz, Request request) { +- var stream = objects.computeIfAbsent(clazz, key -> new HashMap<>()).values().stream() ++ var stream = objects.computeIfAbsent(clazz, key -> new ConcurrentHashMap<>()).values().stream() + .filter(object -> checkCondition(request.getCondition(), object)); + Order order = request.getOrder(); + if (order != null) { +@@ -128,7 +128,7 @@ public class MemoryStorage extends Storage { + if (condition.getDeviceId() > 0 && positionDeviceId != condition.getDeviceId()) { + yield false; + } +- yield objects.computeIfAbsent(Device.class, key -> new HashMap<>()).values().stream() ++ yield objects.computeIfAbsent(Device.class, key -> new ConcurrentHashMap<>()).values().stream() + .anyMatch(device -> (Long) retrieveValue(device, "positionId") == positionId); + } + default -> false; +@@ -179,7 +179,7 @@ public class MemoryStorage extends Storage { + if (!result.add(groupId)) { + break; + } +- Object group = objects.computeIfAbsent(Group.class, key -> new HashMap<>()).get(groupId); ++ Object group = objects.computeIfAbsent(Group.class, key -> new ConcurrentHashMap<>()).get(groupId); + if (group instanceof GroupedModel parent) { + groupId = parent.getGroupId(); + } else { +@@ -200,7 +200,7 @@ public class MemoryStorage extends Storage { + @Override + public long addObject(T entity, Request request) { + long id = increment.incrementAndGet(); +- objects.computeIfAbsent(entity.getClass(), key -> new HashMap<>()).put(id, entity); ++ objects.computeIfAbsent(entity.getClass(), key -> new ConcurrentHashMap<>()).put(id, entity); + return id; + } + +@@ -209,9 +209,10 @@ public class MemoryStorage extends Storage { + Collection items; + if (request.getCondition() != null) { + long id = (Long) ((Condition.Equals) request.getCondition()).getValue(); +- items = List.of(objects.computeIfAbsent(entity.getClass(), key -> new HashMap<>()).get(id)); ++ Object item = objects.computeIfAbsent(entity.getClass(), key -> new ConcurrentHashMap<>()).get(id); ++ items = item != null ? List.of(item) : List.of(); + } else { +- items = objects.computeIfAbsent(entity.getClass(), key -> new HashMap<>()).values(); ++ items = objects.computeIfAbsent(entity.getClass(), key -> new ConcurrentHashMap<>()).values(); + } + var getters = ReflectionCache.getProperties(entity.getClass(), "get"); + var setters = ReflectionCache.getProperties(entity.getClass(), "set"); +@@ -232,11 +233,11 @@ public class MemoryStorage extends Storage { + @Override + public void removeObject(Class clazz, Request request) { + long id = (Long) ((Condition.Equals) request.getCondition()).getValue(); +- objects.computeIfAbsent(clazz, key -> new HashMap<>()).remove(id); ++ objects.computeIfAbsent(clazz, key -> new ConcurrentHashMap<>()).remove(id); + } + + private Set> getPermissionsSet(Class ownerClass, Class propertyClass) { +- return permissions.computeIfAbsent(new Pair<>(ownerClass, propertyClass), k -> new HashSet<>()); ++ return permissions.computeIfAbsent(new Pair<>(ownerClass, propertyClass), k -> ConcurrentHashMap.newKeySet()); + } + + @Override diff --git a/tasks/traccar__traccar-5931/tests/test.sh b/tasks/traccar__traccar-5931/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c9e81ecf7582142e63e3fc0bb88fe0ccb7810dc1 --- /dev/null +++ b/tasks/traccar__traccar-5931/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 35555d03ecb50cf46b1c376dfd9ea2132edd092b > "$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/traccar__traccar-5931/tests/verifier.py b/tasks/traccar__traccar-5931/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5931/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/traccar__traccar-5936/environment/Dockerfile b/tasks/traccar__traccar-5936/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a799a81859866945b89fee4fb5e86d87d4284c21 --- /dev/null +++ b/tasks/traccar__traccar-5936/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9aea33b8418c0651f23527e596142e36ba5a9025 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9aea33b8418c0651f23527e596142e36ba5a9025 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9aea33b8418c0651f23527e596142e36ba5a9025 \ + && 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/traccar__traccar-5936/instruction.md b/tasks/traccar__traccar-5936/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21fd9aa2eb40e5c143d518729c36e21a72e4732d --- /dev/null +++ b/tasks/traccar__traccar-5936/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** Limit MemoryStorage to latest position per device + +## Description + +**The implementation is intentionally minimal and only affects `MemoryStorage`.** + +Currently, when `database.memory=true` is used, every stored position is kept in memory. For high-traffic deployments this can cause the in-memory storage to grow over time. + +Following the suggested approach, this PR updates `MemoryStorage` to keep only the latest position per device. + +### What Changed + +This change updates `MemoryStorage` position handling: + +1. When a new `Position` is added, existing positions for the same device are checked. +2. If there is no newer position for the device, older positions for that device are removed and the new position is stored. +3. If a newer position already exists, the new older position is not stored. +4. SQL-backed storage remains unchanged. + +### Benefits + +1. Prevents unbounded in-memory growth from stored positions when `database.memory=true`. +2. Preserves the latest known position for each device. +3. Keeps the existing persistence flow intact. +4. Does not add any new configuration options. +5. Does not affect SQL-backed storage. + +### Notes + +The comparison only uses `fixTime`, keeping the implementation small and local to `MemoryStorage`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9aea33b8418c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5936/solution/patch.diff b/tasks/traccar__traccar-5936/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2f4f63fabe36b4f7b2314b9c35cbddc5a4ca6918 --- /dev/null +++ b/tasks/traccar__traccar-5936/solution/patch.diff @@ -0,0 +1,37 @@ +diff --git a/src/main/java/org/traccar/storage/MemoryStorage.java b/src/main/java/org/traccar/storage/MemoryStorage.java +index 48046e4da..3b2604d33 100644 +--- a/src/main/java/org/traccar/storage/MemoryStorage.java ++++ b/src/main/java/org/traccar/storage/MemoryStorage.java +@@ -22,6 +22,7 @@ import org.traccar.model.Group; + import org.traccar.model.GroupedModel; + import org.traccar.model.Pair; + import org.traccar.model.Permission; ++import org.traccar.model.Position; + import org.traccar.model.Server; + import org.traccar.storage.query.Condition; + import org.traccar.storage.query.Order; +@@ -200,7 +201,23 @@ public class MemoryStorage extends Storage { + @Override + public long addObject(T entity, Request request) { + long id = increment.incrementAndGet(); +- objects.computeIfAbsent(entity.getClass(), key -> new ConcurrentHashMap<>()).put(id, entity); ++ var items = objects.computeIfAbsent(entity.getClass(), key -> new ConcurrentHashMap<>()); ++ ++ if (entity instanceof Position position) { ++ var iterator = items.values().iterator(); ++ while (iterator.hasNext()) { ++ Position item = (Position) iterator.next(); ++ if (item.getDeviceId() == position.getDeviceId()) { ++ if (item.getFixTime().after(position.getFixTime())) { ++ return id; ++ } ++ iterator.remove(); ++ break; ++ } ++ } ++ } ++ ++ items.put(id, entity); + return id; + } + diff --git a/tasks/traccar__traccar-5936/solution/solve.sh b/tasks/traccar__traccar-5936/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5936/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/traccar__traccar-5936/task.toml b/tasks/traccar__traccar-5936/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..af51823d82da10154f36fdeabddddac155eee308 --- /dev/null +++ b/tasks/traccar__traccar-5936/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5936" +description = "Limit MemoryStorage to latest position per device" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "9aea33b8418c0651f23527e596142e36ba5a9025" +reference = "https://github.com/traccar/traccar/pull/5936" +source_access = "auto" +built_at = "2026-11-16T16:09:42.561987+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:72631c12c4b4c296b676a87476d0b49a4d74fa106fa88a04fc174ca240ba073b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-03T10:11:20Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/storage/MemoryStorage.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 19 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.500154+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:35e52c86f5beae2d41110032109a8144bd23016a52eb2ed702425d1acbbb0735" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5936/tests/capture.py b/tasks/traccar__traccar-5936/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5936/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/traccar__traccar-5936/tests/instruction.md b/tasks/traccar__traccar-5936/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21fd9aa2eb40e5c143d518729c36e21a72e4732d --- /dev/null +++ b/tasks/traccar__traccar-5936/tests/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** Limit MemoryStorage to latest position per device + +## Description + +**The implementation is intentionally minimal and only affects `MemoryStorage`.** + +Currently, when `database.memory=true` is used, every stored position is kept in memory. For high-traffic deployments this can cause the in-memory storage to grow over time. + +Following the suggested approach, this PR updates `MemoryStorage` to keep only the latest position per device. + +### What Changed + +This change updates `MemoryStorage` position handling: + +1. When a new `Position` is added, existing positions for the same device are checked. +2. If there is no newer position for the device, older positions for that device are removed and the new position is stored. +3. If a newer position already exists, the new older position is not stored. +4. SQL-backed storage remains unchanged. + +### Benefits + +1. Prevents unbounded in-memory growth from stored positions when `database.memory=true`. +2. Preserves the latest known position for each device. +3. Keeps the existing persistence flow intact. +4. Does not add any new configuration options. +5. Does not affect SQL-backed storage. + +### Notes + +The comparison only uses `fixTime`, keeping the implementation small and local to `MemoryStorage`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9aea33b8418c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5936/tests/oracle.patch b/tasks/traccar__traccar-5936/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2f4f63fabe36b4f7b2314b9c35cbddc5a4ca6918 --- /dev/null +++ b/tasks/traccar__traccar-5936/tests/oracle.patch @@ -0,0 +1,37 @@ +diff --git a/src/main/java/org/traccar/storage/MemoryStorage.java b/src/main/java/org/traccar/storage/MemoryStorage.java +index 48046e4da..3b2604d33 100644 +--- a/src/main/java/org/traccar/storage/MemoryStorage.java ++++ b/src/main/java/org/traccar/storage/MemoryStorage.java +@@ -22,6 +22,7 @@ import org.traccar.model.Group; + import org.traccar.model.GroupedModel; + import org.traccar.model.Pair; + import org.traccar.model.Permission; ++import org.traccar.model.Position; + import org.traccar.model.Server; + import org.traccar.storage.query.Condition; + import org.traccar.storage.query.Order; +@@ -200,7 +201,23 @@ public class MemoryStorage extends Storage { + @Override + public long addObject(T entity, Request request) { + long id = increment.incrementAndGet(); +- objects.computeIfAbsent(entity.getClass(), key -> new ConcurrentHashMap<>()).put(id, entity); ++ var items = objects.computeIfAbsent(entity.getClass(), key -> new ConcurrentHashMap<>()); ++ ++ if (entity instanceof Position position) { ++ var iterator = items.values().iterator(); ++ while (iterator.hasNext()) { ++ Position item = (Position) iterator.next(); ++ if (item.getDeviceId() == position.getDeviceId()) { ++ if (item.getFixTime().after(position.getFixTime())) { ++ return id; ++ } ++ iterator.remove(); ++ break; ++ } ++ } ++ } ++ ++ items.put(id, entity); + return id; + } + diff --git a/tasks/traccar__traccar-5936/tests/test.sh b/tasks/traccar__traccar-5936/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..888fcf255a6b4cc6813546d4a5fa0070971e5c05 --- /dev/null +++ b/tasks/traccar__traccar-5936/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 9aea33b8418c0651f23527e596142e36ba5a9025 > "$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/traccar__traccar-5936/tests/verifier.py b/tasks/traccar__traccar-5936/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5936/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/traccar__traccar-5940/environment/Dockerfile b/tasks/traccar__traccar-5940/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3d659502bea5562f4dde3a05feacfb5dbd892a1e --- /dev/null +++ b/tasks/traccar__traccar-5940/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f8f043d98358a1e4949df53de8dca7b7aecf1080 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f8f043d98358a1e4949df53de8dca7b7aecf1080 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f8f043d98358a1e4949df53de8dca7b7aecf1080 \ + && 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/traccar__traccar-5940/instruction.md b/tasks/traccar__traccar-5940/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7285fa936fee1f22e0c8dfefe6ceefa94f22986 --- /dev/null +++ b/tasks/traccar__traccar-5940/instruction.md @@ -0,0 +1,57 @@ +# Issue + +**Title:** Forgotten BCE decoder issue where some BCE packets could fail completely + +## Description + +**The implementation is intentionally minimal and only affects `BceProtocolDecoder`.** + +Currently, BCE coordinates are written directly to `Position`. If a BCE record contains an invalid coordinate value, `Position.setLatitude` or `Position.setLongitude` throws an exception. + +In the affected sample, one record contains a longitude outside the valid `-180..180` range. This causes decoding to fail with `Longitude out of range`. + +This case was already present in the codebase as a disabled test with the comment `Needs to be fixed`. + +This PR fixes that case. + +### What Changed + +This change updates BCE coordinate handling: + +1. Longitude and latitude are read into local variables first. +2. The values are checked before they are set on `Position`. +3. The position is only marked as valid if both coordinates are in range. +4. Invalid BCE coordinate values no longer throw from the decoder. +5. The existing disabled BCE test case has been enabled again. + +### Benefits + +1. Fixes the known BCE `Longitude out of range` failure. +2. Keeps the existing strict validation in `Position`. +3. Keeps the change local to `BceProtocolDecoder`. +4. Keeps the implementation small. +5. Adds coverage for the known failing BCE sample. + +### Verification + +`./gradlew test --tests org.traccar.protocol.BceProtocolDecoderTest --tests org.traccar.protocol.BceFrameDecoderTest` + +### Question + +While checking BCE, I noticed that the digital input value is currently stored only as the raw `input` bitmask. + +Would it make sense to also expose this 16-bit bitmask as `in1` through `in16`? + +Suggested implementation: + +`int input = buf.readUnsignedShortLE();` +`position.set(Position.KEY_INPUT, input);` +`for (int i = 0; i < 16; i++) {` +` position.set(Position.PREFIX_IN + (i + 1), BitUtil.check(input, i));` +`}` + +This would keep the existing `input` value unchanged and additionally expose the individual input states. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f8f043d98358`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5940/solution/patch.diff b/tasks/traccar__traccar-5940/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..57c6b344d3841d93cc787e17c04103b51cbfd8d1 --- /dev/null +++ b/tasks/traccar__traccar-5940/solution/patch.diff @@ -0,0 +1,58 @@ +diff --git a/src/main/java/org/traccar/protocol/BceProtocolDecoder.java b/src/main/java/org/traccar/protocol/BceProtocolDecoder.java +index 400cc4be9..2cef7f01b 100644 +--- a/src/main/java/org/traccar/protocol/BceProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/BceProtocolDecoder.java +@@ -52,9 +52,14 @@ public class BceProtocolDecoder extends BaseProtocolDecoder { + private void decodeMask1(ByteBuf buf, int mask, Position position) { + + if (BitUtil.check(mask, 0)) { +- position.setValid(true); +- position.setLongitude(buf.readFloatLE()); +- position.setLatitude(buf.readFloatLE()); ++ int startIndex = buf.readerIndex(); ++ try { ++ position.setLongitude(buf.readFloatLE()); ++ position.setLatitude(buf.readFloatLE()); ++ position.setValid(true); ++ } catch (IllegalArgumentException e) { ++ buf.readerIndex(startIndex + 8); ++ } + position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte())); + + int status = buf.readUnsignedByte(); +diff --git a/src/test/java/org/traccar/protocol/BceProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/BceProtocolDecoderTest.java +index 1c4656cd3..b7e463004 100644 +--- a/src/test/java/org/traccar/protocol/BceProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/BceProtocolDecoderTest.java +@@ -1,28 +1,21 @@ + package org.traccar.protocol; + +-import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; + import org.traccar.ProtocolTest; + import org.traccar.model.Position; + + public class BceProtocolDecoderTest extends ProtocolTest { + +- @Disabled + @Test +- public void testDecodeFail() throws Exception { ++ public void testDecode() throws Exception { + + var decoder = inject(new BceProtocolDecoder(null)); + +- // Needs to be fixed + verifyPositions(decoder, binary( + "18ed450cf3140300c800a53a62972f7bde03c0ffffc0814000e03e354135e34b42121c55fb0000000000d18c060103025d19ab00540000000000000000000000000000000000000000000000000000000000000000000000000000000000000017b5c400000000000000010104080162a72f7bde03c0ffffc0814000ef3e8e4431e34b42061c54fc0000000000d18c060103025d19ab00540000000000000000000000000000000000000000000000000000000000000000000000000000000000000017b5c400000000000000010100000053")); + +- } +- +- @Test +- public void testDecode() throws Exception { +- +- var decoder = inject(new BceProtocolDecoder(null)); ++ verifyPositions(decoder, binary( ++ "0863450cf31403003002a5820a367d64166f07434352302e377d641603c00080400077e7a144cd9b4542131cad560100000000f880060102ad0279a2003b00000000000000000a567d64166f07434352302e577d641603c000804000a7c6f140049c4542141caa590100000000f980060102ad0279a2003b00000000000000000a667d641600a0434352300a967d64166f07434352302e977d641603c00080400083c4f140819c4542181caa5d0100000000f980060102ad0279a2003b00000000000000000aa67d64166f07434352302ea77d641603c00080400005c4f140a09c4542171caa5d0100000000f980060102ad0279a2003b00000000000000000aa67d641600a0434352300ac67d641600a0434352302e477e641603c000804000d6bff140c09d4542131c05610100000000f980060102ad0279a2004700000000000000002e577e641603c00080400069c0f140d99d4542141c11610100000000f980060102ad0279a2004700000000000000002e777e641603c000804000cec1f140089e4542141c0a640100000000f980060102ad0279a2004700000000000000002e877e641603c00080400001c2f140229e4542131c03640100000000f980060102ad0279a2004700000000000000002ec77e641603c00080400013c3f140829e4542111c0d650100000000f980060102ad0279a2004700000000000000002ee77e641603c000804000b2c4f140b39e4542171c14650100000000f980060102ad0279a2004700000000000000000aa67f641600a043435230fa")); + + verifyNull(decoder, binary( + "3ab90b71bc1503000300c10bff11")); diff --git a/tasks/traccar__traccar-5940/solution/solve.sh b/tasks/traccar__traccar-5940/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5940/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/traccar__traccar-5940/task.toml b/tasks/traccar__traccar-5940/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cda929cad69507754f949ec91350083a3de77d37 --- /dev/null +++ b/tasks/traccar__traccar-5940/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5940" +description = "Forgotten BCE decoder issue where some BCE packets could fail completely" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "f8f043d98358a1e4949df53de8dca7b7aecf1080" +reference = "https://github.com/traccar/traccar/pull/5940" +source_access = "auto" +built_at = "2026-11-16T16:09:42.560478+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3231702f2bd822b0cefad216c2a5a31f68053f496f593b2f4193c8ea1ec1a7ee" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-09T14:34:09Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/BceProtocolDecoder.java", + "src/test/java/org/traccar/protocol/BceProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 24 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.500718+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:aab728d533c3b1a31fa9a2ba32d3d1ef5b552613c227ab5a64da5efed053e133" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5940/tests/capture.py b/tasks/traccar__traccar-5940/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5940/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/traccar__traccar-5940/tests/instruction.md b/tasks/traccar__traccar-5940/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7285fa936fee1f22e0c8dfefe6ceefa94f22986 --- /dev/null +++ b/tasks/traccar__traccar-5940/tests/instruction.md @@ -0,0 +1,57 @@ +# Issue + +**Title:** Forgotten BCE decoder issue where some BCE packets could fail completely + +## Description + +**The implementation is intentionally minimal and only affects `BceProtocolDecoder`.** + +Currently, BCE coordinates are written directly to `Position`. If a BCE record contains an invalid coordinate value, `Position.setLatitude` or `Position.setLongitude` throws an exception. + +In the affected sample, one record contains a longitude outside the valid `-180..180` range. This causes decoding to fail with `Longitude out of range`. + +This case was already present in the codebase as a disabled test with the comment `Needs to be fixed`. + +This PR fixes that case. + +### What Changed + +This change updates BCE coordinate handling: + +1. Longitude and latitude are read into local variables first. +2. The values are checked before they are set on `Position`. +3. The position is only marked as valid if both coordinates are in range. +4. Invalid BCE coordinate values no longer throw from the decoder. +5. The existing disabled BCE test case has been enabled again. + +### Benefits + +1. Fixes the known BCE `Longitude out of range` failure. +2. Keeps the existing strict validation in `Position`. +3. Keeps the change local to `BceProtocolDecoder`. +4. Keeps the implementation small. +5. Adds coverage for the known failing BCE sample. + +### Verification + +`./gradlew test --tests org.traccar.protocol.BceProtocolDecoderTest --tests org.traccar.protocol.BceFrameDecoderTest` + +### Question + +While checking BCE, I noticed that the digital input value is currently stored only as the raw `input` bitmask. + +Would it make sense to also expose this 16-bit bitmask as `in1` through `in16`? + +Suggested implementation: + +`int input = buf.readUnsignedShortLE();` +`position.set(Position.KEY_INPUT, input);` +`for (int i = 0; i < 16; i++) {` +` position.set(Position.PREFIX_IN + (i + 1), BitUtil.check(input, i));` +`}` + +This would keep the existing `input` value unchanged and additionally expose the individual input states. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f8f043d98358`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5940/tests/oracle.patch b/tasks/traccar__traccar-5940/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..57c6b344d3841d93cc787e17c04103b51cbfd8d1 --- /dev/null +++ b/tasks/traccar__traccar-5940/tests/oracle.patch @@ -0,0 +1,58 @@ +diff --git a/src/main/java/org/traccar/protocol/BceProtocolDecoder.java b/src/main/java/org/traccar/protocol/BceProtocolDecoder.java +index 400cc4be9..2cef7f01b 100644 +--- a/src/main/java/org/traccar/protocol/BceProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/BceProtocolDecoder.java +@@ -52,9 +52,14 @@ public class BceProtocolDecoder extends BaseProtocolDecoder { + private void decodeMask1(ByteBuf buf, int mask, Position position) { + + if (BitUtil.check(mask, 0)) { +- position.setValid(true); +- position.setLongitude(buf.readFloatLE()); +- position.setLatitude(buf.readFloatLE()); ++ int startIndex = buf.readerIndex(); ++ try { ++ position.setLongitude(buf.readFloatLE()); ++ position.setLatitude(buf.readFloatLE()); ++ position.setValid(true); ++ } catch (IllegalArgumentException e) { ++ buf.readerIndex(startIndex + 8); ++ } + position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte())); + + int status = buf.readUnsignedByte(); +diff --git a/src/test/java/org/traccar/protocol/BceProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/BceProtocolDecoderTest.java +index 1c4656cd3..b7e463004 100644 +--- a/src/test/java/org/traccar/protocol/BceProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/BceProtocolDecoderTest.java +@@ -1,28 +1,21 @@ + package org.traccar.protocol; + +-import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; + import org.traccar.ProtocolTest; + import org.traccar.model.Position; + + public class BceProtocolDecoderTest extends ProtocolTest { + +- @Disabled + @Test +- public void testDecodeFail() throws Exception { ++ public void testDecode() throws Exception { + + var decoder = inject(new BceProtocolDecoder(null)); + +- // Needs to be fixed + verifyPositions(decoder, binary( + "18ed450cf3140300c800a53a62972f7bde03c0ffffc0814000e03e354135e34b42121c55fb0000000000d18c060103025d19ab00540000000000000000000000000000000000000000000000000000000000000000000000000000000000000017b5c400000000000000010104080162a72f7bde03c0ffffc0814000ef3e8e4431e34b42061c54fc0000000000d18c060103025d19ab00540000000000000000000000000000000000000000000000000000000000000000000000000000000000000017b5c400000000000000010100000053")); + +- } +- +- @Test +- public void testDecode() throws Exception { +- +- var decoder = inject(new BceProtocolDecoder(null)); ++ verifyPositions(decoder, binary( ++ "0863450cf31403003002a5820a367d64166f07434352302e377d641603c00080400077e7a144cd9b4542131cad560100000000f880060102ad0279a2003b00000000000000000a567d64166f07434352302e577d641603c000804000a7c6f140049c4542141caa590100000000f980060102ad0279a2003b00000000000000000a667d641600a0434352300a967d64166f07434352302e977d641603c00080400083c4f140819c4542181caa5d0100000000f980060102ad0279a2003b00000000000000000aa67d64166f07434352302ea77d641603c00080400005c4f140a09c4542171caa5d0100000000f980060102ad0279a2003b00000000000000000aa67d641600a0434352300ac67d641600a0434352302e477e641603c000804000d6bff140c09d4542131c05610100000000f980060102ad0279a2004700000000000000002e577e641603c00080400069c0f140d99d4542141c11610100000000f980060102ad0279a2004700000000000000002e777e641603c000804000cec1f140089e4542141c0a640100000000f980060102ad0279a2004700000000000000002e877e641603c00080400001c2f140229e4542131c03640100000000f980060102ad0279a2004700000000000000002ec77e641603c00080400013c3f140829e4542111c0d650100000000f980060102ad0279a2004700000000000000002ee77e641603c000804000b2c4f140b39e4542171c14650100000000f980060102ad0279a2004700000000000000000aa67f641600a043435230fa")); + + verifyNull(decoder, binary( + "3ab90b71bc1503000300c10bff11")); diff --git a/tasks/traccar__traccar-5940/tests/test.sh b/tasks/traccar__traccar-5940/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..32375119e4ffe2a3a83f3e671625168987152ee1 --- /dev/null +++ b/tasks/traccar__traccar-5940/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 f8f043d98358a1e4949df53de8dca7b7aecf1080 > "$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/traccar__traccar-5940/tests/verifier.py b/tasks/traccar__traccar-5940/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5940/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/traccar__traccar-5954/environment/Dockerfile b/tasks/traccar__traccar-5954/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d787097115ef88677b3224ff2187aaf1ba5e19ba --- /dev/null +++ b/tasks/traccar__traccar-5954/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c659809365e0995a3682460946dd33e340b51074 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c659809365e0995a3682460946dd33e340b51074 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c659809365e0995a3682460946dd33e340b51074 \ + && 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/traccar__traccar-5954/instruction.md b/tasks/traccar__traccar-5954/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..447bee142471d60c495b90f2c6d8e170363ba4dd --- /dev/null +++ b/tasks/traccar__traccar-5954/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Include conflicting port in log + +## Description + +Include the connector port in the warning logged when a BindException occurs, while preserving the original exception. + +Expose the configured port through TrackerConnector so ServerManager can include it in the warning. + +Testing: +- ./gradlew check + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c659809365e0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5954/solution/patch.diff b/tasks/traccar__traccar-5954/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3535945125a568f6fb564da920d47e26f15ce1bd --- /dev/null +++ b/tasks/traccar__traccar-5954/solution/patch.diff @@ -0,0 +1,54 @@ +diff --git a/src/main/java/org/traccar/ServerManager.java b/src/main/java/org/traccar/ServerManager.java +index 1b0c441cf..c6b3698c2 100644 +--- a/src/main/java/org/traccar/ServerManager.java ++++ b/src/main/java/org/traccar/ServerManager.java +@@ -73,7 +73,7 @@ public class ServerManager implements LifecycleObject { + try { + connector.start(); + } catch (BindException e) { +- LOGGER.warn("Port disabled due to conflict", e); ++ LOGGER.warn("Port {} disabled due to conflict", connector.getPort(), e); + } catch (ConnectException e) { + LOGGER.warn("Connection failed", e); + } +diff --git a/src/main/java/org/traccar/TrackerClient.java b/src/main/java/org/traccar/TrackerClient.java +index 15c15a266..820d0c302 100644 +--- a/src/main/java/org/traccar/TrackerClient.java ++++ b/src/main/java/org/traccar/TrackerClient.java +@@ -97,6 +97,11 @@ public abstract class TrackerClient implements TrackerConnector { + return devices; + } + ++ @Override ++ public int getPort() { ++ return port; ++ } ++ + @Override + public ChannelGroup getChannelGroup() { + return channelGroup; +diff --git a/src/main/java/org/traccar/TrackerConnector.java b/src/main/java/org/traccar/TrackerConnector.java +index fc6e93399..5fccccebb 100644 +--- a/src/main/java/org/traccar/TrackerConnector.java ++++ b/src/main/java/org/traccar/TrackerConnector.java +@@ -23,6 +23,8 @@ public interface TrackerConnector extends LifecycleObject { + + boolean isSecure(); + ++ int getPort(); ++ + ChannelGroup getChannelGroup(); + + } +diff --git a/src/main/java/org/traccar/TrackerServer.java b/src/main/java/org/traccar/TrackerServer.java +index 3fec3515c..0732f23ff 100644 +--- a/src/main/java/org/traccar/TrackerServer.java ++++ b/src/main/java/org/traccar/TrackerServer.java +@@ -97,6 +97,7 @@ public abstract class TrackerServer implements TrackerConnector { + + protected abstract void addProtocolHandlers(PipelineBuilder pipeline, Config config); + ++ @Override + public int getPort() { + return port; + } diff --git a/tasks/traccar__traccar-5954/solution/solve.sh b/tasks/traccar__traccar-5954/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5954/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/traccar__traccar-5954/task.toml b/tasks/traccar__traccar-5954/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd20518ade84e77a573badfbf3dd51e5586566ba --- /dev/null +++ b/tasks/traccar__traccar-5954/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5954" +description = "Include conflicting port in log" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "c659809365e0995a3682460946dd33e340b51074" +reference = "https://github.com/traccar/traccar/pull/5954" +source_access = "auto" +built_at = "2026-11-16T16:09:42.558744+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b955bf58c31de52bd4d1af1e5e7ac2c3813f47ba40deda935b11fc3be09cf0b8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-23T01:42:07Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/ServerManager.java", + "src/main/java/org/traccar/TrackerClient.java", + "src/main/java/org/traccar/TrackerConnector.java", + "src/main/java/org/traccar/TrackerServer.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 10 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.501330+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:082e8673883b21da27cbe4f28642eedcdde79ea0b595f29c6585053ae67b4988" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5954/tests/capture.py b/tasks/traccar__traccar-5954/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5954/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/traccar__traccar-5954/tests/instruction.md b/tasks/traccar__traccar-5954/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..447bee142471d60c495b90f2c6d8e170363ba4dd --- /dev/null +++ b/tasks/traccar__traccar-5954/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Include conflicting port in log + +## Description + +Include the connector port in the warning logged when a BindException occurs, while preserving the original exception. + +Expose the configured port through TrackerConnector so ServerManager can include it in the warning. + +Testing: +- ./gradlew check + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c659809365e0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5954/tests/oracle.patch b/tasks/traccar__traccar-5954/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3535945125a568f6fb564da920d47e26f15ce1bd --- /dev/null +++ b/tasks/traccar__traccar-5954/tests/oracle.patch @@ -0,0 +1,54 @@ +diff --git a/src/main/java/org/traccar/ServerManager.java b/src/main/java/org/traccar/ServerManager.java +index 1b0c441cf..c6b3698c2 100644 +--- a/src/main/java/org/traccar/ServerManager.java ++++ b/src/main/java/org/traccar/ServerManager.java +@@ -73,7 +73,7 @@ public class ServerManager implements LifecycleObject { + try { + connector.start(); + } catch (BindException e) { +- LOGGER.warn("Port disabled due to conflict", e); ++ LOGGER.warn("Port {} disabled due to conflict", connector.getPort(), e); + } catch (ConnectException e) { + LOGGER.warn("Connection failed", e); + } +diff --git a/src/main/java/org/traccar/TrackerClient.java b/src/main/java/org/traccar/TrackerClient.java +index 15c15a266..820d0c302 100644 +--- a/src/main/java/org/traccar/TrackerClient.java ++++ b/src/main/java/org/traccar/TrackerClient.java +@@ -97,6 +97,11 @@ public abstract class TrackerClient implements TrackerConnector { + return devices; + } + ++ @Override ++ public int getPort() { ++ return port; ++ } ++ + @Override + public ChannelGroup getChannelGroup() { + return channelGroup; +diff --git a/src/main/java/org/traccar/TrackerConnector.java b/src/main/java/org/traccar/TrackerConnector.java +index fc6e93399..5fccccebb 100644 +--- a/src/main/java/org/traccar/TrackerConnector.java ++++ b/src/main/java/org/traccar/TrackerConnector.java +@@ -23,6 +23,8 @@ public interface TrackerConnector extends LifecycleObject { + + boolean isSecure(); + ++ int getPort(); ++ + ChannelGroup getChannelGroup(); + + } +diff --git a/src/main/java/org/traccar/TrackerServer.java b/src/main/java/org/traccar/TrackerServer.java +index 3fec3515c..0732f23ff 100644 +--- a/src/main/java/org/traccar/TrackerServer.java ++++ b/src/main/java/org/traccar/TrackerServer.java +@@ -97,6 +97,7 @@ public abstract class TrackerServer implements TrackerConnector { + + protected abstract void addProtocolHandlers(PipelineBuilder pipeline, Config config); + ++ @Override + public int getPort() { + return port; + } diff --git a/tasks/traccar__traccar-5954/tests/test.sh b/tasks/traccar__traccar-5954/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..33835c1bc72b254f4cf6082fa22a911f1a87e2ce --- /dev/null +++ b/tasks/traccar__traccar-5954/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 c659809365e0995a3682460946dd33e340b51074 > "$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/traccar__traccar-5954/tests/verifier.py b/tasks/traccar__traccar-5954/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5954/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/traccar__traccar-5965/environment/Dockerfile b/tasks/traccar__traccar-5965/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..da1093cff5671757f1df1e89963b4a47b922543f --- /dev/null +++ b/tasks/traccar__traccar-5965/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin eb941d59b7cbdf1d8662da6d90f1253977cf575f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard eb941d59b7cbdf1d8662da6d90f1253977cf575f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base eb941d59b7cbdf1d8662da6d90f1253977cf575f \ + && 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/traccar__traccar-5965/instruction.md b/tasks/traccar__traccar-5965/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14eccfeefcc4c975975c81a5045ed7a93732881f --- /dev/null +++ b/tasks/traccar__traccar-5965/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** Support {uniqueId} placeholder in custom commands + +## Description + +## Summary +- Expand `{uniqueId}` in custom command `data` at send time from the target device. +- Central hook in `CommandsManager` so live, SMS, queue, group, and notificator sends all get the same behavior. +- Fixes + +## Test plan +- [x] Unit tests (`CommandUtilTest`) +- [x] Lab on 6.14.5: outbound log showed real device id substituted for `{uniqueId}` +- [x] Developer's Production Instance: one saved custom command works across multiple devices, each getting its own id +- [ ] Reviewer: one saved custom command, two devices, each gets its own id + +Made with [Cursor](https://cursor.com) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `eb941d59b7cb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5965/solution/patch.diff b/tasks/traccar__traccar-5965/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9cbbbcfe02a8d8edeb4f52dee4a0cb9a79cf6a7f --- /dev/null +++ b/tasks/traccar__traccar-5965/solution/patch.diff @@ -0,0 +1,22 @@ +diff --git a/src/main/java/org/traccar/database/CommandsManager.java b/src/main/java/org/traccar/database/CommandsManager.java +index a90a7122e..497f0e8f2 100644 +--- a/src/main/java/org/traccar/database/CommandsManager.java ++++ b/src/main/java/org/traccar/database/CommandsManager.java +@@ -1,5 +1,5 @@ + /* +- * Copyright 2017 - 2025 Anton Tananaev (anton@traccar.org) ++ * Copyright 2017 - 2026 Anton Tananaev (anton@traccar.org) + * Copyright 2017 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); +@@ -79,6 +79,10 @@ public class CommandsManager implements BroadcastInterface { + long deviceId = command.getDeviceId(); + Device device = storage.getObject(Device.class, new Request( + new Columns.All(), new Condition.Equals("id", deviceId))); ++ String data = command.getString(Command.KEY_DATA); ++ if (data != null && data.contains("{uniqueId}")) { ++ command.set(Command.KEY_DATA, data.replace("{uniqueId}", device.getUniqueId())); ++ } + Position position = storage.getObject(Position.class, new Request( + new Columns.All(), + new Condition.And( diff --git a/tasks/traccar__traccar-5965/solution/solve.sh b/tasks/traccar__traccar-5965/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5965/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/traccar__traccar-5965/task.toml b/tasks/traccar__traccar-5965/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cd68dfe9588aca722d1487597d63b249e59cb67e --- /dev/null +++ b/tasks/traccar__traccar-5965/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5965" +description = "Support {uniqueId} placeholder in custom commands" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "eb941d59b7cbdf1d8662da6d90f1253977cf575f" +reference = "https://github.com/traccar/traccar/pull/5965" +source_access = "auto" +built_at = "2026-11-16T16:09:42.552380+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:03af24e2092493a8859f81d28ba6dc8502a30e8343933c0d37208d66afc4f0f2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-19T12:09:07Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/database/CommandsManager.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.501973+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e430708d0af360303d14ece0af7fec2069f7146e26be2040e08ef2d750d7ce5e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5965/tests/capture.py b/tasks/traccar__traccar-5965/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5965/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/traccar__traccar-5965/tests/instruction.md b/tasks/traccar__traccar-5965/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14eccfeefcc4c975975c81a5045ed7a93732881f --- /dev/null +++ b/tasks/traccar__traccar-5965/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** Support {uniqueId} placeholder in custom commands + +## Description + +## Summary +- Expand `{uniqueId}` in custom command `data` at send time from the target device. +- Central hook in `CommandsManager` so live, SMS, queue, group, and notificator sends all get the same behavior. +- Fixes + +## Test plan +- [x] Unit tests (`CommandUtilTest`) +- [x] Lab on 6.14.5: outbound log showed real device id substituted for `{uniqueId}` +- [x] Developer's Production Instance: one saved custom command works across multiple devices, each getting its own id +- [ ] Reviewer: one saved custom command, two devices, each gets its own id + +Made with [Cursor](https://cursor.com) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `eb941d59b7cb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5965/tests/oracle.patch b/tasks/traccar__traccar-5965/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9cbbbcfe02a8d8edeb4f52dee4a0cb9a79cf6a7f --- /dev/null +++ b/tasks/traccar__traccar-5965/tests/oracle.patch @@ -0,0 +1,22 @@ +diff --git a/src/main/java/org/traccar/database/CommandsManager.java b/src/main/java/org/traccar/database/CommandsManager.java +index a90a7122e..497f0e8f2 100644 +--- a/src/main/java/org/traccar/database/CommandsManager.java ++++ b/src/main/java/org/traccar/database/CommandsManager.java +@@ -1,5 +1,5 @@ + /* +- * Copyright 2017 - 2025 Anton Tananaev (anton@traccar.org) ++ * Copyright 2017 - 2026 Anton Tananaev (anton@traccar.org) + * Copyright 2017 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); +@@ -79,6 +79,10 @@ public class CommandsManager implements BroadcastInterface { + long deviceId = command.getDeviceId(); + Device device = storage.getObject(Device.class, new Request( + new Columns.All(), new Condition.Equals("id", deviceId))); ++ String data = command.getString(Command.KEY_DATA); ++ if (data != null && data.contains("{uniqueId}")) { ++ command.set(Command.KEY_DATA, data.replace("{uniqueId}", device.getUniqueId())); ++ } + Position position = storage.getObject(Position.class, new Request( + new Columns.All(), + new Condition.And( diff --git a/tasks/traccar__traccar-5965/tests/test.sh b/tasks/traccar__traccar-5965/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3103cce88d85b732a58a660ead6d9d9f85cc0ea6 --- /dev/null +++ b/tasks/traccar__traccar-5965/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 eb941d59b7cbdf1d8662da6d90f1253977cf575f > "$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/traccar__traccar-5965/tests/verifier.py b/tasks/traccar__traccar-5965/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5965/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/traccar__traccar-5972/environment/Dockerfile b/tasks/traccar__traccar-5972/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b3c2f90eb5af85cbd62a51a5f7ddf2623583e3d --- /dev/null +++ b/tasks/traccar__traccar-5972/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7b0407d54a259f7bdc4ac82f3c3d49730b319ee9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7b0407d54a259f7bdc4ac82f3c3d49730b319ee9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7b0407d54a259f7bdc4ac82f3c3d49730b319ee9 \ + && 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/traccar__traccar-5972/instruction.md b/tasks/traccar__traccar-5972/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ca614fc39514edcbb8431e87f05a9e7b4c42f710 --- /dev/null +++ b/tasks/traccar__traccar-5972/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** Serve path-suffixed well-known discovery endpoints + +## Description + +`WellKnownServlet` matches only the bare metadata paths, for example `/.well-known/oauth-authorization-server`. + +RFC 8414 (section 3.1) and RFC 9728 (section 3.1) specify that the resource path component is inserted *between* the well-known URI and the rest of the path, so a compliant client requests `/.well-known/oauth-authorization-server/api/oidc` instead. That returns 404 today, which leaves MCP clients unable to complete authorization discovery and is the cause of the blank authorization page reported in the [forum thread](https://www.traccar.org/forums/topic/mcp-function-how-can-the-documentation-can-found/). + +This normalizes the request path so both the bare and path-suffixed forms resolve to the same metadata. The suffix has to match the endpoint it belongs to, so `/oauth-protected-resource/api/oidc` and `/openid-configuration/api/mcp` still fall through to 404 rather than silently returning the wrong document. + +Testing: +- `./gradlew build` +- Added `WellKnownServletTest` covering bare paths, correctly suffixed paths, mismatched suffixes, unknown paths and a null path. + +This is the first of a series splitting up #5970, as requested. The parts are independent of each other except where noted. + +--- +Disclosure: written with AI assistance (Claude), reviewed and tested by me against a production instance. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7b0407d54a25`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5972/solution/patch.diff b/tasks/traccar__traccar-5972/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c8e580bc67e90b9c1737854dd57b22d6e9064db6 --- /dev/null +++ b/tasks/traccar__traccar-5972/solution/patch.diff @@ -0,0 +1,19 @@ +diff --git a/src/main/java/org/traccar/web/WellKnownServlet.java b/src/main/java/org/traccar/web/WellKnownServlet.java +index 20a1f6d50..6bdcc93f1 100644 +--- a/src/main/java/org/traccar/web/WellKnownServlet.java ++++ b/src/main/java/org/traccar/web/WellKnownServlet.java +@@ -46,9 +46,11 @@ public class WellKnownServlet extends HttpServlet { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + String path = req.getPathInfo(); + Map payload = switch (path) { +- case "/openid-configuration" -> openIdConfiguration(); +- case "/oauth-authorization-server" -> authorizationServerConfiguration(); +- case "/oauth-protected-resource" -> protectedResourceConfiguration(); ++ case "/openid-configuration", "/openid-configuration/api/oidc" -> openIdConfiguration(); ++ case "/oauth-authorization-server", "/oauth-authorization-server/api/oidc" -> ++ authorizationServerConfiguration(); ++ case "/oauth-protected-resource", "/oauth-protected-resource/api/mcp" -> ++ protectedResourceConfiguration(); + default -> null; + }; + if (payload != null) { diff --git a/tasks/traccar__traccar-5972/solution/solve.sh b/tasks/traccar__traccar-5972/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5972/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/traccar__traccar-5972/task.toml b/tasks/traccar__traccar-5972/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a670eb8ec7b820c3bd75cc08c1c7a210046ae86b --- /dev/null +++ b/tasks/traccar__traccar-5972/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5972" +description = "Serve path-suffixed well-known discovery endpoints" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "7b0407d54a259f7bdc4ac82f3c3d49730b319ee9" +reference = "https://github.com/traccar/traccar/pull/5972" +source_access = "auto" +built_at = "2026-11-16T16:09:42.553903+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8e63bbf724590001bf51c4cce869e48acb9765a98377cfa7fd65417d9f716f60" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-08T10:52:24Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/web/WellKnownServlet.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.502585+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4262f497364393d1a1aecfdafe8fb57a64a884f84bb3299024ad3b25fa47d1d6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5972/tests/capture.py b/tasks/traccar__traccar-5972/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5972/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/traccar__traccar-5972/tests/instruction.md b/tasks/traccar__traccar-5972/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ca614fc39514edcbb8431e87f05a9e7b4c42f710 --- /dev/null +++ b/tasks/traccar__traccar-5972/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** Serve path-suffixed well-known discovery endpoints + +## Description + +`WellKnownServlet` matches only the bare metadata paths, for example `/.well-known/oauth-authorization-server`. + +RFC 8414 (section 3.1) and RFC 9728 (section 3.1) specify that the resource path component is inserted *between* the well-known URI and the rest of the path, so a compliant client requests `/.well-known/oauth-authorization-server/api/oidc` instead. That returns 404 today, which leaves MCP clients unable to complete authorization discovery and is the cause of the blank authorization page reported in the [forum thread](https://www.traccar.org/forums/topic/mcp-function-how-can-the-documentation-can-found/). + +This normalizes the request path so both the bare and path-suffixed forms resolve to the same metadata. The suffix has to match the endpoint it belongs to, so `/oauth-protected-resource/api/oidc` and `/openid-configuration/api/mcp` still fall through to 404 rather than silently returning the wrong document. + +Testing: +- `./gradlew build` +- Added `WellKnownServletTest` covering bare paths, correctly suffixed paths, mismatched suffixes, unknown paths and a null path. + +This is the first of a series splitting up #5970, as requested. The parts are independent of each other except where noted. + +--- +Disclosure: written with AI assistance (Claude), reviewed and tested by me against a production instance. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7b0407d54a25`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5972/tests/oracle.patch b/tasks/traccar__traccar-5972/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c8e580bc67e90b9c1737854dd57b22d6e9064db6 --- /dev/null +++ b/tasks/traccar__traccar-5972/tests/oracle.patch @@ -0,0 +1,19 @@ +diff --git a/src/main/java/org/traccar/web/WellKnownServlet.java b/src/main/java/org/traccar/web/WellKnownServlet.java +index 20a1f6d50..6bdcc93f1 100644 +--- a/src/main/java/org/traccar/web/WellKnownServlet.java ++++ b/src/main/java/org/traccar/web/WellKnownServlet.java +@@ -46,9 +46,11 @@ public class WellKnownServlet extends HttpServlet { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + String path = req.getPathInfo(); + Map payload = switch (path) { +- case "/openid-configuration" -> openIdConfiguration(); +- case "/oauth-authorization-server" -> authorizationServerConfiguration(); +- case "/oauth-protected-resource" -> protectedResourceConfiguration(); ++ case "/openid-configuration", "/openid-configuration/api/oidc" -> openIdConfiguration(); ++ case "/oauth-authorization-server", "/oauth-authorization-server/api/oidc" -> ++ authorizationServerConfiguration(); ++ case "/oauth-protected-resource", "/oauth-protected-resource/api/mcp" -> ++ protectedResourceConfiguration(); + default -> null; + }; + if (payload != null) { diff --git a/tasks/traccar__traccar-5972/tests/test.sh b/tasks/traccar__traccar-5972/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7f22eca98766ac4a1935ababcac6ed5abd47f1a8 --- /dev/null +++ b/tasks/traccar__traccar-5972/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 7b0407d54a259f7bdc4ac82f3c3d49730b319ee9 > "$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/traccar__traccar-5972/tests/verifier.py b/tasks/traccar__traccar-5972/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5972/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/traccar__traccar-5974/environment/Dockerfile b/tasks/traccar__traccar-5974/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9ebacbd80826bf71255c87d20044058df2874164 --- /dev/null +++ b/tasks/traccar__traccar-5974/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f28f60e8647a25b9e42f1720d07db76fba72da52 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f28f60e8647a25b9e42f1720d07db76fba72da52 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f28f60e8647a25b9e42f1720d07db76fba72da52 \ + && 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/traccar__traccar-5974/instruction.md b/tasks/traccar__traccar-5974/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73a56a3fa961cebb334e064d5c0f17644dc6327d --- /dev/null +++ b/tasks/traccar__traccar-5974/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Add read-only annotations to MCP tools + +## Description + +The MCP tools carry no annotations, so a client cannot tell that they only read data and may prompt for confirmation before calling them. + +This marks both tools read-only and non-destructive. No behaviour change. + +Testing: `./gradlew build` + +Part of the split of #5970. This is the base of the MCP series; the remaining MCP parts build on it in order. + +--- +Disclosure: written with AI assistance (Claude), reviewed and tested by me against a production instance. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f28f60e8647a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5974/solution/patch.diff b/tasks/traccar__traccar-5974/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..440def7cadcd11b23c62ec030b128e6efeb2da8e --- /dev/null +++ b/tasks/traccar__traccar-5974/solution/patch.diff @@ -0,0 +1,30 @@ +diff --git a/src/main/java/org/traccar/web/McpServerHolder.java b/src/main/java/org/traccar/web/McpServerHolder.java +index 1b6c1d316..8805341ee 100644 +--- a/src/main/java/org/traccar/web/McpServerHolder.java ++++ b/src/main/java/org/traccar/web/McpServerHolder.java +@@ -52,6 +52,9 @@ public class McpServerHolder implements AutoCloseable { + + public static final String PATH = "/api/mcp"; + ++ private static final McpSchema.ToolAnnotations READ_ONLY_ANNOTATIONS = new McpSchema.ToolAnnotations( ++ null, true, false, true, false, null); ++ + private final Storage storage; + private final Provider permissionsService; + private final Geocoder geocoder; +@@ -110,6 +113,7 @@ public class McpServerHolder implements AutoCloseable { + .name("traccar-version") + .title("Returns server version name") + .inputSchema(inputSchema) ++ .annotations(READ_ONLY_ANNOTATIONS) + .build(); + + return McpServerFeatures.AsyncToolSpecification.builder() +@@ -138,6 +142,7 @@ public class McpServerHolder implements AutoCloseable { + .name("device-position") + .title("Returns latest device position with address and other parameters") + .inputSchema(inputSchema) ++ .annotations(READ_ONLY_ANNOTATIONS) + .build(); + + return McpServerFeatures.AsyncToolSpecification.builder() diff --git a/tasks/traccar__traccar-5974/solution/solve.sh b/tasks/traccar__traccar-5974/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5974/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/traccar__traccar-5974/task.toml b/tasks/traccar__traccar-5974/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..947477aad43ed2e3f01c8a9fd4e553fcf543b37a --- /dev/null +++ b/tasks/traccar__traccar-5974/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5974" +description = "Add read-only annotations to MCP tools" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "f28f60e8647a25b9e42f1720d07db76fba72da52" +reference = "https://github.com/traccar/traccar/pull/5974" +source_access = "auto" +built_at = "2026-11-16T16:09:42.547539+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9f938ea283acfd9b9495f8c895fc04bc710099cbbaa132b05202ee16c9bd7bcf" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-26T13:10:37Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/web/McpServerHolder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.503158+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2dc175dd368909ee1f66f68f3f2c858fa2e4ae52bf81db43142ed15807fe838" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5974/tests/capture.py b/tasks/traccar__traccar-5974/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5974/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/traccar__traccar-5974/tests/instruction.md b/tasks/traccar__traccar-5974/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73a56a3fa961cebb334e064d5c0f17644dc6327d --- /dev/null +++ b/tasks/traccar__traccar-5974/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Add read-only annotations to MCP tools + +## Description + +The MCP tools carry no annotations, so a client cannot tell that they only read data and may prompt for confirmation before calling them. + +This marks both tools read-only and non-destructive. No behaviour change. + +Testing: `./gradlew build` + +Part of the split of #5970. This is the base of the MCP series; the remaining MCP parts build on it in order. + +--- +Disclosure: written with AI assistance (Claude), reviewed and tested by me against a production instance. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f28f60e8647a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5974/tests/oracle.patch b/tasks/traccar__traccar-5974/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..440def7cadcd11b23c62ec030b128e6efeb2da8e --- /dev/null +++ b/tasks/traccar__traccar-5974/tests/oracle.patch @@ -0,0 +1,30 @@ +diff --git a/src/main/java/org/traccar/web/McpServerHolder.java b/src/main/java/org/traccar/web/McpServerHolder.java +index 1b6c1d316..8805341ee 100644 +--- a/src/main/java/org/traccar/web/McpServerHolder.java ++++ b/src/main/java/org/traccar/web/McpServerHolder.java +@@ -52,6 +52,9 @@ public class McpServerHolder implements AutoCloseable { + + public static final String PATH = "/api/mcp"; + ++ private static final McpSchema.ToolAnnotations READ_ONLY_ANNOTATIONS = new McpSchema.ToolAnnotations( ++ null, true, false, true, false, null); ++ + private final Storage storage; + private final Provider permissionsService; + private final Geocoder geocoder; +@@ -110,6 +113,7 @@ public class McpServerHolder implements AutoCloseable { + .name("traccar-version") + .title("Returns server version name") + .inputSchema(inputSchema) ++ .annotations(READ_ONLY_ANNOTATIONS) + .build(); + + return McpServerFeatures.AsyncToolSpecification.builder() +@@ -138,6 +142,7 @@ public class McpServerHolder implements AutoCloseable { + .name("device-position") + .title("Returns latest device position with address and other parameters") + .inputSchema(inputSchema) ++ .annotations(READ_ONLY_ANNOTATIONS) + .build(); + + return McpServerFeatures.AsyncToolSpecification.builder() diff --git a/tasks/traccar__traccar-5974/tests/test.sh b/tasks/traccar__traccar-5974/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d72e3febb074a42c3f79c9190a23511c2f4a2963 --- /dev/null +++ b/tasks/traccar__traccar-5974/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 f28f60e8647a25b9e42f1720d07db76fba72da52 > "$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/traccar__traccar-5974/tests/verifier.py b/tasks/traccar__traccar-5974/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5974/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/traccar__traccar-5984/environment/Dockerfile b/tasks/traccar__traccar-5984/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..92a0dcb6bb8179b6862cb9083c64c7de7569c55a --- /dev/null +++ b/tasks/traccar__traccar-5984/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fe971bcefd695785f9ae7ddca08665a9d97506d8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fe971bcefd695785f9ae7ddca08665a9d97506d8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fe971bcefd695785f9ae7ddca08665a9d97506d8 \ + && 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/traccar__traccar-5984/instruction.md b/tasks/traccar__traccar-5984/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..161bc340e8f54bc081341724b4f961d69610fdb0 --- /dev/null +++ b/tasks/traccar__traccar-5984/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** Support Akroz reports in TAIP protocol + +## Description + +Adds support for the reports used by Akroz Telematics trackers, as part of the existing TAIP protocol rather than as a new decoder. + +You were right that it is a TAIP variation. The devices reuse the TAIP envelope — the `>` … `;ID=…;#…;*XX<` framing and the same encoding for coordinates, speed, course and status flags — with their own report formats. The manufacturer identifies the protocol as `NT003`, which is the fixed second field of every message, and the reports are prefixed `RUV` followed by the format number. + +Protocol documentation: the manufacturer publishes it at https://wiki.newtectelemetria.com.br/pt-br/vl08-guia-homologacao — that page is access-restricted, so I've attached the relevant sections as a PDF to this PR. +Sample messages: included in the unit tests, captured from a device in the field. + +### Reports + +- `RUV00` — presentation report sent on connection: serial number, firmware and hardware versions, supply voltages and ICCID. It carries no position, so it reports the last known location. +- `RUV01` — position and status: battery and power voltage, engine hours, odometer, RPM, coolant temperature, oil pressure, fuel level, driver unique id +- `RUV02` — end of trip: trip duration, trip distance, fuel used +- `RUV03` — CAN/engine report: throttle, engine hours, odometer, RPM, coolant temperature, oil pressure, fuel level, fuel used, OBD speed, engine torque, engine brake, cruise control, clutch, parking brake, service brake + +`RUV01` to `RUV03` share a status block with the date, position, fix quality, ignition, main power, digital inputs and HDOP. It is decoded by a separate pattern because the header carries the report format and the protocol identifier ahead of the position. + +### Acknowledgement + +These devices retransmit indefinitely until a report is acknowledged, so the acknowledgement is sent before decoding, independently of whether the device is known or the payload parses. They also compute the XOR up to the last `;`, excluding the `*`, which is the same convention already handled for Lantrix devices — with the default calculation the acknowledgement is rejected. + +### Events + +Event codes are reported as `KEY_EVENT`. The subset with a standard equivalent is additionally reported as an alarm: overspeed, high RPM, idle, temperature, hard acceleration, hard braking, hard cornering, power cut, power restored and low battery. + +### Tests + +Seven cases added to `TaipProtocolDecoderTest`, covering the four report formats with both real device captures and samples from the manufacturer documentation. Verified against a live device as well. + +[Protocolo_XVM_NT003_RUV.pdf](https://github.com/user-attachments/files/31203646/Protocolo_XVM_NT003_RUV.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fe971bcefd69`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5984/solution/patch.diff b/tasks/traccar__traccar-5984/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..eedd4a2cc0a81c05414c96b813115ab2b0aa9881 --- /dev/null +++ b/tasks/traccar__traccar-5984/solution/patch.diff @@ -0,0 +1,243 @@ +diff --git a/src/main/java/org/traccar/protocol/TaipProtocolDecoder.java b/src/main/java/org/traccar/protocol/TaipProtocolDecoder.java +index 7e92eeeab..cbcbe30ef 100644 +--- a/src/main/java/org/traccar/protocol/TaipProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TaipProtocolDecoder.java +@@ -49,12 +49,15 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + .groupEnd("?") + .number("(d{5})") // seconds + .or() +- .expression("(?:RGP|RCQ|RCV|RBR|RUS00|RPI),?") // type +- .number("(dd)?") // event +- .number("(dd)(dd)(dd)") // date (mmddyy) ++ .expression("(?:RGP|RCQ|RCV|RBR|RUS00|RPI|RUV[0-9]{2}),?") // type ++ .number("(d+)?") // event ++ .expression(",?") ++ .expression("(?:[A-Z][A-Z0-9]*,)?") // protocol ++ .number("(dd)(dd)(dd)") // date (ddmmyy) + .number("(dd)(dd)(dd)") // time (hhmmss) + .groupEnd() + .groupBegin() ++ .groupBegin() + .number("([-+]dd)(d{5})") // latitude + .number("([-+]ddd)(d{5})") // longitude + .or() +@@ -64,7 +67,7 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + .number("(ddd)") // speed + .number("(ddd)") // course + .groupBegin() +- .number("([023])") // fix mode ++ .number("(d)") // fix mode + .number("xx") // data age + .number("(xx)") // input + .groupBegin() +@@ -105,6 +108,7 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + .groupEnd("?") + .groupEnd("?") + .groupEnd() ++ .groupEnd("?") + .any() + .compile(); + +@@ -156,6 +160,8 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + return null; + } + ++ boolean isAkroz = sentence.startsWith("RUV"); ++ + Position position = new Position(getProtocolName()); + + Boolean valid = null; +@@ -176,22 +182,29 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS)); + } + ++ boolean located = false; + if (parser.hasNext(4)) { + position.setLatitude(parser.nextCoordinate(Parser.CoordinateFormat.DEG_DEG)); + position.setLongitude(parser.nextCoordinate(Parser.CoordinateFormat.DEG_DEG)); ++ located = true; + } + if (parser.hasNext(6)) { + position.setLatitude(parser.nextCoordinate(Parser.CoordinateFormat.HEM_DEG_MIN)); + position.setLongitude(parser.nextCoordinate(Parser.CoordinateFormat.HEM_DEG_MIN)); ++ located = true; + } + +- position.setSpeed(convertSpeed(parser.nextDouble(0), "mph")); ++ position.setSpeed(convertSpeed(parser.nextDouble(0), isAkroz ? "kmh" : "mph")); + position.setCourse(parser.nextDouble(0)); + + if (parser.hasNext(2)) { +- valid = parser.nextInt() > 0; ++ int fixMode = parser.nextInt(); ++ valid = isAkroz ? fixMode >= 2 && fixMode < 8 : fixMode > 0; + int input = parser.nextHexInt(); + position.set(Position.KEY_IGNITION, BitUtil.check(input, 7)); ++ if (isAkroz) { ++ position.set(Position.KEY_CHARGE, BitUtil.check(input, 6)); ++ } + position.set(Position.KEY_INPUT, input); + } + +@@ -206,7 +219,10 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + } + + if (parser.hasNext(2)) { +- event = parser.nextInt(); ++ int value = parser.nextInt(); ++ if (!isAkroz) { ++ event = value; ++ } + position.set(Position.KEY_HDOP, parser.nextInt()); + } + +@@ -228,9 +244,70 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + + position.setValid(valid == null || valid); + ++ if (isAkroz) { ++ String[] values = sentence.substring(0, sentence.indexOf(';')).split(",", -1); ++ int index = 3; ++ switch (Integer.parseInt(sentence.substring(3, 5))) { ++ case 0 -> { ++ String voltage = values[index++]; ++ position.set(Position.KEY_BATTERY, Integer.parseInt(voltage.substring(0, 4)) * 0.01); ++ position.set(Position.KEY_POWER, Integer.parseInt(voltage.substring(4)) * 0.01); ++ position.set("serial", values[index++]); ++ position.set(Position.KEY_VERSION_FW, values[index++]); ++ position.set(Position.KEY_VERSION_HW, values[index++]); ++ index += 5; ++ if (!values[index].isEmpty()) { ++ position.set(Position.KEY_ICCID, values[index]); ++ } ++ } ++ case 1 -> { ++ String voltage = values[index++]; ++ position.set(Position.KEY_BATTERY, Integer.parseInt(voltage.substring(0, 4)) * 0.01); ++ position.set(Position.KEY_POWER, Integer.parseInt(voltage.substring(4)) * 0.01); ++ index += 3; ++ position.set(Position.KEY_HOURS, Long.parseLong(values[index++]) * 60000); ++ position.set(Position.KEY_ODOMETER, Long.parseLong(values[index++])); ++ position.set(Position.KEY_RPM, Integer.parseInt(values[index++])); ++ position.set(Position.KEY_COOLANT_TEMP, Integer.parseInt(values[index++])); ++ position.set("oilPressure", Integer.parseInt(values[index++])); ++ position.set(Position.KEY_FUEL_LEVEL, Integer.parseInt(values[index++])); ++ index += 3; ++ position.set(Position.KEY_DRIVER_UNIQUE_ID, values[index]); ++ } ++ case 2 -> { ++ index += 8; ++ position.set("tripTime", Integer.parseInt(values[index++])); ++ position.set("tripDistance", Long.parseLong(values[index++])); ++ position.set(Position.KEY_FUEL_USED, Long.parseLong(values[index]) / 10.0); ++ } ++ default -> { ++ position.set(Position.KEY_THROTTLE, Integer.parseInt(values[index++])); ++ position.set(Position.KEY_HOURS, Long.parseLong(values[index++]) * 60000); ++ position.set(Position.KEY_ODOMETER, Long.parseLong(values[index++])); ++ position.set(Position.KEY_RPM, Integer.parseInt(values[index++])); ++ position.set(Position.KEY_COOLANT_TEMP, Integer.parseInt(values[index++])); ++ position.set("oilPressure", Integer.parseInt(values[index++])); ++ position.set(Position.KEY_FUEL_LEVEL, Integer.parseInt(values[index++])); ++ position.set(Position.KEY_FUEL_USED, Long.parseLong(values[index++]) / 10.0); ++ index += 1; ++ position.set(Position.KEY_OBD_SPEED, Integer.parseInt(values[index++])); ++ position.set("engineTorque", Integer.parseInt(values[index++])); ++ index += 1; ++ position.set("engineBrake", Integer.parseInt(values[index++])); ++ index += 3; ++ position.set("cruiseControl", BitUtil.check(Integer.parseInt(values[index++]), 0)); ++ position.set("clutchState", BitUtil.check(Integer.parseInt(values[index++]), 6)); ++ position.set("parkingBrake", BitUtil.check(Integer.parseInt(values[index++]), 2)); ++ position.set("serviceBrake", BitUtil.check(Integer.parseInt(values[index]), 3)); ++ } ++ } ++ } ++ + if (event != null) { + position.set(Position.KEY_EVENT, event); +- if (sentence.charAt(5) == ',') { ++ if (isAkroz) { ++ position.addAlarm(decodeAlarmAkroz(event)); ++ } else if (sentence.charAt(5) == ',') { + position.addAlarm(decodeAlarm2(event)); + } else { + position.addAlarm(decodeAlarm(event)); +@@ -238,20 +315,41 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + } + + String[] attributes = null; +- beginIndex = sentence.indexOf(';'); +- if (beginIndex != -1) { +- int endIndex = sentence.indexOf('<', beginIndex); ++ int beginAttributes = sentence.indexOf(';'); ++ if (beginAttributes != -1) { ++ int endIndex = sentence.indexOf('<', beginAttributes); + if (endIndex == -1) { + endIndex = sentence.length(); + } +- attributes = sentence.substring(beginIndex, endIndex).split(";"); ++ attributes = sentence.substring(beginAttributes, endIndex).split(";"); + } + +- return decodeAttributes(channel, remoteAddress, position, attributes); ++ Position result = decodeAttributes(channel, remoteAddress, position, attributes, isAkroz); ++ if (result != null && !located) { ++ getLastLocation(result, result.getDeviceTime()); ++ } ++ return result; ++ } ++ ++ private String decodeAlarmAkroz(int event) { ++ return switch (event) { ++ case 104, 106 -> Position.ALARM_OVERSPEED; ++ case 109 -> Position.ALARM_HIGH_RPM; ++ case 111 -> Position.ALARM_IDLE; ++ case 119 -> Position.ALARM_TEMPERATURE; ++ case 120 -> Position.ALARM_ACCELERATION; ++ case 121 -> Position.ALARM_BRAKING; ++ case 122 -> Position.ALARM_CORNERING; ++ case 127 -> Position.ALARM_POWER_CUT; ++ case 128 -> Position.ALARM_POWER_RESTORED; ++ case 129 -> Position.ALARM_LOW_BATTERY; ++ default -> null; ++ }; + } + + private Position decodeAttributes( +- Channel channel, SocketAddress remoteAddress, Position position, String[] attributes) { ++ Channel channel, SocketAddress remoteAddress, Position position, String[] attributes, ++ boolean plainChecksum) { + + String uniqueId = null; + DeviceSession deviceSession = null; +diff --git a/src/test/java/org/traccar/protocol/TaipProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/TaipProtocolDecoderTest.java +index a8b6d3f3f..f968c93d4 100644 +--- a/src/test/java/org/traccar/protocol/TaipProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/TaipProtocolDecoderTest.java +@@ -117,6 +117,25 @@ public class TaipProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, text( + ">RPV19105+4538405-0739518900000012;ID=9999;*7A<\r\n")); + ++ verifyAttribute(decoder, text( ++ ">RUV0000,NT003,190826125922,00111595,39K40156,0B36 F,203 V,V1.5,JMAK,0,0,0,;ID=FWHS;#0004;*03<"), ++ Position.KEY_VERSION_FW, "0B36 F"); ++ ++ verifyAttribute(decoder, text( ++ ">RUV01120,NT003,190826131202-2353539-046680190500009FFDE0006,00111596,0,0,0,0,50000,500,0,0,0,0,0,4G:0,00000;ID=FWHS;#1A04;*50<"), ++ Position.KEY_ALARM, Position.ALARM_ACCELERATION); ++ ++ verifyAttribute(decoder, text( ++ ">RUV01111,NT003,190826132746-2353539-046680190000009FFDE0006,00111585,0,0,0,16,50000,500,0,0,50,0,0,4G:0,00000;ID=FWHS;#1A69;*5A<"), ++ Position.KEY_ALARM, Position.ALARM_IDLE); ++ ++ verifyAttribute(decoder, text( ++ ">RUV02108,NT003,190826131734-2353539-046680190000009FF5E0006,384,0,0,0,0,385,0,323,6,50000,51515;ID=FWHS;#1A2A;*31<"), ++ Position.KEY_FUEL_USED, 5151.5); ++ ++ verifyPosition(decoder, text( ++ ">RUV03150,NT003,190826131748-2353539-046680190000009FFDE0006,0,6,50000,500,0,0,50,51515,0,0,0,0,0,0,0,0,0,0,0,0;ID=FWHS;#1A2D;*6D<")); ++ + } + + } diff --git a/tasks/traccar__traccar-5984/solution/solve.sh b/tasks/traccar__traccar-5984/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5984/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/traccar__traccar-5984/task.toml b/tasks/traccar__traccar-5984/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0f2680ace19da0ba9f8e3bb9672511ad1fb8ed9f --- /dev/null +++ b/tasks/traccar__traccar-5984/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5984" +description = "Support Akroz reports in TAIP protocol" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "fe971bcefd695785f9ae7ddca08665a9d97506d8" +reference = "https://github.com/traccar/traccar/pull/5984" +source_access = "auto" +built_at = "2026-11-16T16:09:42.550529+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4c25dd7448a86b92ccbc62d4eafd543036a048d9dee1706e186244596f174aef" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-20T13:50:43Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/TaipProtocolDecoder.java", + "src/test/java/org/traccar/protocol/TaipProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 145 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.503736+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:195508974ba891f5e290f11faf19b0f3edcd6f4585ffbd17b4ee28304cf52bdb" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5984/tests/capture.py b/tasks/traccar__traccar-5984/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5984/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/traccar__traccar-5984/tests/instruction.md b/tasks/traccar__traccar-5984/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..161bc340e8f54bc081341724b4f961d69610fdb0 --- /dev/null +++ b/tasks/traccar__traccar-5984/tests/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** Support Akroz reports in TAIP protocol + +## Description + +Adds support for the reports used by Akroz Telematics trackers, as part of the existing TAIP protocol rather than as a new decoder. + +You were right that it is a TAIP variation. The devices reuse the TAIP envelope — the `>` … `;ID=…;#…;*XX<` framing and the same encoding for coordinates, speed, course and status flags — with their own report formats. The manufacturer identifies the protocol as `NT003`, which is the fixed second field of every message, and the reports are prefixed `RUV` followed by the format number. + +Protocol documentation: the manufacturer publishes it at https://wiki.newtectelemetria.com.br/pt-br/vl08-guia-homologacao — that page is access-restricted, so I've attached the relevant sections as a PDF to this PR. +Sample messages: included in the unit tests, captured from a device in the field. + +### Reports + +- `RUV00` — presentation report sent on connection: serial number, firmware and hardware versions, supply voltages and ICCID. It carries no position, so it reports the last known location. +- `RUV01` — position and status: battery and power voltage, engine hours, odometer, RPM, coolant temperature, oil pressure, fuel level, driver unique id +- `RUV02` — end of trip: trip duration, trip distance, fuel used +- `RUV03` — CAN/engine report: throttle, engine hours, odometer, RPM, coolant temperature, oil pressure, fuel level, fuel used, OBD speed, engine torque, engine brake, cruise control, clutch, parking brake, service brake + +`RUV01` to `RUV03` share a status block with the date, position, fix quality, ignition, main power, digital inputs and HDOP. It is decoded by a separate pattern because the header carries the report format and the protocol identifier ahead of the position. + +### Acknowledgement + +These devices retransmit indefinitely until a report is acknowledged, so the acknowledgement is sent before decoding, independently of whether the device is known or the payload parses. They also compute the XOR up to the last `;`, excluding the `*`, which is the same convention already handled for Lantrix devices — with the default calculation the acknowledgement is rejected. + +### Events + +Event codes are reported as `KEY_EVENT`. The subset with a standard equivalent is additionally reported as an alarm: overspeed, high RPM, idle, temperature, hard acceleration, hard braking, hard cornering, power cut, power restored and low battery. + +### Tests + +Seven cases added to `TaipProtocolDecoderTest`, covering the four report formats with both real device captures and samples from the manufacturer documentation. Verified against a live device as well. + +[Protocolo_XVM_NT003_RUV.pdf](https://github.com/user-attachments/files/31203646/Protocolo_XVM_NT003_RUV.pdf) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fe971bcefd69`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5984/tests/oracle.patch b/tasks/traccar__traccar-5984/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..eedd4a2cc0a81c05414c96b813115ab2b0aa9881 --- /dev/null +++ b/tasks/traccar__traccar-5984/tests/oracle.patch @@ -0,0 +1,243 @@ +diff --git a/src/main/java/org/traccar/protocol/TaipProtocolDecoder.java b/src/main/java/org/traccar/protocol/TaipProtocolDecoder.java +index 7e92eeeab..cbcbe30ef 100644 +--- a/src/main/java/org/traccar/protocol/TaipProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TaipProtocolDecoder.java +@@ -49,12 +49,15 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + .groupEnd("?") + .number("(d{5})") // seconds + .or() +- .expression("(?:RGP|RCQ|RCV|RBR|RUS00|RPI),?") // type +- .number("(dd)?") // event +- .number("(dd)(dd)(dd)") // date (mmddyy) ++ .expression("(?:RGP|RCQ|RCV|RBR|RUS00|RPI|RUV[0-9]{2}),?") // type ++ .number("(d+)?") // event ++ .expression(",?") ++ .expression("(?:[A-Z][A-Z0-9]*,)?") // protocol ++ .number("(dd)(dd)(dd)") // date (ddmmyy) + .number("(dd)(dd)(dd)") // time (hhmmss) + .groupEnd() + .groupBegin() ++ .groupBegin() + .number("([-+]dd)(d{5})") // latitude + .number("([-+]ddd)(d{5})") // longitude + .or() +@@ -64,7 +67,7 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + .number("(ddd)") // speed + .number("(ddd)") // course + .groupBegin() +- .number("([023])") // fix mode ++ .number("(d)") // fix mode + .number("xx") // data age + .number("(xx)") // input + .groupBegin() +@@ -105,6 +108,7 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + .groupEnd("?") + .groupEnd("?") + .groupEnd() ++ .groupEnd("?") + .any() + .compile(); + +@@ -156,6 +160,8 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + return null; + } + ++ boolean isAkroz = sentence.startsWith("RUV"); ++ + Position position = new Position(getProtocolName()); + + Boolean valid = null; +@@ -176,22 +182,29 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS)); + } + ++ boolean located = false; + if (parser.hasNext(4)) { + position.setLatitude(parser.nextCoordinate(Parser.CoordinateFormat.DEG_DEG)); + position.setLongitude(parser.nextCoordinate(Parser.CoordinateFormat.DEG_DEG)); ++ located = true; + } + if (parser.hasNext(6)) { + position.setLatitude(parser.nextCoordinate(Parser.CoordinateFormat.HEM_DEG_MIN)); + position.setLongitude(parser.nextCoordinate(Parser.CoordinateFormat.HEM_DEG_MIN)); ++ located = true; + } + +- position.setSpeed(convertSpeed(parser.nextDouble(0), "mph")); ++ position.setSpeed(convertSpeed(parser.nextDouble(0), isAkroz ? "kmh" : "mph")); + position.setCourse(parser.nextDouble(0)); + + if (parser.hasNext(2)) { +- valid = parser.nextInt() > 0; ++ int fixMode = parser.nextInt(); ++ valid = isAkroz ? fixMode >= 2 && fixMode < 8 : fixMode > 0; + int input = parser.nextHexInt(); + position.set(Position.KEY_IGNITION, BitUtil.check(input, 7)); ++ if (isAkroz) { ++ position.set(Position.KEY_CHARGE, BitUtil.check(input, 6)); ++ } + position.set(Position.KEY_INPUT, input); + } + +@@ -206,7 +219,10 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + } + + if (parser.hasNext(2)) { +- event = parser.nextInt(); ++ int value = parser.nextInt(); ++ if (!isAkroz) { ++ event = value; ++ } + position.set(Position.KEY_HDOP, parser.nextInt()); + } + +@@ -228,9 +244,70 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + + position.setValid(valid == null || valid); + ++ if (isAkroz) { ++ String[] values = sentence.substring(0, sentence.indexOf(';')).split(",", -1); ++ int index = 3; ++ switch (Integer.parseInt(sentence.substring(3, 5))) { ++ case 0 -> { ++ String voltage = values[index++]; ++ position.set(Position.KEY_BATTERY, Integer.parseInt(voltage.substring(0, 4)) * 0.01); ++ position.set(Position.KEY_POWER, Integer.parseInt(voltage.substring(4)) * 0.01); ++ position.set("serial", values[index++]); ++ position.set(Position.KEY_VERSION_FW, values[index++]); ++ position.set(Position.KEY_VERSION_HW, values[index++]); ++ index += 5; ++ if (!values[index].isEmpty()) { ++ position.set(Position.KEY_ICCID, values[index]); ++ } ++ } ++ case 1 -> { ++ String voltage = values[index++]; ++ position.set(Position.KEY_BATTERY, Integer.parseInt(voltage.substring(0, 4)) * 0.01); ++ position.set(Position.KEY_POWER, Integer.parseInt(voltage.substring(4)) * 0.01); ++ index += 3; ++ position.set(Position.KEY_HOURS, Long.parseLong(values[index++]) * 60000); ++ position.set(Position.KEY_ODOMETER, Long.parseLong(values[index++])); ++ position.set(Position.KEY_RPM, Integer.parseInt(values[index++])); ++ position.set(Position.KEY_COOLANT_TEMP, Integer.parseInt(values[index++])); ++ position.set("oilPressure", Integer.parseInt(values[index++])); ++ position.set(Position.KEY_FUEL_LEVEL, Integer.parseInt(values[index++])); ++ index += 3; ++ position.set(Position.KEY_DRIVER_UNIQUE_ID, values[index]); ++ } ++ case 2 -> { ++ index += 8; ++ position.set("tripTime", Integer.parseInt(values[index++])); ++ position.set("tripDistance", Long.parseLong(values[index++])); ++ position.set(Position.KEY_FUEL_USED, Long.parseLong(values[index]) / 10.0); ++ } ++ default -> { ++ position.set(Position.KEY_THROTTLE, Integer.parseInt(values[index++])); ++ position.set(Position.KEY_HOURS, Long.parseLong(values[index++]) * 60000); ++ position.set(Position.KEY_ODOMETER, Long.parseLong(values[index++])); ++ position.set(Position.KEY_RPM, Integer.parseInt(values[index++])); ++ position.set(Position.KEY_COOLANT_TEMP, Integer.parseInt(values[index++])); ++ position.set("oilPressure", Integer.parseInt(values[index++])); ++ position.set(Position.KEY_FUEL_LEVEL, Integer.parseInt(values[index++])); ++ position.set(Position.KEY_FUEL_USED, Long.parseLong(values[index++]) / 10.0); ++ index += 1; ++ position.set(Position.KEY_OBD_SPEED, Integer.parseInt(values[index++])); ++ position.set("engineTorque", Integer.parseInt(values[index++])); ++ index += 1; ++ position.set("engineBrake", Integer.parseInt(values[index++])); ++ index += 3; ++ position.set("cruiseControl", BitUtil.check(Integer.parseInt(values[index++]), 0)); ++ position.set("clutchState", BitUtil.check(Integer.parseInt(values[index++]), 6)); ++ position.set("parkingBrake", BitUtil.check(Integer.parseInt(values[index++]), 2)); ++ position.set("serviceBrake", BitUtil.check(Integer.parseInt(values[index]), 3)); ++ } ++ } ++ } ++ + if (event != null) { + position.set(Position.KEY_EVENT, event); +- if (sentence.charAt(5) == ',') { ++ if (isAkroz) { ++ position.addAlarm(decodeAlarmAkroz(event)); ++ } else if (sentence.charAt(5) == ',') { + position.addAlarm(decodeAlarm2(event)); + } else { + position.addAlarm(decodeAlarm(event)); +@@ -238,20 +315,41 @@ public class TaipProtocolDecoder extends BaseProtocolDecoder { + } + + String[] attributes = null; +- beginIndex = sentence.indexOf(';'); +- if (beginIndex != -1) { +- int endIndex = sentence.indexOf('<', beginIndex); ++ int beginAttributes = sentence.indexOf(';'); ++ if (beginAttributes != -1) { ++ int endIndex = sentence.indexOf('<', beginAttributes); + if (endIndex == -1) { + endIndex = sentence.length(); + } +- attributes = sentence.substring(beginIndex, endIndex).split(";"); ++ attributes = sentence.substring(beginAttributes, endIndex).split(";"); + } + +- return decodeAttributes(channel, remoteAddress, position, attributes); ++ Position result = decodeAttributes(channel, remoteAddress, position, attributes, isAkroz); ++ if (result != null && !located) { ++ getLastLocation(result, result.getDeviceTime()); ++ } ++ return result; ++ } ++ ++ private String decodeAlarmAkroz(int event) { ++ return switch (event) { ++ case 104, 106 -> Position.ALARM_OVERSPEED; ++ case 109 -> Position.ALARM_HIGH_RPM; ++ case 111 -> Position.ALARM_IDLE; ++ case 119 -> Position.ALARM_TEMPERATURE; ++ case 120 -> Position.ALARM_ACCELERATION; ++ case 121 -> Position.ALARM_BRAKING; ++ case 122 -> Position.ALARM_CORNERING; ++ case 127 -> Position.ALARM_POWER_CUT; ++ case 128 -> Position.ALARM_POWER_RESTORED; ++ case 129 -> Position.ALARM_LOW_BATTERY; ++ default -> null; ++ }; + } + + private Position decodeAttributes( +- Channel channel, SocketAddress remoteAddress, Position position, String[] attributes) { ++ Channel channel, SocketAddress remoteAddress, Position position, String[] attributes, ++ boolean plainChecksum) { + + String uniqueId = null; + DeviceSession deviceSession = null; +diff --git a/src/test/java/org/traccar/protocol/TaipProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/TaipProtocolDecoderTest.java +index a8b6d3f3f..f968c93d4 100644 +--- a/src/test/java/org/traccar/protocol/TaipProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/TaipProtocolDecoderTest.java +@@ -117,6 +117,25 @@ public class TaipProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, text( + ">RPV19105+4538405-0739518900000012;ID=9999;*7A<\r\n")); + ++ verifyAttribute(decoder, text( ++ ">RUV0000,NT003,190826125922,00111595,39K40156,0B36 F,203 V,V1.5,JMAK,0,0,0,;ID=FWHS;#0004;*03<"), ++ Position.KEY_VERSION_FW, "0B36 F"); ++ ++ verifyAttribute(decoder, text( ++ ">RUV01120,NT003,190826131202-2353539-046680190500009FFDE0006,00111596,0,0,0,0,50000,500,0,0,0,0,0,4G:0,00000;ID=FWHS;#1A04;*50<"), ++ Position.KEY_ALARM, Position.ALARM_ACCELERATION); ++ ++ verifyAttribute(decoder, text( ++ ">RUV01111,NT003,190826132746-2353539-046680190000009FFDE0006,00111585,0,0,0,16,50000,500,0,0,50,0,0,4G:0,00000;ID=FWHS;#1A69;*5A<"), ++ Position.KEY_ALARM, Position.ALARM_IDLE); ++ ++ verifyAttribute(decoder, text( ++ ">RUV02108,NT003,190826131734-2353539-046680190000009FF5E0006,384,0,0,0,0,385,0,323,6,50000,51515;ID=FWHS;#1A2A;*31<"), ++ Position.KEY_FUEL_USED, 5151.5); ++ ++ verifyPosition(decoder, text( ++ ">RUV03150,NT003,190826131748-2353539-046680190000009FFDE0006,0,6,50000,500,0,0,50,51515,0,0,0,0,0,0,0,0,0,0,0,0;ID=FWHS;#1A2D;*6D<")); ++ + } + + } diff --git a/tasks/traccar__traccar-5984/tests/test.sh b/tasks/traccar__traccar-5984/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a5f8af99c8cc544f24c6a37c4d0c7504e5aebdf --- /dev/null +++ b/tasks/traccar__traccar-5984/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 fe971bcefd695785f9ae7ddca08665a9d97506d8 > "$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/traccar__traccar-5984/tests/verifier.py b/tasks/traccar__traccar-5984/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5984/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/traccar__traccar-5997/environment/Dockerfile b/tasks/traccar__traccar-5997/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d35250a7f81912cff6d59879b1abe3545ff600a --- /dev/null +++ b/tasks/traccar__traccar-5997/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b15554cf3f9808dc462d412834896fe0634a4e0e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b15554cf3f9808dc462d412834896fe0634a4e0e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b15554cf3f9808dc462d412834896fe0634a4e0e \ + && 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/traccar__traccar-5997/instruction.md b/tasks/traccar__traccar-5997/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4acdede8e38b490cefa7cfb96145d2b61b8ccc93 --- /dev/null +++ b/tasks/traccar__traccar-5997/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Decode JT808 location query and parameter query responses + +## Description + +### Summary +Split out the **decoder** part of the JT808 work. The encoder side (new command types) is kept in a separate PR. + +### Decoder changes (`Jt808ProtocolDecoder.java`) +- Decode `0x0201` (location query response): reply with a general response and parse the embedded location. +- Decode `0x0104` (parameter query response) and map the parameters real devices actually report: + - `0x0001` → heartbeat interval + - `0x0010` → APN + - `0x0013` → server address + - `0x0018` → server TCP port + - `0x0027` → ignition-off interval + - `0x0028` → report interval + - `0x0029` → ignition-on interval + - `0x0055` → overspeed speed threshold + - `0x0056` → overspeed duration + - `0x0080` → odometer + +### Tests +- `testDecodeLocationQueryResponse` uses a **real device capture**. +- `testDecodeParameterQueryResponse` uses a **real device capture**. +- All `Jt808ProtocolDecoderTest` tests pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b15554cf3f98`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5997/solution/patch.diff b/tasks/traccar__traccar-5997/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9752100b8e6b851fd97c1060a39bde5e90612a1b --- /dev/null +++ b/tasks/traccar__traccar-5997/solution/patch.diff @@ -0,0 +1,140 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index aa3e76961..bc865b755 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -57,6 +57,9 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter + .ofPattern("yyyyMMddHHmmss").withZone(ZoneOffset.UTC); + ++ private static final Charset CHARSET_GBK = ++ Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII; ++ + public Jt808ProtocolDecoder(Protocol protocol) { + super(protocol); + } +@@ -73,6 +76,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_TERMINAL_AUTH = 0x0102; + public static final int MSG_TERMINAL_ATTRIBUTES = 0x0107; + public static final int MSG_LOCATION_REPORT = 0x0200; ++ public static final int MSG_LOCATION_QUERY_RESPONSE = 0x0201; + public static final int MSG_LOCATION_BATCH_2 = 0x0210; + public static final int MSG_ACCELERATION = 0x2070; + public static final int MSG_LOCATION_REPORT_2 = 0x5501; +@@ -94,6 +98,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_DRIVER_IDENTITY = 0x0702; + public static final int MSG_VIDEO_REQUEST = 0x9101; + public static final int MSG_VIDEO_CONTROL = 0x9102; ++ public static final int MSG_PARAMETER_QUERY_RESPONSE = 0x0104; + public static final int MSG_PARAMETER_QUERY_ALL = 0x8104; + public static final int MSG_LOCATION_QUERY = 0x8201; + public static final int MSG_TEMPORARY_TRACKING = 0x8202; +@@ -401,9 +406,8 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + getLastLocation(position, null); + + buf.readUnsignedByte(); // encoding +- Charset charset = Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII; + +- position.set(Position.KEY_RESULT, buf.readCharSequence(buf.readableBytes() - 2, charset).toString()); ++ position.set(Position.KEY_RESULT, buf.readCharSequence(buf.readableBytes() - 2, CHARSET_GBK).toString()); + + return position; + +@@ -469,6 +473,12 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + requestAttachments(channel, remoteAddress, id, position); + return position; + ++ } else if (type == MSG_LOCATION_QUERY_RESPONSE) { ++ ++ buf.readUnsignedShort(); // response serial number ++ ++ return decodeLocation(deviceSession, buf); ++ + } else if (type == MSG_LOCATION_REPORT_2 || type == MSG_LOCATION_REPORT_BLIND) { + + if (BitUtil.check(attribute, 15)) { +@@ -575,6 +585,66 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + + return position; + ++ } else if (type == MSG_PARAMETER_QUERY_RESPONSE) { ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ getLastLocation(position, null); ++ ++ buf.readUnsignedShort(); // response serial number ++ buf.readUnsignedByte(); // parameter count ++ ++ while (buf.readableBytes() - 2 >= 5) { ++ ++ int subtype = buf.readInt(); ++ int length = buf.readUnsignedByte(); ++ int endIndex = buf.readerIndex() + length; ++ if (endIndex > buf.writerIndex() - 2) { ++ break; ++ } ++ switch (subtype) { ++ case 0x0001: ++ position.set("heartbeatInterval", buf.readUnsignedInt()); ++ break; ++ case 0x0010: ++ position.set("apn", buf.readCharSequence(length, CHARSET_GBK).toString()); ++ break; ++ case 0x0013: ++ position.set("server", buf.readCharSequence(length, CHARSET_GBK).toString()); ++ break; ++ case 0x0018: ++ position.set("port", buf.readUnsignedInt()); ++ break; ++ case 0x0027: ++ position.set("sleepReportInterval", buf.readUnsignedInt()); ++ break; ++ case 0x0028: ++ position.set("emergencyReportInterval", buf.readUnsignedInt()); ++ break; ++ case 0x0029: ++ position.set("defaultReportInterval", buf.readUnsignedInt()); ++ break; ++ case 0x0055: ++ position.set("overspeedThreshold", buf.readUnsignedInt()); ++ break; ++ case 0x0056: ++ position.set("speedLimitDuration", buf.readUnsignedInt()); ++ break; ++ case 0x0080: ++ position.set(Position.KEY_ODOMETER, buf.readUnsignedInt() * 100); ++ break; ++ case 0x0083: ++ position.set("plateNumber", buf.readCharSequence(length, CHARSET_GBK).toString().trim()); ++ break; ++ default: ++ break; ++ } ++ buf.readerIndex(endIndex); ++ } ++ ++ return position; ++ + } + + return null; +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 2574435f9..d3d43caff 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -433,6 +433,14 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7E09000049487060054219000E54100000000000000000000000000000000000240112034640001F2401120345210C4100F4011C00F3FFE80008004003FE001F2401120345510C4100F4011C00F3FFF0000800A003FEB67E"), + Position.KEY_DEVICE_TEMP, 24.4); + ++ verifyPosition(decoder, binary( ++ "7e0201003c0145382363912db0000000000000000000020101313605bb3b58000c000001292608251203040104000b620beb16000c00b28995018202107439115800060089fffffffece7e"), ++ position("2026-08-25 04:03:04.000", true, 16.85535, 96.156504)); ++ ++ verifyAttribute(decoder, binary( ++ "7e0104018502453031334908d600002c0000000104000000b400000002040000000000000003040000000000000004040000000000000005040000000000000006040000000000000007040000000000000010066d70746e657400000011000000001200000000130f3136382e3134342e3130342e32323400000014000000001500000000160000000017000000001804000013970000001904000000000000002004000000000000002104000000000000002204000000000000002704000001f400000028040000000000000029040000000a0000002c04000000000000003004000000140000005004000000000000005204000000000000005304000000000000005504000000000000005604000000050000005704000000000000005804000000000000005904000000000000005a04000000000000007004000000000000007104000000000000007204000000000000007304000000000000007404000000000000008004000000000000008102002c0000008202012f000000830cd4c142383838383820202020000000840101787e"), ++ "plateNumber", "粤B88888"); ++ + } + + } diff --git a/tasks/traccar__traccar-5997/solution/solve.sh b/tasks/traccar__traccar-5997/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5997/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/traccar__traccar-5997/task.toml b/tasks/traccar__traccar-5997/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..566457ddfad4c0a290a0be55bb352b2be0b6b779 --- /dev/null +++ b/tasks/traccar__traccar-5997/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5997" +description = "Decode JT808 location query and parameter query responses" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "b15554cf3f9808dc462d412834896fe0634a4e0e" +reference = "https://github.com/traccar/traccar/pull/5997" +source_access = "auto" +built_at = "2026-11-16T16:09:42.544263+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:df97a4471181528cd7466f5782c3bc517ded6f93f088d9991a8ff0ae975e3436" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-06T13:31:18Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 82 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.504487+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2aff0ef241ec03e6e88c1737365613e9b3ec3b735c954c7ec4395fb5984805d1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5997/tests/capture.py b/tasks/traccar__traccar-5997/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5997/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/traccar__traccar-5997/tests/instruction.md b/tasks/traccar__traccar-5997/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4acdede8e38b490cefa7cfb96145d2b61b8ccc93 --- /dev/null +++ b/tasks/traccar__traccar-5997/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Decode JT808 location query and parameter query responses + +## Description + +### Summary +Split out the **decoder** part of the JT808 work. The encoder side (new command types) is kept in a separate PR. + +### Decoder changes (`Jt808ProtocolDecoder.java`) +- Decode `0x0201` (location query response): reply with a general response and parse the embedded location. +- Decode `0x0104` (parameter query response) and map the parameters real devices actually report: + - `0x0001` → heartbeat interval + - `0x0010` → APN + - `0x0013` → server address + - `0x0018` → server TCP port + - `0x0027` → ignition-off interval + - `0x0028` → report interval + - `0x0029` → ignition-on interval + - `0x0055` → overspeed speed threshold + - `0x0056` → overspeed duration + - `0x0080` → odometer + +### Tests +- `testDecodeLocationQueryResponse` uses a **real device capture**. +- `testDecodeParameterQueryResponse` uses a **real device capture**. +- All `Jt808ProtocolDecoderTest` tests pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b15554cf3f98`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5997/tests/oracle.patch b/tasks/traccar__traccar-5997/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9752100b8e6b851fd97c1060a39bde5e90612a1b --- /dev/null +++ b/tasks/traccar__traccar-5997/tests/oracle.patch @@ -0,0 +1,140 @@ +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index aa3e76961..bc865b755 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -57,6 +57,9 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter + .ofPattern("yyyyMMddHHmmss").withZone(ZoneOffset.UTC); + ++ private static final Charset CHARSET_GBK = ++ Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII; ++ + public Jt808ProtocolDecoder(Protocol protocol) { + super(protocol); + } +@@ -73,6 +76,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_TERMINAL_AUTH = 0x0102; + public static final int MSG_TERMINAL_ATTRIBUTES = 0x0107; + public static final int MSG_LOCATION_REPORT = 0x0200; ++ public static final int MSG_LOCATION_QUERY_RESPONSE = 0x0201; + public static final int MSG_LOCATION_BATCH_2 = 0x0210; + public static final int MSG_ACCELERATION = 0x2070; + public static final int MSG_LOCATION_REPORT_2 = 0x5501; +@@ -94,6 +98,7 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_DRIVER_IDENTITY = 0x0702; + public static final int MSG_VIDEO_REQUEST = 0x9101; + public static final int MSG_VIDEO_CONTROL = 0x9102; ++ public static final int MSG_PARAMETER_QUERY_RESPONSE = 0x0104; + public static final int MSG_PARAMETER_QUERY_ALL = 0x8104; + public static final int MSG_LOCATION_QUERY = 0x8201; + public static final int MSG_TEMPORARY_TRACKING = 0x8202; +@@ -401,9 +406,8 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + getLastLocation(position, null); + + buf.readUnsignedByte(); // encoding +- Charset charset = Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII; + +- position.set(Position.KEY_RESULT, buf.readCharSequence(buf.readableBytes() - 2, charset).toString()); ++ position.set(Position.KEY_RESULT, buf.readCharSequence(buf.readableBytes() - 2, CHARSET_GBK).toString()); + + return position; + +@@ -469,6 +473,12 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + requestAttachments(channel, remoteAddress, id, position); + return position; + ++ } else if (type == MSG_LOCATION_QUERY_RESPONSE) { ++ ++ buf.readUnsignedShort(); // response serial number ++ ++ return decodeLocation(deviceSession, buf); ++ + } else if (type == MSG_LOCATION_REPORT_2 || type == MSG_LOCATION_REPORT_BLIND) { + + if (BitUtil.check(attribute, 15)) { +@@ -575,6 +585,66 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + + return position; + ++ } else if (type == MSG_PARAMETER_QUERY_RESPONSE) { ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ getLastLocation(position, null); ++ ++ buf.readUnsignedShort(); // response serial number ++ buf.readUnsignedByte(); // parameter count ++ ++ while (buf.readableBytes() - 2 >= 5) { ++ ++ int subtype = buf.readInt(); ++ int length = buf.readUnsignedByte(); ++ int endIndex = buf.readerIndex() + length; ++ if (endIndex > buf.writerIndex() - 2) { ++ break; ++ } ++ switch (subtype) { ++ case 0x0001: ++ position.set("heartbeatInterval", buf.readUnsignedInt()); ++ break; ++ case 0x0010: ++ position.set("apn", buf.readCharSequence(length, CHARSET_GBK).toString()); ++ break; ++ case 0x0013: ++ position.set("server", buf.readCharSequence(length, CHARSET_GBK).toString()); ++ break; ++ case 0x0018: ++ position.set("port", buf.readUnsignedInt()); ++ break; ++ case 0x0027: ++ position.set("sleepReportInterval", buf.readUnsignedInt()); ++ break; ++ case 0x0028: ++ position.set("emergencyReportInterval", buf.readUnsignedInt()); ++ break; ++ case 0x0029: ++ position.set("defaultReportInterval", buf.readUnsignedInt()); ++ break; ++ case 0x0055: ++ position.set("overspeedThreshold", buf.readUnsignedInt()); ++ break; ++ case 0x0056: ++ position.set("speedLimitDuration", buf.readUnsignedInt()); ++ break; ++ case 0x0080: ++ position.set(Position.KEY_ODOMETER, buf.readUnsignedInt() * 100); ++ break; ++ case 0x0083: ++ position.set("plateNumber", buf.readCharSequence(length, CHARSET_GBK).toString().trim()); ++ break; ++ default: ++ break; ++ } ++ buf.readerIndex(endIndex); ++ } ++ ++ return position; ++ + } + + return null; +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +index 2574435f9..d3d43caff 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolDecoderTest.java +@@ -433,6 +433,14 @@ public class Jt808ProtocolDecoderTest extends ProtocolTest { + "7E09000049487060054219000E54100000000000000000000000000000000000240112034640001F2401120345210C4100F4011C00F3FFE80008004003FE001F2401120345510C4100F4011C00F3FFF0000800A003FEB67E"), + Position.KEY_DEVICE_TEMP, 24.4); + ++ verifyPosition(decoder, binary( ++ "7e0201003c0145382363912db0000000000000000000020101313605bb3b58000c000001292608251203040104000b620beb16000c00b28995018202107439115800060089fffffffece7e"), ++ position("2026-08-25 04:03:04.000", true, 16.85535, 96.156504)); ++ ++ verifyAttribute(decoder, binary( ++ "7e0104018502453031334908d600002c0000000104000000b400000002040000000000000003040000000000000004040000000000000005040000000000000006040000000000000007040000000000000010066d70746e657400000011000000001200000000130f3136382e3134342e3130342e32323400000014000000001500000000160000000017000000001804000013970000001904000000000000002004000000000000002104000000000000002204000000000000002704000001f400000028040000000000000029040000000a0000002c04000000000000003004000000140000005004000000000000005204000000000000005304000000000000005504000000000000005604000000050000005704000000000000005804000000000000005904000000000000005a04000000000000007004000000000000007104000000000000007204000000000000007304000000000000007404000000000000008004000000000000008102002c0000008202012f000000830cd4c142383838383820202020000000840101787e"), ++ "plateNumber", "粤B88888"); ++ + } + + } diff --git a/tasks/traccar__traccar-5997/tests/test.sh b/tasks/traccar__traccar-5997/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e01acb8af3ea26d5727528506759ba65361835d6 --- /dev/null +++ b/tasks/traccar__traccar-5997/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 b15554cf3f9808dc462d412834896fe0634a4e0e > "$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/traccar__traccar-5997/tests/verifier.py b/tasks/traccar__traccar-5997/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5997/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/traccar__traccar-5998/environment/Dockerfile b/tasks/traccar__traccar-5998/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8165a0b70e561f6a17f0200efcb0ddc5ded80c33 --- /dev/null +++ b/tasks/traccar__traccar-5998/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0a51fab445b83fe7384a2fd7ac39011f2daf2ddc 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0a51fab445b83fe7384a2fd7ac39011f2daf2ddc \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0a51fab445b83fe7384a2fd7ac39011f2daf2ddc \ + && 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/traccar__traccar-5998/instruction.md b/tasks/traccar__traccar-5998/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..67cfc5117493f7251a759448e941b4555afe9418 --- /dev/null +++ b/tasks/traccar__traccar-5998/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Add JT808 downlink command types + +## Description + +### Summary +Split out the **encoder** part of the JT808 work. The decoder changes are kept in a separate PR (#5997). + +### Encoder changes (`Jt808ProtocolEncoder.java`) +Encode the standard JT808 downlink commands and register them in `Jt808Protocol.java`: +- `TYPE_SET_CONNECTION` → `0x8103` (server address `0x13` + TCP port `0x18`) +- `TYPE_POSITION_SINGLE` / `TYPE_POSITION_STOP` → `0x8201` / `0x8202` +- `TYPE_ALARM_DISMISS` → `0x8203` +- `TYPE_POWER_OFF` / `TYPE_FACTORY_RESET` → `0x8105` terminal control +- `TYPE_MESSAGE` / `TYPE_VOICE_MESSAGE` → `0x8300` (GBK) +- `TYPE_REQUEST_PHOTO` → `0x8801` +- `TYPE_SET_SPEED_LIMIT` → `0x8103` (overspeed threshold `0x55`; duration `0x56` written only when provided) +- `TYPE_OUTPUT_CONTROL` → `0x8500` +- `TYPE_CONFIGURATION` → `0x8104` + +Existing command behavior (`TYPE_REBOOT_DEVICE`, `TYPE_POSITION_PERIODIC`, `TYPE_ALARM_ARM`/`TYPE_ALARM_DISARM`, and others) is left untouched in this PR. Any change to existing behavior will be proposed separately for review first. + +### Tests +All `Jt808ProtocolEncoderTest` tests pass. The new downlink command tests are consolidated into the existing `testEncode()` method. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0a51fab445b8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5998/solution/patch.diff b/tasks/traccar__traccar-5998/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..94905838953229046d996b1841f48f11f59514b8 --- /dev/null +++ b/tasks/traccar__traccar-5998/solution/patch.diff @@ -0,0 +1,231 @@ +diff --git a/src/main/java/org/traccar/model/Command.java b/src/main/java/org/traccar/model/Command.java +index f0304d059..552a9bec4 100644 +--- a/src/main/java/org/traccar/model/Command.java ++++ b/src/main/java/org/traccar/model/Command.java +@@ -81,6 +81,7 @@ public class Command extends BaseCommand { + public static final String KEY_MESSAGE = "message"; + public static final String KEY_ENABLE = "enable"; + public static final String KEY_DATA = "data"; ++ public static final String KEY_DURATION = "duration"; + public static final String KEY_INDEX = "index"; + public static final String KEY_PHONE = "phone"; + public static final String KEY_SERVER = "server"; +diff --git a/src/main/java/org/traccar/protocol/Jt808Protocol.java b/src/main/java/org/traccar/protocol/Jt808Protocol.java +index a61efd5d0..4f375d949 100644 +--- a/src/main/java/org/traccar/protocol/Jt808Protocol.java ++++ b/src/main/java/org/traccar/protocol/Jt808Protocol.java +@@ -29,12 +29,24 @@ public class Jt808Protocol extends BaseProtocol { + public Jt808Protocol(Config config) { + setSupportedDataCommands( + Command.TYPE_CUSTOM, ++ Command.TYPE_CONFIGURATION, + Command.TYPE_REBOOT_DEVICE, + Command.TYPE_POSITION_PERIODIC, ++ Command.TYPE_POSITION_SINGLE, ++ Command.TYPE_POSITION_STOP, + Command.TYPE_ALARM_ARM, + Command.TYPE_ALARM_DISARM, ++ Command.TYPE_ALARM_DISMISS, + Command.TYPE_ENGINE_STOP, + Command.TYPE_ENGINE_RESUME, ++ Command.TYPE_SET_CONNECTION, ++ Command.TYPE_POWER_OFF, ++ Command.TYPE_FACTORY_RESET, ++ Command.TYPE_MESSAGE, ++ Command.TYPE_VOICE_MESSAGE, ++ Command.TYPE_REQUEST_PHOTO, ++ Command.TYPE_SET_SPEED_LIMIT, ++ Command.TYPE_OUTPUT_CONTROL, + Command.TYPE_VIDEO_START, + Command.TYPE_VIDEO_STOP); + addServer(new TrackerServer(config, getName(), false) { +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index e2d732a1c..aa3e76961 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -94,6 +94,12 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_DRIVER_IDENTITY = 0x0702; + public static final int MSG_VIDEO_REQUEST = 0x9101; + public static final int MSG_VIDEO_CONTROL = 0x9102; ++ public static final int MSG_PARAMETER_QUERY_ALL = 0x8104; ++ public static final int MSG_LOCATION_QUERY = 0x8201; ++ public static final int MSG_TEMPORARY_TRACKING = 0x8202; ++ public static final int MSG_ALARM_ACK = 0x8203; ++ public static final int MSG_VEHICLE_CONTROL = 0x8500; ++ public static final int MSG_TAKE_PHOTO = 0x8801; + + public static final int RESULT_SUCCESS = 0; + +@@ -108,6 +114,10 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + return protocolVersion; + } + ++ public void setProtocolVersion(int protocolVersion) { ++ this.protocolVersion = protocolVersion; ++ } ++ + public ByteBuf formatMessage(int type, ByteBuf id, boolean shortIndex, ByteBuf data) { + ByteBuf buf = Unpooled.buffer(); + buf.writeByte(delimiter); +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +index 7a8edd2f7..16d4df2be 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +@@ -98,6 +98,14 @@ public class Jt808ProtocolEncoder extends BaseProtocolEncoder { + data.writeInt(command.getInteger(Command.KEY_FREQUENCY)); + return decoder.formatMessage( + Jt808ProtocolDecoder.MSG_PARAMETER_SETTING, id, false, data); ++ case Command.TYPE_POSITION_SINGLE: ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_LOCATION_QUERY, id, false, data); ++ case Command.TYPE_POSITION_STOP: ++ data.writeShort(0); ++ data.writeInt(0); ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_TEMPORARY_TRACKING, id, false, data); + case Command.TYPE_ALARM_ARM: + case Command.TYPE_ALARM_DISARM: + data.writeByte(1); // number of parameters +@@ -108,6 +116,11 @@ public class Jt808ProtocolEncoder extends BaseProtocolEncoder { + data.writeCharSequence(username, StandardCharsets.US_ASCII); + return decoder.formatMessage( + Jt808ProtocolDecoder.MSG_PARAMETER_SETTING, id, false, data); ++ case Command.TYPE_ALARM_DISMISS: ++ data.writeShort(0); ++ data.writeInt(0); ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_ALARM_ACK, id, false, data); + case Command.TYPE_ENGINE_STOP: + case Command.TYPE_ENGINE_RESUME: + if (alternative) { +@@ -127,6 +140,63 @@ public class Jt808ProtocolEncoder extends BaseProtocolEncoder { + return decoder.formatMessage( + Jt808ProtocolDecoder.MSG_TERMINAL_CONTROL, id, false, data); + } ++ case Command.TYPE_SET_CONNECTION: ++ data.writeByte(2); // number of parameters ++ String server = command.getString(Command.KEY_SERVER); ++ data.writeInt(0x13); // server address ++ data.writeByte(server.length()); ++ data.writeCharSequence(server, StandardCharsets.US_ASCII); ++ data.writeInt(0x18); // server tcp port ++ data.writeByte(4); ++ data.writeInt(command.getInteger(Command.KEY_PORT)); ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_CONFIGURATION_PARAMETERS, id, false, data); ++ case Command.TYPE_POWER_OFF: ++ data.writeByte(0x02); // power off ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_TERMINAL_CONTROL, id, false, data); ++ case Command.TYPE_FACTORY_RESET: ++ data.writeByte(0x03); // factory reset ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_TERMINAL_CONTROL, id, false, data); ++ case Command.TYPE_MESSAGE: ++ data.writeByte(0x04); // display on terminal ++ data.writeCharSequence(command.getString(Command.KEY_MESSAGE), ++ Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII); ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_SEND_TEXT_MESSAGE, id, false, data); ++ case Command.TYPE_VOICE_MESSAGE: ++ data.writeByte(0x08); // tts voice broadcast ++ data.writeCharSequence(command.getString(Command.KEY_MESSAGE), ++ Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII); ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_SEND_TEXT_MESSAGE, id, false, data); ++ case Command.TYPE_REQUEST_PHOTO: ++ data.writeByte(command.getInteger(Command.KEY_INDEX, 0)); // channel ++ data.writeShort(1); // take one photo ++ data.writeZero(9); // photo interval and image parameters ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_TAKE_PHOTO, id, false, data); ++ case Command.TYPE_SET_SPEED_LIMIT: ++ boolean hasDuration = command.hasAttribute(Command.KEY_DURATION); ++ data.writeByte(hasDuration ? 2 : 1); // number of parameters ++ data.writeInt(0x0055); // overspeed threshold ++ data.writeByte(4); ++ data.writeInt(command.getInteger(Command.KEY_DATA)); ++ if (hasDuration) { ++ data.writeInt(0x0056); // overspeed duration ++ data.writeByte(4); ++ data.writeInt(command.getInteger(Command.KEY_DURATION)); ++ } ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_CONFIGURATION_PARAMETERS, id, false, data); ++ case Command.TYPE_OUTPUT_CONTROL: ++ data.writeByte(command.getInteger(Command.KEY_INDEX, 0)); // control flag ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_VEHICLE_CONTROL, id, false, data); ++ case Command.TYPE_CONFIGURATION: ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_PARAMETER_QUERY_ALL, id, false, data); + case Command.TYPE_VIDEO_START: + var config = getCacheManager().getConfig(); + String host = URI.create(config.getString(Keys.WEB_URL)).getHost(); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java +index 09ce62bb5..b3c6cdced 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java +@@ -35,6 +35,62 @@ public class Jt808ProtocolEncoderTest extends ProtocolTest { + binary("7e830000140b3a73ce2ff2000001546573742c20436f6d6d616e642c2031323323a57e"), + encodeCommand(encoder, decoder, command)); + ++ command.setType(Command.TYPE_POSITION_SINGLE); ++ verifyFrame( ++ binary("7e820100000b3a73ce2ff20000d27e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_POSITION_STOP); ++ verifyFrame( ++ binary("7e820200060b3a73ce2ff20000000000000000d77e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_ALARM_DISMISS); ++ verifyFrame( ++ binary("7e820300060b3a73ce2ff20000000000000000d67e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_SET_CONNECTION); ++ command.set(Command.KEY_SERVER, "168.144.104.224"); ++ command.set(Command.KEY_PORT, 5015); ++ verifyFrame( ++ binary("7e8103001e0b3a73ce2ff2000002000000130f3136382e3134342e3130342e3232340000001804000013976a7e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_MESSAGE); ++ command.set(Command.KEY_MESSAGE, "Hello"); ++ verifyFrame( ++ binary("7e830000060b3a73ce2ff200000448656c6c6f927e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_REQUEST_PHOTO); ++ verifyFrame( ++ binary("7e8801000c0b3a73ce2ff20000000001000000000000000000d57e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_SET_SPEED_LIMIT); ++ command.set(Command.KEY_DATA, 100); ++ verifyFrame( ++ binary("7e8103000a0b3a73ce2ff2000001000000550400000064ed7e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.set(Command.KEY_DURATION, 35); ++ verifyFrame( ++ binary("7e810300130b3a73ce2ff2000002000000550400000064000000560400000023867e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_CONFIGURATION); ++ verifyFrame( ++ binary("7e810400000b3a73ce2ff20000d47e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ decoder.setProtocolVersion(3); ++ ++ command.setType(Command.TYPE_POSITION_SINGLE); ++ verifyFrame( ++ binary("7e82014000030000012345678901234500002e7e"), ++ encodeCommand(encoder, decoder, command)); ++ + } + + @Test diff --git a/tasks/traccar__traccar-5998/solution/solve.sh b/tasks/traccar__traccar-5998/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-5998/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/traccar__traccar-5998/task.toml b/tasks/traccar__traccar-5998/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..156410f2e4b482c7f7dd731a76fcb4cb5782249f --- /dev/null +++ b/tasks/traccar__traccar-5998/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-5998" +description = "Add JT808 downlink command types" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "0a51fab445b83fe7384a2fd7ac39011f2daf2ddc" +reference = "https://github.com/traccar/traccar/pull/5998" +source_access = "auto" +built_at = "2026-11-16T16:09:42.546053+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5bd76a70da72216b38f1c81da0215c32aa6a79498439c6c34b16934958e8d670" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-03T04:04:14Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/model/Command.java", + "src/main/java/org/traccar/protocol/Jt808Protocol.java", + "src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java", + "src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java", + "src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 149 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.505416+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7f20a1063d990181f2933738d83a127e443c2de7b806dc6b6d726e84dcafe7bf" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-5998/tests/capture.py b/tasks/traccar__traccar-5998/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-5998/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/traccar__traccar-5998/tests/instruction.md b/tasks/traccar__traccar-5998/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..67cfc5117493f7251a759448e941b4555afe9418 --- /dev/null +++ b/tasks/traccar__traccar-5998/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Add JT808 downlink command types + +## Description + +### Summary +Split out the **encoder** part of the JT808 work. The decoder changes are kept in a separate PR (#5997). + +### Encoder changes (`Jt808ProtocolEncoder.java`) +Encode the standard JT808 downlink commands and register them in `Jt808Protocol.java`: +- `TYPE_SET_CONNECTION` → `0x8103` (server address `0x13` + TCP port `0x18`) +- `TYPE_POSITION_SINGLE` / `TYPE_POSITION_STOP` → `0x8201` / `0x8202` +- `TYPE_ALARM_DISMISS` → `0x8203` +- `TYPE_POWER_OFF` / `TYPE_FACTORY_RESET` → `0x8105` terminal control +- `TYPE_MESSAGE` / `TYPE_VOICE_MESSAGE` → `0x8300` (GBK) +- `TYPE_REQUEST_PHOTO` → `0x8801` +- `TYPE_SET_SPEED_LIMIT` → `0x8103` (overspeed threshold `0x55`; duration `0x56` written only when provided) +- `TYPE_OUTPUT_CONTROL` → `0x8500` +- `TYPE_CONFIGURATION` → `0x8104` + +Existing command behavior (`TYPE_REBOOT_DEVICE`, `TYPE_POSITION_PERIODIC`, `TYPE_ALARM_ARM`/`TYPE_ALARM_DISARM`, and others) is left untouched in this PR. Any change to existing behavior will be proposed separately for review first. + +### Tests +All `Jt808ProtocolEncoderTest` tests pass. The new downlink command tests are consolidated into the existing `testEncode()` method. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0a51fab445b8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-5998/tests/oracle.patch b/tasks/traccar__traccar-5998/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..94905838953229046d996b1841f48f11f59514b8 --- /dev/null +++ b/tasks/traccar__traccar-5998/tests/oracle.patch @@ -0,0 +1,231 @@ +diff --git a/src/main/java/org/traccar/model/Command.java b/src/main/java/org/traccar/model/Command.java +index f0304d059..552a9bec4 100644 +--- a/src/main/java/org/traccar/model/Command.java ++++ b/src/main/java/org/traccar/model/Command.java +@@ -81,6 +81,7 @@ public class Command extends BaseCommand { + public static final String KEY_MESSAGE = "message"; + public static final String KEY_ENABLE = "enable"; + public static final String KEY_DATA = "data"; ++ public static final String KEY_DURATION = "duration"; + public static final String KEY_INDEX = "index"; + public static final String KEY_PHONE = "phone"; + public static final String KEY_SERVER = "server"; +diff --git a/src/main/java/org/traccar/protocol/Jt808Protocol.java b/src/main/java/org/traccar/protocol/Jt808Protocol.java +index a61efd5d0..4f375d949 100644 +--- a/src/main/java/org/traccar/protocol/Jt808Protocol.java ++++ b/src/main/java/org/traccar/protocol/Jt808Protocol.java +@@ -29,12 +29,24 @@ public class Jt808Protocol extends BaseProtocol { + public Jt808Protocol(Config config) { + setSupportedDataCommands( + Command.TYPE_CUSTOM, ++ Command.TYPE_CONFIGURATION, + Command.TYPE_REBOOT_DEVICE, + Command.TYPE_POSITION_PERIODIC, ++ Command.TYPE_POSITION_SINGLE, ++ Command.TYPE_POSITION_STOP, + Command.TYPE_ALARM_ARM, + Command.TYPE_ALARM_DISARM, ++ Command.TYPE_ALARM_DISMISS, + Command.TYPE_ENGINE_STOP, + Command.TYPE_ENGINE_RESUME, ++ Command.TYPE_SET_CONNECTION, ++ Command.TYPE_POWER_OFF, ++ Command.TYPE_FACTORY_RESET, ++ Command.TYPE_MESSAGE, ++ Command.TYPE_VOICE_MESSAGE, ++ Command.TYPE_REQUEST_PHOTO, ++ Command.TYPE_SET_SPEED_LIMIT, ++ Command.TYPE_OUTPUT_CONTROL, + Command.TYPE_VIDEO_START, + Command.TYPE_VIDEO_STOP); + addServer(new TrackerServer(config, getName(), false) { +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +index e2d732a1c..aa3e76961 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolDecoder.java +@@ -94,6 +94,12 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + public static final int MSG_DRIVER_IDENTITY = 0x0702; + public static final int MSG_VIDEO_REQUEST = 0x9101; + public static final int MSG_VIDEO_CONTROL = 0x9102; ++ public static final int MSG_PARAMETER_QUERY_ALL = 0x8104; ++ public static final int MSG_LOCATION_QUERY = 0x8201; ++ public static final int MSG_TEMPORARY_TRACKING = 0x8202; ++ public static final int MSG_ALARM_ACK = 0x8203; ++ public static final int MSG_VEHICLE_CONTROL = 0x8500; ++ public static final int MSG_TAKE_PHOTO = 0x8801; + + public static final int RESULT_SUCCESS = 0; + +@@ -108,6 +114,10 @@ public class Jt808ProtocolDecoder extends BaseProtocolDecoder { + return protocolVersion; + } + ++ public void setProtocolVersion(int protocolVersion) { ++ this.protocolVersion = protocolVersion; ++ } ++ + public ByteBuf formatMessage(int type, ByteBuf id, boolean shortIndex, ByteBuf data) { + ByteBuf buf = Unpooled.buffer(); + buf.writeByte(delimiter); +diff --git a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +index 7a8edd2f7..16d4df2be 100644 +--- a/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java ++++ b/src/main/java/org/traccar/protocol/Jt808ProtocolEncoder.java +@@ -98,6 +98,14 @@ public class Jt808ProtocolEncoder extends BaseProtocolEncoder { + data.writeInt(command.getInteger(Command.KEY_FREQUENCY)); + return decoder.formatMessage( + Jt808ProtocolDecoder.MSG_PARAMETER_SETTING, id, false, data); ++ case Command.TYPE_POSITION_SINGLE: ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_LOCATION_QUERY, id, false, data); ++ case Command.TYPE_POSITION_STOP: ++ data.writeShort(0); ++ data.writeInt(0); ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_TEMPORARY_TRACKING, id, false, data); + case Command.TYPE_ALARM_ARM: + case Command.TYPE_ALARM_DISARM: + data.writeByte(1); // number of parameters +@@ -108,6 +116,11 @@ public class Jt808ProtocolEncoder extends BaseProtocolEncoder { + data.writeCharSequence(username, StandardCharsets.US_ASCII); + return decoder.formatMessage( + Jt808ProtocolDecoder.MSG_PARAMETER_SETTING, id, false, data); ++ case Command.TYPE_ALARM_DISMISS: ++ data.writeShort(0); ++ data.writeInt(0); ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_ALARM_ACK, id, false, data); + case Command.TYPE_ENGINE_STOP: + case Command.TYPE_ENGINE_RESUME: + if (alternative) { +@@ -127,6 +140,63 @@ public class Jt808ProtocolEncoder extends BaseProtocolEncoder { + return decoder.formatMessage( + Jt808ProtocolDecoder.MSG_TERMINAL_CONTROL, id, false, data); + } ++ case Command.TYPE_SET_CONNECTION: ++ data.writeByte(2); // number of parameters ++ String server = command.getString(Command.KEY_SERVER); ++ data.writeInt(0x13); // server address ++ data.writeByte(server.length()); ++ data.writeCharSequence(server, StandardCharsets.US_ASCII); ++ data.writeInt(0x18); // server tcp port ++ data.writeByte(4); ++ data.writeInt(command.getInteger(Command.KEY_PORT)); ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_CONFIGURATION_PARAMETERS, id, false, data); ++ case Command.TYPE_POWER_OFF: ++ data.writeByte(0x02); // power off ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_TERMINAL_CONTROL, id, false, data); ++ case Command.TYPE_FACTORY_RESET: ++ data.writeByte(0x03); // factory reset ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_TERMINAL_CONTROL, id, false, data); ++ case Command.TYPE_MESSAGE: ++ data.writeByte(0x04); // display on terminal ++ data.writeCharSequence(command.getString(Command.KEY_MESSAGE), ++ Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII); ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_SEND_TEXT_MESSAGE, id, false, data); ++ case Command.TYPE_VOICE_MESSAGE: ++ data.writeByte(0x08); // tts voice broadcast ++ data.writeCharSequence(command.getString(Command.KEY_MESSAGE), ++ Charset.isSupported("GBK") ? Charset.forName("GBK") : StandardCharsets.US_ASCII); ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_SEND_TEXT_MESSAGE, id, false, data); ++ case Command.TYPE_REQUEST_PHOTO: ++ data.writeByte(command.getInteger(Command.KEY_INDEX, 0)); // channel ++ data.writeShort(1); // take one photo ++ data.writeZero(9); // photo interval and image parameters ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_TAKE_PHOTO, id, false, data); ++ case Command.TYPE_SET_SPEED_LIMIT: ++ boolean hasDuration = command.hasAttribute(Command.KEY_DURATION); ++ data.writeByte(hasDuration ? 2 : 1); // number of parameters ++ data.writeInt(0x0055); // overspeed threshold ++ data.writeByte(4); ++ data.writeInt(command.getInteger(Command.KEY_DATA)); ++ if (hasDuration) { ++ data.writeInt(0x0056); // overspeed duration ++ data.writeByte(4); ++ data.writeInt(command.getInteger(Command.KEY_DURATION)); ++ } ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_CONFIGURATION_PARAMETERS, id, false, data); ++ case Command.TYPE_OUTPUT_CONTROL: ++ data.writeByte(command.getInteger(Command.KEY_INDEX, 0)); // control flag ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_VEHICLE_CONTROL, id, false, data); ++ case Command.TYPE_CONFIGURATION: ++ return decoder.formatMessage( ++ Jt808ProtocolDecoder.MSG_PARAMETER_QUERY_ALL, id, false, data); + case Command.TYPE_VIDEO_START: + var config = getCacheManager().getConfig(); + String host = URI.create(config.getString(Keys.WEB_URL)).getHost(); +diff --git a/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java b/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java +index 09ce62bb5..b3c6cdced 100644 +--- a/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java ++++ b/src/test/java/org/traccar/protocol/Jt808ProtocolEncoderTest.java +@@ -35,6 +35,62 @@ public class Jt808ProtocolEncoderTest extends ProtocolTest { + binary("7e830000140b3a73ce2ff2000001546573742c20436f6d6d616e642c2031323323a57e"), + encodeCommand(encoder, decoder, command)); + ++ command.setType(Command.TYPE_POSITION_SINGLE); ++ verifyFrame( ++ binary("7e820100000b3a73ce2ff20000d27e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_POSITION_STOP); ++ verifyFrame( ++ binary("7e820200060b3a73ce2ff20000000000000000d77e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_ALARM_DISMISS); ++ verifyFrame( ++ binary("7e820300060b3a73ce2ff20000000000000000d67e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_SET_CONNECTION); ++ command.set(Command.KEY_SERVER, "168.144.104.224"); ++ command.set(Command.KEY_PORT, 5015); ++ verifyFrame( ++ binary("7e8103001e0b3a73ce2ff2000002000000130f3136382e3134342e3130342e3232340000001804000013976a7e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_MESSAGE); ++ command.set(Command.KEY_MESSAGE, "Hello"); ++ verifyFrame( ++ binary("7e830000060b3a73ce2ff200000448656c6c6f927e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_REQUEST_PHOTO); ++ verifyFrame( ++ binary("7e8801000c0b3a73ce2ff20000000001000000000000000000d57e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_SET_SPEED_LIMIT); ++ command.set(Command.KEY_DATA, 100); ++ verifyFrame( ++ binary("7e8103000a0b3a73ce2ff2000001000000550400000064ed7e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.set(Command.KEY_DURATION, 35); ++ verifyFrame( ++ binary("7e810300130b3a73ce2ff2000002000000550400000064000000560400000023867e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ command.setType(Command.TYPE_CONFIGURATION); ++ verifyFrame( ++ binary("7e810400000b3a73ce2ff20000d47e"), ++ encodeCommand(encoder, decoder, command)); ++ ++ decoder.setProtocolVersion(3); ++ ++ command.setType(Command.TYPE_POSITION_SINGLE); ++ verifyFrame( ++ binary("7e82014000030000012345678901234500002e7e"), ++ encodeCommand(encoder, decoder, command)); ++ + } + + @Test diff --git a/tasks/traccar__traccar-5998/tests/test.sh b/tasks/traccar__traccar-5998/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a472279b2b6b7d84c3c2ce41929ebb12fc8d75 --- /dev/null +++ b/tasks/traccar__traccar-5998/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 0a51fab445b83fe7384a2fd7ac39011f2daf2ddc > "$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/traccar__traccar-5998/tests/verifier.py b/tasks/traccar__traccar-5998/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-5998/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/traccar__traccar-6014/environment/Dockerfile b/tasks/traccar__traccar-6014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d35250a7f81912cff6d59879b1abe3545ff600a --- /dev/null +++ b/tasks/traccar__traccar-6014/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b15554cf3f9808dc462d412834896fe0634a4e0e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b15554cf3f9808dc462d412834896fe0634a4e0e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b15554cf3f9808dc462d412834896fe0634a4e0e \ + && 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/traccar__traccar-6014/instruction.md b/tasks/traccar__traccar-6014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..12da8e0112463e835706067691d337686692c775 --- /dev/null +++ b/tasks/traccar__traccar-6014/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** feat: handshake decoding and test for tk103 protocol + +## Description + +### Description + +I have a TK103 device (which may be a clone) that sends the battery level as a hexadecimal value after `HSOP`, for example: + +`072105039432BP00352672105039432HSOP4B` + +Traccar currently does not decode this value. + +This PR detects this message pattern and decodes the hexadecimal value after `HSOP` to determine the battery level. + +### Testing + +Tested with my device and verified that the battery level is correctly decoded. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b15554cf3f98`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6014/solution/patch.diff b/tasks/traccar__traccar-6014/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b7df6da880bbcb82f9b98ef75b8bd04c8e2d6d6e --- /dev/null +++ b/tasks/traccar__traccar-6014/solution/patch.diff @@ -0,0 +1,85 @@ +diff --git a/src/main/java/org/traccar/protocol/Tk103ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Tk103ProtocolDecoder.java +index ef22f4382..f6a82dfde 100644 +--- a/src/main/java/org/traccar/protocol/Tk103ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Tk103ProtocolDecoder.java +@@ -156,6 +156,16 @@ public class Tk103ProtocolDecoder extends BaseProtocolDecoder { + .text(")") + .compile(); + ++ private static final Pattern PATTERN_HANDSHAKE = new PatternBuilder() ++ .text("(") ++ .expression("(.{12})") // device id ++ .text("BP00") ++ .number("(?:d{15})?") // imei ++ .text("HSOP") ++ .number("(xx)") // battery level ++ .text(")") ++ .compile(); ++ + private String decodeAlarm(int value) { + return switch (value) { + case 1 -> Position.ALARM_ACCIDENT; +@@ -380,6 +390,27 @@ public class Tk103ProtocolDecoder extends BaseProtocolDecoder { + return position; + } + ++ private Position decodeHandshake(Channel channel, SocketAddress remoteAddress, String sentence) { ++ Parser parser = new Parser(PATTERN_HANDSHAKE, sentence); ++ if (!parser.matches()) { ++ return null; ++ } ++ ++ DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); ++ if (deviceSession == null) { ++ return null; ++ } ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ getLastLocation(position, null); ++ ++ position.set(Position.KEY_BATTERY_LEVEL, parser.nextHexInt()); ++ ++ return position; ++ } ++ + private Position decodeBms(Channel channel, SocketAddress remoteAddress, String sentence) { + String id = sentence.substring(1, 13); + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id); +@@ -489,7 +520,6 @@ public class Tk103ProtocolDecoder extends BaseProtocolDecoder { + String type = sentence.substring(13, 17); + if (type.equals("BP00")) { + channel.writeAndFlush(new NetworkMessage("(" + id + "AP01HSO)", remoteAddress)); +- return null; + } else if (type.equals("BP05")) { + channel.writeAndFlush(new NetworkMessage("(" + id + "AP05)", remoteAddress)); + } +@@ -509,6 +539,8 @@ public class Tk103ProtocolDecoder extends BaseProtocolDecoder { + return decodeVin(channel, remoteAddress, sentence); + } else if (sentence.contains("BS50") || sentence.contains("BS51")) { + return decodeBms(channel, remoteAddress, sentence); ++ } else if (sentence.contains("BP00")) { ++ return decodeHandshake(channel, remoteAddress, sentence); + } + + Parser parser = new Parser(PATTERN, sentence); +diff --git a/src/test/java/org/traccar/protocol/Tk103ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Tk103ProtocolDecoderTest.java +index 81ea57b5e..540cbe65b 100644 +--- a/src/test/java/org/traccar/protocol/Tk103ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Tk103ProtocolDecoderTest.java +@@ -11,6 +11,14 @@ public class Tk103ProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Tk103ProtocolDecoder(null)); + ++ verifyAttribute(decoder, text( ++ "(087075108195BP00HSOP55)"), ++ Position.KEY_BATTERY_LEVEL, 85); ++ ++ verifyAttribute(decoder, text( ++ "(072105039432BP00352672105039432HSOP4B)"), ++ Position.KEY_BATTERY_LEVEL, 75); ++ + verifyAttributes(decoder, text( + "(007030201454BS5190:02150000753001DC,91:0EE8060EDC0A01DC,92:42014201DC0A01DC,93:00010127000037C8,94:0E01000002000000,95:020EE10EE20EE800030EE40EE00EE700040EDD0EE40EE400050EDC0EDF0EE400,96:0142000000000000,97:0000000000000000,98:0000000000000000)")); + diff --git a/tasks/traccar__traccar-6014/solution/solve.sh b/tasks/traccar__traccar-6014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6014/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/traccar__traccar-6014/task.toml b/tasks/traccar__traccar-6014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..59987c5e0f5a128c0dc7d030df08ce980051b53f --- /dev/null +++ b/tasks/traccar__traccar-6014/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6014" +description = "feat: handshake decoding and test for tk103 protocol" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "b15554cf3f9808dc462d412834896fe0634a4e0e" +reference = "https://github.com/traccar/traccar/pull/6014" +source_access = "auto" +built_at = "2026-11-16T16:09:42.541004+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a281eaacfa94ac8dc8bb7bf4deaa318c6010652ba14c45139c2e10a4581d9972" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T16:57:30Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Tk103ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Tk103ProtocolDecoderTest.java", +] +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:03.509602+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2aff0ef241ec03e6e88c1737365613e9b3ec3b735c954c7ec4395fb5984805d1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6014/tests/capture.py b/tasks/traccar__traccar-6014/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6014/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/traccar__traccar-6014/tests/instruction.md b/tasks/traccar__traccar-6014/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..12da8e0112463e835706067691d337686692c775 --- /dev/null +++ b/tasks/traccar__traccar-6014/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** feat: handshake decoding and test for tk103 protocol + +## Description + +### Description + +I have a TK103 device (which may be a clone) that sends the battery level as a hexadecimal value after `HSOP`, for example: + +`072105039432BP00352672105039432HSOP4B` + +Traccar currently does not decode this value. + +This PR detects this message pattern and decodes the hexadecimal value after `HSOP` to determine the battery level. + +### Testing + +Tested with my device and verified that the battery level is correctly decoded. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b15554cf3f98`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6014/tests/oracle.patch b/tasks/traccar__traccar-6014/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b7df6da880bbcb82f9b98ef75b8bd04c8e2d6d6e --- /dev/null +++ b/tasks/traccar__traccar-6014/tests/oracle.patch @@ -0,0 +1,85 @@ +diff --git a/src/main/java/org/traccar/protocol/Tk103ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Tk103ProtocolDecoder.java +index ef22f4382..f6a82dfde 100644 +--- a/src/main/java/org/traccar/protocol/Tk103ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Tk103ProtocolDecoder.java +@@ -156,6 +156,16 @@ public class Tk103ProtocolDecoder extends BaseProtocolDecoder { + .text(")") + .compile(); + ++ private static final Pattern PATTERN_HANDSHAKE = new PatternBuilder() ++ .text("(") ++ .expression("(.{12})") // device id ++ .text("BP00") ++ .number("(?:d{15})?") // imei ++ .text("HSOP") ++ .number("(xx)") // battery level ++ .text(")") ++ .compile(); ++ + private String decodeAlarm(int value) { + return switch (value) { + case 1 -> Position.ALARM_ACCIDENT; +@@ -380,6 +390,27 @@ public class Tk103ProtocolDecoder extends BaseProtocolDecoder { + return position; + } + ++ private Position decodeHandshake(Channel channel, SocketAddress remoteAddress, String sentence) { ++ Parser parser = new Parser(PATTERN_HANDSHAKE, sentence); ++ if (!parser.matches()) { ++ return null; ++ } ++ ++ DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); ++ if (deviceSession == null) { ++ return null; ++ } ++ ++ Position position = new Position(getProtocolName()); ++ position.setDeviceId(deviceSession.getDeviceId()); ++ ++ getLastLocation(position, null); ++ ++ position.set(Position.KEY_BATTERY_LEVEL, parser.nextHexInt()); ++ ++ return position; ++ } ++ + private Position decodeBms(Channel channel, SocketAddress remoteAddress, String sentence) { + String id = sentence.substring(1, 13); + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id); +@@ -489,7 +520,6 @@ public class Tk103ProtocolDecoder extends BaseProtocolDecoder { + String type = sentence.substring(13, 17); + if (type.equals("BP00")) { + channel.writeAndFlush(new NetworkMessage("(" + id + "AP01HSO)", remoteAddress)); +- return null; + } else if (type.equals("BP05")) { + channel.writeAndFlush(new NetworkMessage("(" + id + "AP05)", remoteAddress)); + } +@@ -509,6 +539,8 @@ public class Tk103ProtocolDecoder extends BaseProtocolDecoder { + return decodeVin(channel, remoteAddress, sentence); + } else if (sentence.contains("BS50") || sentence.contains("BS51")) { + return decodeBms(channel, remoteAddress, sentence); ++ } else if (sentence.contains("BP00")) { ++ return decodeHandshake(channel, remoteAddress, sentence); + } + + Parser parser = new Parser(PATTERN, sentence); +diff --git a/src/test/java/org/traccar/protocol/Tk103ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Tk103ProtocolDecoderTest.java +index 81ea57b5e..540cbe65b 100644 +--- a/src/test/java/org/traccar/protocol/Tk103ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Tk103ProtocolDecoderTest.java +@@ -11,6 +11,14 @@ public class Tk103ProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Tk103ProtocolDecoder(null)); + ++ verifyAttribute(decoder, text( ++ "(087075108195BP00HSOP55)"), ++ Position.KEY_BATTERY_LEVEL, 85); ++ ++ verifyAttribute(decoder, text( ++ "(072105039432BP00352672105039432HSOP4B)"), ++ Position.KEY_BATTERY_LEVEL, 75); ++ + verifyAttributes(decoder, text( + "(007030201454BS5190:02150000753001DC,91:0EE8060EDC0A01DC,92:42014201DC0A01DC,93:00010127000037C8,94:0E01000002000000,95:020EE10EE20EE800030EE40EE00EE700040EDD0EE40EE400050EDC0EDF0EE400,96:0142000000000000,97:0000000000000000,98:0000000000000000)")); + diff --git a/tasks/traccar__traccar-6014/tests/test.sh b/tasks/traccar__traccar-6014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e01acb8af3ea26d5727528506759ba65361835d6 --- /dev/null +++ b/tasks/traccar__traccar-6014/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 b15554cf3f9808dc462d412834896fe0634a4e0e > "$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/traccar__traccar-6014/tests/verifier.py b/tasks/traccar__traccar-6014/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-6014/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/traccar__traccar-6016/environment/Dockerfile b/tasks/traccar__traccar-6016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b4774e780e6436ab202cb0cbd1fb5143aa4898f4 --- /dev/null +++ b/tasks/traccar__traccar-6016/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8d8a9bd12c3440d44cc16e6710906ed5af485c8d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8d8a9bd12c3440d44cc16e6710906ed5af485c8d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8d8a9bd12c3440d44cc16e6710906ed5af485c8d \ + && 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/traccar__traccar-6016/instruction.md b/tasks/traccar__traccar-6016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c1b1506eb222f937edee2b4137a8eee3f53b5d60 --- /dev/null +++ b/tasks/traccar__traccar-6016/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Support Teltonika FT platform parameters + +## Description + +The FT platform (FTC880, FTM880, FTC921, ...) shares most AVL IDs with FMB, but the decoder gated them behind the `fmbXXX` predicate, so FT devices lost external voltage, battery level and several alarms, keeping them only as raw `ioNNN` attributes. + +Per Teltonika's [AVL ID differences between FMB and FT platforms](https://wiki.teltonika-gps.com/view/AVL_ID_differences_between_FMB_and_FT_platforms), only IDs 70, 155, 156, 157, 358, 359, 360, 641 and 800 change meaning between the two platforms; every other shared ID keeps its FMB semantics. This change adds an `ftXXX` predicate (`FT[A-Z]\d{3}`) and only extends IDs that are **not** in that list, so their meaning is identical on FT: + +- `68` battery current, `113` battery level, `200` sleep mode +- `246` towing, `249` jamming, `251` excessive idling, `252` unplug (power cut) +- `175` auto geofence + +Each of those was checked against the [FTC880 parameter list](https://wiki.teltonika-gps.com/view/FTC880_Teltonika_Data_Sending_Parameters_ID) for id, size and unit, so nothing shifts inside the record: 68 is 2 bytes mA, 113 is 1 byte %, and the rest are 1-byte flags with the same polarity as on FMB. + +External voltage is the one changed ID handled here: FT devices report a wider range than the two-byte AVL 66 allows, so Teltonika moved it to **AVL 800**, four bytes in mV. + +It is registered for `ftXXX` only, not for every model. On [TFT100 and TST100](https://wiki.teltonika-gps.com/view/TFT100_AVL_ID_List) the same id is *Extended External Voltage*, four bytes already **in volts**, used above 65 V — dividing that by 1000 would be wrong. Those models are matched by the existing `tatXXX` predicate and are untouched here. + +Accident is deliberately left untouched: FMB AVL 247 does not exist on FT, where a crash is reported through AVL 1429–1432 instead. + +Verified with two assertions at the end of `testDecode`, on a real Codec 8 Extended record from an FTC880 running 6.15.3 (external voltage 800 and battery level 113). The network identifiers, odometer and timestamp in that frame were zeroed and the CRC recomputed, because they identify the vehicle; the two asserted values are exactly as the device sent them. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8d8a9bd12c34`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6016/solution/patch.diff b/tasks/traccar__traccar-6016/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5ed3fa3bac40105b0ae56a9cab3869bb9138617c --- /dev/null +++ b/tasks/traccar__traccar-6016/solution/patch.diff @@ -0,0 +1,91 @@ +diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +index ed6d6a19d..7f8cc9a00 100644 +--- a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +@@ -190,6 +190,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + Predicate fmbXXX = (m) -> m != null && m.matches("FM[B-Z]...|MTB100|MSP500"); + Predicate fmb6XX = (m) -> m != null && m.matches("FM.6.."); + Predicate tatXXX = (m) -> m != null && m.matches("T.T..."); ++ Predicate ftXXX = (m) -> m != null && m.matches("FT[A-Z]\\d{3}"); + + register(1, any, (p, b) -> p.set(Position.PREFIX_IN + 1, b.readUnsignedByte() > 0)); + register(2, any, (p, b) -> p.set(Position.PREFIX_IN + 2, b.readUnsignedByte() > 0)); +@@ -218,7 +219,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + register(57, fmbXXX, (p, b) -> p.set("hybridBatteryLevel", b.readByte())); + register(66, any, (p, b) -> p.set(Position.KEY_POWER, b.readUnsignedShort() / 1000.0)); + register(67, any, (p, b) -> p.set(Position.KEY_BATTERY, b.readUnsignedShort() / 1000.0)); +- register(68, fmbXXX, (p, b) -> p.set("batteryCurrent", b.readUnsignedShort() / 1000.0)); ++ register(68, fmbXXX.or(ftXXX), (p, b) -> p.set("batteryCurrent", b.readUnsignedShort() / 1000.0)); + register(72, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 1, b.readInt() / 10.0)); + register(73, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 2, b.readInt() / 10.0)); + register(74, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 3, b.readInt() / 10.0)); +@@ -239,7 +240,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + register(89, fmbXXX.and(fmb6XX.negate()), (p, b) -> p.set(Position.KEY_FUEL_LEVEL, b.readUnsignedByte())); + register(107, fmbXXX, (p, b) -> p.set(Position.KEY_FUEL_USED, b.readUnsignedInt() / 10.0)); + register(110, fmbXXX, (p, b) -> p.set(Position.KEY_FUEL_CONSUMPTION, b.readUnsignedShort() / 10.0)); +- register(113, fmbXXX, (p, b) -> p.set(Position.KEY_BATTERY_LEVEL, b.readUnsignedByte())); ++ register(113, fmbXXX.or(ftXXX), (p, b) -> p.set(Position.KEY_BATTERY_LEVEL, b.readUnsignedByte())); + register(115, fmbXXX, (p, b) -> p.set(Position.KEY_ENGINE_TEMP, b.readShort() / 10.0)); + register(389, "FMB003"::equals, (p, b) -> p.set(Position.KEY_OBD_ODOMETER, b.readUnsignedInt() * 1000)); + register(701, fmb6XX, (p, b) -> p.set("bleTemp1", b.readShort() / 10.0)); +@@ -251,18 +252,19 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + register(181, any, (p, b) -> p.set(Position.KEY_PDOP, b.readUnsignedShort() / 10.0)); + register(182, any, (p, b) -> p.set(Position.KEY_HDOP, b.readUnsignedShort() / 10.0)); + register(199, any, (p, b) -> p.set(Position.KEY_ODOMETER_TRIP, b.readUnsignedInt())); +- register(200, fmbXXX, (p, b) -> p.set("sleepMode", b.readUnsignedByte())); ++ register(200, fmbXXX.or(ftXXX), (p, b) -> p.set("sleepMode", b.readUnsignedByte())); + register(205, fmbXXX.or(tatXXX), (p, b) -> p.set("cid2g", b.readUnsignedShort())); + register(206, fmbXXX.or(tatXXX), (p, b) -> p.set("lac", b.readUnsignedShort())); + register(236, any, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_GENERAL : null)); + register(239, any, (p, b) -> p.set(Position.KEY_IGNITION, b.readUnsignedByte() > 0)); + register(240, any, (p, b) -> p.set(Position.KEY_MOTION, b.readUnsignedByte() > 0)); + register(241, any, (p, b) -> p.set(Position.KEY_OPERATOR, b.readUnsignedInt())); +- register(246, fmbXXX, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_TOW : null)); ++ register(246, fmbXXX.or(ftXXX), (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_TOW : null)); + register(247, fmbXXX, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_ACCIDENT : null)); +- register(249, fmbXXX, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_JAMMING : null)); +- register(251, fmbXXX, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_IDLE : null)); +- register(252, fmbXXX, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_POWER_CUT : null)); ++ register(249, fmbXXX.or(ftXXX), (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_JAMMING : null)); ++ register(251, fmbXXX.or(ftXXX), (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_IDLE : null)); ++ register(252, fmbXXX.or(ftXXX), (p, b) -> ++ p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_POWER_CUT : null)); + register(253, any, (p, b) -> { + switch (b.readUnsignedByte()) { + case 1 -> p.addAlarm(Position.ALARM_ACCELERATION); +@@ -270,11 +272,12 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + case 3 -> p.addAlarm(Position.ALARM_CORNERING); + } + }); +- register(175, fmbXXX, (p, b) -> { ++ register(175, fmbXXX.or(ftXXX), (p, b) -> { + p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_GEOFENCE_ENTER : Position.ALARM_GEOFENCE_EXIT); + }); + register(636, fmbXXX.or(tatXXX), (p, b) -> p.set("cid4g", b.readUnsignedInt())); + register(662, fmbXXX, (p, b) -> p.set(Position.KEY_DOOR, b.readUnsignedByte() > 0)); ++ register(800, ftXXX, (p, b) -> p.set(Position.KEY_POWER, b.readUnsignedInt() / 1000.0)); + register(10644, fmbXXX, (p, b) -> p.set("tempProbe1", b.readShort() / 100.0)); + register(10645, fmbXXX, (p, b) -> p.set("tempProbe2", b.readShort() / 100.0)); + register(10646, fmbXXX, (p, b) -> p.set("tempProbe3", b.readShort() / 100.0)); +diff --git a/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java +index d7cadf669..107b6859f 100644 +--- a/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java +@@ -161,6 +161,17 @@ public class TeltonikaProtocolDecoderTest extends ProtocolTest { + verifyPositions(decoder, false, binary( + "00000000000003b5080b0000015ab5642a8800d5db1769ec01d70a020a00e3040004000e0501010200030004006000060900100a00010b0000130000422f1318000302c700000000f7000000000001cb000000000000000000000000000000000000015ab5642e7000d5db178aec01d6d6020a0070040003000e0501010200030004006000060900100a00000b0000130000422f1318000302c700000000f7000000000001cb000000000000000000000000000000000000015ab567050000d5db1805ec01da3c02060101040006000e05010102000300040060000609000f0a00010b0000130000422f0c18000302c700000046f7000000000001cb000000000000000000000000000000000000015ab56708e800d5db1723ec01d9ec020600e5040006000e05010102000300040060000609000f0a00010b0000130000422f1018000502c700000003f7000000000001cb000000000000000000000000000000000000015ab5685cc000d5db20f7ec01d8fa02080033050007000e05010102000300040060000609000f0a00010b0000130000422f0a18000502c700000030f7000000000001cb000000000000000000000000000000000000015ab5693b6800d5db2367ec01d9430211011b040006000e05010102000300040060000609000f0a00010b0000130000422f0c18000302c700000027f7000000000001cb000000000000000000000000000000000000015ab569433800d5db1fb2ec01d9310211008b040006000e0501010200030004006000060900110a00000b0000130000422f1318000402c700000009f7000000000001cb000000000000000000000000000000000000015ab56a0e5800d5db22a2ec01da5502100041050007000e05010102000300040060000609000f0a00000b0000130000422f1118000602c70000000ef7000000000001cb000000000000000000000000000000000000015ab56a700000d5db2afcec01ddb2020a0012050008000e05010102000300040060000609000e0a00000b0000130000422f0918000502c700000026f7000000000001cb000000000000000000000000000000000000015ab56a73e800d5db2ad8ec01de65020a014e050008000e05010102000300040060000609000f0a00010b0000130000422f0818000702c700000002f7000000000001cb000000000000000000000000000000000000015ab56a7bb800d5db2971ec01e00e020a013f040008000e0501010200030004006000060900100a00020b0000130000422f0b18000802c700000004f7000000000001cb000000000000000000000000000000000b00007c5f")); + ++ decoder.setExtended(false); ++ decoder.setModelOverride("FTC880"); ++ ++ verifyAttribute(decoder, binary( ++ "00000000000000968e010000019b76daa800000000000000000000000000000000000000001b000b00150500450000716400c80300ed0200ef0000f000012f00017f0333d20833d30a000a0011ffd30012ffe70013002300430fd400440000004600ee00b5000000b6000000ce000001820000000600100000000000c70000000000cd0000000000f100000000032000003249047c00000000000000000100003e0b"), ++ Position.KEY_POWER, 12.873); ++ ++ verifyAttribute(decoder, binary( ++ "00000000000000968e010000019b76daa800000000000000000000000000000000000000001b000b00150500450000716400c80300ed0200ef0000f000012f00017f0333d20833d30a000a0011ffd30012ffe70013002300430fd400440000004600ee00b5000000b6000000ce000001820000000600100000000000c70000000000cd0000000000f100000000032000003249047c00000000000000000100003e0b"), ++ Position.KEY_BATTERY_LEVEL, 100); ++ + } + + @Test diff --git a/tasks/traccar__traccar-6016/solution/solve.sh b/tasks/traccar__traccar-6016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6016/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/traccar__traccar-6016/task.toml b/tasks/traccar__traccar-6016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1e406cb9ce57a0a9c0a9a36a7a7ad1674ee7ad75 --- /dev/null +++ b/tasks/traccar__traccar-6016/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6016" +description = "Support Teltonika FT platform parameters" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "8d8a9bd12c3440d44cc16e6710906ed5af485c8d" +reference = "https://github.com/traccar/traccar/pull/6016" +source_access = "auto" +built_at = "2026-11-16T16:09:42.527760+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c98e8f60a7b725c377666e2220cbaa0070ae0561d2d70f5fad99d10eff70a038" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-06T15:08:35Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java", + "src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 30 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.521671+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:03a08b680acd977fabd3ca248fea706f59467c0567ae37ca02db34ff977d1b9a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6016/tests/capture.py b/tasks/traccar__traccar-6016/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6016/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/traccar__traccar-6016/tests/instruction.md b/tasks/traccar__traccar-6016/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c1b1506eb222f937edee2b4137a8eee3f53b5d60 --- /dev/null +++ b/tasks/traccar__traccar-6016/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Support Teltonika FT platform parameters + +## Description + +The FT platform (FTC880, FTM880, FTC921, ...) shares most AVL IDs with FMB, but the decoder gated them behind the `fmbXXX` predicate, so FT devices lost external voltage, battery level and several alarms, keeping them only as raw `ioNNN` attributes. + +Per Teltonika's [AVL ID differences between FMB and FT platforms](https://wiki.teltonika-gps.com/view/AVL_ID_differences_between_FMB_and_FT_platforms), only IDs 70, 155, 156, 157, 358, 359, 360, 641 and 800 change meaning between the two platforms; every other shared ID keeps its FMB semantics. This change adds an `ftXXX` predicate (`FT[A-Z]\d{3}`) and only extends IDs that are **not** in that list, so their meaning is identical on FT: + +- `68` battery current, `113` battery level, `200` sleep mode +- `246` towing, `249` jamming, `251` excessive idling, `252` unplug (power cut) +- `175` auto geofence + +Each of those was checked against the [FTC880 parameter list](https://wiki.teltonika-gps.com/view/FTC880_Teltonika_Data_Sending_Parameters_ID) for id, size and unit, so nothing shifts inside the record: 68 is 2 bytes mA, 113 is 1 byte %, and the rest are 1-byte flags with the same polarity as on FMB. + +External voltage is the one changed ID handled here: FT devices report a wider range than the two-byte AVL 66 allows, so Teltonika moved it to **AVL 800**, four bytes in mV. + +It is registered for `ftXXX` only, not for every model. On [TFT100 and TST100](https://wiki.teltonika-gps.com/view/TFT100_AVL_ID_List) the same id is *Extended External Voltage*, four bytes already **in volts**, used above 65 V — dividing that by 1000 would be wrong. Those models are matched by the existing `tatXXX` predicate and are untouched here. + +Accident is deliberately left untouched: FMB AVL 247 does not exist on FT, where a crash is reported through AVL 1429–1432 instead. + +Verified with two assertions at the end of `testDecode`, on a real Codec 8 Extended record from an FTC880 running 6.15.3 (external voltage 800 and battery level 113). The network identifiers, odometer and timestamp in that frame were zeroed and the CRC recomputed, because they identify the vehicle; the two asserted values are exactly as the device sent them. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8d8a9bd12c34`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6016/tests/oracle.patch b/tasks/traccar__traccar-6016/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5ed3fa3bac40105b0ae56a9cab3869bb9138617c --- /dev/null +++ b/tasks/traccar__traccar-6016/tests/oracle.patch @@ -0,0 +1,91 @@ +diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +index ed6d6a19d..7f8cc9a00 100644 +--- a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +@@ -190,6 +190,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + Predicate fmbXXX = (m) -> m != null && m.matches("FM[B-Z]...|MTB100|MSP500"); + Predicate fmb6XX = (m) -> m != null && m.matches("FM.6.."); + Predicate tatXXX = (m) -> m != null && m.matches("T.T..."); ++ Predicate ftXXX = (m) -> m != null && m.matches("FT[A-Z]\\d{3}"); + + register(1, any, (p, b) -> p.set(Position.PREFIX_IN + 1, b.readUnsignedByte() > 0)); + register(2, any, (p, b) -> p.set(Position.PREFIX_IN + 2, b.readUnsignedByte() > 0)); +@@ -218,7 +219,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + register(57, fmbXXX, (p, b) -> p.set("hybridBatteryLevel", b.readByte())); + register(66, any, (p, b) -> p.set(Position.KEY_POWER, b.readUnsignedShort() / 1000.0)); + register(67, any, (p, b) -> p.set(Position.KEY_BATTERY, b.readUnsignedShort() / 1000.0)); +- register(68, fmbXXX, (p, b) -> p.set("batteryCurrent", b.readUnsignedShort() / 1000.0)); ++ register(68, fmbXXX.or(ftXXX), (p, b) -> p.set("batteryCurrent", b.readUnsignedShort() / 1000.0)); + register(72, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 1, b.readInt() / 10.0)); + register(73, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 2, b.readInt() / 10.0)); + register(74, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 3, b.readInt() / 10.0)); +@@ -239,7 +240,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + register(89, fmbXXX.and(fmb6XX.negate()), (p, b) -> p.set(Position.KEY_FUEL_LEVEL, b.readUnsignedByte())); + register(107, fmbXXX, (p, b) -> p.set(Position.KEY_FUEL_USED, b.readUnsignedInt() / 10.0)); + register(110, fmbXXX, (p, b) -> p.set(Position.KEY_FUEL_CONSUMPTION, b.readUnsignedShort() / 10.0)); +- register(113, fmbXXX, (p, b) -> p.set(Position.KEY_BATTERY_LEVEL, b.readUnsignedByte())); ++ register(113, fmbXXX.or(ftXXX), (p, b) -> p.set(Position.KEY_BATTERY_LEVEL, b.readUnsignedByte())); + register(115, fmbXXX, (p, b) -> p.set(Position.KEY_ENGINE_TEMP, b.readShort() / 10.0)); + register(389, "FMB003"::equals, (p, b) -> p.set(Position.KEY_OBD_ODOMETER, b.readUnsignedInt() * 1000)); + register(701, fmb6XX, (p, b) -> p.set("bleTemp1", b.readShort() / 10.0)); +@@ -251,18 +252,19 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + register(181, any, (p, b) -> p.set(Position.KEY_PDOP, b.readUnsignedShort() / 10.0)); + register(182, any, (p, b) -> p.set(Position.KEY_HDOP, b.readUnsignedShort() / 10.0)); + register(199, any, (p, b) -> p.set(Position.KEY_ODOMETER_TRIP, b.readUnsignedInt())); +- register(200, fmbXXX, (p, b) -> p.set("sleepMode", b.readUnsignedByte())); ++ register(200, fmbXXX.or(ftXXX), (p, b) -> p.set("sleepMode", b.readUnsignedByte())); + register(205, fmbXXX.or(tatXXX), (p, b) -> p.set("cid2g", b.readUnsignedShort())); + register(206, fmbXXX.or(tatXXX), (p, b) -> p.set("lac", b.readUnsignedShort())); + register(236, any, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_GENERAL : null)); + register(239, any, (p, b) -> p.set(Position.KEY_IGNITION, b.readUnsignedByte() > 0)); + register(240, any, (p, b) -> p.set(Position.KEY_MOTION, b.readUnsignedByte() > 0)); + register(241, any, (p, b) -> p.set(Position.KEY_OPERATOR, b.readUnsignedInt())); +- register(246, fmbXXX, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_TOW : null)); ++ register(246, fmbXXX.or(ftXXX), (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_TOW : null)); + register(247, fmbXXX, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_ACCIDENT : null)); +- register(249, fmbXXX, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_JAMMING : null)); +- register(251, fmbXXX, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_IDLE : null)); +- register(252, fmbXXX, (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_POWER_CUT : null)); ++ register(249, fmbXXX.or(ftXXX), (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_JAMMING : null)); ++ register(251, fmbXXX.or(ftXXX), (p, b) -> p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_IDLE : null)); ++ register(252, fmbXXX.or(ftXXX), (p, b) -> ++ p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_POWER_CUT : null)); + register(253, any, (p, b) -> { + switch (b.readUnsignedByte()) { + case 1 -> p.addAlarm(Position.ALARM_ACCELERATION); +@@ -270,11 +272,12 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { + case 3 -> p.addAlarm(Position.ALARM_CORNERING); + } + }); +- register(175, fmbXXX, (p, b) -> { ++ register(175, fmbXXX.or(ftXXX), (p, b) -> { + p.addAlarm(b.readUnsignedByte() > 0 ? Position.ALARM_GEOFENCE_ENTER : Position.ALARM_GEOFENCE_EXIT); + }); + register(636, fmbXXX.or(tatXXX), (p, b) -> p.set("cid4g", b.readUnsignedInt())); + register(662, fmbXXX, (p, b) -> p.set(Position.KEY_DOOR, b.readUnsignedByte() > 0)); ++ register(800, ftXXX, (p, b) -> p.set(Position.KEY_POWER, b.readUnsignedInt() / 1000.0)); + register(10644, fmbXXX, (p, b) -> p.set("tempProbe1", b.readShort() / 100.0)); + register(10645, fmbXXX, (p, b) -> p.set("tempProbe2", b.readShort() / 100.0)); + register(10646, fmbXXX, (p, b) -> p.set("tempProbe3", b.readShort() / 100.0)); +diff --git a/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java +index d7cadf669..107b6859f 100644 +--- a/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java +@@ -161,6 +161,17 @@ public class TeltonikaProtocolDecoderTest extends ProtocolTest { + verifyPositions(decoder, false, binary( + "00000000000003b5080b0000015ab5642a8800d5db1769ec01d70a020a00e3040004000e0501010200030004006000060900100a00010b0000130000422f1318000302c700000000f7000000000001cb000000000000000000000000000000000000015ab5642e7000d5db178aec01d6d6020a0070040003000e0501010200030004006000060900100a00000b0000130000422f1318000302c700000000f7000000000001cb000000000000000000000000000000000000015ab567050000d5db1805ec01da3c02060101040006000e05010102000300040060000609000f0a00010b0000130000422f0c18000302c700000046f7000000000001cb000000000000000000000000000000000000015ab56708e800d5db1723ec01d9ec020600e5040006000e05010102000300040060000609000f0a00010b0000130000422f1018000502c700000003f7000000000001cb000000000000000000000000000000000000015ab5685cc000d5db20f7ec01d8fa02080033050007000e05010102000300040060000609000f0a00010b0000130000422f0a18000502c700000030f7000000000001cb000000000000000000000000000000000000015ab5693b6800d5db2367ec01d9430211011b040006000e05010102000300040060000609000f0a00010b0000130000422f0c18000302c700000027f7000000000001cb000000000000000000000000000000000000015ab569433800d5db1fb2ec01d9310211008b040006000e0501010200030004006000060900110a00000b0000130000422f1318000402c700000009f7000000000001cb000000000000000000000000000000000000015ab56a0e5800d5db22a2ec01da5502100041050007000e05010102000300040060000609000f0a00000b0000130000422f1118000602c70000000ef7000000000001cb000000000000000000000000000000000000015ab56a700000d5db2afcec01ddb2020a0012050008000e05010102000300040060000609000e0a00000b0000130000422f0918000502c700000026f7000000000001cb000000000000000000000000000000000000015ab56a73e800d5db2ad8ec01de65020a014e050008000e05010102000300040060000609000f0a00010b0000130000422f0818000702c700000002f7000000000001cb000000000000000000000000000000000000015ab56a7bb800d5db2971ec01e00e020a013f040008000e0501010200030004006000060900100a00020b0000130000422f0b18000802c700000004f7000000000001cb000000000000000000000000000000000b00007c5f")); + ++ decoder.setExtended(false); ++ decoder.setModelOverride("FTC880"); ++ ++ verifyAttribute(decoder, binary( ++ "00000000000000968e010000019b76daa800000000000000000000000000000000000000001b000b00150500450000716400c80300ed0200ef0000f000012f00017f0333d20833d30a000a0011ffd30012ffe70013002300430fd400440000004600ee00b5000000b6000000ce000001820000000600100000000000c70000000000cd0000000000f100000000032000003249047c00000000000000000100003e0b"), ++ Position.KEY_POWER, 12.873); ++ ++ verifyAttribute(decoder, binary( ++ "00000000000000968e010000019b76daa800000000000000000000000000000000000000001b000b00150500450000716400c80300ed0200ef0000f000012f00017f0333d20833d30a000a0011ffd30012ffe70013002300430fd400440000004600ee00b5000000b6000000ce000001820000000600100000000000c70000000000cd0000000000f100000000032000003249047c00000000000000000100003e0b"), ++ Position.KEY_BATTERY_LEVEL, 100); ++ + } + + @Test diff --git a/tasks/traccar__traccar-6016/tests/test.sh b/tasks/traccar__traccar-6016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..49c2c592d062f419ec0a71fa56fe8f0d83d3985e --- /dev/null +++ b/tasks/traccar__traccar-6016/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 8d8a9bd12c3440d44cc16e6710906ed5af485c8d > "$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/traccar__traccar-6016/tests/verifier.py b/tasks/traccar__traccar-6016/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-6016/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/traccar__traccar-6021/environment/Dockerfile b/tasks/traccar__traccar-6021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b93ab252c85c78b391ed46cf40de2e706de6409e --- /dev/null +++ b/tasks/traccar__traccar-6021/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3106d83c30e8a564267f6020b3286122244efeb5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3106d83c30e8a564267f6020b3286122244efeb5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3106d83c30e8a564267f6020b3286122244efeb5 \ + && 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/traccar__traccar-6021/instruction.md b/tasks/traccar__traccar-6021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e27234f4c9da0319786ab35a552c92400c34cfb --- /dev/null +++ b/tasks/traccar__traccar-6021/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Gl200: read the GTINF charge flag from the Charging field + +## Description + +`decodeInf` consumes the Charging field in the `if` and then parses the *next* field +(LED on) as the charge flag, so `charge` is true whenever the LED is on, and the index +runs one field ahead for everything after it. + +The GL300 @Track Air Interface Protocol (rev 6.00, §3.3.2 Device Information Report) +lists the GTINF tail in this order: + +``` +... Battery voltage, Charging, LED on, GPS on need, GPS antenna type, + GPS antenna state, Last GPS fix UTC time, battery percentage, ... +``` + +Observed on a GL320MG (protocol version prefix C3): 286 GTINF frames between +2026-08-27 and 2026-09-09 all report LED on = 1, and 280 of them report Charging = 0. +Traccar stored `charge: true` for all 286. + +Fix: parse `v[index - 1]`. The fixture is one of those frames, asserting `charge` is +absent; on master the same frame decodes as `charge: true`. + +On the GV310LAU block right after this: its skips start with `// led state`, which only +lines up if `index` points at LED on — which is what this patch produces. On master the +index is one further along, so the ADC reads there look like they were already one field +late. I don't have that device's protocol document, so please confirm. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3106d83c30e8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6021/solution/patch.diff b/tasks/traccar__traccar-6021/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3d20e803f13825dd6b64d210c28b762f85b744b7 --- /dev/null +++ b/tasks/traccar__traccar-6021/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +index 0f8fe8060..c70e9227a 100644 +--- a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +@@ -260,7 +260,7 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_BATTERY, Double.parseDouble(v[index - 1])); + } + if (!v[index++].isEmpty()) { +- position.set(Position.KEY_CHARGE, Integer.parseInt(v[index++]) == 1 ? true : null); ++ position.set(Position.KEY_CHARGE, Integer.parseInt(v[index - 1]) == 1 ? true : null); + } + + if (model.equals("GV310LAU")) { +diff --git a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +index 597c5a5d6..db2f7e08e 100644 +--- a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Gl200TextProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Gl200TextProtocolDecoder(null)); + ++ verifyAttribute(decoder, buffer( ++ "+RESP:GTINF,C30302,860201067023286,,41,89880000000000000000,14,99,0,0.0,,3.77,0,1,2,,,20260908143011,30,,25.9,,,20260909020028,46B4$"), ++ Position.KEY_CHARGE, null); ++ + verifyPositions(decoder, buffer( + "+RESP:GTFRI,DF0200,868487004353181,cv100,14051,10,1,0,0.0,0,264.1,114.015515,22.537178,20210608064328,0460,0001,25F8,061A7D02,,0.0,,,,100,21,,,,20210608144354,32DB$")); + diff --git a/tasks/traccar__traccar-6021/solution/solve.sh b/tasks/traccar__traccar-6021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6021/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/traccar__traccar-6021/task.toml b/tasks/traccar__traccar-6021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d865fcf9d670b42c76c9f775653efb614cd98f0b --- /dev/null +++ b/tasks/traccar__traccar-6021/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6021" +description = "Gl200: read the GTINF charge flag from the Charging field" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "3106d83c30e8a564267f6020b3286122244efeb5" +reference = "https://github.com/traccar/traccar/pull/6021" +source_access = "auto" +built_at = "2026-11-16T16:09:42.542549+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b9022746bc28518cd2457da04efb157b9b715e22f0d52802455d5acc637d4e54" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T00:43:08Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.522280+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9875af9b7e1d15c6a8313bced7c3b87a68518fed5a5785545ebcea2b2b1eb6b9" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6021/tests/capture.py b/tasks/traccar__traccar-6021/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6021/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/traccar__traccar-6021/tests/instruction.md b/tasks/traccar__traccar-6021/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e27234f4c9da0319786ab35a552c92400c34cfb --- /dev/null +++ b/tasks/traccar__traccar-6021/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Gl200: read the GTINF charge flag from the Charging field + +## Description + +`decodeInf` consumes the Charging field in the `if` and then parses the *next* field +(LED on) as the charge flag, so `charge` is true whenever the LED is on, and the index +runs one field ahead for everything after it. + +The GL300 @Track Air Interface Protocol (rev 6.00, §3.3.2 Device Information Report) +lists the GTINF tail in this order: + +``` +... Battery voltage, Charging, LED on, GPS on need, GPS antenna type, + GPS antenna state, Last GPS fix UTC time, battery percentage, ... +``` + +Observed on a GL320MG (protocol version prefix C3): 286 GTINF frames between +2026-08-27 and 2026-09-09 all report LED on = 1, and 280 of them report Charging = 0. +Traccar stored `charge: true` for all 286. + +Fix: parse `v[index - 1]`. The fixture is one of those frames, asserting `charge` is +absent; on master the same frame decodes as `charge: true`. + +On the GV310LAU block right after this: its skips start with `// led state`, which only +lines up if `index` points at LED on — which is what this patch produces. On master the +index is one further along, so the ADC reads there look like they were already one field +late. I don't have that device's protocol document, so please confirm. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3106d83c30e8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6021/tests/oracle.patch b/tasks/traccar__traccar-6021/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3d20e803f13825dd6b64d210c28b762f85b744b7 --- /dev/null +++ b/tasks/traccar__traccar-6021/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +index 0f8fe8060..c70e9227a 100644 +--- a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +@@ -260,7 +260,7 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_BATTERY, Double.parseDouble(v[index - 1])); + } + if (!v[index++].isEmpty()) { +- position.set(Position.KEY_CHARGE, Integer.parseInt(v[index++]) == 1 ? true : null); ++ position.set(Position.KEY_CHARGE, Integer.parseInt(v[index - 1]) == 1 ? true : null); + } + + if (model.equals("GV310LAU")) { +diff --git a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +index 597c5a5d6..db2f7e08e 100644 +--- a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Gl200TextProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Gl200TextProtocolDecoder(null)); + ++ verifyAttribute(decoder, buffer( ++ "+RESP:GTINF,C30302,860201067023286,,41,89880000000000000000,14,99,0,0.0,,3.77,0,1,2,,,20260908143011,30,,25.9,,,20260909020028,46B4$"), ++ Position.KEY_CHARGE, null); ++ + verifyPositions(decoder, buffer( + "+RESP:GTFRI,DF0200,868487004353181,cv100,14051,10,1,0,0.0,0,264.1,114.015515,22.537178,20210608064328,0460,0001,25F8,061A7D02,,0.0,,,,100,21,,,,20210608144354,32DB$")); + diff --git a/tasks/traccar__traccar-6021/tests/test.sh b/tasks/traccar__traccar-6021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3e3921fb5d46479e6e304d1b5e4fae90a5814166 --- /dev/null +++ b/tasks/traccar__traccar-6021/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 3106d83c30e8a564267f6020b3286122244efeb5 > "$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/traccar__traccar-6021/tests/verifier.py b/tasks/traccar__traccar-6021/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-6021/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/traccar__traccar-6024/environment/Dockerfile b/tasks/traccar__traccar-6024/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6e1a71e2204b5ca0a8c2c7cb4b8d9573afb8d601 --- /dev/null +++ b/tasks/traccar__traccar-6024/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a42b1190a08d0742d031485a76f9c91336d7dc8b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a42b1190a08d0742d031485a76f9c91336d7dc8b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a42b1190a08d0742d031485a76f9c91336d7dc8b \ + && 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/traccar__traccar-6024/instruction.md b/tasks/traccar__traccar-6024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e5b848bab6fdb6d5eac89f1acb9a3504ce3a00f9 --- /dev/null +++ b/tasks/traccar__traccar-6024/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** Fix T800x vehicle bus data alignment + +## Description + +The vehicle bus block at the end of the TopFlyTech `0x2626` position message (TLD2-D, TLD1-DA/DE) is read two bytes late, and only its first single-byte value is ever read. + + (#5555) started reading speed from bytes 65–66 but kept the `KEY_OBD_SPEED` read that was already consuming those two bytes, so everything after it shifted by two. Separately, since the block was added in , the seven single-byte values are all evaluated from one `readUnsignedByte()`. + +The attached [TOPFLYtech 0x26 0x26 Protocol 2023-08-02](https://github.com/user-attachments/files/32117883/TOPFLYtech.0x260x26.Protocol.2023-08-02.TorchX.100.TLD2-D.TLD1-DA.or.DE.xlsx), sheet `0x260x260x02`, lists the tail of the 83-byte message as: + +| Bytes | Field | +|---|---| +| 65–66 | speed (BCD, 0.1 km/h) | +| 67–70 | accumulated fuel consumption (ml) | +| 71–74 | instant fuel consumption (ml/h) | +| 75–76 | RPM | +| 77–83 | air input, air pressure, coolant temperature, air inflow temperature, engine load, throttle position, remaining fuel | + +It also says `0xFF` means the value can't be read from the vehicle, and that remaining fuel is in litres when its most significant bit is set and a percentage otherwise. There is no OBD speed field. + +This change: +- drops the `KEY_OBD_SPEED` read and reads each single-byte value separately; +- skips unavailable values per field, including the fuel counters and RPM; +- stores the percentage case in `KEY_FUEL_LEVEL` — `KEY_FUEL` means litres since #5670/#5674, and the rename was applied mechanically here. + +The fixtures are the two existing `0x2626` frames, now asserting values instead of only the position: + +- The TLD2-D frame from #5555. On master: `rpm=65280`, `airTemp=93`, `engineLoad=133`, `throttle=133`, `fuel=133`. With this change: `rpm=858`, `airTemp=54`, `engineLoad=15`, `throttle=14`, `fuelLevel=32`. +- A frame where only the remaining fuel byte is available. On master: `fuelUsed=165871.615`, `fuelConsumption=4294967.295`, `rpm=65535`, no fuel level. With this change: `fuelUsed=2.53`, `fuelLevel=9`. + +This also affects fuel events. `FuelEventHandler` raises fuel increase and drop events from changes in `fuel`, and on master that attribute receives the raw coolant byte — `fuel=133` in the first fixture, next to `coolantTemp=93`. With a threshold configured, a coolant temperature change of that size is reported as a fuel event. With this change `fuel` is only set when the device reports litres. + +Also checked on three TLD2-D units on three vehicles. Availability differs per vehicle, even between adjacent bytes: a 2017 Ford reports air pressure but not air input, and a 2026 Toyota the opposite. The third vehicle reports nothing at all; on master every one of its positions carries `fuelUsed=65.535`, `fuelConsumption=4294967.295` and `rpm=65535`. + +This is the first of a few small `0x2626` fixes; the others will follow one at a time. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a42b1190a08d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6024/solution/patch.diff b/tasks/traccar__traccar-6024/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..10d8179bb5f804435e95a925be3f1b5e2b26e52c --- /dev/null +++ b/tasks/traccar__traccar-6024/solution/patch.diff @@ -0,0 +1,88 @@ +diff --git a/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java b/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java +index 03935b8d5..8d59791da 100644 +--- a/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java +@@ -498,32 +498,49 @@ public class T800xProtocolDecoder extends BaseProtocolDecoder { + } + if (buf.readableBytes() >= 19) { + position.setSpeed(UnitsConverter.knotsFromKph(BcdUtil.readInteger(buf, 4) / 10.0)); +- position.set(Position.KEY_OBD_SPEED, BcdUtil.readInteger(buf, 4) / 100.0); +- position.set(Position.KEY_FUEL_USED, buf.readUnsignedInt() / 1000.0); +- position.set(Position.KEY_FUEL_CONSUMPTION, buf.readUnsignedInt() / 1000.0); +- position.set(Position.KEY_RPM, buf.readUnsignedShort()); +- int value; ++ long fuelUsed = buf.readUnsignedInt(); ++ if (fuelUsed != 0xffffffffL) { ++ position.set(Position.KEY_FUEL_USED, fuelUsed / 1000.0); ++ } ++ long fuelConsumption = buf.readUnsignedInt(); ++ if (fuelConsumption != 0xffffffffL) { ++ position.set(Position.KEY_FUEL_CONSUMPTION, fuelConsumption / 1000.0); ++ } ++ int value = buf.readUnsignedShort(); ++ if (value != 0xffff) { ++ position.set(Position.KEY_RPM, value); ++ } + value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set("airInput", value); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set("airPressure", value); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set(Position.KEY_COOLANT_TEMP, value - 40); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set("airTemp", value - 40); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set(Position.KEY_ENGINE_LOAD, value); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set(Position.KEY_THROTTLE, value); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { +- position.set(Position.KEY_FUEL, value); ++ if (BitUtil.check(value, 7)) { ++ position.set(Position.KEY_FUEL, BitUtil.to(value, 7)); ++ } else { ++ position.set(Position.KEY_FUEL_LEVEL, value); ++ } + } + } + } +diff --git a/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java +index 5082c3095..26cb78b4f 100644 +--- a/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java +@@ -24,8 +24,9 @@ public class T800xProtocolDecoderTest extends ProtocolTest { + "252513005909060867284062764958000a02581900640064480000050700000000000000000000ffffffffffff00d50004cf180026061510121100c03745a8c24d422ae00e420010011203911297ffffff0000280003ffffff"), + Position.KEY_POWER, 12.97); + +- verifyPosition(decoder, binary( +- "262602005356f408696160608183510032012c140064001f51c000010100004004000000b187660025050814571700000000571b74c2b0fa0bc2000000bc130701500000000700000000035aff00855e0f0e20")); ++ verifyAttribute(decoder, binary( ++ "262602005356f408696160608183510032012c140064001f51c000010100004004000000b187660025050814571700000000571b74c2b0fa0bc2000000bc130701500000000700000000035aff00855e0f0e20"), ++ Position.KEY_RPM, 858); + + verifyAttributes(decoder, binary( + "25251300594a1b0869738060144917003c0e101e03e85a2dc8c00005070000410000000000000000000000005b000003a5b45e00230919102252e3a5094288fabfc0e98b15420000010403921352ffff0000001cffffffffff25251300594a1c0869738060144917003c0e101e03e85a2ac7c00005070000410000000000000000000000002d000003a5b48b002309191023522d320642abfebfc0e98b15420000010c03921345ffff0000001bffffffffff25251300594a1d0869738060144917003c0e101e03e85a1ac9c000050700004100000000000000000000000024000003a5b4af00230919102452b81ef9410002c0c0ec8b15420108011403911345ffff0000001dffffffffff25251300594a1e0869738060144917003c0e101e03e85a3ec7c00005070000410000000000000000000000000e000003a5b4bd002309191025060ad7ec41da02c0c0058c15420084016303921345ffff0000001cffffffffff25251300594a1f0869738060144917003c0e101e03e85a3ec7c020050700004100000000000000000000000005000003a5b4c2002309191025090e2deb410203c0c0108c15420089014303921338ffff0000001dffffffffff25251300594a200869738060144917003c0e101e03e85a1ec5c000050700004100000000000000000000000020000003a5b4e20023091910260948e1bc412205c0c0458c15420040013603921355ffff0000001bffffffffff25251300594a210869738060144917003c0e101e03e85a00c5c020050700004100000000000000000000000000000003a5b4e20023091910270948e1bc412205c0c0458c15420040013603911332ffff0000001dffffffffff")); +@@ -55,8 +56,9 @@ public class T800xProtocolDecoderTest extends ProtocolTest { + "2727020049052e086528404072393849002008060310110000000068b7c8c286eaa441000000008000008100001617410700019ce782b0001e000002581e00000530d4801f00000000"), + Position.KEY_BATTERY_LEVEL, 100); + +- verifyPosition(decoder, binary( +- "262602005308090865284040309670000f000f0f0000005a47c000050100000020000000008bfd0020022505185300004041dcc9d6c243b3c6410000012712400000000009e2ffffffffffffffffffffffff09")); ++ verifyAttribute(decoder, binary( ++ "262602005308090865284040309670000f000f0f0000005a47c000050100000020000000008bfd0020022505185300004041dcc9d6c243b3c6410000012712400000000009e2ffffffffffffffffffffffff09"), ++ Position.KEY_FUEL_LEVEL, 9); + + verifyPosition(decoder, binary( + "2727040049001b0866425039645728c916190604005240000000007739d2c25b681f420000000080000081000020174105000005458216001e000000f01e00001e30d0000000000000")); diff --git a/tasks/traccar__traccar-6024/solution/solve.sh b/tasks/traccar__traccar-6024/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6024/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/traccar__traccar-6024/task.toml b/tasks/traccar__traccar-6024/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a0f62a065a45d8254ede7f358fbc3317971c0904 --- /dev/null +++ b/tasks/traccar__traccar-6024/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6024" +description = "Fix T800x vehicle bus data alignment" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "a42b1190a08d0742d031485a76f9c91336d7dc8b" +reference = "https://github.com/traccar/traccar/pull/6024" +source_access = "auto" +built_at = "2026-11-16T16:09:42.539393+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b2093fbe1c7c037c5f1501cdd73ee9d65f0a61a2d3e25e673e457f6738852551" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-11T18:20:33Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/T800xProtocolDecoder.java", + "src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 39 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.522891+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2a002fd2b3e2b6cef23706f9c1905683e14eabc00741a76253b67aaf98f1caae" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6024/tests/capture.py b/tasks/traccar__traccar-6024/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6024/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/traccar__traccar-6024/tests/instruction.md b/tasks/traccar__traccar-6024/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e5b848bab6fdb6d5eac89f1acb9a3504ce3a00f9 --- /dev/null +++ b/tasks/traccar__traccar-6024/tests/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** Fix T800x vehicle bus data alignment + +## Description + +The vehicle bus block at the end of the TopFlyTech `0x2626` position message (TLD2-D, TLD1-DA/DE) is read two bytes late, and only its first single-byte value is ever read. + + (#5555) started reading speed from bytes 65–66 but kept the `KEY_OBD_SPEED` read that was already consuming those two bytes, so everything after it shifted by two. Separately, since the block was added in , the seven single-byte values are all evaluated from one `readUnsignedByte()`. + +The attached [TOPFLYtech 0x26 0x26 Protocol 2023-08-02](https://github.com/user-attachments/files/32117883/TOPFLYtech.0x260x26.Protocol.2023-08-02.TorchX.100.TLD2-D.TLD1-DA.or.DE.xlsx), sheet `0x260x260x02`, lists the tail of the 83-byte message as: + +| Bytes | Field | +|---|---| +| 65–66 | speed (BCD, 0.1 km/h) | +| 67–70 | accumulated fuel consumption (ml) | +| 71–74 | instant fuel consumption (ml/h) | +| 75–76 | RPM | +| 77–83 | air input, air pressure, coolant temperature, air inflow temperature, engine load, throttle position, remaining fuel | + +It also says `0xFF` means the value can't be read from the vehicle, and that remaining fuel is in litres when its most significant bit is set and a percentage otherwise. There is no OBD speed field. + +This change: +- drops the `KEY_OBD_SPEED` read and reads each single-byte value separately; +- skips unavailable values per field, including the fuel counters and RPM; +- stores the percentage case in `KEY_FUEL_LEVEL` — `KEY_FUEL` means litres since #5670/#5674, and the rename was applied mechanically here. + +The fixtures are the two existing `0x2626` frames, now asserting values instead of only the position: + +- The TLD2-D frame from #5555. On master: `rpm=65280`, `airTemp=93`, `engineLoad=133`, `throttle=133`, `fuel=133`. With this change: `rpm=858`, `airTemp=54`, `engineLoad=15`, `throttle=14`, `fuelLevel=32`. +- A frame where only the remaining fuel byte is available. On master: `fuelUsed=165871.615`, `fuelConsumption=4294967.295`, `rpm=65535`, no fuel level. With this change: `fuelUsed=2.53`, `fuelLevel=9`. + +This also affects fuel events. `FuelEventHandler` raises fuel increase and drop events from changes in `fuel`, and on master that attribute receives the raw coolant byte — `fuel=133` in the first fixture, next to `coolantTemp=93`. With a threshold configured, a coolant temperature change of that size is reported as a fuel event. With this change `fuel` is only set when the device reports litres. + +Also checked on three TLD2-D units on three vehicles. Availability differs per vehicle, even between adjacent bytes: a 2017 Ford reports air pressure but not air input, and a 2026 Toyota the opposite. The third vehicle reports nothing at all; on master every one of its positions carries `fuelUsed=65.535`, `fuelConsumption=4294967.295` and `rpm=65535`. + +This is the first of a few small `0x2626` fixes; the others will follow one at a time. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a42b1190a08d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6024/tests/oracle.patch b/tasks/traccar__traccar-6024/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..10d8179bb5f804435e95a925be3f1b5e2b26e52c --- /dev/null +++ b/tasks/traccar__traccar-6024/tests/oracle.patch @@ -0,0 +1,88 @@ +diff --git a/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java b/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java +index 03935b8d5..8d59791da 100644 +--- a/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java +@@ -498,32 +498,49 @@ public class T800xProtocolDecoder extends BaseProtocolDecoder { + } + if (buf.readableBytes() >= 19) { + position.setSpeed(UnitsConverter.knotsFromKph(BcdUtil.readInteger(buf, 4) / 10.0)); +- position.set(Position.KEY_OBD_SPEED, BcdUtil.readInteger(buf, 4) / 100.0); +- position.set(Position.KEY_FUEL_USED, buf.readUnsignedInt() / 1000.0); +- position.set(Position.KEY_FUEL_CONSUMPTION, buf.readUnsignedInt() / 1000.0); +- position.set(Position.KEY_RPM, buf.readUnsignedShort()); +- int value; ++ long fuelUsed = buf.readUnsignedInt(); ++ if (fuelUsed != 0xffffffffL) { ++ position.set(Position.KEY_FUEL_USED, fuelUsed / 1000.0); ++ } ++ long fuelConsumption = buf.readUnsignedInt(); ++ if (fuelConsumption != 0xffffffffL) { ++ position.set(Position.KEY_FUEL_CONSUMPTION, fuelConsumption / 1000.0); ++ } ++ int value = buf.readUnsignedShort(); ++ if (value != 0xffff) { ++ position.set(Position.KEY_RPM, value); ++ } + value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set("airInput", value); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set("airPressure", value); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set(Position.KEY_COOLANT_TEMP, value - 40); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set("airTemp", value - 40); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set(Position.KEY_ENGINE_LOAD, value); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { + position.set(Position.KEY_THROTTLE, value); + } ++ value = buf.readUnsignedByte(); + if (value != 0xff) { +- position.set(Position.KEY_FUEL, value); ++ if (BitUtil.check(value, 7)) { ++ position.set(Position.KEY_FUEL, BitUtil.to(value, 7)); ++ } else { ++ position.set(Position.KEY_FUEL_LEVEL, value); ++ } + } + } + } +diff --git a/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java +index 5082c3095..26cb78b4f 100644 +--- a/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java +@@ -24,8 +24,9 @@ public class T800xProtocolDecoderTest extends ProtocolTest { + "252513005909060867284062764958000a02581900640064480000050700000000000000000000ffffffffffff00d50004cf180026061510121100c03745a8c24d422ae00e420010011203911297ffffff0000280003ffffff"), + Position.KEY_POWER, 12.97); + +- verifyPosition(decoder, binary( +- "262602005356f408696160608183510032012c140064001f51c000010100004004000000b187660025050814571700000000571b74c2b0fa0bc2000000bc130701500000000700000000035aff00855e0f0e20")); ++ verifyAttribute(decoder, binary( ++ "262602005356f408696160608183510032012c140064001f51c000010100004004000000b187660025050814571700000000571b74c2b0fa0bc2000000bc130701500000000700000000035aff00855e0f0e20"), ++ Position.KEY_RPM, 858); + + verifyAttributes(decoder, binary( + "25251300594a1b0869738060144917003c0e101e03e85a2dc8c00005070000410000000000000000000000005b000003a5b45e00230919102252e3a5094288fabfc0e98b15420000010403921352ffff0000001cffffffffff25251300594a1c0869738060144917003c0e101e03e85a2ac7c00005070000410000000000000000000000002d000003a5b48b002309191023522d320642abfebfc0e98b15420000010c03921345ffff0000001bffffffffff25251300594a1d0869738060144917003c0e101e03e85a1ac9c000050700004100000000000000000000000024000003a5b4af00230919102452b81ef9410002c0c0ec8b15420108011403911345ffff0000001dffffffffff25251300594a1e0869738060144917003c0e101e03e85a3ec7c00005070000410000000000000000000000000e000003a5b4bd002309191025060ad7ec41da02c0c0058c15420084016303921345ffff0000001cffffffffff25251300594a1f0869738060144917003c0e101e03e85a3ec7c020050700004100000000000000000000000005000003a5b4c2002309191025090e2deb410203c0c0108c15420089014303921338ffff0000001dffffffffff25251300594a200869738060144917003c0e101e03e85a1ec5c000050700004100000000000000000000000020000003a5b4e20023091910260948e1bc412205c0c0458c15420040013603921355ffff0000001bffffffffff25251300594a210869738060144917003c0e101e03e85a00c5c020050700004100000000000000000000000000000003a5b4e20023091910270948e1bc412205c0c0458c15420040013603911332ffff0000001dffffffffff")); +@@ -55,8 +56,9 @@ public class T800xProtocolDecoderTest extends ProtocolTest { + "2727020049052e086528404072393849002008060310110000000068b7c8c286eaa441000000008000008100001617410700019ce782b0001e000002581e00000530d4801f00000000"), + Position.KEY_BATTERY_LEVEL, 100); + +- verifyPosition(decoder, binary( +- "262602005308090865284040309670000f000f0f0000005a47c000050100000020000000008bfd0020022505185300004041dcc9d6c243b3c6410000012712400000000009e2ffffffffffffffffffffffff09")); ++ verifyAttribute(decoder, binary( ++ "262602005308090865284040309670000f000f0f0000005a47c000050100000020000000008bfd0020022505185300004041dcc9d6c243b3c6410000012712400000000009e2ffffffffffffffffffffffff09"), ++ Position.KEY_FUEL_LEVEL, 9); + + verifyPosition(decoder, binary( + "2727040049001b0866425039645728c916190604005240000000007739d2c25b681f420000000080000081000020174105000005458216001e000000f01e00001e30d0000000000000")); diff --git a/tasks/traccar__traccar-6024/tests/test.sh b/tasks/traccar__traccar-6024/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b69679391c1537197f240f3f84ee7aa374cd56da --- /dev/null +++ b/tasks/traccar__traccar-6024/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 a42b1190a08d0742d031485a76f9c91336d7dc8b > "$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/traccar__traccar-6024/tests/verifier.py b/tasks/traccar__traccar-6024/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-6024/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/traccar__traccar-6025/environment/Dockerfile b/tasks/traccar__traccar-6025/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f7cf4f8f5986aba1df155e2761f9faa87255d89a --- /dev/null +++ b/tasks/traccar__traccar-6025/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f8141eff6d2e8443c9f70a1c6b6143ca0189795b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f8141eff6d2e8443c9f70a1c6b6143ca0189795b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f8141eff6d2e8443c9f70a1c6b6143ca0189795b \ + && 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/traccar__traccar-6025/instruction.md b/tasks/traccar__traccar-6025/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aab26c95380d1a972a4e6482cbee538ec6810a14 --- /dev/null +++ b/tasks/traccar__traccar-6025/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** Skip empty T800x 0x2626 cell towers + +## Description + +. + +When a TopFlyTech `0x2626` position has no GNSS fix, bytes 47–62 carry MCC, MNC and three LAC/CI pairs. If MCC and MNC are `0xFFFF` the decoder doesn't build the network, but it also doesn't consume the three pairs, so the rest of the message is read 12 bytes early. + +In the [TOPFLYtech 0x26 0x26 Protocol 2023-08-02](https://github.com/user-attachments/files/32117883/TOPFLYtech.0x260x26.Protocol.2023-08-02.TorchX.100.TLD2-D.TLD1-DA.or.DE.xlsx) document (the same one attached to #6024), sheet `0x260x260x02`, the block is a fixed 16 bytes, filled with `0xFF` when there is no cell information. + +A TLD2-D sends these frames when it has neither a fix nor cell data — 4 of the 429 position and alarm messages from one unit over a day. The fixture is one of them, an ignition-off alarm with the external supply at 12.12 V. On master it decodes as `power=166.65`, a speed of 1666.5 km/h, `rpm=4626` and `coolantTemp=-40`; with this change `power=12.12` and speed 0. + +The skip is limited to `0x2626`, the only variant I could verify. The T880X (`0x2323`) specification has the same fixed block, but nothing follows it there, so it makes no difference. If `0x2525` and `0x2727` also always include the block, the condition can go — you'd know better than me. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f8141eff6d2e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6025/solution/patch.diff b/tasks/traccar__traccar-6025/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e1d0f60a5ca3b7c8bdc5e2beb6745d2fa00df051 --- /dev/null +++ b/tasks/traccar__traccar-6025/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java b/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java +index 8d59791da..1e3f352c6 100644 +--- a/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java +@@ -445,6 +445,8 @@ public class T800xProtocolDecoder extends BaseProtocolDecoder { + mcc, mnc, buf.readUnsignedShortLE(), buf.readUnsignedShortLE())); + } + position.setNetwork(network); ++ } else if (header == 0x2626) { ++ buf.skipBytes(12); // cell towers + } + + } +diff --git a/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java +index 26cb78b4f..1c7331314 100644 +--- a/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class T800xProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new T800xProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "262604005330c40863257069370825001902581e0000003f80c0200505000000041600001b5b2800260908230233ffffffffffffffffffffffffffffffff1212000000000000ffffffffffffffffffffffffff"), ++ Position.KEY_POWER, 12.12); ++ + verifyPositions(decoder, false, binary( + "26260500400406086961606257315205250513182132ffffffffffffffffffffffff0000ffff0000250513182137ffffffffffffffffffffffff0770ffff0aec")); + diff --git a/tasks/traccar__traccar-6025/solution/solve.sh b/tasks/traccar__traccar-6025/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6025/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/traccar__traccar-6025/task.toml b/tasks/traccar__traccar-6025/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0b0826cb58b12fbcdc3973d1847cb53adb70620a --- /dev/null +++ b/tasks/traccar__traccar-6025/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6025" +description = "Skip empty T800x 0x2626 cell towers" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "f8141eff6d2e8443c9f70a1c6b6143ca0189795b" +reference = "https://github.com/traccar/traccar/pull/6025" +source_access = "auto" +built_at = "2026-11-16T16:09:42.537711+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:bf3671c79d2b63e9d2f177a9d8f1f35375405c44fb198afe08a1c6f0e2697dde" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-12T04:52:07Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/T800xProtocolDecoder.java", + "src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.523421+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6a6fca25353e6e9f239d4fade11e545bd9e48c0cb1e97b96b6240c0c46734b15" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6025/tests/capture.py b/tasks/traccar__traccar-6025/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6025/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/traccar__traccar-6025/tests/instruction.md b/tasks/traccar__traccar-6025/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aab26c95380d1a972a4e6482cbee538ec6810a14 --- /dev/null +++ b/tasks/traccar__traccar-6025/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** Skip empty T800x 0x2626 cell towers + +## Description + +. + +When a TopFlyTech `0x2626` position has no GNSS fix, bytes 47–62 carry MCC, MNC and three LAC/CI pairs. If MCC and MNC are `0xFFFF` the decoder doesn't build the network, but it also doesn't consume the three pairs, so the rest of the message is read 12 bytes early. + +In the [TOPFLYtech 0x26 0x26 Protocol 2023-08-02](https://github.com/user-attachments/files/32117883/TOPFLYtech.0x260x26.Protocol.2023-08-02.TorchX.100.TLD2-D.TLD1-DA.or.DE.xlsx) document (the same one attached to #6024), sheet `0x260x260x02`, the block is a fixed 16 bytes, filled with `0xFF` when there is no cell information. + +A TLD2-D sends these frames when it has neither a fix nor cell data — 4 of the 429 position and alarm messages from one unit over a day. The fixture is one of them, an ignition-off alarm with the external supply at 12.12 V. On master it decodes as `power=166.65`, a speed of 1666.5 km/h, `rpm=4626` and `coolantTemp=-40`; with this change `power=12.12` and speed 0. + +The skip is limited to `0x2626`, the only variant I could verify. The T880X (`0x2323`) specification has the same fixed block, but nothing follows it there, so it makes no difference. If `0x2525` and `0x2727` also always include the block, the condition can go — you'd know better than me. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f8141eff6d2e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6025/tests/oracle.patch b/tasks/traccar__traccar-6025/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e1d0f60a5ca3b7c8bdc5e2beb6745d2fa00df051 --- /dev/null +++ b/tasks/traccar__traccar-6025/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java b/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java +index 8d59791da..1e3f352c6 100644 +--- a/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/T800xProtocolDecoder.java +@@ -445,6 +445,8 @@ public class T800xProtocolDecoder extends BaseProtocolDecoder { + mcc, mnc, buf.readUnsignedShortLE(), buf.readUnsignedShortLE())); + } + position.setNetwork(network); ++ } else if (header == 0x2626) { ++ buf.skipBytes(12); // cell towers + } + + } +diff --git a/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java +index 26cb78b4f..1c7331314 100644 +--- a/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/T800xProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class T800xProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new T800xProtocolDecoder(null)); + ++ verifyAttribute(decoder, binary( ++ "262604005330c40863257069370825001902581e0000003f80c0200505000000041600001b5b2800260908230233ffffffffffffffffffffffffffffffff1212000000000000ffffffffffffffffffffffffff"), ++ Position.KEY_POWER, 12.12); ++ + verifyPositions(decoder, false, binary( + "26260500400406086961606257315205250513182132ffffffffffffffffffffffff0000ffff0000250513182137ffffffffffffffffffffffff0770ffff0aec")); + diff --git a/tasks/traccar__traccar-6025/tests/test.sh b/tasks/traccar__traccar-6025/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..40622f64ec4c626ba10e55bcb4c3426e3d677e27 --- /dev/null +++ b/tasks/traccar__traccar-6025/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 f8141eff6d2e8443c9f70a1c6b6143ca0189795b > "$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/traccar__traccar-6025/tests/verifier.py b/tasks/traccar__traccar-6025/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-6025/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/traccar__traccar-6031/environment/Dockerfile b/tasks/traccar__traccar-6031/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7200ad8456de0d08fa234abd6514fe351267cc61 --- /dev/null +++ b/tasks/traccar__traccar-6031/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c3332bcc0d99f879b1461af89e9f618284754f09 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c3332bcc0d99f879b1461af89e9f618284754f09 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c3332bcc0d99f879b1461af89e9f618284754f09 \ + && 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/traccar__traccar-6031/instruction.md b/tasks/traccar__traccar-6031/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1ea61927679592ed777930f871968413569afe65 --- /dev/null +++ b/tasks/traccar__traccar-6031/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Handle NaN GPS coordinates in Xexun3 protocol decoder + +## Description + +**Summary** + +The Xexun3 protocol decoder was accepting NaN GPS coordinates (sent by the device as 0xFFFFFFFFFFFFFFFF when there is no GPS fix) as a valid location, resulting in positions with valid=true and lat/lon=NaN. + +In the GPS body handler (case 0x64), latitude and longitude are now checked with before being set on the position. If either value is NaN or infinite, valid is not set to true and hasLocation remains false, so getLastLocation() fills in the last known position instead. + +Added a test entry in Xexun3ProtocolDecoderTest using a real device frame with NaN coordinates and LBS cell tower data, asserting the decoded position is valid=false with lat=0, lon=0. + +**Log evidence:** + +``` +2026-09-14 16:51:46 INFO: [T5b13abe3: xexun3 < 185.57.216.166] fc005c0320140**862596080926201**64226aa8261dffffffffffffffffffffffffffffffff00000637004b000641000006913c66116aa8261d01060003000091c400ce5421ff6a1863000116061d000008ffffffffffffff6aa8261d01010000bbfccf +2026-09-14 16:51:46 INFO: [T5b13abe3: xexun3 > 185.57.216.166] fc000c0320140862596080926201006800cf +2026-09-14 16:51:49 INFO: [T5b13abe3] id: **862596080926201**, time: 2026-09-14 16:51:41, lat: **NaN**, lon: **NaN**, speed: 864.5, course: 0.0 +``` + +**Xexun Protocol Documentation (NEW)** +[Xexun API 260614 en.docx](https://github.com/user-attachments/files/32237433/Xexun.API.260614.en.docx) + +This also produced an **Frontend Error**: + +image + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c3332bcc0d99`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6031/solution/patch.diff b/tasks/traccar__traccar-6031/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5da82d5f7e604c9b12f861c9e11058bfe9e62d9a --- /dev/null +++ b/tasks/traccar__traccar-6031/solution/patch.diff @@ -0,0 +1,44 @@ +diff --git a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +index d14b1260f..78419846c 100644 +--- a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +@@ -118,15 +118,19 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder { + switch (subType) { + case 0x64 -> { + position.setTime(new Date(buf.readUnsignedInt() * 1000)); +- position.setValid(true); +- position.setLatitude(buf.readDouble()); +- position.setLongitude(buf.readDouble()); ++ double latitude = buf.readDouble(); ++ double longitude = buf.readDouble(); ++ if (Double.isFinite(latitude) && Double.isFinite(longitude)) { ++ position.setValid(true); ++ position.setLatitude(latitude); ++ position.setLongitude(longitude); ++ hasLocation = true; ++ } + position.setAltitude(buf.readFloat()); + buf.readUnsignedByte(); // ephemeris + position.set(Position.KEY_SATELLITES, buf.readUnsignedByte()); + buf.readUnsignedByte(); // signal + position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort())); +- hasLocation = true; + } + case 0x65 -> { + position.setDeviceTime(new Date(buf.readUnsignedInt() * 1000)); +diff --git a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java +index 02f506e10..30e803395 100644 +--- a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java +@@ -16,6 +16,11 @@ public class Xexun3ProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, binary( + "fc0040032006086104508038701564216913f223403693012f635344405c829142b302f7427f33331a2e000000a40011046a1055ffff1f0000000000ffffff04ff09ff1a30cf")); + ++ // Frame with NaN GPS coordinates (0xFFFFFFFFFFFFFFFF) and LBS cell tower data — invalid fix ++ verifyPosition(decoder, binary( ++ "fc005c032014086259608092620164226aa8261dffffffffffffffffffffffffffffffff00000637004b000641000006913c66116aa8261d01060003000091c400ce5421ff6a1863000116061d000008ffffffffffffff6aa8261d01010000bbfccf"), ++ position("2026-09-14 16:51:41.000", false, 0, 0)); ++ + } + + } diff --git a/tasks/traccar__traccar-6031/solution/solve.sh b/tasks/traccar__traccar-6031/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6031/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/traccar__traccar-6031/task.toml b/tasks/traccar__traccar-6031/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bff2ad7a8296841177a6e03ff791bd22c4f785cc --- /dev/null +++ b/tasks/traccar__traccar-6031/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6031" +description = "Handle NaN GPS coordinates in Xexun3 protocol decoder" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "c3332bcc0d99f879b1461af89e9f618284754f09" +reference = "https://github.com/traccar/traccar/pull/6031" +source_access = "auto" +built_at = "2026-11-16T16:09:42.536220+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:da042e9b129d3bde60960cc39c869a74aae7fbbbcb9f4b708e84065676fa05de" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-15T13:28:51Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java", +] +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:03.523955+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c316de2cd25ac9addf398f44fabb43b96f10680dbac8875d70e43e34498f7245" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6031/tests/capture.py b/tasks/traccar__traccar-6031/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6031/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/traccar__traccar-6031/tests/instruction.md b/tasks/traccar__traccar-6031/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1ea61927679592ed777930f871968413569afe65 --- /dev/null +++ b/tasks/traccar__traccar-6031/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Handle NaN GPS coordinates in Xexun3 protocol decoder + +## Description + +**Summary** + +The Xexun3 protocol decoder was accepting NaN GPS coordinates (sent by the device as 0xFFFFFFFFFFFFFFFF when there is no GPS fix) as a valid location, resulting in positions with valid=true and lat/lon=NaN. + +In the GPS body handler (case 0x64), latitude and longitude are now checked with before being set on the position. If either value is NaN or infinite, valid is not set to true and hasLocation remains false, so getLastLocation() fills in the last known position instead. + +Added a test entry in Xexun3ProtocolDecoderTest using a real device frame with NaN coordinates and LBS cell tower data, asserting the decoded position is valid=false with lat=0, lon=0. + +**Log evidence:** + +``` +2026-09-14 16:51:46 INFO: [T5b13abe3: xexun3 < 185.57.216.166] fc005c0320140**862596080926201**64226aa8261dffffffffffffffffffffffffffffffff00000637004b000641000006913c66116aa8261d01060003000091c400ce5421ff6a1863000116061d000008ffffffffffffff6aa8261d01010000bbfccf +2026-09-14 16:51:46 INFO: [T5b13abe3: xexun3 > 185.57.216.166] fc000c0320140862596080926201006800cf +2026-09-14 16:51:49 INFO: [T5b13abe3] id: **862596080926201**, time: 2026-09-14 16:51:41, lat: **NaN**, lon: **NaN**, speed: 864.5, course: 0.0 +``` + +**Xexun Protocol Documentation (NEW)** +[Xexun API 260614 en.docx](https://github.com/user-attachments/files/32237433/Xexun.API.260614.en.docx) + +This also produced an **Frontend Error**: + +image + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c3332bcc0d99`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6031/tests/oracle.patch b/tasks/traccar__traccar-6031/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5da82d5f7e604c9b12f861c9e11058bfe9e62d9a --- /dev/null +++ b/tasks/traccar__traccar-6031/tests/oracle.patch @@ -0,0 +1,44 @@ +diff --git a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +index d14b1260f..78419846c 100644 +--- a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +@@ -118,15 +118,19 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder { + switch (subType) { + case 0x64 -> { + position.setTime(new Date(buf.readUnsignedInt() * 1000)); +- position.setValid(true); +- position.setLatitude(buf.readDouble()); +- position.setLongitude(buf.readDouble()); ++ double latitude = buf.readDouble(); ++ double longitude = buf.readDouble(); ++ if (Double.isFinite(latitude) && Double.isFinite(longitude)) { ++ position.setValid(true); ++ position.setLatitude(latitude); ++ position.setLongitude(longitude); ++ hasLocation = true; ++ } + position.setAltitude(buf.readFloat()); + buf.readUnsignedByte(); // ephemeris + position.set(Position.KEY_SATELLITES, buf.readUnsignedByte()); + buf.readUnsignedByte(); // signal + position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort())); +- hasLocation = true; + } + case 0x65 -> { + position.setDeviceTime(new Date(buf.readUnsignedInt() * 1000)); +diff --git a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java +index 02f506e10..30e803395 100644 +--- a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java +@@ -16,6 +16,11 @@ public class Xexun3ProtocolDecoderTest extends ProtocolTest { + verifyPosition(decoder, binary( + "fc0040032006086104508038701564216913f223403693012f635344405c829142b302f7427f33331a2e000000a40011046a1055ffff1f0000000000ffffff04ff09ff1a30cf")); + ++ // Frame with NaN GPS coordinates (0xFFFFFFFFFFFFFFFF) and LBS cell tower data — invalid fix ++ verifyPosition(decoder, binary( ++ "fc005c032014086259608092620164226aa8261dffffffffffffffffffffffffffffffff00000637004b000641000006913c66116aa8261d01060003000091c400ce5421ff6a1863000116061d000008ffffffffffffff6aa8261d01010000bbfccf"), ++ position("2026-09-14 16:51:41.000", false, 0, 0)); ++ + } + + } diff --git a/tasks/traccar__traccar-6031/tests/test.sh b/tasks/traccar__traccar-6031/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e99351cc96229b4ff186a3b0a98d486a43c2bf2d --- /dev/null +++ b/tasks/traccar__traccar-6031/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 c3332bcc0d99f879b1461af89e9f618284754f09 > "$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/traccar__traccar-6031/tests/verifier.py b/tasks/traccar__traccar-6031/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-6031/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/traccar__traccar-6032/environment/Dockerfile b/tasks/traccar__traccar-6032/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..61bd420b3ec4aee4f6dbeea355efd5d66fcb0fc8 --- /dev/null +++ b/tasks/traccar__traccar-6032/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 847edd2c8c4dcc47426fb76b7800b342dea3cde6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 847edd2c8c4dcc47426fb76b7800b342dea3cde6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 847edd2c8c4dcc47426fb76b7800b342dea3cde6 \ + && 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/traccar__traccar-6032/instruction.md b/tasks/traccar__traccar-6032/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d3474f09ae74979cbff098dd122af7881022165 --- /dev/null +++ b/tasks/traccar__traccar-6032/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** Fix Xexun3 GPS Body heading/course decoding (0x64) + +## Description + +**Summary:** + +Add heading field decoding to the Xexun3 GPS Body (subType 0x64). Per [Xexun API 260614 en.docx](https://github.com/user-attachments/files/32248351/Xexun.API.260614.en.docx) field 11, Heading is a U16 (big-endian) whose raw value must be divided by 10 to obtain degrees. + +Previously the decoder stopped after the Speed field (field 10) and skipped the heading bytes via buf.readerIndex(subEnd), so course was always 0.0. + +**Test changes:** +- Existing frame (fc0040...) changed from verifyPosition to verifyNotNull because its heading raw value (a4 00 = 41984 -> 4198.4 deg) is invalid and would fail the course <= 360 check in verifyPosition. +- New test entry with real device frame (fc00490320e8...) from IMEI 862596080926201, heading raw 00 9f = 159 -> 15.9 deg, verified via verifyAttribute course = 15.9. + +**Protocol documentation references:** +- Field 10 Speed (U16): divide by 10 for km/h (already handled, but devision by 10 is missing, follow-up PR) +- Field 11 Heading (U16): divide by 10 for degrees (this PR) +- Field 12 Accuracy factor (U16): skipped by subEnd (follow-up PR) +- Field 13 Tracking duration (U8): skipped by subEnd (follow-up PR) + +**Log evidence:** +``` +2026-09-15 11:43:31 INFO: [T11d03210: xexun3 < 185.57.216.148] fc00490320e8086259608092620164226aa92f624049b01fff79c842401c97788f16414443084ccd400e19001c009f000e006a18630000173a2f0001a3ffffffffffffff6aa92f622101000030f4cf +2026-09-15 11:43:31 INFO: [T11d03210: xexun3 > 185.57.216.148] fc000c0320e8086259608092620100b4cbcf +2026-09-15 11:43:32 INFO: Event id: 862596080926201, time: 2026-09-15 11:43:28, type: alarm, notifications: 0 +2026-09-15 11:43:32 INFO: [T11d03210] id: 862596080926201, time: 2026-09-15 11:43:09, lat: 51.37589, lon: 7.14771, course: 0.0 +2026-09-15 11:43:34 INFO: [T11d03210] id: 862596080926201, time: 2026-09-15 11:43:30, lat: 51.37598, lon: 7.14792, speed: 15.1, course: 0.0 +``` + +-- Cheers, Nils + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `847edd2c8c4d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6032/solution/patch.diff b/tasks/traccar__traccar-6032/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bf96552333e013df7a46f4d3aecdd67b614a3036 --- /dev/null +++ b/tasks/traccar__traccar-6032/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +index 78419846c..5b874a7f3 100644 +--- a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +@@ -131,6 +131,7 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_SATELLITES, buf.readUnsignedByte()); + buf.readUnsignedByte(); // signal + position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort())); ++ position.setCourse(buf.readUnsignedShort() / 10.0); + } + case 0x65 -> { + position.setDeviceTime(new Date(buf.readUnsignedInt() * 1000)); +diff --git a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java +index 9b69920df..4bc0f65a9 100644 +--- a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java +@@ -18,7 +18,8 @@ public class Xexun3ProtocolDecoderTest extends ProtocolTest { + "fc000b03200108610450803870158318cf")); + + verifyPosition(decoder, binary( +- "fc0040032006086104508038701564216913f223403693012f635344405c829142b302f7427f33331a2e000000a40011046a1055ffff1f0000000000ffffff04ff09ff1a30cf")); ++ "fc00490320e8086259608092620164226aa92f624049b01fff79c842401c97788f16414443084ccd400e19001c009f000e006a18630000173a2f0001a3ffffffffffffff6aa92f622101000030f4cf"), ++ position("2026-09-15 11:43:30.000", true, 51.37597649999999, 7.147920833333334)); + + } + diff --git a/tasks/traccar__traccar-6032/solution/solve.sh b/tasks/traccar__traccar-6032/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6032/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/traccar__traccar-6032/task.toml b/tasks/traccar__traccar-6032/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0852b021a81a8252d48233fd683862c301257bf4 --- /dev/null +++ b/tasks/traccar__traccar-6032/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6032" +description = "Fix Xexun3 GPS Body heading/course decoding (0x64)" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "847edd2c8c4dcc47426fb76b7800b342dea3cde6" +reference = "https://github.com/traccar/traccar/pull/6032" +source_access = "auto" +built_at = "2026-11-16T16:09:42.534721+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c9b8993ad7991770a27d2a31b3525d7b50dd5f7c39a89c555d0345989a82850a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-18T16:08:38Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.524510+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0d12d93c2d493f0067db6fc05642665272924c52936338508ee729203e86bf64" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6032/tests/capture.py b/tasks/traccar__traccar-6032/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6032/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/traccar__traccar-6032/tests/instruction.md b/tasks/traccar__traccar-6032/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d3474f09ae74979cbff098dd122af7881022165 --- /dev/null +++ b/tasks/traccar__traccar-6032/tests/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** Fix Xexun3 GPS Body heading/course decoding (0x64) + +## Description + +**Summary:** + +Add heading field decoding to the Xexun3 GPS Body (subType 0x64). Per [Xexun API 260614 en.docx](https://github.com/user-attachments/files/32248351/Xexun.API.260614.en.docx) field 11, Heading is a U16 (big-endian) whose raw value must be divided by 10 to obtain degrees. + +Previously the decoder stopped after the Speed field (field 10) and skipped the heading bytes via buf.readerIndex(subEnd), so course was always 0.0. + +**Test changes:** +- Existing frame (fc0040...) changed from verifyPosition to verifyNotNull because its heading raw value (a4 00 = 41984 -> 4198.4 deg) is invalid and would fail the course <= 360 check in verifyPosition. +- New test entry with real device frame (fc00490320e8...) from IMEI 862596080926201, heading raw 00 9f = 159 -> 15.9 deg, verified via verifyAttribute course = 15.9. + +**Protocol documentation references:** +- Field 10 Speed (U16): divide by 10 for km/h (already handled, but devision by 10 is missing, follow-up PR) +- Field 11 Heading (U16): divide by 10 for degrees (this PR) +- Field 12 Accuracy factor (U16): skipped by subEnd (follow-up PR) +- Field 13 Tracking duration (U8): skipped by subEnd (follow-up PR) + +**Log evidence:** +``` +2026-09-15 11:43:31 INFO: [T11d03210: xexun3 < 185.57.216.148] fc00490320e8086259608092620164226aa92f624049b01fff79c842401c97788f16414443084ccd400e19001c009f000e006a18630000173a2f0001a3ffffffffffffff6aa92f622101000030f4cf +2026-09-15 11:43:31 INFO: [T11d03210: xexun3 > 185.57.216.148] fc000c0320e8086259608092620100b4cbcf +2026-09-15 11:43:32 INFO: Event id: 862596080926201, time: 2026-09-15 11:43:28, type: alarm, notifications: 0 +2026-09-15 11:43:32 INFO: [T11d03210] id: 862596080926201, time: 2026-09-15 11:43:09, lat: 51.37589, lon: 7.14771, course: 0.0 +2026-09-15 11:43:34 INFO: [T11d03210] id: 862596080926201, time: 2026-09-15 11:43:30, lat: 51.37598, lon: 7.14792, speed: 15.1, course: 0.0 +``` + +-- Cheers, Nils + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `847edd2c8c4d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6032/tests/oracle.patch b/tasks/traccar__traccar-6032/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bf96552333e013df7a46f4d3aecdd67b614a3036 --- /dev/null +++ b/tasks/traccar__traccar-6032/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +index 78419846c..5b874a7f3 100644 +--- a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +@@ -131,6 +131,7 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder { + position.set(Position.KEY_SATELLITES, buf.readUnsignedByte()); + buf.readUnsignedByte(); // signal + position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort())); ++ position.setCourse(buf.readUnsignedShort() / 10.0); + } + case 0x65 -> { + position.setDeviceTime(new Date(buf.readUnsignedInt() * 1000)); +diff --git a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java +index 9b69920df..4bc0f65a9 100644 +--- a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java +@@ -18,7 +18,8 @@ public class Xexun3ProtocolDecoderTest extends ProtocolTest { + "fc000b03200108610450803870158318cf")); + + verifyPosition(decoder, binary( +- "fc0040032006086104508038701564216913f223403693012f635344405c829142b302f7427f33331a2e000000a40011046a1055ffff1f0000000000ffffff04ff09ff1a30cf")); ++ "fc00490320e8086259608092620164226aa92f624049b01fff79c842401c97788f16414443084ccd400e19001c009f000e006a18630000173a2f0001a3ffffffffffffff6aa92f622101000030f4cf"), ++ position("2026-09-15 11:43:30.000", true, 51.37597649999999, 7.147920833333334)); + + } + diff --git a/tasks/traccar__traccar-6032/tests/test.sh b/tasks/traccar__traccar-6032/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..23586ac45825c9a6ea7d115b5fe71e364d147aae --- /dev/null +++ b/tasks/traccar__traccar-6032/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 847edd2c8c4dcc47426fb76b7800b342dea3cde6 > "$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/traccar__traccar-6032/tests/verifier.py b/tasks/traccar__traccar-6032/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-6032/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/traccar__traccar-6036/environment/Dockerfile b/tasks/traccar__traccar-6036/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8c5b00ae5fc943d908f2e85e288db509de0dead0 --- /dev/null +++ b/tasks/traccar__traccar-6036/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e1564c7aaa877ff7d769d55ae053e7ae2076872e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e1564c7aaa877ff7d769d55ae053e7ae2076872e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e1564c7aaa877ff7d769d55ae053e7ae2076872e \ + && 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/traccar__traccar-6036/instruction.md b/tasks/traccar__traccar-6036/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f464ad40404af4b85529def835ddd13a1ac312dc --- /dev/null +++ b/tasks/traccar__traccar-6036/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Add GPS accuracy and tracking duration fields to Xexun3 decoder + +## Description + +Parse the precision factor (field 12) and tracking duration (field 13) from the GPS message body (0x64) in Xexun3ProtocolDecoder. + +- Precision is converted from centimeters to meters and set via position.setAccuracy(), consistent with other decoders (e.g. Gt06). +- Tracking duration is stored as a custom attribute since no standard Position key exists for it in Traccar. +- Both fields are guarded by buffer-length checks and sentinel-value (0xFFFF / 0xFF) validation to handle variable-length sub-messages. + +Evidence via [Xexun API 260916 EN.docx](https://github.com/user-attachments/files/32436204/Xexun.API.260916.EN.docx) + +-- Cheers, Nils + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1564c7aaa87`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6036/solution/patch.diff b/tasks/traccar__traccar-6036/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1645e7e618973c60ce44359ca749ef610a3d85cb --- /dev/null +++ b/tasks/traccar__traccar-6036/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +index 5b874a7f3..5504f0c88 100644 +--- a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +@@ -132,6 +132,18 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder { + buf.readUnsignedByte(); // signal + position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort())); + position.setCourse(buf.readUnsignedShort() / 10.0); ++ if (subEnd - buf.readerIndex() >= 2) { ++ int precision = buf.readUnsignedShort(); ++ if (precision != 0xFFFF) { ++ position.setAccuracy(precision / 10.0); ++ } ++ } ++ if (subEnd - buf.readerIndex() >= 1) { ++ int trackingDuration = buf.readUnsignedByte(); ++ if (trackingDuration != 0xFF) { ++ position.set("trackingDuration", trackingDuration); ++ } ++ } + } + case 0x65 -> { + position.setDeviceTime(new Date(buf.readUnsignedInt() * 1000)); diff --git a/tasks/traccar__traccar-6036/solution/solve.sh b/tasks/traccar__traccar-6036/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6036/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/traccar__traccar-6036/task.toml b/tasks/traccar__traccar-6036/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..886672fdbd74c33e25ffe61b2b53ca5132953743 --- /dev/null +++ b/tasks/traccar__traccar-6036/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6036" +description = "Add GPS accuracy and tracking duration fields to Xexun3 decoder" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "e1564c7aaa877ff7d769d55ae053e7ae2076872e" +reference = "https://github.com/traccar/traccar/pull/6036" +source_access = "auto" +built_at = "2026-11-16T16:09:42.533131+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9dcb36c936210b512c7bd9c7d9e8f24897ce4e4619022e7ae9c82dda12002ac1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-22T12:43:11Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.525041+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b1180b0d36d4eab065d623eee10c2ef1d0f5d89f620db10508fc57e5db1a351d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6036/tests/capture.py b/tasks/traccar__traccar-6036/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6036/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/traccar__traccar-6036/tests/instruction.md b/tasks/traccar__traccar-6036/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f464ad40404af4b85529def835ddd13a1ac312dc --- /dev/null +++ b/tasks/traccar__traccar-6036/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Add GPS accuracy and tracking duration fields to Xexun3 decoder + +## Description + +Parse the precision factor (field 12) and tracking duration (field 13) from the GPS message body (0x64) in Xexun3ProtocolDecoder. + +- Precision is converted from centimeters to meters and set via position.setAccuracy(), consistent with other decoders (e.g. Gt06). +- Tracking duration is stored as a custom attribute since no standard Position key exists for it in Traccar. +- Both fields are guarded by buffer-length checks and sentinel-value (0xFFFF / 0xFF) validation to handle variable-length sub-messages. + +Evidence via [Xexun API 260916 EN.docx](https://github.com/user-attachments/files/32436204/Xexun.API.260916.EN.docx) + +-- Cheers, Nils + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1564c7aaa87`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6036/tests/oracle.patch b/tasks/traccar__traccar-6036/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1645e7e618973c60ce44359ca749ef610a3d85cb --- /dev/null +++ b/tasks/traccar__traccar-6036/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +index 5b874a7f3..5504f0c88 100644 +--- a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java +@@ -132,6 +132,18 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder { + buf.readUnsignedByte(); // signal + position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort())); + position.setCourse(buf.readUnsignedShort() / 10.0); ++ if (subEnd - buf.readerIndex() >= 2) { ++ int precision = buf.readUnsignedShort(); ++ if (precision != 0xFFFF) { ++ position.setAccuracy(precision / 10.0); ++ } ++ } ++ if (subEnd - buf.readerIndex() >= 1) { ++ int trackingDuration = buf.readUnsignedByte(); ++ if (trackingDuration != 0xFF) { ++ position.set("trackingDuration", trackingDuration); ++ } ++ } + } + case 0x65 -> { + position.setDeviceTime(new Date(buf.readUnsignedInt() * 1000)); diff --git a/tasks/traccar__traccar-6036/tests/test.sh b/tasks/traccar__traccar-6036/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..880705932483801c73ca6e6efcd0fee1bf2621a5 --- /dev/null +++ b/tasks/traccar__traccar-6036/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 e1564c7aaa877ff7d769d55ae053e7ae2076872e > "$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/traccar__traccar-6036/tests/verifier.py b/tasks/traccar__traccar-6036/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-6036/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/traccar__traccar-6039/environment/Dockerfile b/tasks/traccar__traccar-6039/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4c826f9a4ddc7e04c417cb4b3d38af6d093d0eb3 --- /dev/null +++ b/tasks/traccar__traccar-6039/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin acd55bd0feebd9189213af362bbccbd01da62d29 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard acd55bd0feebd9189213af362bbccbd01da62d29 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base acd55bd0feebd9189213af362bbccbd01da62d29 \ + && 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/traccar__traccar-6039/instruction.md b/tasks/traccar__traccar-6039/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9876d82b92e24945b0e3caca781295ca620ac01c --- /dev/null +++ b/tasks/traccar__traccar-6039/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Decode GV50M series FRI reports + +## Description + +The Queclink GV50M series (GV50M / GV50MG, protocol version prefix `FE`) sends `+RESP:GTFRI` with this layout after the cell fields, per the [GV50M Series @Track Air Interface Protocol V17.12](https://github.com/traccar/traccar/files/7629509/GV50M.Series.%40Track.Air.Interface.Protocol_V17.12.pdf) (uploaded to #4776), section "+RESP:GTFRI": + +``` +Reserved, Mileage, Hour Meter Count, Battery Percentage, Device Status, Reserved, Reserved, Send Time, Count Number +``` + +There are no ADC fields after the hour meter and no RPM / fuel fields after device status. Sample from a live GV50MG: + +``` ++RESP:GTFRI,FE1712,015700000310332,,11308,10,1,1,0.0,0,1393.0,-111.891047,40.760780,20260922234154,0310,0410,4E20,0B4F2A01,,129297.4,02792:32:17,68,110000,,,20260922234153,F646$ +``` + +On current master the generic path reads the battery percentage as ADC1 and device status as ADC2, then tries to parse the send time as fuel level and throws `NumberFormatException: For input string: "20260922234153"`, so the whole report is dropped (the added test fails this way without the decoder change). External Power VCC (`11308` mV) is lost with it. + +Commits: +1. Map protocol prefix `FE` to `GV50M`, skip the ADC and RPM / fuel fields for `GV50M*` in `decodeFri`, and add the sample above as a test verifying `power` = 11.308. +2. Treat an empty device model string like no model, so the protocol version prefix is used for detection. My device had been saved with an empty model, which made the declared model `""` and bypassed the prefix lookup entirely. + +`GTINF` from the same device already decodes correctly and is unchanged. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `acd55bd0feeb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6039/solution/patch.diff b/tasks/traccar__traccar-6039/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..141d1a79f2fcca4fa8db2eaa11384b6a75f7300a --- /dev/null +++ b/tasks/traccar__traccar-6039/solution/patch.diff @@ -0,0 +1,58 @@ +diff --git a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +index 2e54c3a41..d15905568 100644 +--- a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +@@ -98,6 +98,7 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + Map.entry("F1", "GV350M"), + Map.entry("F8", "GV800W"), + Map.entry("FC", "GV600W"), ++ Map.entry("FE", "GV50M"), + Map.entry("802004", "GV58LAU"), + Map.entry("802005", "GV355CEU"), + Map.entry("80201E", "GV30CEU")); +@@ -115,7 +116,7 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + + private String getDeviceModel(DeviceSession deviceSession, String protocolVersion) { + String declaredModel = getDeviceModel(deviceSession); +- if (declaredModel != null) { ++ if (declaredModel != null && !declaredModel.isEmpty()) { + return declaredModel.toUpperCase(Locale.ROOT); + } + String versionPrefix; +@@ -961,10 +962,10 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + } + if (!model.startsWith("GL5") && !model.equals("GL320M")) { + position.set(Position.KEY_HOURS, parseHours(v[index++])); +- if (!v[index++].isEmpty()) { ++ if (!model.startsWith("GV50M") && !v[index++].isEmpty()) { + decodeAnalog(position, 1, v[index - 1]); + } +- if (!model.equals("GV350M") && !model.startsWith("GV600M") ++ if (!model.equals("GV350M") && !model.startsWith("GV600M") && !model.startsWith("GV50M") + && (!extended || model.startsWith("GV") && !model.startsWith("GV6"))) { + if (!v[index++].isEmpty()) { + decodeAnalog(position, 2, v[index - 1]); +@@ -1005,7 +1006,7 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + } + if (extended) { + index += 1; // reserved / uart device type / external power 2 +- } else if (!model.equals("GV350M") && !model.startsWith("GV600M")) { ++ } else if (!model.equals("GV350M") && !model.startsWith("GV600M") && !model.startsWith("GV50M")) { + position.set(Position.KEY_RPM, v[index++].isEmpty() ? null : Integer.parseInt(v[index - 1])); + index += 1; // fuel consumption + position.set(Position.KEY_FUEL, v[index++].isEmpty() ? null : Integer.parseInt(v[index - 1])); +diff --git a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +index a073a1fed..42e950cc4 100644 +--- a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Gl200TextProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Gl200TextProtocolDecoder(null)); + ++ verifyAttribute(decoder, buffer( ++ "+RESP:GTFRI,FE1712,015700000310332,,11308,10,1,1,0.0,0,1393.0,-111.891047,40.760780,20260922234154,0310,0410,4E20,0B4F2A01,,129297.4,02792:32:17,68,110000,,,20260922234153,F646$"), ++ Position.KEY_POWER, 11.308); ++ + verifyAttribute(decoder, buffer( + "+RESP:GTFRI,DC0103,862170019025640,,12000,10,1,1,4.3,92,70.0,121.354335,31.222073,20140511093254,0460,0003,18D8,014B,00,2000.0,12345:12:34,5000,,80,210100,12500,,,20140511093255,11F0$"), + Position.KEY_BATTERY_LEVEL, 80); diff --git a/tasks/traccar__traccar-6039/solution/solve.sh b/tasks/traccar__traccar-6039/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6039/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/traccar__traccar-6039/task.toml b/tasks/traccar__traccar-6039/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..99d9e75eb90d2926f1091aa3d9a0d763ab56cfeb --- /dev/null +++ b/tasks/traccar__traccar-6039/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6039" +description = "Decode GV50M series FRI reports" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "acd55bd0feebd9189213af362bbccbd01da62d29" +reference = "https://github.com/traccar/traccar/pull/6039" +source_access = "auto" +built_at = "2026-11-16T16:09:42.531304+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6670be40e99d1fc38b4a88ed60d8c58870c18e29de7355abd755ffabe1f75611" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-24T03:50:04Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java", +] +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:03.525644+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:682505b558b0249e0a2ba424eab6e52a7036dfba949c58ec142436389f322a40" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6039/tests/capture.py b/tasks/traccar__traccar-6039/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6039/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/traccar__traccar-6039/tests/instruction.md b/tasks/traccar__traccar-6039/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9876d82b92e24945b0e3caca781295ca620ac01c --- /dev/null +++ b/tasks/traccar__traccar-6039/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Decode GV50M series FRI reports + +## Description + +The Queclink GV50M series (GV50M / GV50MG, protocol version prefix `FE`) sends `+RESP:GTFRI` with this layout after the cell fields, per the [GV50M Series @Track Air Interface Protocol V17.12](https://github.com/traccar/traccar/files/7629509/GV50M.Series.%40Track.Air.Interface.Protocol_V17.12.pdf) (uploaded to #4776), section "+RESP:GTFRI": + +``` +Reserved, Mileage, Hour Meter Count, Battery Percentage, Device Status, Reserved, Reserved, Send Time, Count Number +``` + +There are no ADC fields after the hour meter and no RPM / fuel fields after device status. Sample from a live GV50MG: + +``` ++RESP:GTFRI,FE1712,015700000310332,,11308,10,1,1,0.0,0,1393.0,-111.891047,40.760780,20260922234154,0310,0410,4E20,0B4F2A01,,129297.4,02792:32:17,68,110000,,,20260922234153,F646$ +``` + +On current master the generic path reads the battery percentage as ADC1 and device status as ADC2, then tries to parse the send time as fuel level and throws `NumberFormatException: For input string: "20260922234153"`, so the whole report is dropped (the added test fails this way without the decoder change). External Power VCC (`11308` mV) is lost with it. + +Commits: +1. Map protocol prefix `FE` to `GV50M`, skip the ADC and RPM / fuel fields for `GV50M*` in `decodeFri`, and add the sample above as a test verifying `power` = 11.308. +2. Treat an empty device model string like no model, so the protocol version prefix is used for detection. My device had been saved with an empty model, which made the declared model `""` and bypassed the prefix lookup entirely. + +`GTINF` from the same device already decodes correctly and is unchanged. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `acd55bd0feeb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6039/tests/oracle.patch b/tasks/traccar__traccar-6039/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..141d1a79f2fcca4fa8db2eaa11384b6a75f7300a --- /dev/null +++ b/tasks/traccar__traccar-6039/tests/oracle.patch @@ -0,0 +1,58 @@ +diff --git a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +index 2e54c3a41..d15905568 100644 +--- a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +@@ -98,6 +98,7 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + Map.entry("F1", "GV350M"), + Map.entry("F8", "GV800W"), + Map.entry("FC", "GV600W"), ++ Map.entry("FE", "GV50M"), + Map.entry("802004", "GV58LAU"), + Map.entry("802005", "GV355CEU"), + Map.entry("80201E", "GV30CEU")); +@@ -115,7 +116,7 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + + private String getDeviceModel(DeviceSession deviceSession, String protocolVersion) { + String declaredModel = getDeviceModel(deviceSession); +- if (declaredModel != null) { ++ if (declaredModel != null && !declaredModel.isEmpty()) { + return declaredModel.toUpperCase(Locale.ROOT); + } + String versionPrefix; +@@ -961,10 +962,10 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + } + if (!model.startsWith("GL5") && !model.equals("GL320M")) { + position.set(Position.KEY_HOURS, parseHours(v[index++])); +- if (!v[index++].isEmpty()) { ++ if (!model.startsWith("GV50M") && !v[index++].isEmpty()) { + decodeAnalog(position, 1, v[index - 1]); + } +- if (!model.equals("GV350M") && !model.startsWith("GV600M") ++ if (!model.equals("GV350M") && !model.startsWith("GV600M") && !model.startsWith("GV50M") + && (!extended || model.startsWith("GV") && !model.startsWith("GV6"))) { + if (!v[index++].isEmpty()) { + decodeAnalog(position, 2, v[index - 1]); +@@ -1005,7 +1006,7 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + } + if (extended) { + index += 1; // reserved / uart device type / external power 2 +- } else if (!model.equals("GV350M") && !model.startsWith("GV600M")) { ++ } else if (!model.equals("GV350M") && !model.startsWith("GV600M") && !model.startsWith("GV50M")) { + position.set(Position.KEY_RPM, v[index++].isEmpty() ? null : Integer.parseInt(v[index - 1])); + index += 1; // fuel consumption + position.set(Position.KEY_FUEL, v[index++].isEmpty() ? null : Integer.parseInt(v[index - 1])); +diff --git a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +index a073a1fed..42e950cc4 100644 +--- a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Gl200TextProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Gl200TextProtocolDecoder(null)); + ++ verifyAttribute(decoder, buffer( ++ "+RESP:GTFRI,FE1712,015700000310332,,11308,10,1,1,0.0,0,1393.0,-111.891047,40.760780,20260922234154,0310,0410,4E20,0B4F2A01,,129297.4,02792:32:17,68,110000,,,20260922234153,F646$"), ++ Position.KEY_POWER, 11.308); ++ + verifyAttribute(decoder, buffer( + "+RESP:GTFRI,DC0103,862170019025640,,12000,10,1,1,4.3,92,70.0,121.354335,31.222073,20140511093254,0460,0003,18D8,014B,00,2000.0,12345:12:34,5000,,80,210100,12500,,,20140511093255,11F0$"), + Position.KEY_BATTERY_LEVEL, 80); diff --git a/tasks/traccar__traccar-6039/tests/test.sh b/tasks/traccar__traccar-6039/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b0ac2dc8a37babc68e002da59ce2c24af5e0ba5 --- /dev/null +++ b/tasks/traccar__traccar-6039/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 acd55bd0feebd9189213af362bbccbd01da62d29 > "$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/traccar__traccar-6039/tests/verifier.py b/tasks/traccar__traccar-6039/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-6039/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/traccar__traccar-6040/environment/Dockerfile b/tasks/traccar__traccar-6040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1f2b4926684459c0f1906f827c0364c8625892a3 --- /dev/null +++ b/tasks/traccar__traccar-6040/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 19b951f913d8973daca72697b15e37f4ff750de6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 19b951f913d8973daca72697b15e37f4ff750de6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 19b951f913d8973daca72697b15e37f4ff750de6 \ + && 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/traccar__traccar-6040/instruction.md b/tasks/traccar__traccar-6040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27a42dded7d74415f1c85d0965d0f14bc669618c --- /dev/null +++ b/tasks/traccar__traccar-6040/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Fix GTIGL ignition state for GV50M, GV300 and GV350M + +## Description + +The GTIGL report type is decoded as `1` = ignition on. The Queclink documents for these models define it the other way round: + +- **[GV50M Series @Track Air Interface Protocol V17.12](https://github.com/traccar/traccar/files/7629509/GV50M.Series.%40Track.Air.Interface.Protocol_V17.12.pdf)** (uploaded to #4776): "In the message of ignition on and ignition off message +RESP:GTIGL: 0: The engine is ignition on. 1: The engine is ignition off." +- **[GV300N @Track Air Interface Protocol V3.01](https://controlsatperu.com/Manuales/GV300N/Document/GV300N%20@Track%20Air%20Interface%20Protocol%20V3.01.pdf)**: "0: the engine is ignition on. 1: the engine is ignition off." +- **[GV350M Series @Track Air Interface Protocol V3.11](https://www.traccar.org/protocol/5004-gl200/GV350M%C2%A0Series%C2%A0@Track%C2%A0Air%C2%A0Interface%C2%A0Protocol_V3.11.pdf)** (traccar.org protocol archive): "In the report of ignition on and ignition off report +RESP:GTIGL: 0: Ignition on. 1: Ignition off." + +Live traffic from a GV50MG agrees: every GTIGL `00` follows a GTSTT state `21` (ignition on) and every `01` follows state `11` (ignition off), and the GTINF states match the measured external power (14.2 V running, 12.4 V after shutoff). The result today is an inverted `ignitionOn` / `ignitionOff` event on every GTIGL, then a second, opposite event when the next FRI or INF report carries the real state. + +Changes: +- For `GV50M*`, `GV300` / `GV300N` and `GV350M`, decode GTIGL report type `0` as ignition on. Other models keep the current mapping. Both protocol version prefixes `06` and `25` map to `GV300`; `GV300N` is matched as well for devices with that model set explicitly. +- Test: the GTIGL example from the GV50M document (`00` → ignition on). Without the decoder change it fails with `expected: but was: `. + +Verified on a live GV50MG: a start produced a single `ignitionOn` from the GTIGL `00` and a stop a single `ignitionOff` from the GTIGL `01`, with the following FRI agreeing in both cases. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `19b951f913d8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6040/solution/patch.diff b/tasks/traccar__traccar-6040/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a11d2a1a034b4278fcc2de7a556b1c97b12a22b0 --- /dev/null +++ b/tasks/traccar__traccar-6040/solution/patch.diff @@ -0,0 +1,45 @@ +diff --git a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +index d15905568..95e3f8b40 100644 +--- a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +@@ -1654,18 +1654,23 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + ++ String model = getDeviceModel(deviceSession, protocolVersion); ++ + if (v[index + 2].matches("\\p{XDigit}{1,2}")) { + int reportType = Integer.parseInt(v[index + 2], 16); + switch (type) { + case "STR", "CTN" -> { + String battery = v[index + 5]; +- if (getDeviceModel(deviceSession, protocolVersion).matches("GL5[03]0") && !battery.isEmpty()) { ++ if (model.matches("GL5[03]0") && !battery.isEmpty()) { + position.set(Position.KEY_BATTERY_LEVEL, Integer.parseInt(battery)); + } + } + case "NMR" -> position.set(Position.KEY_MOTION, reportType == 1); + case "DIS" -> position.set(Position.PREFIX_IN + reportType / 0x10, reportType % 0x10 == 1); +- case "IGL" -> position.set(Position.KEY_IGNITION, reportType % 0x10 == 1); ++ case "IGL" -> { ++ boolean invertedIgnition = model.matches("GV50M.*|GV300N?|GV350M"); ++ position.set(Position.KEY_IGNITION, reportType % 0x10 == (invertedIgnition ? 0 : 1)); ++ } + case "HBM" -> { + switch (reportType % 0x10) { + case 0, 3 -> position.addAlarm(Position.ALARM_BRAKING); +diff --git a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +index 42e950cc4..1cb3ec2b5 100644 +--- a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Gl200TextProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Gl200TextProtocolDecoder(null)); + ++ verifyAttribute(decoder, buffer( ++ "+RESP:GTIGL,FE110A,866425030925657,gv50m,,00,1,1,17.7,98,14.0,113.950840,22.568487,20190923043110,0460,0000,2495,116F,,13670.4,20190923123107,5568$"), ++ Position.KEY_IGNITION, true); ++ + verifyAttribute(decoder, buffer( + "+RESP:GTFRI,FE1712,015700000310332,,11308,10,1,1,0.0,0,1393.0,-111.891047,40.760780,20260922234154,0310,0410,4E20,0B4F2A01,,129297.4,02792:32:17,68,110000,,,20260922234153,F646$"), + Position.KEY_POWER, 11.308); diff --git a/tasks/traccar__traccar-6040/solution/solve.sh b/tasks/traccar__traccar-6040/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6040/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/traccar__traccar-6040/task.toml b/tasks/traccar__traccar-6040/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f8b546f09fcbab06a7f41bc1a7d8b47b0145330c --- /dev/null +++ b/tasks/traccar__traccar-6040/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6040" +description = "Fix GTIGL ignition state for GV50M, GV300 and GV350M" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "19b951f913d8973daca72697b15e37f4ff750de6" +reference = "https://github.com/traccar/traccar/pull/6040" +source_access = "auto" +built_at = "2026-11-16T16:09:42.529454+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b68f96f0f973b35c1405949e28452208e39d11f1232c2cf118bfaf8e168bfb11" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-25T11:52:12Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java", +] +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:03.526182+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:790c0c8a6f3679d27934a467d732b0390be741f0f0876ae224a0293d922bf59a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6040/tests/capture.py b/tasks/traccar__traccar-6040/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6040/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/traccar__traccar-6040/tests/instruction.md b/tasks/traccar__traccar-6040/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27a42dded7d74415f1c85d0965d0f14bc669618c --- /dev/null +++ b/tasks/traccar__traccar-6040/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Fix GTIGL ignition state for GV50M, GV300 and GV350M + +## Description + +The GTIGL report type is decoded as `1` = ignition on. The Queclink documents for these models define it the other way round: + +- **[GV50M Series @Track Air Interface Protocol V17.12](https://github.com/traccar/traccar/files/7629509/GV50M.Series.%40Track.Air.Interface.Protocol_V17.12.pdf)** (uploaded to #4776): "In the message of ignition on and ignition off message +RESP:GTIGL: 0: The engine is ignition on. 1: The engine is ignition off." +- **[GV300N @Track Air Interface Protocol V3.01](https://controlsatperu.com/Manuales/GV300N/Document/GV300N%20@Track%20Air%20Interface%20Protocol%20V3.01.pdf)**: "0: the engine is ignition on. 1: the engine is ignition off." +- **[GV350M Series @Track Air Interface Protocol V3.11](https://www.traccar.org/protocol/5004-gl200/GV350M%C2%A0Series%C2%A0@Track%C2%A0Air%C2%A0Interface%C2%A0Protocol_V3.11.pdf)** (traccar.org protocol archive): "In the report of ignition on and ignition off report +RESP:GTIGL: 0: Ignition on. 1: Ignition off." + +Live traffic from a GV50MG agrees: every GTIGL `00` follows a GTSTT state `21` (ignition on) and every `01` follows state `11` (ignition off), and the GTINF states match the measured external power (14.2 V running, 12.4 V after shutoff). The result today is an inverted `ignitionOn` / `ignitionOff` event on every GTIGL, then a second, opposite event when the next FRI or INF report carries the real state. + +Changes: +- For `GV50M*`, `GV300` / `GV300N` and `GV350M`, decode GTIGL report type `0` as ignition on. Other models keep the current mapping. Both protocol version prefixes `06` and `25` map to `GV300`; `GV300N` is matched as well for devices with that model set explicitly. +- Test: the GTIGL example from the GV50M document (`00` → ignition on). Without the decoder change it fails with `expected: but was: `. + +Verified on a live GV50MG: a start produced a single `ignitionOn` from the GTIGL `00` and a stop a single `ignitionOff` from the GTIGL `01`, with the following FRI agreeing in both cases. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `19b951f913d8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6040/tests/oracle.patch b/tasks/traccar__traccar-6040/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a11d2a1a034b4278fcc2de7a556b1c97b12a22b0 --- /dev/null +++ b/tasks/traccar__traccar-6040/tests/oracle.patch @@ -0,0 +1,45 @@ +diff --git a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +index d15905568..95e3f8b40 100644 +--- a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +@@ -1654,18 +1654,23 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + ++ String model = getDeviceModel(deviceSession, protocolVersion); ++ + if (v[index + 2].matches("\\p{XDigit}{1,2}")) { + int reportType = Integer.parseInt(v[index + 2], 16); + switch (type) { + case "STR", "CTN" -> { + String battery = v[index + 5]; +- if (getDeviceModel(deviceSession, protocolVersion).matches("GL5[03]0") && !battery.isEmpty()) { ++ if (model.matches("GL5[03]0") && !battery.isEmpty()) { + position.set(Position.KEY_BATTERY_LEVEL, Integer.parseInt(battery)); + } + } + case "NMR" -> position.set(Position.KEY_MOTION, reportType == 1); + case "DIS" -> position.set(Position.PREFIX_IN + reportType / 0x10, reportType % 0x10 == 1); +- case "IGL" -> position.set(Position.KEY_IGNITION, reportType % 0x10 == 1); ++ case "IGL" -> { ++ boolean invertedIgnition = model.matches("GV50M.*|GV300N?|GV350M"); ++ position.set(Position.KEY_IGNITION, reportType % 0x10 == (invertedIgnition ? 0 : 1)); ++ } + case "HBM" -> { + switch (reportType % 0x10) { + case 0, 3 -> position.addAlarm(Position.ALARM_BRAKING); +diff --git a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +index 42e950cc4..1cb3ec2b5 100644 +--- a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Gl200TextProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Gl200TextProtocolDecoder(null)); + ++ verifyAttribute(decoder, buffer( ++ "+RESP:GTIGL,FE110A,866425030925657,gv50m,,00,1,1,17.7,98,14.0,113.950840,22.568487,20190923043110,0460,0000,2495,116F,,13670.4,20190923123107,5568$"), ++ Position.KEY_IGNITION, true); ++ + verifyAttribute(decoder, buffer( + "+RESP:GTFRI,FE1712,015700000310332,,11308,10,1,1,0.0,0,1393.0,-111.891047,40.760780,20260922234154,0310,0410,4E20,0B4F2A01,,129297.4,02792:32:17,68,110000,,,20260922234153,F646$"), + Position.KEY_POWER, 11.308); diff --git a/tasks/traccar__traccar-6040/tests/test.sh b/tasks/traccar__traccar-6040/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..11bd61e6b955d948b2b59429c50c2952bef228c5 --- /dev/null +++ b/tasks/traccar__traccar-6040/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 19b951f913d8973daca72697b15e37f4ff750de6 > "$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/traccar__traccar-6040/tests/verifier.py b/tasks/traccar__traccar-6040/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-6040/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/traccar__traccar-6047/environment/Dockerfile b/tasks/traccar__traccar-6047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..94427870d9d7448b2d6eb55c57c3e27a19b1ad74 --- /dev/null +++ b/tasks/traccar__traccar-6047/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 464588afca4498b77df9b283e62de88fa28ed9b8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 464588afca4498b77df9b283e62de88fa28ed9b8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 464588afca4498b77df9b283e62de88fa28ed9b8 \ + && 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/traccar__traccar-6047/instruction.md b/tasks/traccar__traccar-6047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..74b87db4406e34b04a55b19ffc52e8d276f8bc50 --- /dev/null +++ b/tasks/traccar__traccar-6047/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** [FIX] sanitize uniqueId taken from MQTT like topic replacing slashes by dashes #6046 + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `464588afca44`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6047/solution/patch.diff b/tasks/traccar__traccar-6047/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cd22313fb0fbf379efaa8179e85bc92c2e8741e5 --- /dev/null +++ b/tasks/traccar__traccar-6047/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java b/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java +index 74d7f02a7..75bc729c3 100644 +--- a/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java +@@ -58,6 +58,10 @@ public class OwnTracksProtocolDecoder extends BaseHttpProtocolDecoder { + uniqueId = root.getString("tid"); + } + ++ if (uniqueId != null) { ++ uniqueId = uniqueId.replace('/', '-'); ++ } ++ + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, uniqueId); + if (deviceSession == null) { + sendResponse(channel, HttpResponseStatus.BAD_REQUEST); diff --git a/tasks/traccar__traccar-6047/solution/solve.sh b/tasks/traccar__traccar-6047/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6047/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/traccar__traccar-6047/task.toml b/tasks/traccar__traccar-6047/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3468702bc35dce6325046a24ff13dc1ba180ae17 --- /dev/null +++ b/tasks/traccar__traccar-6047/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6047" +description = "[FIX] sanitize uniqueId taken from MQTT like topic replacing slashes by dashes #6046" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "464588afca4498b77df9b283e62de88fa28ed9b8" +reference = "https://github.com/traccar/traccar/pull/6047" +source_access = "auto" +built_at = "2026-11-16T16:09:42.524625+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1cb2db672381c3a641ad007385ee17169d28141c002dabc66ebcab8cc61a0329" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T11:46:43Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.526730+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:08178834f748cbc6802e1959faaef64b326ca7a71c81f72f4795c7bf86cdce1d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6047/tests/capture.py b/tasks/traccar__traccar-6047/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6047/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/traccar__traccar-6047/tests/instruction.md b/tasks/traccar__traccar-6047/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..74b87db4406e34b04a55b19ffc52e8d276f8bc50 --- /dev/null +++ b/tasks/traccar__traccar-6047/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** [FIX] sanitize uniqueId taken from MQTT like topic replacing slashes by dashes #6046 + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `464588afca44`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6047/tests/oracle.patch b/tasks/traccar__traccar-6047/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cd22313fb0fbf379efaa8179e85bc92c2e8741e5 --- /dev/null +++ b/tasks/traccar__traccar-6047/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java b/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java +index 74d7f02a7..75bc729c3 100644 +--- a/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/OwnTracksProtocolDecoder.java +@@ -58,6 +58,10 @@ public class OwnTracksProtocolDecoder extends BaseHttpProtocolDecoder { + uniqueId = root.getString("tid"); + } + ++ if (uniqueId != null) { ++ uniqueId = uniqueId.replace('/', '-'); ++ } ++ + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, uniqueId); + if (deviceSession == null) { + sendResponse(channel, HttpResponseStatus.BAD_REQUEST); diff --git a/tasks/traccar__traccar-6047/tests/test.sh b/tasks/traccar__traccar-6047/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..db617f6696a4decd929d9bddf2b2e991fb1f90d2 --- /dev/null +++ b/tasks/traccar__traccar-6047/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 464588afca4498b77df9b283e62de88fa28ed9b8 > "$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/traccar__traccar-6047/tests/verifier.py b/tasks/traccar__traccar-6047/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/traccar__traccar-6047/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/traccar__traccar-6051/environment/Dockerfile b/tasks/traccar__traccar-6051/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..69d1049439f6748abdafc0c90433850f8b806961 --- /dev/null +++ b/tasks/traccar__traccar-6051/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/traccar/traccar.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/traccar/traccar.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f9bd485b4a6e576de0c167b8f93651d3a8a64c9e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f9bd485b4a6e576de0c167b8f93651d3a8a64c9e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f9bd485b4a6e576de0c167b8f93651d3a8a64c9e \ + && 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/traccar__traccar-6051/instruction.md b/tasks/traccar__traccar-6051/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d31f865f6800e5f6fbd892efda735e384a23716d --- /dev/null +++ b/tasks/traccar__traccar-6051/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Fall back to basic decoder for OKAI FRI layout + +## Description + +. + +Since e1564c7a, `decodeFri` parses OKAI scooter reports (protocol version `EF802C`, two extra fields after the device name) as a standard FRI and throws `NumberFormatException` on the power field. Before that change the regex did not match, `decodeFri` returned null and `decodeBasic` decoded these messages correctly. + +This restores the fallback: when the power field is present but not numeric, `decodeFri` returns null and the message goes to `decodeBasic`. Added GTFRI and GTRTL samples from a live OKAI unit (IMEI replaced). + +Checked the 91 existing FRI/ERI/GEO/RTL/DOG samples in `Gl200TextProtocolDecoderTest`: none of them has a non-numeric value in that position, so their decoding path is unchanged. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f9bd485b4a6e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6051/solution/patch.diff b/tasks/traccar__traccar-6051/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8fa078e0361e735601c991bde2b98374e1946c0e --- /dev/null +++ b/tasks/traccar__traccar-6051/solution/patch.diff @@ -0,0 +1,29 @@ +diff --git a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +index 165416530..f2aff140f 100644 +--- a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +@@ -898,6 +898,9 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + String vin = model.startsWith("GV500") ? v[index++] : null; + index += 1; // device name + long mask = extended ? Long.parseLong(v[index++], 16) : 0; ++ if (!v[index].isEmpty() && !v[index].chars().allMatch(Character::isDigit)) { ++ return null; // non-standard format, handled by basic decoder ++ } + Double power = v[index++].isEmpty() ? null : Integer.parseInt(v[index - 1]) / 1000.0; + Integer reportType = v[index++].isEmpty() ? null : Integer.parseInt(v[index - 1]); + +diff --git a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +index 4af577bd6..2eb807993 100644 +--- a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Gl200TextProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Gl200TextProtocolDecoder(null)); + ++ verifyDecode(decoder, buffer( ++ "+RESP:GTFRI,EF802C,864431040000001,JoJoSharingIoT,OK200428000950,OUKAI,,,0,0000000000000000,2,0.0,0,7.7,22.630466,38.078765,20260929061303,,0202,0005,002B,4F31,14&99,1,41,0,51848,4076,91,0,0,1,,0.0&0.00&0.0&269.9&0&0&0&000000362021022701090000&000000CF2019090301000000&0&0&00000000000000000000&2&2&00000000000000,84,20260929061305,CFE1$"), ++ position().attribute(Position.KEY_BATTERY_LEVEL, 84)); ++ + verifyDecode(decoder, buffer( + "+RESP:GTIGL,FE110A,866425030925657,gv50m,,00,1,1,17.7,98,14.0,113.950840,22.568487,20190923043110,0460,0000,2495,116F,,13670.4,20190923123107,5568$"), + position().attribute(Position.KEY_IGNITION, true)); diff --git a/tasks/traccar__traccar-6051/solution/solve.sh b/tasks/traccar__traccar-6051/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/traccar__traccar-6051/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/traccar__traccar-6051/task.toml b/tasks/traccar__traccar-6051/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1e8b8c381b2898d4c47378e695848e0bf9b2a70c --- /dev/null +++ b/tasks/traccar__traccar-6051/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/traccar__traccar-6051" +description = "Fall back to basic decoder for OKAI FRI layout" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "traccar", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "traccar/traccar" +ref = "f9bd485b4a6e576de0c167b8f93651d3a8a64c9e" +reference = "https://github.com/traccar/traccar/pull/6051" +source_access = "auto" +built_at = "2026-11-16T16:09:42.523060+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b14540176b9c9a4c012000650064584a5536d01e3054805e9c05e36de804a0e0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T14:54:56Z" +diff_format = "unified" +context_files = [ + "src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java", + "src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 7 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.527340+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:11c8c4fa0a2bb232ab30537cb020675e51ed019b8dd50b922939645fb9019b1d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/traccar__traccar-6051/tests/capture.py b/tasks/traccar__traccar-6051/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/traccar__traccar-6051/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/traccar__traccar-6051/tests/instruction.md b/tasks/traccar__traccar-6051/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d31f865f6800e5f6fbd892efda735e384a23716d --- /dev/null +++ b/tasks/traccar__traccar-6051/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Fall back to basic decoder for OKAI FRI layout + +## Description + +. + +Since e1564c7a, `decodeFri` parses OKAI scooter reports (protocol version `EF802C`, two extra fields after the device name) as a standard FRI and throws `NumberFormatException` on the power field. Before that change the regex did not match, `decodeFri` returned null and `decodeBasic` decoded these messages correctly. + +This restores the fallback: when the power field is present but not numeric, `decodeFri` returns null and the message goes to `decodeBasic`. Added GTFRI and GTRTL samples from a live OKAI unit (IMEI replaced). + +Checked the 91 existing FRI/ERI/GEO/RTL/DOG samples in `Gl200TextProtocolDecoderTest`: none of them has a non-numeric value in that position, so their decoding path is unchanged. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f9bd485b4a6e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/traccar__traccar-6051/tests/oracle.patch b/tasks/traccar__traccar-6051/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8fa078e0361e735601c991bde2b98374e1946c0e --- /dev/null +++ b/tasks/traccar__traccar-6051/tests/oracle.patch @@ -0,0 +1,29 @@ +diff --git a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +index 165416530..f2aff140f 100644 +--- a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java ++++ b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +@@ -898,6 +898,9 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { + String vin = model.startsWith("GV500") ? v[index++] : null; + index += 1; // device name + long mask = extended ? Long.parseLong(v[index++], 16) : 0; ++ if (!v[index].isEmpty() && !v[index].chars().allMatch(Character::isDigit)) { ++ return null; // non-standard format, handled by basic decoder ++ } + Double power = v[index++].isEmpty() ? null : Integer.parseInt(v[index - 1]) / 1000.0; + Integer reportType = v[index++].isEmpty() ? null : Integer.parseInt(v[index - 1]); + +diff --git a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +index 4af577bd6..2eb807993 100644 +--- a/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java ++++ b/src/test/java/org/traccar/protocol/Gl200TextProtocolDecoderTest.java +@@ -11,6 +11,10 @@ public class Gl200TextProtocolDecoderTest extends ProtocolTest { + + var decoder = inject(new Gl200TextProtocolDecoder(null)); + ++ verifyDecode(decoder, buffer( ++ "+RESP:GTFRI,EF802C,864431040000001,JoJoSharingIoT,OK200428000950,OUKAI,,,0,0000000000000000,2,0.0,0,7.7,22.630466,38.078765,20260929061303,,0202,0005,002B,4F31,14&99,1,41,0,51848,4076,91,0,0,1,,0.0&0.00&0.0&269.9&0&0&0&000000362021022701090000&000000CF2019090301000000&0&0&00000000000000000000&2&2&00000000000000,84,20260929061305,CFE1$"), ++ position().attribute(Position.KEY_BATTERY_LEVEL, 84)); ++ + verifyDecode(decoder, buffer( + "+RESP:GTIGL,FE110A,866425030925657,gv50m,,00,1,1,17.7,98,14.0,113.950840,22.568487,20190923043110,0460,0000,2495,116F,,13670.4,20190923123107,5568$"), + position().attribute(Position.KEY_IGNITION, true));