diff --git a/dataworld-p002876-consequence-1/tests/grade.py b/dataworld-p002876-consequence-1/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p002876-consequence-1/tests/grade.py +++ b/dataworld-p002876-consequence-1/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p002876-consequence-1/tests/judge.env b/dataworld-p002876-consequence-1/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p002876-consequence-1/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p002876-consequence-1/tests/judge.py b/dataworld-p002876-consequence-1/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p002876-consequence-1/tests/judge.py +++ b/dataworld-p002876-consequence-1/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p002876-consequence-1/tests/judge_prompt.py b/dataworld-p002876-consequence-1/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p002876-consequence-1/tests/judge_prompt.py +++ b/dataworld-p002876-consequence-1/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p002876-consequence-1/tests/test.sh b/dataworld-p002876-consequence-1/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p002876-consequence-1/tests/test.sh +++ b/dataworld-p002876-consequence-1/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p004607-cause-2/environment/Dockerfile b/dataworld-p004607-cause-2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p004607-cause-2/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p004607-cause-2/tests/grade.py b/dataworld-p004607-cause-2/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p004607-cause-2/tests/grade.py +++ b/dataworld-p004607-cause-2/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p004607-cause-2/tests/judge.env b/dataworld-p004607-cause-2/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p004607-cause-2/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p004607-cause-2/tests/judge.py b/dataworld-p004607-cause-2/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p004607-cause-2/tests/judge.py +++ b/dataworld-p004607-cause-2/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p004607-cause-2/tests/judge_prompt.py b/dataworld-p004607-cause-2/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p004607-cause-2/tests/judge_prompt.py +++ b/dataworld-p004607-cause-2/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p004607-cause-2/tests/test.sh b/dataworld-p004607-cause-2/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p004607-cause-2/tests/test.sh +++ b/dataworld-p004607-cause-2/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p004607-consequence-2/environment/Dockerfile b/dataworld-p004607-consequence-2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p004607-consequence-2/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p004607-consequence-2/tests/grade.py b/dataworld-p004607-consequence-2/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p004607-consequence-2/tests/grade.py +++ b/dataworld-p004607-consequence-2/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p004607-consequence-2/tests/judge.env b/dataworld-p004607-consequence-2/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p004607-consequence-2/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p004607-consequence-2/tests/judge.py b/dataworld-p004607-consequence-2/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p004607-consequence-2/tests/judge.py +++ b/dataworld-p004607-consequence-2/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p004607-consequence-2/tests/judge_prompt.py b/dataworld-p004607-consequence-2/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p004607-consequence-2/tests/judge_prompt.py +++ b/dataworld-p004607-consequence-2/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p004607-consequence-2/tests/test.sh b/dataworld-p004607-consequence-2/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p004607-consequence-2/tests/test.sh +++ b/dataworld-p004607-consequence-2/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p006499-cause-2/environment/Dockerfile b/dataworld-p006499-cause-2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p006499-cause-2/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p006499-cause-2/tests/grade.py b/dataworld-p006499-cause-2/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p006499-cause-2/tests/grade.py +++ b/dataworld-p006499-cause-2/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p006499-cause-2/tests/judge.env b/dataworld-p006499-cause-2/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p006499-cause-2/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p006499-cause-2/tests/judge.py b/dataworld-p006499-cause-2/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p006499-cause-2/tests/judge.py +++ b/dataworld-p006499-cause-2/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p006499-cause-2/tests/judge_prompt.py b/dataworld-p006499-cause-2/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p006499-cause-2/tests/judge_prompt.py +++ b/dataworld-p006499-cause-2/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p006499-cause-2/tests/test.sh b/dataworld-p006499-cause-2/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p006499-cause-2/tests/test.sh +++ b/dataworld-p006499-cause-2/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p006499-consequence-2/environment/Dockerfile b/dataworld-p006499-consequence-2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p006499-consequence-2/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p006499-consequence-2/tests/grade.py b/dataworld-p006499-consequence-2/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p006499-consequence-2/tests/grade.py +++ b/dataworld-p006499-consequence-2/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p006499-consequence-2/tests/judge.env b/dataworld-p006499-consequence-2/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p006499-consequence-2/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p006499-consequence-2/tests/judge.py b/dataworld-p006499-consequence-2/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p006499-consequence-2/tests/judge.py +++ b/dataworld-p006499-consequence-2/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p006499-consequence-2/tests/judge_prompt.py b/dataworld-p006499-consequence-2/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p006499-consequence-2/tests/judge_prompt.py +++ b/dataworld-p006499-consequence-2/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p006499-consequence-2/tests/test.sh b/dataworld-p006499-consequence-2/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p006499-consequence-2/tests/test.sh +++ b/dataworld-p006499-consequence-2/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p006632-cause-1/environment/Dockerfile b/dataworld-p006632-cause-1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p006632-cause-1/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p006632-cause-1/tests/grade.py b/dataworld-p006632-cause-1/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p006632-cause-1/tests/grade.py +++ b/dataworld-p006632-cause-1/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p006632-cause-1/tests/judge.env b/dataworld-p006632-cause-1/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p006632-cause-1/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p006632-cause-1/tests/judge.py b/dataworld-p006632-cause-1/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p006632-cause-1/tests/judge.py +++ b/dataworld-p006632-cause-1/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p006632-cause-1/tests/judge_prompt.py b/dataworld-p006632-cause-1/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p006632-cause-1/tests/judge_prompt.py +++ b/dataworld-p006632-cause-1/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p006632-cause-1/tests/test.sh b/dataworld-p006632-cause-1/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p006632-cause-1/tests/test.sh +++ b/dataworld-p006632-cause-1/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p006632-consequence-2/environment/Dockerfile b/dataworld-p006632-consequence-2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p006632-consequence-2/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p006632-consequence-2/tests/grade.py b/dataworld-p006632-consequence-2/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p006632-consequence-2/tests/grade.py +++ b/dataworld-p006632-consequence-2/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p006632-consequence-2/tests/judge.env b/dataworld-p006632-consequence-2/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p006632-consequence-2/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p006632-consequence-2/tests/judge.py b/dataworld-p006632-consequence-2/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p006632-consequence-2/tests/judge.py +++ b/dataworld-p006632-consequence-2/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p006632-consequence-2/tests/judge_prompt.py b/dataworld-p006632-consequence-2/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p006632-consequence-2/tests/judge_prompt.py +++ b/dataworld-p006632-consequence-2/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p006632-consequence-2/tests/test.sh b/dataworld-p006632-consequence-2/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p006632-consequence-2/tests/test.sh +++ b/dataworld-p006632-consequence-2/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p006802-cause-2/environment/Dockerfile b/dataworld-p006802-cause-2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p006802-cause-2/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p006802-cause-2/tests/grade.py b/dataworld-p006802-cause-2/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p006802-cause-2/tests/grade.py +++ b/dataworld-p006802-cause-2/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p006802-cause-2/tests/judge.env b/dataworld-p006802-cause-2/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p006802-cause-2/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p006802-cause-2/tests/judge.py b/dataworld-p006802-cause-2/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p006802-cause-2/tests/judge.py +++ b/dataworld-p006802-cause-2/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p006802-cause-2/tests/judge_prompt.py b/dataworld-p006802-cause-2/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p006802-cause-2/tests/judge_prompt.py +++ b/dataworld-p006802-cause-2/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p006802-cause-2/tests/test.sh b/dataworld-p006802-cause-2/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p006802-cause-2/tests/test.sh +++ b/dataworld-p006802-cause-2/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p006802-consequence-2/environment/Dockerfile b/dataworld-p006802-consequence-2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p006802-consequence-2/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p006802-consequence-2/tests/grade.py b/dataworld-p006802-consequence-2/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p006802-consequence-2/tests/grade.py +++ b/dataworld-p006802-consequence-2/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p006802-consequence-2/tests/judge.env b/dataworld-p006802-consequence-2/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p006802-consequence-2/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p006802-consequence-2/tests/judge.py b/dataworld-p006802-consequence-2/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p006802-consequence-2/tests/judge.py +++ b/dataworld-p006802-consequence-2/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p006802-consequence-2/tests/judge_prompt.py b/dataworld-p006802-consequence-2/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p006802-consequence-2/tests/judge_prompt.py +++ b/dataworld-p006802-consequence-2/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p006802-consequence-2/tests/test.sh b/dataworld-p006802-consequence-2/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p006802-consequence-2/tests/test.sh +++ b/dataworld-p006802-consequence-2/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p007107-cause-1/environment/Dockerfile b/dataworld-p007107-cause-1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p007107-cause-1/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p007107-cause-1/tests/grade.py b/dataworld-p007107-cause-1/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p007107-cause-1/tests/grade.py +++ b/dataworld-p007107-cause-1/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p007107-cause-1/tests/judge.env b/dataworld-p007107-cause-1/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p007107-cause-1/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p007107-cause-1/tests/judge.py b/dataworld-p007107-cause-1/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p007107-cause-1/tests/judge.py +++ b/dataworld-p007107-cause-1/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p007107-cause-1/tests/judge_prompt.py b/dataworld-p007107-cause-1/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p007107-cause-1/tests/judge_prompt.py +++ b/dataworld-p007107-cause-1/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p007107-cause-1/tests/test.sh b/dataworld-p007107-cause-1/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p007107-cause-1/tests/test.sh +++ b/dataworld-p007107-cause-1/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p007107-consequence-2/environment/Dockerfile b/dataworld-p007107-consequence-2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p007107-consequence-2/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p007107-consequence-2/tests/grade.py b/dataworld-p007107-consequence-2/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p007107-consequence-2/tests/grade.py +++ b/dataworld-p007107-consequence-2/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p007107-consequence-2/tests/judge.env b/dataworld-p007107-consequence-2/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p007107-consequence-2/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p007107-consequence-2/tests/judge.py b/dataworld-p007107-consequence-2/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p007107-consequence-2/tests/judge.py +++ b/dataworld-p007107-consequence-2/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p007107-consequence-2/tests/judge_prompt.py b/dataworld-p007107-consequence-2/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p007107-consequence-2/tests/judge_prompt.py +++ b/dataworld-p007107-consequence-2/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p007107-consequence-2/tests/test.sh b/dataworld-p007107-consequence-2/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p007107-consequence-2/tests/test.sh +++ b/dataworld-p007107-consequence-2/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p009238-cause-1/environment/Dockerfile b/dataworld-p009238-cause-1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p009238-cause-1/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p009238-cause-1/tests/grade.py b/dataworld-p009238-cause-1/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p009238-cause-1/tests/grade.py +++ b/dataworld-p009238-cause-1/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p009238-cause-1/tests/judge.env b/dataworld-p009238-cause-1/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p009238-cause-1/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p009238-cause-1/tests/judge.py b/dataworld-p009238-cause-1/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p009238-cause-1/tests/judge.py +++ b/dataworld-p009238-cause-1/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p009238-cause-1/tests/judge_prompt.py b/dataworld-p009238-cause-1/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p009238-cause-1/tests/judge_prompt.py +++ b/dataworld-p009238-cause-1/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p009238-cause-1/tests/test.sh b/dataworld-p009238-cause-1/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p009238-cause-1/tests/test.sh +++ b/dataworld-p009238-cause-1/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p009238-consequence-1/environment/Dockerfile b/dataworld-p009238-consequence-1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p009238-consequence-1/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p009238-consequence-1/tests/grade.py b/dataworld-p009238-consequence-1/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p009238-consequence-1/tests/grade.py +++ b/dataworld-p009238-consequence-1/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p009238-consequence-1/tests/judge.env b/dataworld-p009238-consequence-1/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p009238-consequence-1/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p009238-consequence-1/tests/judge.py b/dataworld-p009238-consequence-1/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p009238-consequence-1/tests/judge.py +++ b/dataworld-p009238-consequence-1/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p009238-consequence-1/tests/judge_prompt.py b/dataworld-p009238-consequence-1/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p009238-consequence-1/tests/judge_prompt.py +++ b/dataworld-p009238-consequence-1/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p009238-consequence-1/tests/test.sh b/dataworld-p009238-consequence-1/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p009238-consequence-1/tests/test.sh +++ b/dataworld-p009238-consequence-1/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p009406-cause-1/environment/Dockerfile b/dataworld-p009406-cause-1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p009406-cause-1/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p009406-cause-1/tests/grade.py b/dataworld-p009406-cause-1/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p009406-cause-1/tests/grade.py +++ b/dataworld-p009406-cause-1/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p009406-cause-1/tests/judge.env b/dataworld-p009406-cause-1/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p009406-cause-1/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p009406-cause-1/tests/judge.py b/dataworld-p009406-cause-1/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p009406-cause-1/tests/judge.py +++ b/dataworld-p009406-cause-1/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p009406-cause-1/tests/judge_prompt.py b/dataworld-p009406-cause-1/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p009406-cause-1/tests/judge_prompt.py +++ b/dataworld-p009406-cause-1/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p009406-cause-1/tests/test.sh b/dataworld-p009406-cause-1/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p009406-cause-1/tests/test.sh +++ b/dataworld-p009406-cause-1/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p009406-consequence-1/environment/Dockerfile b/dataworld-p009406-consequence-1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p009406-consequence-1/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p009406-consequence-1/tests/grade.py b/dataworld-p009406-consequence-1/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p009406-consequence-1/tests/grade.py +++ b/dataworld-p009406-consequence-1/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p009406-consequence-1/tests/judge.env b/dataworld-p009406-consequence-1/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p009406-consequence-1/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p009406-consequence-1/tests/judge.py b/dataworld-p009406-consequence-1/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p009406-consequence-1/tests/judge.py +++ b/dataworld-p009406-consequence-1/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p009406-consequence-1/tests/judge_prompt.py b/dataworld-p009406-consequence-1/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p009406-consequence-1/tests/judge_prompt.py +++ b/dataworld-p009406-consequence-1/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p009406-consequence-1/tests/test.sh b/dataworld-p009406-consequence-1/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p009406-consequence-1/tests/test.sh +++ b/dataworld-p009406-consequence-1/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p009851-cause-2/environment/Dockerfile b/dataworld-p009851-cause-2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p009851-cause-2/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p009851-cause-2/tests/grade.py b/dataworld-p009851-cause-2/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p009851-cause-2/tests/grade.py +++ b/dataworld-p009851-cause-2/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p009851-cause-2/tests/judge.env b/dataworld-p009851-cause-2/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p009851-cause-2/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p009851-cause-2/tests/judge.py b/dataworld-p009851-cause-2/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p009851-cause-2/tests/judge.py +++ b/dataworld-p009851-cause-2/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p009851-cause-2/tests/judge_prompt.py b/dataworld-p009851-cause-2/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p009851-cause-2/tests/judge_prompt.py +++ b/dataworld-p009851-cause-2/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p009851-cause-2/tests/test.sh b/dataworld-p009851-cause-2/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p009851-cause-2/tests/test.sh +++ b/dataworld-p009851-cause-2/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/dataworld-p009851-consequence-1/environment/Dockerfile b/dataworld-p009851-consequence-1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..980916ac9506a4dacaf908ecfc0adde7b6a9aaf8 --- /dev/null +++ b/dataworld-p009851-consequence-1/environment/Dockerfile @@ -0,0 +1,64 @@ +# Data-World task image (self-contained): the data lives in the task directory under +# environment/data/ and is COPYed into /app/data/ at build time; no world base image is +# required. +# Leak prevention: the whitelist COPYs only data/ -- WORLD.md, .build and dag.json must +# never make it into the image. +# [RELEASE] Replace the base image below with your own generic image (it needs +# python3/pip, otherwise the apt step below installs them); the apt/pip steps all probe +# for existence first, so anything the base image already provides is not reinstalled. +FROM :latest + +# Package mirrors -- the release build uses public mirrors (the original build +# environment had no internet access and went through internal mirrors). +# Ubuntu 24.04 (noble) uses the deb822 file /etc/apt/sources.list.d/ubuntu.sources. +ARG APT_MIRROR=http://archive.ubuntu.com/ubuntu/ +ARG PIP_INDEX=https://pypi.org/simple +ARG PIP_TRUSTED_HOST=pypi.org + +# The apt mirror is rewritten only when the deb822 file exists; installing python3/pip3 +# is skipped when they are already present. +RUN set -eux; \ + if command -v apt-get >/dev/null 2>&1; then \ + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then \ + sed -i "s|http://archive.ubuntu.com/ubuntu/|${APT_MIRROR}|g; s|http://security.ubuntu.com/ubuntu/|${APT_MIRROR}|g" \ + /etc/apt/sources.list.d/ubuntu.sources; \ + fi; \ + if ! command -v python3 >/dev/null 2>&1 || ! command -v pip3 >/dev/null 2>&1; then \ + apt-get update -qq; \ + apt-get install -y -qq --no-install-recommends python3 python3-pip; \ + rm -rf /var/lib/apt/lists/*; \ + fi; \ + fi + +# Install only the solver's analysis dependencies; the verifier itself has zero +# third-party dependencies (the judge goes through stdlib urllib). +# --break-system-packages is the PEP 668 switch on new pip; fall back when pip is too old +# to know it. +RUN set -eux; \ + pip3 install --no-cache-dir --break-system-packages \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow \ + || pip3 install --no-cache-dir \ + -i "${PIP_INDEX}" --trusted-host "${PIP_TRUSTED_HOST}" \ + pandas pyarrow openpyxl scipy statsmodels h5py pypdf pillow + +WORKDIR /app + +# task.toml declares the user fields of [agent]/[verifier] and the platform switches to +# those users when executing, so the image has to actually create them; /app is opened up +# for writing (the agent writes answer.txt, the verifier writes a placeholder as a +# fallback). +RUN set -eux; \ + id -u agent >/dev/null 2>&1 || useradd -m agent; \ + id -u verifier >/dev/null 2>&1 || useradd -m verifier; \ + mkdir -p /app/data; \ + chmod 777 /app + +COPY data/ /app/data/ + +# The data must be readable by non-root users +RUN chmod -R a+rX /app/data + +# Build-time assertion: no canonical-truth material may be present in the environment +RUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ + && test -d /app/data diff --git a/dataworld-p009851-consequence-1/tests/grade.py b/dataworld-p009851-consequence-1/tests/grade.py index 23a35566c55247060ed04003c55a38d142f73534..c7aa840bdf06001a85a83c1ad78490f03c7a1c3a 100644 --- a/dataworld-p009851-consequence-1/tests/grade.py +++ b/dataworld-p009851-consequence-1/tests/grade.py @@ -1,20 +1,35 @@ -"""判分:LLM judge 按 rubric 逐条给 verdict,折算 reward(负分透传:触发错误结论扣分项时为负,不截断到 0)。 - -**评分语义的唯一实现处**。本机评测(``evaluate.py``)与 harbor 容器内 verifier -(``harbor.py`` 导出时把本文件拷进 ``tests/``)导入同一份代码——判分口径只有一个 -真值来源,不允许两条路径各自演化。 - -判分约定(与出题纪律对应): - -- 正分项:``status=satisfied`` 得分,``not_satisfied`` 不得分; -- 负分项(``points<0``,"错误结论扣分"):``status=triggered`` 时扣分; -- 报告没提到的结论不得分也不扣分,除非命中负分项描述的错误结论; -- ``reward = 2*(raw - 下限) / (上限 - 下限) - 1``,其中上限=正分项总分、下限=负分项总分(全负项 triggered 且正项全不满足的 raw)。raw 逐题按自身 rubric 上下限归一到 [-1, 1]:正项全满足=+1,负项全触发=-1,判分基础设施失败仍写 0(与真实分数空间区分开的哨兵值)。 - -容器内零依赖:本模块只用 stdlib,judge 的 HTTP 调用由 ``judge.py`` 负责。 - -命令行入口(harbor verifier 用):``python3 grade.py``,路径全部可由环境变量覆盖, -缺省值遵循 harbor 约定。判分链路任何失败都写 reward 0 + ``judge_error``,绝不崩溃。 +"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts are +folded into a reward. + +**The single source of truth for scoring semantics.** The local evaluation path +(``evaluate.py``) and the in-container harbor verifier (``harbor.py`` copies this +file into ``tests/`` when exporting) import the very same code -- there is exactly +one definition of the scoring rule, and the two paths are not allowed to drift +apart. + +Scoring contract (mirrors the task-authoring discipline): + +- Positive criteria: ``status=satisfied`` earns the points, ``not_satisfied`` earns 0; +- Negative criteria (``points<0``, "wrong-conclusion penalties"): ``status=triggered`` + deducts the points; +- A conclusion the report never mentions neither earns nor loses points, unless it + matches the wrong conclusion named by a negative criterion; +- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positive + criteria and ``lo`` the total of the negative ones (the raw score reached when every + negative criterion is triggered and no positive criterion is satisfied). The raw + score is therefore normalized per task, against that task's own rubric bounds, onto + **[0, 100]**: all positive criteria satisfied = 100, all negative criteria triggered + = 0. Grading-infrastructure failures are reported through a separate ``judge_error`` + key rather than through the reward value (see :func:`write_failure`); a value of 0 in + ``reward`` alone is ambiguous, because 0 is also the legitimate floor. + +Zero dependencies inside the container: this module uses stdlib only, and the judge's +HTTP call lives in ``judge.py``. + +Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every path +can be overridden through environment variables, and the defaults follow harbor's +conventions. Any failure anywhere in the grading pipeline writes reward 0 plus +``judge_error``; it never crashes. """ from __future__ import annotations @@ -28,26 +43,28 @@ import traceback from pathlib import Path from typing import Any, Dict, List, Optional -#: judge 连续失败的重试上限。 +#: Maximum number of consecutive judge failures before giving up. MAX_JUDGE_ATTEMPTS = 4 -#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。 +#: Truncation window for over-long reports (the judge context is limited; the head +#: holds the conclusion and method, the tail holds limitations and recommendations). REPORT_HEAD, REPORT_TAIL = 150_000, 20_000 -# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ────────────────────── -# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的 -# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同 -# 一个真值来源)。两种模式共用下面同一段判分逻辑。 +# -- Two modes: standalone run (container verifier) and in-package import (local eval) -- +# Inside the container this file is copied to /tests/grade.py with no task package to +# import from; in that case the prompt comes from the sibling judge_prompt.py (produced +# by prompts.JUDGE_PROMPT at export time -- still the same single source of truth). Both +# modes share the one scoring implementation below. try: from .prompts import JUDGE_PROMPT -except ImportError: # pragma: no cover - 容器内独立运行 +except ImportError: # pragma: no cover - standalone run inside the container sys.path.insert(0, str(Path(__file__).resolve().parent)) from judge_prompt import JUDGE_PROMPT # type: ignore[no-redef] def render_rubric(rubric: Dict[str, Any]) -> str: - """把打平后的 criteria 渲染成 judge 可读的清单。""" + """Render the flattened criteria into a checklist the judge can read.""" return "\n".join( f"- id={c['id']} | section={c['section']} | points={c['points']}\n" f" criterion: {c['criterion']}" @@ -62,7 +79,8 @@ def truncate_report(text: str, head: int = REPORT_HEAD, tail: int = REPORT_TAIL) def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: - """按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。""" + """Fold verdicts into a reward; a criterion with no verdict is ``missing`` and + earns 0 (the caller decides whether to retry).""" by_id = {v["id"]: v for v in verdicts if isinstance(v, dict) and "id" in v} total_positive = sum(c["points"] for c in rubric["criteria"] if c["points"] > 0) total_negative = sum(c["points"] for c in rubric["criteria"] if c["points"] < 0) @@ -81,17 +99,19 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: "points": criterion["points"], "status": status or "missing", "earned": earned, "reason": verdict.get("reason", ""), }) - # 按本题 rubric 的可达上下限归一到 [-1, 1]:hi=正分总分(全 satisfied), - # lo=负分总分(全 triggered 且正项零分)。hi<=lo(无正分项或空 rubric) - # 时判分无意义,返回 0。raw 数学上落在 [lo, hi],clamp 只是防御。 + # Normalize against this rubric's own reachable bounds: hi = every positive + # criterion satisfied, lo = every negative criterion triggered with zero positive + # points. raw is mathematically inside [lo, hi]; the clamp is defensive only. + # hi <= lo (no positive criteria, or an empty rubric) means the rubric carries no + # meaningful score, so 0 is returned. hi, lo = total_positive, total_negative if hi > lo: - normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0 - normalized = max(-1.0, min(1.0, normalized)) + reward = 100.0 * (raw_score - lo) / (hi - lo) + reward = max(0.0, min(100.0, reward)) else: - normalized = 0.0 + reward = 0.0 return { - "reward": round(normalized, 4), + "reward": round(reward, 2), "raw_score": raw_score, "total_positive": total_positive, "total_negative": total_negative, @@ -100,22 +120,25 @@ def score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]: } -# ── verdict 解析容错 ────────────────────────────────────────────────────────── -# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用 -# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平 -# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值 -# 不含引号,reason 取到最后一个引号即可正确还原。 +# -- Tolerance when parsing verdicts -------------------------------------------------- +# Two typical malformed judge outputs: long reasoning truncates the JSON (the trailing +# object is incomplete), and a reason quoting the report verbatim contains unescaped +# ASCII double quotes (so a whole-blob json.loads is guaranteed to fail). Verdict objects +# are flat (no nested braces), so they can be recovered one by one with a regex; a broken +# object then goes through field-level salvage -- id/status are enum values that never +# contain quotes, and reason can be recovered by taking everything up to the final quote. _VERDICT_OBJ_RE = re.compile(r'\{[^{}]*"id"[^{}]*\}', re.S) _VERDICT_ID_RE = re.compile(r'"id"\s*:\s*"([^"]+)"') _VERDICT_STATUS_RE = re.compile(r'"status"\s*:\s*"([^"]+)"') _VERDICT_REASON_RE = re.compile(r'"reason"\s*:\s*"(.*)"\s*\}\s*$', re.S) -#: 打捞到的 verdict 少于 criteria 的这个比例即判失败重试(而非接受一份残缺判分)。 +#: Salvaging fewer verdicts than this fraction of the criteria counts as a failure and +#: triggers a retry (rather than accepting a partial grading). _SALVAGE_MIN_RATIO = 2 / 3 def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: - """解析单个 verdict 对象;严格解析失败时按字段正则抢救。""" + """Parse a single verdict object; on strict-parse failure, salvage it field by field.""" try: obj = json.loads(blob) if isinstance(obj, dict) and "id" in obj and "status" in obj: @@ -132,10 +155,13 @@ def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]: def parse_verdicts(text: str, n_criteria: int) -> List[Any]: - """先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。 + """Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdict + objects one by one. - 打捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也 - 不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。 + Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving the + retry to the caller -- a result missing that many criteria is worth re-judging, + because missing criteria are silently recorded as 0 by :func:`score` and would + pollute the statistics. """ stripped = text.strip() if stripped.startswith("```"): @@ -155,20 +181,24 @@ def parse_verdicts(text: str, n_criteria: int) -> List[Any]: for m in _VERDICT_OBJ_RE.finditer(text)) if obj is not None] if len(verdicts) < max(1, int(n_criteria * _SALVAGE_MIN_RATIO)): - raise ValueError(f"verdicts 打捞不足: {len(verdicts)}/{n_criteria}") + raise ValueError(f"too few verdicts salvaged: {len(verdicts)}/{n_criteria}") return verdicts def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, report_path: str = "报告", attempts: int = MAX_JUDGE_ATTEMPTS, on_raw: Any = None) -> Dict[str, Any]: - """判一份报告:构造 prompt → 调 judge → 容错解析 → 折算 reward。 + """Grade one report: build the prompt -> call the judge -> parse tolerantly -> + fold into a reward. - ``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端, - 容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。 + ``call_judge(prompt) -> str`` is injected by the caller (the local path uses the + client from ``judge.py``, and the container path does the same), so this module + contains no network code at all. A result with missing criteria is retried while + attempts remain. - judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障 - 与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。 + After repeated judge failures it returns ``{"reward": None, "judge_error": ...}``: + a broken grading infrastructure and a genuine score of 0 are two different things, + and conflating them would pollute both the statistics and the RL data. """ prompt = JUDGE_PROMPT.format( rubric_text=render_rubric(rubric), @@ -184,20 +214,21 @@ def judge_report(rubric: Dict[str, Any], report_text: str, call_judge: Any, on_raw(text) verdicts = parse_verdicts(text, n_criteria) result = score(rubric, verdicts) - # 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。 + # Missing criteria are silently scored 0 by score(), so they must not be + # accepted as a normal result: retry while attempts remain. if result["missing_verdicts"] and attempt < attempts - 1: - raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}") + raise ValueError(f"missing verdicts: {result['missing_verdicts']}") return result - except Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试 + except Exception as exc: # noqa: BLE001 -- any judge/parse error is retried last_error = exc - print(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {exc}", + print(f"[grade] judge attempt {attempt + 1}/{attempts} failed: {exc}", file=sys.stderr, flush=True) if attempt < attempts - 1: time.sleep(min(10 * (attempt + 1), 60)) return {"reward": None, "judge_error": str(last_error)[:300], "criteria": []} -# ── harbor 容器 verifier 入口 ───────────────────────────────────────────────── +# -- Harbor container verifier entry point --------------------------------------------- ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt") RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json") @@ -214,10 +245,15 @@ def write_reward(result: Dict[str, Any]) -> None: def write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None: - """判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。 + """Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never a + non-zero exit. + + Harbor treats a non-zero verifier exit as an infrastructure failure of the task, so + everything is funneled into a 0 score plus diagnostics here, keeping a whole + evaluation batch from being interrupted by one task's grading failure. - harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 + - 诊断信息,让整批评测不因单题判分失败中断。 + Consumers must detect this case through the ``judge_error`` key and not through the + reward value: under the [0, 100] scale, 0 is also the legitimate floor. """ result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []} if extra: @@ -242,13 +278,13 @@ def _grade_container() -> None: if blank_reason: # Not the rubric-weighted blank score: an agent that ran but failed to # submit broke the task protocol itself, which is strictly worse than - # a submitted empty report. Flat -1 (rubric floor) regardless of the + # a submitted empty report. Flat 0 (the rubric floor) regardless of the # negative share -- deliberate uniform penalty, easy for RL to learn. result = score(rubric, []) - result["reward"] = -1.0 + result["reward"] = 0.0 result["blank"] = blank_reason write_reward(result) - print(f"[grade] blank submission ({blank_reason}): reward=-1.0 " + print(f"[grade] blank submission ({blank_reason}): reward=0.0 " f"(rubric blank would be {result['raw_score']})") return @@ -259,12 +295,12 @@ def _grade_container() -> None: try: call_judge = judge.make_judge() except judge.JudgeConfigError as exc: - write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True}) + write_failure(f"judge config error: {exc}", extra={"judge_config_error": True}) return result = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH)) if result.get("reward") is None: - write_failure(f"judge 连续 {MAX_JUDGE_ATTEMPTS} 次失败: {result.get('judge_error')}") + write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}") return write_reward(result) print(f"[grade] reward={result['reward']} " @@ -274,7 +310,7 @@ def _grade_container() -> None: def main() -> int: try: _grade_container() - except Exception: # noqa: BLE001 — 兜底也不许崩溃 + except Exception: # noqa: BLE001 -- even the catch-all must not crash write_failure(f"grader crashed: {traceback.format_exc()[-500:]}") return 0 diff --git a/dataworld-p009851-consequence-1/tests/judge.env b/dataworld-p009851-consequence-1/tests/judge.env new file mode 100644 index 0000000000000000000000000000000000000000..aa142d15b28152e87b8f3f17ebaad980d5f405fe --- /dev/null +++ b/dataworld-p009851-consequence-1/tests/judge.env @@ -0,0 +1,4 @@ +# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*) +ANTHROPIC_AUTH_TOKEN= +ANTHROPIC_BASE_URL=http://:8413/v1 +ANTHROPIC_MODEL= diff --git a/dataworld-p009851-consequence-1/tests/judge.py b/dataworld-p009851-consequence-1/tests/judge.py index 14f71125b7880f7bf27eab8462cf76e2b078ecc0..0f36108d06c84a54d757b64919cf7a656e54c76c 100644 --- a/dataworld-p009851-consequence-1/tests/judge.py +++ b/dataworld-p009851-consequence-1/tests/judge.py @@ -1,28 +1,36 @@ -"""Judge 客户端:给一段 prompt,返回模型的原始文本。 - -只负责"发一次请求、拿回文本",判分语义全在 ``grade.py``——两者分开,才能让 -容器与本机共用同一份评分口径而各用自己的网关。 - -**凭据只从环境变量读,代码里不落任何 token**。本机由 ``data_world.envfile`` -从项目根 ``.env`` 注入(与 data_world/dag_factory 同一套凭据);harbor 容器由 -镜像构建或运行期注入(见 ``harbor.py``)。因此本模块不提供任何"零环境变量默认 -可用"的内置密钥——那等于把密钥写进代码库。 - -两种网关形态(``JUDGE_API`` 选择): - -- ``openai`` ``POST {base}/v1/chat/completions``,鉴权 Bearer(项目内网关的形态); -- ``anthropic`` ``POST {base}/v1/messages``,鉴权 ``x-api-key`` + Bearer。 - -base_url 末尾有无 ``/v1`` 都可以::func:`normalize_base` 统一剥掉,各形态自己拼 -完整路径。``.env`` 里的 ``ANTHROPIC_BASE_URL`` 带 ``/v1``,而 claude CLI 要求裸 host、 -本模块要求带 ``/v1`` 的完整路径——归一化后两边共用同一个变量不会互相踩。 - -**一律流式(SSE)**。judge 的输出可以很长(rubric 几十条),非流式请求要等整段 -生成完才回第一个字节,网关与客户端的超时都容易在此误杀一次本来会成功的判分。 -流式下超时的语义变成"两个 chunk 之间的空档",只要模型还在吐字就不会被判超时, -判分链路因此不需要靠"让模型少输出"来规避超时。 - -零第三方依赖(``urllib``),容器镜像不必装 requests。 +"""Judge client: hand it a prompt and it returns the model's raw text. + +It only does "send one request, get the text back"; all scoring semantics live in +``grade.py``. Keeping the two apart is what lets the container and the local machine +share one scoring rule while each uses its own gateway. + +**Credentials are read from environment variables only; no token is ever stored in the +code.** Locally they are injected by ``data_world.envfile`` from the project-root +``.env`` (the same credentials used by data_world/dag_factory); inside the harbor +container they are injected at build or run time (see ``harbor.py``). This module +therefore provides no built-in "works with zero environment variables" key -- that would +amount to committing a key into the repository. + +Two gateway shapes (selected by ``JUDGE_API``): + +- ``openai`` ``POST {base}/v1/chat/completions``, ``Bearer`` auth (the shape of the + in-project gateway); +- ``anthropic`` ``POST {base}/v1/messages``, ``x-api-key`` plus ``Bearer`` auth. + +``base_url`` may or may not end in ``/v1``: :func:`normalize_base` strips it either way +and each shape builds the full path itself. ``ANTHROPIC_BASE_URL`` in ``.env`` carries +``/v1``, whereas the claude CLI wants a bare host and this module wants the full path +with ``/v1`` -- after normalization both can share one variable without stepping on each +other. + +**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens of +criteria), and a non-streaming request only returns its first byte once the whole +generation is done, so both the gateway and the client tend to time out and kill a +judgment that would have succeeded. Under streaming, a timeout means "a gap between two +chunks", so as long as the model keeps emitting tokens it is never judged as timed out, +and the grading pipeline needs no "make the model emit less" workaround. + +Zero third-party dependencies (``urllib``), so the container image does not need requests. """ from __future__ import annotations @@ -33,26 +41,32 @@ import urllib.error import urllib.request from typing import Any, Callable, Dict, Iterator, Optional -#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出; -#: 判分本身不贵,宁可给足。 +#: Judge output cap. The judge often reasons at length before the verdicts, and a +#: small cap truncates the JSON into invalid output; grading itself is cheap, so it is +#: better to allow plenty. MAX_TOKENS = 131_072 -#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。 +#: Idle timeout for the stream (seconds): only a gap longer than this between two +#: chunks counts as a hang. #: -#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时, -#: 只有真正卡住(网关挂起、连接半开)才触发。 +#: Because the request is streamed, this is not "total generation time" -- as long as +#: the model keeps emitting tokens it is never considered timed out; only a genuine +#: stall (gateway hung, half-open connection) trips it. TIMEOUT_SEC = 180.0 -#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``ANTHROPIC_*``。 +#: Environment variable names: judge-specific ones (``JUDGE_*``) win, otherwise fall +#: back to the project-wide ``ANTHROPIC_*``. _BASE_URL_KEYS = ("JUDGE_BASE_URL", "ANTHROPIC_BASE_URL") _TOKEN_KEYS = ("JUDGE_API_KEY", "JUDGE_APP_ID", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY") _MODEL_KEYS = ("JUDGE_MODEL", "ANTHROPIC_MODEL") class JudgeConfigError(RuntimeError): - """judge 凭据/配置缺失。``grade.py`` 捕获后写 reward 0 + 诊断信息。 + """Judge credentials/configuration are missing. ``grade.py`` catches it and writes + reward 0 plus diagnostics. - 与"judge 调用失败"区分开:配置错误不该重试,重试只会重复失败。 + Kept distinct from "the judge call failed": a configuration error must not be + retried, since retrying only repeats the failure. """ @@ -67,16 +81,18 @@ def _first_env(keys: tuple[str, ...]) -> Optional[str]: def _require(keys: tuple[str, ...], what: str) -> str: value = _first_env(keys) if not value: - raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}") + raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}") return value def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Iterator[Dict[str, Any]]: - """POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。 + """POST a streaming request and yield the JSON events found in SSE ``data:`` lines. - ``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。 - 显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。 + ``timeout`` is handed to the socket, so it measures a single blocking read (the gap + between chunks) rather than the total duration. Proxies are explicitly disabled: + gateways usually live on an internal network, and an egress proxy would make the + request fail outright. """ request = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -95,16 +111,17 @@ def _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any], try: event = json.loads(data) except json.JSONDecodeError: - continue # 心跳/注释等非 JSON 帧 + continue # heartbeats/comments and other non-JSON frames if isinstance(event, dict): yield event def normalize_base(url: str) -> str: - """剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。 + """Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only the + bare host prefix. - 与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用, - 完整路径由各 API 形态自己拼。 + Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shape + the caller passes works, and each API shape builds its own full path. """ normalized = (url or "").rstrip("/") for suffix in ("/v1/anthropic", "/anthropic", "/v1"): @@ -129,14 +146,15 @@ def _call_anthropic(base_url: str, token: str, model: str, prompt: str, if delta.get("type") == "text_delta": chunks.append(delta.get("text") or "") elif event.get("type") == "error": - raise RuntimeError(f"judge 流式错误: {str(event.get('error'))[:200]}") + raise RuntimeError(f"judge stream error: {str(event.get('error'))[:200]}") return "".join(chunks) def _call_openai(base_url: str, token: str, model: str, prompt: str, timeout: float) -> str: - # 不用 response_format=json_object:部分网关不支持严格模式会直接 400; - # JSON 约束靠 prompt,解析端(grade.parse_verdicts)有容错打捞。 + # Deliberately not using response_format=json_object: some gateways reject strict + # mode with a 400. The JSON contract is carried by the prompt, and the parsing side + # (grade.parse_verdicts) has tolerant salvage. events = _iter_sse( f"{base_url}/v1/chat/completions", {"authorization": f"Bearer {token}"}, @@ -146,7 +164,7 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, chunks = [] for event in events: if event.get("error"): - raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}") + raise RuntimeError(f"judge stream error: {str(event['error'])[:200]}") for choice in event.get("choices") or []: content = (choice.get("delta") or {}).get("content") if content: @@ -156,19 +174,20 @@ def _call_openai(base_url: str, token: str, model: str, prompt: str, _APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai} -#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是 -#: OpenAI 兼容的 chat/completions,不是 Anthropic Messages。 +#: Default API shape: the in-project gateway (``ANTHROPIC_BASE_URL`` in ``.env``) speaks +#: the OpenAI-compatible chat/completions protocol, not Anthropic Messages. DEFAULT_API = "openai" def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Dict[str, Any]: - """解析不含凭据的 judge 身份,供调用与评测缓存共同使用。""" + """Resolve the credential-free judge identity, shared by the call path and the + evaluation cache.""" api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower() if api_name not in _APIS: raise JudgeConfigError( - f"未知 JUDGE_API={api_name!r},可选 {'/'.join(sorted(_APIS))}") + f"unknown JUDGE_API={api_name!r}; expected one of {'/'.join(sorted(_APIS))}") return { "api": api_name, "base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")), @@ -180,9 +199,11 @@ def resolve_judge_identity(api: Optional[str] = None, base_url: Optional[str] = def make_judge(api: Optional[str] = None, base_url: Optional[str] = None, token: Optional[str] = None, model: Optional[str] = None, timeout: float = TIMEOUT_SEC) -> Callable[[str], str]: - """构造 ``call_judge(prompt) -> str``;缺凭据时抛 :class:`JudgeConfigError`。 + """Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` when + credentials are missing. - 显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。 + Explicit arguments take precedence over environment variables, which lets a CLI + override things such as ``--judge-model``. """ identity = resolve_judge_identity(api=api, base_url=base_url, model=model, timeout=timeout) diff --git a/dataworld-p009851-consequence-1/tests/judge_prompt.py b/dataworld-p009851-consequence-1/tests/judge_prompt.py index 56bf32a67b09a069a41f46966bf823c36900bcb9..c7948420324150aefff60158d04f4974066175b9 100644 --- a/dataworld-p009851-consequence-1/tests/judge_prompt.py +++ b/dataworld-p009851-consequence-1/tests/judge_prompt.py @@ -1,3 +1,3 @@ -"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。""" +"""Judge prompt (generated by task/harbor.py from task/prompts.py; do not edit by hand).""" JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n\n{report}\n\n\n[判定规则]\n1. 每个评分点自身写明了判定所需的一切——口径、数值或区间、以及它描述的是正确做法\n 还是错误做法。你只依据 criterion 的文字和报告正文判定,不要再去设想别的标准。\n2. 对每个评分点输出一个 verdict:\n - 正分评分点(points > 0):报告实质满足该点则 status="satisfied",否则 "not_satisfied"。\n 正分点写的都是**确定性事实**——出题者已核实过,任何合法口径都会得到同一结论,\n 所以只看结果对不对,不看用什么路径算出来的:实现方式、工具、中间步骤与 criterion\n 描述的不同一律不扣,但结论性数值(行数、系数、方向与量级)应与 criterion 给出的\n 数值或区间一致,或在合理误差内。criterion 给的是区间时,落在区间内即算满足。\n - 负分评分点(points < 0):报告确实犯下该错误则 status="triggered",否则 "not_triggered"。\n 负分点写的是这道题上**已知会走偏**的做法或结论——要么是容易踩的具体错误,要么是\n 一条看似合理但会得出错误数值的路径。报告没提到相关内容不算 triggered;必须报告\n 明确采用了该做法或明确主张了该结论才 triggered。报告用了另一条口径、得到的数值\n 与任何正分点都不冲突,这不构成 triggered——负分只惩罚被点名的那个错误。\n3. 严格按报告内容判定,不要脑补报告没有的内容;也不要因为措辞不同而误判实质正确的内容。\n4. 每条 reason 用中文一句话说明依据,不要大段照抄 criterion 原文。\n\n[输出格式] 只输出一个 JSON 对象,不要输出任何其他文字:\n{{\n "verdicts": [\n {{"id": "<评分点 id>", "status": "satisfied|not_satisfied|triggered|not_triggered", "reason": "<一句话>"}},\n ...\n ]\n}}' diff --git a/dataworld-p009851-consequence-1/tests/test.sh b/dataworld-p009851-consequence-1/tests/test.sh index 2c90c378de5d2b6e5b8e34a0289cb098b06b00f8..34c3abda19f9887cd42c0a3a1f662623fe68302a 100644 --- a/dataworld-p009851-consequence-1/tests/test.sh +++ b/dataworld-p009851-consequence-1/tests/test.sh @@ -1,20 +1,25 @@ #!/bin/bash -# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。 -# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑); -# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。 +# Data-World harbor verifier entry point: grades /app/answer.txt and produces +# reward.txt + details.json. +# Judge credentials come from the sibling judge.env (see the source logic below); +# any failure falls back to writing reward 0 and exiting 0 -- a non-zero verifier exit +# is treated by harbor as an infrastructure failure. set -euo pipefail ANSWER_PATH="${ANSWER_PATH:-/app/answer.txt}" REWARD_PATH="${REWARD_PATH:-/logs/verifier/reward.txt}" DETAILS_PATH="${DETAILS_PATH:-/logs/verifier/details.json}" ARTIFACT_DIR="${ARTIFACT_DIR:-/logs/artifacts}" -# 判分脚本与 rubric 与本文件同目录:容器里是 /tests/,本机复核时是导出目录里的 -# tests/。用脚本自身位置定位而非硬编码 /tests,同一份 test.sh 两处都能跑。 +# The grading script and the rubric live next to this file: /tests/ inside the +# container, and the tests/ of an exported directory when re-checking locally. +# Locating them from the script's own path rather than hard-coding /tests is what lets +# the same test.sh run in both places. TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" export ANSWER_PATH REWARD_PATH DETAILS_PATH export RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}" -# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。 +# Judge credentials travel with the task directory (the evaluation platform offers no +# run-time injection channel; see judge.env). if [ -f "$TESTS_DIR/judge.env" ]; then set -a; . "$TESTS_DIR/judge.env"; set +a fi @@ -25,16 +30,18 @@ if [ ! -f "$ANSWER_PATH" ] || [ ! -s "$ANSWER_PATH" ]; then mkdir -p "$(dirname "$ANSWER_PATH")" echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH" fi -# 运行器可能已把 ANSWER_PATH 收进 ARTIFACT_DIR;cp 源==目标会报错。 +# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with +# source == destination fails. if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; then cp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt" fi -# judge 网关在内网:清掉公网出口代理,否则请求被拦。 +# The judge gateway is on an internal network: clear the egress proxy, otherwise the +# request is blocked. unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true -# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure), -# 这里只做最后兜底。 +# grade.py itself writes reward.txt + details.json on any failure (write_failure); +# this is only the last-resort fallback. set +e python3 "$TESTS_DIR/grade.py" 2>&1 status=$? diff --git a/sample_manifest.json b/sample_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..3dfd6e14bb1b3a4f7511579cce86d11066c070d0 --- /dev/null +++ b/sample_manifest.json @@ -0,0 +1,1225 @@ +{ + "dataset_name": "DataWorld-Bench", + "status": "FINAL (human-preference verified)", + "source": "dataworld_v7 (harbor dataset, v7 full, 9692 tasks)", + "curation_pipeline": [ + "1. audit filter: 1302 worlds -> 852 with audit pass-rate 100% (0 failures)", + "2. taxonomy balance: 50 worlds stratified over 16 domain categories, 2 tasks each (cause-1 + consequence-1) = 100", + "3. human preference: each selected task paired with its next-best sibling (-2), 100 pairs, >=2 distinct annotators per pair, disagreements adjudicated by owner (dataset owner); winners below" + ], + "sample_size": 100, + "side_counts": { + "-1 (original)": 50, + "-2 (challenger)": 50 + }, + "decision_how": { + "majority": 73, + "owner_decided": 27 + }, + "annotators": 15, + "labeling_system": "internal labeling UI, votes.json + adjudicated.json", + "selection_file": "../../results/v7_perfect_balanced50x2.tsv", + "audit_report": "../../results/v7_audit_all.tsv", + "tasks": { + "dataworld-p000014-cause-1": { + "pair": 22, + "world": "p000014", + "kind": "cause", + "category_id": "4", + "category_name": "Operations, Supply Chain & Manufacturing / 运营·供应链·制造", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-01": "A" + } + }, + "dataworld-p000014-consequence-2": { + "pair": 23, + "world": "p000014", + "kind": "consequence", + "category_id": "4", + "category_name": "Operations, Supply Chain & Manufacturing / 运营·供应链·制造", + "decision": "majority", + "votes": { + "annotator-10": "B", + "annotator-07": "B" + } + }, + "dataworld-p000049-cause-2": { + "pair": 94, + "world": "p000049", + "kind": "cause", + "category_id": "16", + "category_name": "Transportation & Mobility / 交通与移动性", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-01": "B" + } + }, + "dataworld-p000049-consequence-2": { + "pair": 95, + "world": "p000049", + "kind": "consequence", + "category_id": "16", + "category_name": "Transportation & Mobility / 交通与移动性", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-09": "A" + } + }, + "dataworld-p000072-cause-2": { + "pair": 90, + "world": "p000072", + "kind": "cause", + "category_id": "15", + "category_name": "Social Science, Survey & Behavioral / 社会科学·调查·行为", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-14": "B" + } + }, + "dataworld-p000072-consequence-1": { + "pair": 91, + "world": "p000072", + "kind": "consequence", + "category_id": "15", + "category_name": "Social Science, Survey & Behavioral / 社会科学·调查·行为", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-14": "B" + } + }, + "dataworld-p000096-cause-2": { + "pair": 30, + "world": "p000096", + "kind": "cause", + "category_id": "6", + "category_name": "Risk, Fraud & Compliance / 风险·欺诈·合规", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-10": "B" + } + }, + "dataworld-p000096-consequence-1": { + "pair": 31, + "world": "p000096", + "kind": "consequence", + "category_id": "6", + "category_name": "Risk, Fraud & Compliance / 风险·欺诈·合规", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-10": "A" + } + }, + "dataworld-p000129-cause-2": { + "pair": 0, + "world": "p000129", + "kind": "cause", + "category_id": "1", + "category_name": "Commercial Growth & Acquisition / 商业增长与获客", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-09": "A" + } + }, + "dataworld-p000129-consequence-1": { + "pair": 1, + "world": "p000129", + "kind": "consequence", + "category_id": "1", + "category_name": "Commercial Growth & Acquisition / 商业增长与获客", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-01": "B" + } + }, + "dataworld-p000151-cause-2": { + "pair": 96, + "world": "p000151", + "kind": "cause", + "category_id": "16", + "category_name": "Transportation & Mobility / 交通与移动性", + "decision": "majority", + "votes": { + "annotator-09": "B", + "annotator-07": "B" + } + }, + "dataworld-p000151-consequence-1": { + "pair": 97, + "world": "p000151", + "kind": "consequence", + "category_id": "16", + "category_name": "Transportation & Mobility / 交通与移动性", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-09": "A" + } + }, + "dataworld-p000183-cause-2": { + "pair": 66, + "world": "p000183", + "kind": "cause", + "category_id": "12", + "category_name": "Energy, Utilities & IoT / 能源·公用事业·IoT", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-01": "B" + } + }, + "dataworld-p000183-consequence-1": { + "pair": 67, + "world": "p000183", + "kind": "consequence", + "category_id": "12", + "category_name": "Energy, Utilities & IoT / 能源·公用事业·IoT", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-01": "A" + } + }, + "dataworld-p000211-cause-2": { + "pair": 74, + "world": "p000211", + "kind": "cause", + "category_id": "13", + "category_name": "Public Policy & Program Evaluation / 公共政策与项目评估", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-04": "B" + } + }, + "dataworld-p000211-consequence-1": { + "pair": 75, + "world": "p000211", + "kind": "consequence", + "category_id": "13", + "category_name": "Public Policy & Program Evaluation / 公共政策与项目评估", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-04": "B" + } + }, + "dataworld-p000213-cause-2": { + "pair": 62, + "world": "p000213", + "kind": "cause", + "category_id": "11", + "category_name": "Environment, Climate & Geospatial / 环境·气候·地理空间", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-03": "A" + } + }, + "dataworld-p000213-consequence-2": { + "pair": 63, + "world": "p000213", + "kind": "consequence", + "category_id": "11", + "category_name": "Environment, Climate & Geospatial / 环境·气候·地理空间", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-03": "A" + } + }, + "dataworld-p000221-cause-2": { + "pair": 80, + "world": "p000221", + "kind": "cause", + "category_id": "14", + "category_name": "Education & Learning Analytics / 教育与学习分析", + "decision": "majority", + "votes": { + "annotator-02": "B", + "annotator-07": "B" + } + }, + "dataworld-p000221-consequence-2": { + "pair": 81, + "world": "p000221", + "kind": "consequence", + "category_id": "14", + "category_name": "Education & Learning Analytics / 教育与学习分析", + "decision": "majority", + "votes": { + "annotator-02": "B", + "annotator-07": "B" + } + }, + "dataworld-p000231-cause-1": { + "pair": 50, + "world": "p000231", + "kind": "cause", + "category_id": "9", + "category_name": "Bioinformatics & Omics / 生物信息·组学", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-06": "A" + } + }, + "dataworld-p000231-consequence-2": { + "pair": 51, + "world": "p000231", + "kind": "consequence", + "category_id": "9", + "category_name": "Bioinformatics & Omics / 生物信息·组学", + "decision": "majority", + "votes": { + "annotator-06": "B", + "annotator-07": "B" + } + }, + "dataworld-p000233-cause-1": { + "pair": 28, + "world": "p000233", + "kind": "cause", + "category_id": "5", + "category_name": "People / HR & Org / 人力与组织", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-12": "A" + } + }, + "dataworld-p000233-consequence-1": { + "pair": 29, + "world": "p000233", + "kind": "consequence", + "category_id": "5", + "category_name": "People / HR & Org / 人力与组织", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-10": "A" + } + }, + "dataworld-p000236-cause-2": { + "pair": 88, + "world": "p000236", + "kind": "cause", + "category_id": "15", + "category_name": "Social Science, Survey & Behavioral / 社会科学·调查·行为", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-14": "B" + } + }, + "dataworld-p000236-consequence-1": { + "pair": 89, + "world": "p000236", + "kind": "consequence", + "category_id": "15", + "category_name": "Social Science, Survey & Behavioral / 社会科学·调查·行为", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-14": "B" + } + }, + "dataworld-p000249-cause-1": { + "pair": 64, + "world": "p000249", + "kind": "cause", + "category_id": "11", + "category_name": "Environment, Climate & Geospatial / 环境·气候·地理空间", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-01": "A" + } + }, + "dataworld-p000249-consequence-1": { + "pair": 65, + "world": "p000249", + "kind": "consequence", + "category_id": "11", + "category_name": "Environment, Climate & Geospatial / 环境·气候·地理空间", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-01": "A" + } + }, + "dataworld-p000341-cause-2": { + "pair": 24, + "world": "p000341", + "kind": "cause", + "category_id": "5", + "category_name": "People / HR & Org / 人力与组织", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-12": "B" + } + }, + "dataworld-p000341-consequence-2": { + "pair": 25, + "world": "p000341", + "kind": "consequence", + "category_id": "5", + "category_name": "People / HR & Org / 人力与组织", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-12": "B" + } + }, + "dataworld-p000348-cause-2": { + "pair": 34, + "world": "p000348", + "kind": "cause", + "category_id": "6", + "category_name": "Risk, Fraud & Compliance / 风险·欺诈·合规", + "decision": "majority", + "votes": { + "annotator-05": "B", + "annotator-07": "B" + } + }, + "dataworld-p000348-consequence-1": { + "pair": 35, + "world": "p000348", + "kind": "consequence", + "category_id": "6", + "category_name": "Risk, Fraud & Compliance / 风险·欺诈·合规", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-05": "A" + } + }, + "dataworld-p000350-cause-2": { + "pair": 60, + "world": "p000350", + "kind": "cause", + "category_id": "11", + "category_name": "Environment, Climate & Geospatial / 环境·气候·地理空间", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-03": "B" + } + }, + "dataworld-p000350-consequence-2": { + "pair": 61, + "world": "p000350", + "kind": "consequence", + "category_id": "11", + "category_name": "Environment, Climate & Geospatial / 环境·气候·地理空间", + "decision": "majority", + "votes": { + "annotator-03": "B", + "annotator-07": "B" + } + }, + "dataworld-p000372-cause-2": { + "pair": 76, + "world": "p000372", + "kind": "cause", + "category_id": "13", + "category_name": "Public Policy & Program Evaluation / 公共政策与项目评估", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-02": "B" + } + }, + "dataworld-p000372-consequence-1": { + "pair": 77, + "world": "p000372", + "kind": "consequence", + "category_id": "13", + "category_name": "Public Policy & Program Evaluation / 公共政策与项目评估", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-02": "A" + } + }, + "dataworld-p000384-cause-1": { + "pair": 32, + "world": "p000384", + "kind": "cause", + "category_id": "6", + "category_name": "Risk, Fraud & Compliance / 风险·欺诈·合规", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-10": "A" + } + }, + "dataworld-p000384-consequence-1": { + "pair": 33, + "world": "p000384", + "kind": "consequence", + "category_id": "6", + "category_name": "Risk, Fraud & Compliance / 风险·欺诈·合规", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-10": "A" + } + }, + "dataworld-p000419-cause-2": { + "pair": 40, + "world": "p000419", + "kind": "cause", + "category_id": "7", + "category_name": "Clinical & Healthcare / 临床与医疗", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-15": "A" + } + }, + "dataworld-p000419-consequence-1": { + "pair": 41, + "world": "p000419", + "kind": "consequence", + "category_id": "7", + "category_name": "Clinical & Healthcare / 临床与医疗", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-15": "A" + } + }, + "dataworld-p000478-cause-1": { + "pair": 86, + "world": "p000478", + "kind": "cause", + "category_id": "15", + "category_name": "Social Science, Survey & Behavioral / 社会科学·调查·行为", + "decision": "majority", + "votes": { + "annotator-01": "A", + "annotator-07": "A" + } + }, + "dataworld-p000478-consequence-1": { + "pair": 87, + "world": "p000478", + "kind": "consequence", + "category_id": "15", + "category_name": "Social Science, Survey & Behavioral / 社会科学·调查·行为", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-01": "B" + } + }, + "dataworld-p000565-cause-1": { + "pair": 58, + "world": "p000565", + "kind": "cause", + "category_id": "10", + "category_name": "Experimental & Physical Science / 实验与物理科学", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-03": "A" + } + }, + "dataworld-p000565-consequence-1": { + "pair": 59, + "world": "p000565", + "kind": "consequence", + "category_id": "10", + "category_name": "Experimental & Physical Science / 实验与物理科学", + "decision": "majority", + "votes": { + "annotator-03": "A", + "annotator-07": "A" + } + }, + "dataworld-p000619-cause-2": { + "pair": 72, + "world": "p000619", + "kind": "cause", + "category_id": "13", + "category_name": "Public Policy & Program Evaluation / 公共政策与项目评估", + "decision": "majority", + "votes": { + "annotator-04": "B", + "annotator-07": "B" + } + }, + "dataworld-p000619-consequence-1": { + "pair": 73, + "world": "p000619", + "kind": "consequence", + "category_id": "13", + "category_name": "Public Policy & Program Evaluation / 公共政策与项目评估", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-04": "B" + } + }, + "dataworld-p000631-cause-1": { + "pair": 4, + "world": "p000631", + "kind": "cause", + "category_id": "1", + "category_name": "Commercial Growth & Acquisition / 商业增长与获客", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-01": "B" + } + }, + "dataworld-p000631-consequence-2": { + "pair": 5, + "world": "p000631", + "kind": "consequence", + "category_id": "1", + "category_name": "Commercial Growth & Acquisition / 商业增长与获客", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-01": "A" + } + }, + "dataworld-p000917-cause-1": { + "pair": 98, + "world": "p000917", + "kind": "cause", + "category_id": "16", + "category_name": "Transportation & Mobility / 交通与移动性", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-09": "B" + } + }, + "dataworld-p000917-consequence-1": { + "pair": 99, + "world": "p000917", + "kind": "consequence", + "category_id": "16", + "category_name": "Transportation & Mobility / 交通与移动性", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-09": "B" + } + }, + "dataworld-p000923-cause-2": { + "pair": 38, + "world": "p000923", + "kind": "cause", + "category_id": "7", + "category_name": "Clinical & Healthcare / 临床与医疗", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-05": "B" + } + }, + "dataworld-p000923-consequence-1": { + "pair": 39, + "world": "p000923", + "kind": "consequence", + "category_id": "7", + "category_name": "Clinical & Healthcare / 临床与医疗", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-05": "A" + } + }, + "dataworld-p000924-cause-2": { + "pair": 54, + "world": "p000924", + "kind": "cause", + "category_id": "10", + "category_name": "Experimental & Physical Science / 实验与物理科学", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-01": "A" + } + }, + "dataworld-p000924-consequence-2": { + "pair": 55, + "world": "p000924", + "kind": "consequence", + "category_id": "10", + "category_name": "Experimental & Physical Science / 实验与物理科学", + "decision": "majority", + "votes": { + "annotator-01": "B", + "annotator-07": "B" + } + }, + "dataworld-p001067-cause-1": { + "pair": 56, + "world": "p001067", + "kind": "cause", + "category_id": "10", + "category_name": "Experimental & Physical Science / 实验与物理科学", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-01": "B" + } + }, + "dataworld-p001067-consequence-1": { + "pair": 57, + "world": "p001067", + "kind": "consequence", + "category_id": "10", + "category_name": "Experimental & Physical Science / 实验与物理科学", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-01": "A" + } + }, + "dataworld-p001071-cause-2": { + "pair": 70, + "world": "p001071", + "kind": "cause", + "category_id": "12", + "category_name": "Energy, Utilities & IoT / 能源·公用事业·IoT", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-04": "B" + } + }, + "dataworld-p001071-consequence-1": { + "pair": 71, + "world": "p001071", + "kind": "consequence", + "category_id": "12", + "category_name": "Energy, Utilities & IoT / 能源·公用事业·IoT", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-04": "B" + } + }, + "dataworld-p001083-cause-1": { + "pair": 2, + "world": "p001083", + "kind": "cause", + "category_id": "1", + "category_name": "Commercial Growth & Acquisition / 商业增长与获客", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-08": "A" + } + }, + "dataworld-p001083-consequence-1": { + "pair": 3, + "world": "p001083", + "kind": "consequence", + "category_id": "1", + "category_name": "Commercial Growth & Acquisition / 商业增长与获客", + "decision": "majority", + "votes": { + "annotator-01": "A", + "annotator-07": "A" + } + }, + "dataworld-p001115-cause-1": { + "pair": 20, + "world": "p001115", + "kind": "cause", + "category_id": "4", + "category_name": "Operations, Supply Chain & Manufacturing / 运营·供应链·制造", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-01": "A" + } + }, + "dataworld-p001115-consequence-2": { + "pair": 21, + "world": "p001115", + "kind": "consequence", + "category_id": "4", + "category_name": "Operations, Supply Chain & Manufacturing / 运营·供应链·制造", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-01": "A" + } + }, + "dataworld-p001119-cause-1": { + "pair": 42, + "world": "p001119", + "kind": "cause", + "category_id": "8", + "category_name": "Epidemiology & Public Health / 流行病学与公共卫生", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-15": "A" + } + }, + "dataworld-p001119-consequence-1": { + "pair": 43, + "world": "p001119", + "kind": "consequence", + "category_id": "8", + "category_name": "Epidemiology & Public Health / 流行病学与公共卫生", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-15": "A" + } + }, + "dataworld-p001147-cause-2": { + "pair": 44, + "world": "p001147", + "kind": "cause", + "category_id": "8", + "category_name": "Epidemiology & Public Health / 流行病学与公共卫生", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-15": "A" + } + }, + "dataworld-p001147-consequence-1": { + "pair": 45, + "world": "p001147", + "kind": "consequence", + "category_id": "8", + "category_name": "Epidemiology & Public Health / 流行病学与公共卫生", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-15": "B" + } + }, + "dataworld-p001201-cause-1": { + "pair": 8, + "world": "p001201", + "kind": "cause", + "category_id": "2", + "category_name": "Customer, Pricing & Revenue / 客户·定价·收益", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-12": "A" + } + }, + "dataworld-p001201-consequence-1": { + "pair": 9, + "world": "p001201", + "kind": "consequence", + "category_id": "2", + "category_name": "Customer, Pricing & Revenue / 客户·定价·收益", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-01": "A" + } + }, + "dataworld-p001203-cause-2": { + "pair": 52, + "world": "p001203", + "kind": "cause", + "category_id": "9", + "category_name": "Bioinformatics & Omics / 生物信息·组学", + "decision": "majority", + "votes": { + "annotator-11": "B", + "annotator-07": "B" + } + }, + "dataworld-p001203-consequence-2": { + "pair": 53, + "world": "p001203", + "kind": "consequence", + "category_id": "9", + "category_name": "Bioinformatics & Omics / 生物信息·组学", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-01": "A" + } + }, + "dataworld-p001219-cause-2": { + "pair": 84, + "world": "p001219", + "kind": "cause", + "category_id": "14", + "category_name": "Education & Learning Analytics / 教育与学习分析", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-01": "B" + } + }, + "dataworld-p001219-consequence-1": { + "pair": 85, + "world": "p001219", + "kind": "consequence", + "category_id": "14", + "category_name": "Education & Learning Analytics / 教育与学习分析", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-01": "A" + } + }, + "dataworld-p001223-cause-2": { + "pair": 92, + "world": "p001223", + "kind": "cause", + "category_id": "15", + "category_name": "Social Science, Survey & Behavioral / 社会科学·调查·行为", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-14": "B" + } + }, + "dataworld-p001223-consequence-2": { + "pair": 93, + "world": "p001223", + "kind": "consequence", + "category_id": "15", + "category_name": "Social Science, Survey & Behavioral / 社会科学·调查·行为", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-14": "B" + } + }, + "dataworld-p001237-cause-2": { + "pair": 82, + "world": "p001237", + "kind": "cause", + "category_id": "14", + "category_name": "Education & Learning Analytics / 教育与学习分析", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-01": "A" + } + }, + "dataworld-p001237-consequence-1": { + "pair": 83, + "world": "p001237", + "kind": "consequence", + "category_id": "14", + "category_name": "Education & Learning Analytics / 教育与学习分析", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-01": "B" + } + }, + "dataworld-p001290-cause-2": { + "pair": 78, + "world": "p001290", + "kind": "cause", + "category_id": "13", + "category_name": "Public Policy & Program Evaluation / 公共政策与项目评估", + "decision": "majority", + "votes": { + "annotator-02": "B", + "annotator-07": "B" + } + }, + "dataworld-p001290-consequence-2": { + "pair": 79, + "world": "p001290", + "kind": "consequence", + "category_id": "13", + "category_name": "Public Policy & Program Evaluation / 公共政策与项目评估", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-02": "B" + } + }, + "dataworld-p001313-cause-2": { + "pair": 6, + "world": "p001313", + "kind": "cause", + "category_id": "2", + "category_name": "Customer, Pricing & Revenue / 客户·定价·收益", + "decision": "owner_decided", + "votes": { + "annotator-07": "B", + "annotator-01": "A" + } + }, + "dataworld-p001313-consequence-1": { + "pair": 7, + "world": "p001313", + "kind": "consequence", + "category_id": "2", + "category_name": "Customer, Pricing & Revenue / 客户·定价·收益", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-01": "A" + } + }, + "dataworld-p001656-cause-2": { + "pair": 12, + "world": "p001656", + "kind": "cause", + "category_id": "3", + "category_name": "Finance, FP&A & Markets / 财务·FP&A·金融市场", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-01": "B" + } + }, + "dataworld-p001656-consequence-1": { + "pair": 13, + "world": "p001656", + "kind": "consequence", + "category_id": "3", + "category_name": "Finance, FP&A & Markets / 财务·FP&A·金融市场", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-08": "A" + } + }, + "dataworld-p002876-cause-2": { + "pair": 68, + "world": "p002876", + "kind": "cause", + "category_id": "12", + "category_name": "Energy, Utilities & IoT / 能源·公用事业·IoT", + "decision": "majority", + "votes": { + "annotator-01": "B", + "annotator-07": "B" + } + }, + "dataworld-p002876-consequence-1": { + "pair": 69, + "world": "p002876", + "kind": "consequence", + "category_id": "12", + "category_name": "Energy, Utilities & IoT / 能源·公用事业·IoT", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-01": "A" + } + }, + "dataworld-p004607-cause-2": { + "pair": 18, + "world": "p004607", + "kind": "cause", + "category_id": "4", + "category_name": "Operations, Supply Chain & Manufacturing / 运营·供应链·制造", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-13": "B" + } + }, + "dataworld-p004607-consequence-2": { + "pair": 19, + "world": "p004607", + "kind": "consequence", + "category_id": "4", + "category_name": "Operations, Supply Chain & Manufacturing / 运营·供应链·制造", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-01": "B" + } + }, + "dataworld-p006499-cause-2": { + "pair": 10, + "world": "p006499", + "kind": "cause", + "category_id": "2", + "category_name": "Customer, Pricing & Revenue / 客户·定价·收益", + "decision": "majority", + "votes": { + "annotator-01": "B", + "annotator-07": "B" + } + }, + "dataworld-p006499-consequence-2": { + "pair": 11, + "world": "p006499", + "kind": "consequence", + "category_id": "2", + "category_name": "Customer, Pricing & Revenue / 客户·定价·收益", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-01": "B" + } + }, + "dataworld-p006632-cause-1": { + "pair": 26, + "world": "p006632", + "kind": "cause", + "category_id": "5", + "category_name": "People / HR & Org / 人力与组织", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-12": "A" + } + }, + "dataworld-p006632-consequence-2": { + "pair": 27, + "world": "p006632", + "kind": "consequence", + "category_id": "5", + "category_name": "People / HR & Org / 人力与组织", + "decision": "majority", + "votes": { + "annotator-12": "B", + "annotator-07": "B" + } + }, + "dataworld-p006802-cause-2": { + "pair": 36, + "world": "p006802", + "kind": "cause", + "category_id": "7", + "category_name": "Clinical & Healthcare / 临床与医疗", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-05": "B" + } + }, + "dataworld-p006802-consequence-2": { + "pair": 37, + "world": "p006802", + "kind": "consequence", + "category_id": "7", + "category_name": "Clinical & Healthcare / 临床与医疗", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-05": "B" + } + }, + "dataworld-p007107-cause-1": { + "pair": 48, + "world": "p007107", + "kind": "cause", + "category_id": "9", + "category_name": "Bioinformatics & Omics / 生物信息·组学", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-06": "B" + } + }, + "dataworld-p007107-consequence-2": { + "pair": 49, + "world": "p007107", + "kind": "consequence", + "category_id": "9", + "category_name": "Bioinformatics & Omics / 生物信息·组学", + "decision": "majority", + "votes": { + "annotator-07": "B", + "annotator-06": "B" + } + }, + "dataworld-p009238-cause-1": { + "pair": 46, + "world": "p009238", + "kind": "cause", + "category_id": "8", + "category_name": "Epidemiology & Public Health / 流行病学与公共卫生", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-06": "A" + } + }, + "dataworld-p009238-consequence-1": { + "pair": 47, + "world": "p009238", + "kind": "consequence", + "category_id": "8", + "category_name": "Epidemiology & Public Health / 流行病学与公共卫生", + "decision": "owner_decided", + "votes": { + "annotator-07": "A", + "annotator-06": "B" + } + }, + "dataworld-p009406-cause-1": { + "pair": 14, + "world": "p009406", + "kind": "cause", + "category_id": "3", + "category_name": "Finance, FP&A & Markets / 财务·FP&A·金融市场", + "decision": "majority", + "votes": { + "annotator-08": "A", + "annotator-07": "A" + } + }, + "dataworld-p009406-consequence-1": { + "pair": 15, + "world": "p009406", + "kind": "consequence", + "category_id": "3", + "category_name": "Finance, FP&A & Markets / 财务·FP&A·金融市场", + "decision": "majority", + "votes": { + "annotator-07": "A", + "annotator-08": "A" + } + }, + "dataworld-p009851-cause-2": { + "pair": 16, + "world": "p009851", + "kind": "cause", + "category_id": "3", + "category_name": "Finance, FP&A & Markets / 财务·FP&A·金融市场", + "decision": "majority", + "votes": { + "annotator-08": "B", + "annotator-07": "B" + } + }, + "dataworld-p009851-consequence-1": { + "pair": 17, + "world": "p009851", + "kind": "consequence", + "category_id": "3", + "category_name": "Finance, FP&A & Markets / 财务·FP&A·金融市场", + "decision": "majority", + "votes": { + "annotator-08": "A", + "annotator-07": "A" + } + } + } +} \ No newline at end of file