DataWorld-Bench: release overlay - sanitized Dockerfile/judge.env/sample_manifest, English code comments & log messages, grader reward normalized to [0,100] (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- dataworld-p002876-consequence-1/tests/grade.py+99-63
- dataworld-p002876-consequence-1/tests/judge.envAdded+4
- dataworld-p002876-consequence-1/tests/judge.py+72-51
- dataworld-p002876-consequence-1/tests/judge_prompt.py+1-1
- dataworld-p002876-consequence-1/tests/test.sh+17-10
- dataworld-p004607-cause-2/environment/DockerfileAdded+64
- dataworld-p004607-cause-2/tests/grade.py+99-63
- dataworld-p004607-cause-2/tests/judge.envAdded+4
- dataworld-p004607-cause-2/tests/judge.py+72-51
- dataworld-p004607-cause-2/tests/judge_prompt.py+1-1
- dataworld-p004607-cause-2/tests/test.sh+17-10
- dataworld-p004607-consequence-2/environment/DockerfileAdded+64
- dataworld-p004607-consequence-2/tests/grade.py+99-63
- dataworld-p004607-consequence-2/tests/judge.envAdded+4
- dataworld-p004607-consequence-2/tests/judge.py+72-51
- dataworld-p004607-consequence-2/tests/judge_prompt.py+1-1
- dataworld-p004607-consequence-2/tests/test.sh+17-10
- dataworld-p006499-cause-2/environment/DockerfileAdded+64
- dataworld-p006499-cause-2/tests/grade.py+99-63
- dataworld-p006499-cause-2/tests/judge.envAdded+4
- dataworld-p006499-cause-2/tests/judge.py+72-51
- dataworld-p006499-cause-2/tests/judge_prompt.py+1-1
- dataworld-p006499-cause-2/tests/test.sh+17-10
- dataworld-p006499-consequence-2/environment/DockerfileAdded+64
- dataworld-p006499-consequence-2/tests/grade.py+99-63
- dataworld-p006499-consequence-2/tests/judge.envAdded+4
- dataworld-p006499-consequence-2/tests/judge.py+72-51
- dataworld-p006499-consequence-2/tests/judge_prompt.py+1-1
- dataworld-p006499-consequence-2/tests/test.sh+17-10
- dataworld-p006632-cause-1/environment/DockerfileAdded+64
- dataworld-p006632-cause-1/tests/grade.py+99-63
- dataworld-p006632-cause-1/tests/judge.envAdded+4
- dataworld-p006632-cause-1/tests/judge.py+72-51
- dataworld-p006632-cause-1/tests/judge_prompt.py+1-1
- dataworld-p006632-cause-1/tests/test.sh+17-10
- dataworld-p006632-consequence-2/environment/DockerfileAdded+64
- dataworld-p006632-consequence-2/tests/grade.py+99-63
- dataworld-p006632-consequence-2/tests/judge.envAdded+4
- dataworld-p006632-consequence-2/tests/judge.py+72-51
- dataworld-p006632-consequence-2/tests/judge_prompt.py+1-1
- dataworld-p006632-consequence-2/tests/test.sh+17-10
- dataworld-p006802-cause-2/environment/DockerfileAdded+64
- dataworld-p006802-cause-2/tests/grade.py+99-63
- dataworld-p006802-cause-2/tests/judge.envAdded+4
- dataworld-p006802-cause-2/tests/judge.py+72-51
- dataworld-p006802-cause-2/tests/judge_prompt.py+1-1
- dataworld-p006802-cause-2/tests/test.sh+17-10
- dataworld-p006802-consequence-2/environment/DockerfileAdded+64
- dataworld-p006802-consequence-2/tests/grade.py+99-63
- dataworld-p006802-consequence-2/tests/judge.envAdded+4
12345678910111213141516171819207 unmodified lines28293031323334353637383940414243444546474849505152538 unmodified lines6263646566676812 unmodified lines81828384858687888990919293949596972 unmodified lines10010110210310410510610710810911011111211311411511611711811912012110 unmodified lines13213313413513613713813914014113 unmodified lines1551561571581591601611621631641651661671681691701711721731749 unmodified lines18418518618718818919019119219319419519619719819920020120220310 unmodified lines21421521621721821922022122222318 unmodified lines2422432442452462472482492502512522532544 unmodified lines2592602612622632642652662672682692703 unmodified lines274275276277278279280"""判分: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``,绝不崩溃。"""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: judge 连续失败的重试上限。MAX_JUDGE_ATTEMPTS = 4#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。REPORT_HEAD, REPORT_TAIL = 150_000, 20_000# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ──────────────────────# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同# 一个真值来源)。两种模式共用下面同一段判分逻辑。try:from .prompts import JUDGE_PROMPTexcept ImportError: # pragma: no cover - 容器内独立运行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 可读的清单。"""return "\n".join(f"- id={c['id']} | section={c['section']} | points={c['points']}\n"f" criterion: {c['criterion']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。"""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)12 unmodified lines"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 只是防御。hi, lo = total_positive, total_negativeif hi > lo:normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0normalized = max(-1.0, min(1.0, normalized))else:normalized = 0.0return {"reward": round(normalized, 4),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# ── verdict 解析容错 ──────────────────────────────────────────────────────────# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值# 不含引号,reason 取到最后一个引号即可正确还原。_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 的这个比例即判失败重试(而非接受一份残缺判分)。_SALVAGE_MIN_RATIO = 2 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""解析单个 verdict 对象;严格解析失败时按字段正则抢救。"""try:obj = json.loads(blob)if isinstance(obj, dict) and "id" in obj and "status" in obj:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。��捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。"""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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}")return verdictsdef 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。``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端,容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。"""prompt = JUDGE_PROMPT.format(rubric_text=render_rubric(rubric),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。if result["missing_verdicts"] and attempt < attempts - 1:raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试last_error = excprint(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {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 入口 ─────────────────────────────────────────────────ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt")RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 +诊断信息,让整批评测不因单题判分失败中断。"""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = -1.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=-1.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True})returnresult = 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')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 — 兜底也不许崩溃write_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 012345678910111213141516171819202122232425262728293031323334357 unmodified lines434445464748495051525354555657585960616263646566676869708 unmodified lines798081828384858612 unmodified lines991001011021031041051061071081091101111121131141151161172 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314410 unmodified lines15515615715815916016116216316416516616713 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032049 unmodified lines21421521621721821922022122222322422522622722822923023123223323410 unmodified lines24524624724824925025125225325425525625725825918 unmodified lines2782792802812822832842852862872882892904 unmodified lines2952962972982993003013023033043053063 unmodified lines310311312313314315316"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts arefolded 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 thisfile into ``tests/`` when exporting) import the very same code -- there is exactlyone definition of the scoring rule, and the two paths are not allowed to driftapart.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 itmatches the wrong conclusion named by a negative criterion;- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positivecriteria and ``lo`` the total of the negative ones (the raw score reached when everynegative criterion is triggered and no positive criterion is satisfied). The rawscore 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'sHTTP call lives in ``judge.py``.Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every pathcan be overridden through environment variables, and the defaults follow harbor'sconventions. Any failure anywhere in the grading pipeline writes reward 0 plus``judge_error``; it never crashes."""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: Maximum number of consecutive judge failures before giving up.MAX_JUDGE_ATTEMPTS = 4#: 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# -- 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_PROMPTexcept ImportError: # pragma: no cover - standalone run inside the containersys.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:"""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']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""Fold verdicts into a reward; a criterion with no verdict is ``missing`` andearns 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)12 unmodified lines"points": criterion["points"], "status": status or "missing","earned": earned, "reason": verdict.get("reason", ""),})# 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_negativeif hi > lo:reward = 100.0 * (raw_score - lo) / (hi - lo)reward = max(0.0, min(100.0, reward))else:reward = 0.0return {"reward": round(reward, 2),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# -- 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)#: 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 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""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:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdictobjects one by one.Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving theretry 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 wouldpollute the statistics."""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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"too few verdicts salvaged: {len(verdicts)}/{n_criteria}")return verdictsdef 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]:"""Grade one report: build the prompt -> call the judge -> parse tolerantly ->fold into a reward.``call_judge(prompt) -> str`` is injected by the caller (the local path uses theclient from ``judge.py``, and the container path does the same), so this modulecontains no network code at all. A result with missing criteria is retried whileattempts remain.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),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 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"missing verdicts: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 -- any judge/parse error is retriedlast_error = excprint(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 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")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never anon-zero exit.Harbor treats a non-zero verifier exit as an infrastructure failure of the task, soeverything is funneled into a 0 score plus diagnostics here, keeping a wholeevaluation batch from being interrupted by one task's grading failure.Consumers must detect this case through the ``judge_error`` key and not through thereward value: under the [0, 100] scale, 0 is also the legitimate floor."""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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 0 (the rubric floor) regardless of the# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = 0.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=0.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge config error: {exc}", extra={"judge_config_error": True})returnresult = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH))if result.get("reward") is None:write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 -- even the catch-all must not crashwrite_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 0
1234# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*)ANTHROPIC_AUTH_TOKEN=<your-judge-token>ANTHROPIC_BASE_URL=http://<judge-gateway>:8413/v1ANTHROPIC_MODEL=<judge-model-path-or-id>123456789101112131415161718192021222324252627284 unmodified lines33343536373839404142434445464748495051525354555657588 unmodified lines6768697071727374757677787980818212 unmodified lines959697989910010110210310410510610710810911018 unmodified lines1291301311321331341351361371381391401411423 unmodified lines1461471481491501511523 unmodified lines1561571581591601611621631641651661671681691701711721731745 unmodified lines180181182183184185186187188"""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。"""from __future__ import annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出;#: 判分本身不贵,宁可给足。MAX_TOKENS = 131_072#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。#:#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时,#: 只有真正卡住(网关挂起、连接半开)才触发。TIMEOUT_SEC = 180.0#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``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 调用失败"区分开:配置错误不该重试,重试只会重复失败。"""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。"""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # 心跳/注释等非 JSON 帧if isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用,完整路径由各 API 形态自己拼。"""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif 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]}")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)有容错打捞。events = _iter_sse(f"{base_url}/v1/chat/completions",{"authorization": f"Bearer {token}"},3 unmodified lineschunks = []for event in events:if event.get("error"):raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}")for choice in event.get("choices") or []:content = (choice.get("delta") or {}).get("content")if content:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是#: OpenAI 兼容的 chat/completions,不是 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 身份,供调用与评测缓存共同使用。"""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))}")return {"api": api_name,"base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")),5 unmodified linesdef 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`。显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。"""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)1234567891011121314151617181920212223242526272829303132333435364 unmodified lines41424344454647484950515253545556575859606162636465666768697071728 unmodified lines81828384858687888990919293949596979812 unmodified lines11111211311411511611711811912012112212312412512612718 unmodified lines1461471481491501511521531541551561571581591603 unmodified lines1641651661671681691703 unmodified lines1741751761771781791801811821831841851861871881891901911921935 unmodified lines199200201202203204205206207208209"""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 machineshare one scoring rule while each uses its own gateway.**Credentials are read from environment variables only; no token is ever stored in thecode.** Locally they are injected by ``data_world.envfile`` from the project-root``.env`` (the same credentials used by data_world/dag_factory); inside the harborcontainer they are injected at build or run time (see ``harbor.py``). This moduletherefore provides no built-in "works with zero environment variables" key -- that wouldamount 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 thein-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 wayand 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 pathwith ``/v1`` -- after normalization both can share one variable without stepping on eachother.**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens ofcriteria), and a non-streaming request only returns its first byte once the wholegeneration is done, so both the gateway and the client tend to time out and kill ajudgment that would have succeeded. Under streaming, a timeout means "a gap between twochunks", 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 annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: 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#: 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#: 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 credentials/configuration are missing. ``grade.py`` catches it and writesreward 0 plus diagnostics.Kept distinct from "the judge call failed": a configuration error must not beretried, since retrying only repeats the failure."""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST a streaming request and yield the JSON events found in SSE ``data:`` lines.``timeout`` is handed to the socket, so it measures a single blocking read (the gapbetween chunks) rather than the total duration. Proxies are explicitly disabled:gateways usually live on an internal network, and an egress proxy would make therequest fail outright."""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # heartbeats/comments and other non-JSON framesif isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only thebare host prefix.Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shapethe caller passes works, and each API shape builds its own full path."""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif delta.get("type") == "text_delta":chunks.append(delta.get("text") or "")elif event.get("type") == "error":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:# 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}"},3 unmodified lineschunks = []for event in events:if event.get("error"):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:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 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]:"""Resolve the credential-free judge identity, shared by the call path and theevaluation cache."""api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower()if api_name not in _APIS:raise JudgeConfigError(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")),5 unmodified linesdef 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]:"""Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` whencredentials are missing.Explicit arguments take precedence over environment variables, which lets a CLIoverride things such as ``--judge-model``."""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)
123"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。"""JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n<report>\n{report}\n</report>\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}}'123"""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<report>\n{report}\n</report>\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}}'
12345678910111213141516171819204 unmodified lines25262728293031323334353637383940#!/bin/bash# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑);# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。set -euo pipefailANSWER_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 两处都能跑。TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"export ANSWER_PATH REWARD_PATH DETAILS_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。if [ -f "$TESTS_DIR/judge.env" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -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 源==目标会报错。if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# judge 网关在内网:清掉公网出口代理,否则请求被拦。unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure),# 这里只做最后兜底。set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?123456789101112131415161718192021222324254 unmodified lines303132333435363738394041424344454647#!/bin/bash# 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 pipefailANSWER_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}"# 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_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# 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" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -p "$(dirname "$ANSWER_PATH")"echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH"fi# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with# source == destination fails.if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# 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 itself writes reward.txt + details.json on any failure (write_failure);# this is only the last-resort fallback.set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# 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 <base-image>: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/simpleARG 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 usersRUN chmod -R a+rX /app/data
# Build-time assertion: no canonical-truth material may be present in the environmentRUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ && test -d /app/data12345678910111213141516171819207 unmodified lines28293031323334353637383940414243444546474849505152538 unmodified lines6263646566676812 unmodified lines81828384858687888990919293949596972 unmodified lines10010110210310410510610710810911011111211311411511611711811912012110 unmodified lines13213313413513613713813914014113 unmodified lines1551561571581591601611621631641651661671681691701711721731749 unmodified lines18418518618718818919019119219319419519619719819920020120220310 unmodified lines21421521621721821922022122222318 unmodified lines2422432442452462472482492502512522532544 unmodified lines2592602612622632642652662672682692703 unmodified lines274275276277278279280"""判分: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``,绝不崩溃。"""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: judge 连续失败的重试上限。MAX_JUDGE_ATTEMPTS = 4#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。REPORT_HEAD, REPORT_TAIL = 150_000, 20_000# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ──────────────────────# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同# 一个真值来源)。两种模式共用下面同一段判分逻辑。try:from .prompts import JUDGE_PROMPTexcept ImportError: # pragma: no cover - 容器内独立运行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 可读的清单。"""return "\n".join(f"- id={c['id']} | section={c['section']} | points={c['points']}\n"f" criterion: {c['criterion']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。"""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)12 unmodified lines"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 只是防御。hi, lo = total_positive, total_negativeif hi > lo:normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0normalized = max(-1.0, min(1.0, normalized))else:normalized = 0.0return {"reward": round(normalized, 4),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# ── verdict 解析容错 ──────────────────────────────────────────────────────────# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值# 不含引号,reason 取到最后一个引号即可正确还原。_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 的这个比例即判失败重试(而非接受一份残缺判分)。_SALVAGE_MIN_RATIO = 2 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""解析单个 verdict 对象;严格解析失败时按字段正则抢救。"""try:obj = json.loads(blob)if isinstance(obj, dict) and "id" in obj and "status" in obj:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。��捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。"""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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}")return verdictsdef 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。``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端,容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。"""prompt = JUDGE_PROMPT.format(rubric_text=render_rubric(rubric),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。if result["missing_verdicts"] and attempt < attempts - 1:raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试last_error = excprint(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {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 入口 ─────────────────────────────────────────────────ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt")RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 +诊断信息,让整批评测不因单题判分失败中断。"""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = -1.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=-1.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True})returnresult = 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')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 — 兜底也不许崩溃write_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 012345678910111213141516171819202122232425262728293031323334357 unmodified lines434445464748495051525354555657585960616263646566676869708 unmodified lines798081828384858612 unmodified lines991001011021031041051061071081091101111121131141151161172 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314410 unmodified lines15515615715815916016116216316416516616713 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032049 unmodified lines21421521621721821922022122222322422522622722822923023123223323410 unmodified lines24524624724824925025125225325425525625725825918 unmodified lines2782792802812822832842852862872882892904 unmodified lines2952962972982993003013023033043053063 unmodified lines310311312313314315316"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts arefolded 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 thisfile into ``tests/`` when exporting) import the very same code -- there is exactlyone definition of the scoring rule, and the two paths are not allowed to driftapart.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 itmatches the wrong conclusion named by a negative criterion;- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positivecriteria and ``lo`` the total of the negative ones (the raw score reached when everynegative criterion is triggered and no positive criterion is satisfied). The rawscore 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'sHTTP call lives in ``judge.py``.Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every pathcan be overridden through environment variables, and the defaults follow harbor'sconventions. Any failure anywhere in the grading pipeline writes reward 0 plus``judge_error``; it never crashes."""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: Maximum number of consecutive judge failures before giving up.MAX_JUDGE_ATTEMPTS = 4#: 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# -- 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_PROMPTexcept ImportError: # pragma: no cover - standalone run inside the containersys.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:"""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']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""Fold verdicts into a reward; a criterion with no verdict is ``missing`` andearns 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)12 unmodified lines"points": criterion["points"], "status": status or "missing","earned": earned, "reason": verdict.get("reason", ""),})# 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_negativeif hi > lo:reward = 100.0 * (raw_score - lo) / (hi - lo)reward = max(0.0, min(100.0, reward))else:reward = 0.0return {"reward": round(reward, 2),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# -- 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)#: 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 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""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:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdictobjects one by one.Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving theretry 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 wouldpollute the statistics."""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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"too few verdicts salvaged: {len(verdicts)}/{n_criteria}")return verdictsdef 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]:"""Grade one report: build the prompt -> call the judge -> parse tolerantly ->fold into a reward.``call_judge(prompt) -> str`` is injected by the caller (the local path uses theclient from ``judge.py``, and the container path does the same), so this modulecontains no network code at all. A result with missing criteria is retried whileattempts remain.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),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 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"missing verdicts: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 -- any judge/parse error is retriedlast_error = excprint(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 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")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never anon-zero exit.Harbor treats a non-zero verifier exit as an infrastructure failure of the task, soeverything is funneled into a 0 score plus diagnostics here, keeping a wholeevaluation batch from being interrupted by one task's grading failure.Consumers must detect this case through the ``judge_error`` key and not through thereward value: under the [0, 100] scale, 0 is also the legitimate floor."""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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 0 (the rubric floor) regardless of the# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = 0.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=0.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge config error: {exc}", extra={"judge_config_error": True})returnresult = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH))if result.get("reward") is None:write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 -- even the catch-all must not crashwrite_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 0
1234# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*)ANTHROPIC_AUTH_TOKEN=<your-judge-token>ANTHROPIC_BASE_URL=http://<judge-gateway>:8413/v1ANTHROPIC_MODEL=<judge-model-path-or-id>123456789101112131415161718192021222324252627284 unmodified lines33343536373839404142434445464748495051525354555657588 unmodified lines6768697071727374757677787980818212 unmodified lines959697989910010110210310410510610710810911018 unmodified lines1291301311321331341351361371381391401411423 unmodified lines1461471481491501511523 unmodified lines1561571581591601611621631641651661671681691701711721731745 unmodified lines180181182183184185186187188"""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。"""from __future__ import annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出;#: 判分本身不贵,宁可给足。MAX_TOKENS = 131_072#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。#:#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时,#: 只有真正卡住(网关挂起、连接半开)才触发。TIMEOUT_SEC = 180.0#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``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 调用失败"区分开:配置错误不该重试,重试只会重复失败。"""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。"""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # 心跳/注释等非 JSON 帧if isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用,完整路径由各 API 形态自己拼。"""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif 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]}")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)有容错打捞。events = _iter_sse(f"{base_url}/v1/chat/completions",{"authorization": f"Bearer {token}"},3 unmodified lineschunks = []for event in events:if event.get("error"):raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}")for choice in event.get("choices") or []:content = (choice.get("delta") or {}).get("content")if content:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是#: OpenAI 兼容的 chat/completions,不是 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 身份,供调用与评测缓存共同使用。"""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))}")return {"api": api_name,"base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")),5 unmodified linesdef 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`。显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。"""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)1234567891011121314151617181920212223242526272829303132333435364 unmodified lines41424344454647484950515253545556575859606162636465666768697071728 unmodified lines81828384858687888990919293949596979812 unmodified lines11111211311411511611711811912012112212312412512612718 unmodified lines1461471481491501511521531541551561571581591603 unmodified lines1641651661671681691703 unmodified lines1741751761771781791801811821831841851861871881891901911921935 unmodified lines199200201202203204205206207208209"""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 machineshare one scoring rule while each uses its own gateway.**Credentials are read from environment variables only; no token is ever stored in thecode.** Locally they are injected by ``data_world.envfile`` from the project-root``.env`` (the same credentials used by data_world/dag_factory); inside the harborcontainer they are injected at build or run time (see ``harbor.py``). This moduletherefore provides no built-in "works with zero environment variables" key -- that wouldamount 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 thein-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 wayand 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 pathwith ``/v1`` -- after normalization both can share one variable without stepping on eachother.**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens ofcriteria), and a non-streaming request only returns its first byte once the wholegeneration is done, so both the gateway and the client tend to time out and kill ajudgment that would have succeeded. Under streaming, a timeout means "a gap between twochunks", 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 annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: 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#: 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#: 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 credentials/configuration are missing. ``grade.py`` catches it and writesreward 0 plus diagnostics.Kept distinct from "the judge call failed": a configuration error must not beretried, since retrying only repeats the failure."""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST a streaming request and yield the JSON events found in SSE ``data:`` lines.``timeout`` is handed to the socket, so it measures a single blocking read (the gapbetween chunks) rather than the total duration. Proxies are explicitly disabled:gateways usually live on an internal network, and an egress proxy would make therequest fail outright."""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # heartbeats/comments and other non-JSON framesif isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only thebare host prefix.Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shapethe caller passes works, and each API shape builds its own full path."""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif delta.get("type") == "text_delta":chunks.append(delta.get("text") or "")elif event.get("type") == "error":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:# 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}"},3 unmodified lineschunks = []for event in events:if event.get("error"):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:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 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]:"""Resolve the credential-free judge identity, shared by the call path and theevaluation cache."""api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower()if api_name not in _APIS:raise JudgeConfigError(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")),5 unmodified linesdef 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]:"""Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` whencredentials are missing.Explicit arguments take precedence over environment variables, which lets a CLIoverride things such as ``--judge-model``."""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)
123"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。"""JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n<report>\n{report}\n</report>\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}}'123"""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<report>\n{report}\n</report>\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}}'
12345678910111213141516171819204 unmodified lines25262728293031323334353637383940#!/bin/bash# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑);# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。set -euo pipefailANSWER_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 两处都能跑。TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"export ANSWER_PATH REWARD_PATH DETAILS_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。if [ -f "$TESTS_DIR/judge.env" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -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 源==目标会报错。if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# judge 网关在内网:清掉公网出口代理,否则请求被拦。unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure),# 这里只做最后兜底。set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?123456789101112131415161718192021222324254 unmodified lines303132333435363738394041424344454647#!/bin/bash# 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 pipefailANSWER_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}"# 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_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# 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" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -p "$(dirname "$ANSWER_PATH")"echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH"fi# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with# source == destination fails.if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# 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 itself writes reward.txt + details.json on any failure (write_failure);# this is only the last-resort fallback.set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# 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 <base-image>: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/simpleARG 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 usersRUN chmod -R a+rX /app/data
# Build-time assertion: no canonical-truth material may be present in the environmentRUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ && test -d /app/data12345678910111213141516171819207 unmodified lines28293031323334353637383940414243444546474849505152538 unmodified lines6263646566676812 unmodified lines81828384858687888990919293949596972 unmodified lines10010110210310410510610710810911011111211311411511611711811912012110 unmodified lines13213313413513613713813914014113 unmodified lines1551561571581591601611621631641651661671681691701711721731749 unmodified lines18418518618718818919019119219319419519619719819920020120220310 unmodified lines21421521621721821922022122222318 unmodified lines2422432442452462472482492502512522532544 unmodified lines2592602612622632642652662672682692703 unmodified lines274275276277278279280"""判分: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``,绝不崩溃。"""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: judge 连续失败的重试上限。MAX_JUDGE_ATTEMPTS = 4#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。REPORT_HEAD, REPORT_TAIL = 150_000, 20_000# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ──────────────────────# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同# 一个真值来源)。两种模式共用下面同一段判分逻辑。try:from .prompts import JUDGE_PROMPTexcept ImportError: # pragma: no cover - 容器内独立运行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 可读的清单。"""return "\n".join(f"- id={c['id']} | section={c['section']} | points={c['points']}\n"f" criterion: {c['criterion']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。"""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)12 unmodified lines"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 只是防御。hi, lo = total_positive, total_negativeif hi > lo:normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0normalized = max(-1.0, min(1.0, normalized))else:normalized = 0.0return {"reward": round(normalized, 4),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# ── verdict 解析容错 ──────────────────────────────────────────────────────────# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值# 不含引号,reason 取到最后一个引号即可正确还原。_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 的这个比例即判失败重试(而非接受一份残缺判分)。_SALVAGE_MIN_RATIO = 2 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""解析单个 verdict 对象;严格解析失败时按字段正则抢救。"""try:obj = json.loads(blob)if isinstance(obj, dict) and "id" in obj and "status" in obj:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。��捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。"""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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}")return verdictsdef 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。``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端,容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。"""prompt = JUDGE_PROMPT.format(rubric_text=render_rubric(rubric),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。if result["missing_verdicts"] and attempt < attempts - 1:raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试last_error = excprint(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {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 入口 ─────────────────────────────────────────────────ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt")RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 +诊断信息,让整批评测不因单题判分失败中断。"""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = -1.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=-1.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True})returnresult = 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')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 — 兜底也不许崩溃write_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 012345678910111213141516171819202122232425262728293031323334357 unmodified lines434445464748495051525354555657585960616263646566676869708 unmodified lines798081828384858612 unmodified lines991001011021031041051061071081091101111121131141151161172 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314410 unmodified lines15515615715815916016116216316416516616713 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032049 unmodified lines21421521621721821922022122222322422522622722822923023123223323410 unmodified lines24524624724824925025125225325425525625725825918 unmodified lines2782792802812822832842852862872882892904 unmodified lines2952962972982993003013023033043053063 unmodified lines310311312313314315316"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts arefolded 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 thisfile into ``tests/`` when exporting) import the very same code -- there is exactlyone definition of the scoring rule, and the two paths are not allowed to driftapart.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 itmatches the wrong conclusion named by a negative criterion;- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positivecriteria and ``lo`` the total of the negative ones (the raw score reached when everynegative criterion is triggered and no positive criterion is satisfied). The rawscore 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'sHTTP call lives in ``judge.py``.Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every pathcan be overridden through environment variables, and the defaults follow harbor'sconventions. Any failure anywhere in the grading pipeline writes reward 0 plus``judge_error``; it never crashes."""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: Maximum number of consecutive judge failures before giving up.MAX_JUDGE_ATTEMPTS = 4#: 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# -- 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_PROMPTexcept ImportError: # pragma: no cover - standalone run inside the containersys.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:"""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']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""Fold verdicts into a reward; a criterion with no verdict is ``missing`` andearns 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)12 unmodified lines"points": criterion["points"], "status": status or "missing","earned": earned, "reason": verdict.get("reason", ""),})# 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_negativeif hi > lo:reward = 100.0 * (raw_score - lo) / (hi - lo)reward = max(0.0, min(100.0, reward))else:reward = 0.0return {"reward": round(reward, 2),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# -- 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)#: 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 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""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:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdictobjects one by one.Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving theretry 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 wouldpollute the statistics."""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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"too few verdicts salvaged: {len(verdicts)}/{n_criteria}")return verdictsdef 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]:"""Grade one report: build the prompt -> call the judge -> parse tolerantly ->fold into a reward.``call_judge(prompt) -> str`` is injected by the caller (the local path uses theclient from ``judge.py``, and the container path does the same), so this modulecontains no network code at all. A result with missing criteria is retried whileattempts remain.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),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 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"missing verdicts: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 -- any judge/parse error is retriedlast_error = excprint(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 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")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never anon-zero exit.Harbor treats a non-zero verifier exit as an infrastructure failure of the task, soeverything is funneled into a 0 score plus diagnostics here, keeping a wholeevaluation batch from being interrupted by one task's grading failure.Consumers must detect this case through the ``judge_error`` key and not through thereward value: under the [0, 100] scale, 0 is also the legitimate floor."""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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 0 (the rubric floor) regardless of the# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = 0.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=0.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge config error: {exc}", extra={"judge_config_error": True})returnresult = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH))if result.get("reward") is None:write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 -- even the catch-all must not crashwrite_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 0
1234# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*)ANTHROPIC_AUTH_TOKEN=<your-judge-token>ANTHROPIC_BASE_URL=http://<judge-gateway>:8413/v1ANTHROPIC_MODEL=<judge-model-path-or-id>123456789101112131415161718192021222324252627284 unmodified lines33343536373839404142434445464748495051525354555657588 unmodified lines6768697071727374757677787980818212 unmodified lines959697989910010110210310410510610710810911018 unmodified lines1291301311321331341351361371381391401411423 unmodified lines1461471481491501511523 unmodified lines1561571581591601611621631641651661671681691701711721731745 unmodified lines180181182183184185186187188"""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。"""from __future__ import annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出;#: 判分本身不贵,宁可给足。MAX_TOKENS = 131_072#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。#:#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时,#: 只有真正卡住(网关挂起、连接半开)才触发。TIMEOUT_SEC = 180.0#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``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 调用失败"区分开:配置错误不该重试,重试只会重复失败。"""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。"""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # 心跳/注释等非 JSON 帧if isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用,完整路径由各 API 形态自己拼。"""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif 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]}")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)有容错打捞。events = _iter_sse(f"{base_url}/v1/chat/completions",{"authorization": f"Bearer {token}"},3 unmodified lineschunks = []for event in events:if event.get("error"):raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}")for choice in event.get("choices") or []:content = (choice.get("delta") or {}).get("content")if content:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是#: OpenAI 兼容的 chat/completions,不是 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 身份,供调用与评测缓存共同使用。"""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))}")return {"api": api_name,"base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")),5 unmodified linesdef 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`。显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。"""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)1234567891011121314151617181920212223242526272829303132333435364 unmodified lines41424344454647484950515253545556575859606162636465666768697071728 unmodified lines81828384858687888990919293949596979812 unmodified lines11111211311411511611711811912012112212312412512612718 unmodified lines1461471481491501511521531541551561571581591603 unmodified lines1641651661671681691703 unmodified lines1741751761771781791801811821831841851861871881891901911921935 unmodified lines199200201202203204205206207208209"""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 machineshare one scoring rule while each uses its own gateway.**Credentials are read from environment variables only; no token is ever stored in thecode.** Locally they are injected by ``data_world.envfile`` from the project-root``.env`` (the same credentials used by data_world/dag_factory); inside the harborcontainer they are injected at build or run time (see ``harbor.py``). This moduletherefore provides no built-in "works with zero environment variables" key -- that wouldamount 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 thein-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 wayand 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 pathwith ``/v1`` -- after normalization both can share one variable without stepping on eachother.**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens ofcriteria), and a non-streaming request only returns its first byte once the wholegeneration is done, so both the gateway and the client tend to time out and kill ajudgment that would have succeeded. Under streaming, a timeout means "a gap between twochunks", 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 annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: 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#: 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#: 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 credentials/configuration are missing. ``grade.py`` catches it and writesreward 0 plus diagnostics.Kept distinct from "the judge call failed": a configuration error must not beretried, since retrying only repeats the failure."""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST a streaming request and yield the JSON events found in SSE ``data:`` lines.``timeout`` is handed to the socket, so it measures a single blocking read (the gapbetween chunks) rather than the total duration. Proxies are explicitly disabled:gateways usually live on an internal network, and an egress proxy would make therequest fail outright."""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # heartbeats/comments and other non-JSON framesif isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only thebare host prefix.Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shapethe caller passes works, and each API shape builds its own full path."""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif delta.get("type") == "text_delta":chunks.append(delta.get("text") or "")elif event.get("type") == "error":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:# 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}"},3 unmodified lineschunks = []for event in events:if event.get("error"):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:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 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]:"""Resolve the credential-free judge identity, shared by the call path and theevaluation cache."""api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower()if api_name not in _APIS:raise JudgeConfigError(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")),5 unmodified linesdef 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]:"""Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` whencredentials are missing.Explicit arguments take precedence over environment variables, which lets a CLIoverride things such as ``--judge-model``."""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)
123"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。"""JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n<report>\n{report}\n</report>\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}}'123"""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<report>\n{report}\n</report>\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}}'
12345678910111213141516171819204 unmodified lines25262728293031323334353637383940#!/bin/bash# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑);# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。set -euo pipefailANSWER_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 两处都能跑。TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"export ANSWER_PATH REWARD_PATH DETAILS_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。if [ -f "$TESTS_DIR/judge.env" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -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 源==目标会报错。if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# judge 网关在内网:清掉公网出口代理,否则请求被拦。unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure),# 这里只做最后兜底。set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?123456789101112131415161718192021222324254 unmodified lines303132333435363738394041424344454647#!/bin/bash# 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 pipefailANSWER_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}"# 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_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# 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" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -p "$(dirname "$ANSWER_PATH")"echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH"fi# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with# source == destination fails.if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# 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 itself writes reward.txt + details.json on any failure (write_failure);# this is only the last-resort fallback.set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# 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 <base-image>: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/simpleARG 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 usersRUN chmod -R a+rX /app/data
# Build-time assertion: no canonical-truth material may be present in the environmentRUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ && test -d /app/data12345678910111213141516171819207 unmodified lines28293031323334353637383940414243444546474849505152538 unmodified lines6263646566676812 unmodified lines81828384858687888990919293949596972 unmodified lines10010110210310410510610710810911011111211311411511611711811912012110 unmodified lines13213313413513613713813914014113 unmodified lines1551561571581591601611621631641651661671681691701711721731749 unmodified lines18418518618718818919019119219319419519619719819920020120220310 unmodified lines21421521621721821922022122222318 unmodified lines2422432442452462472482492502512522532544 unmodified lines2592602612622632642652662672682692703 unmodified lines274275276277278279280"""判分: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``,绝不崩溃。"""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: judge 连续失败的重试上限。MAX_JUDGE_ATTEMPTS = 4#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。REPORT_HEAD, REPORT_TAIL = 150_000, 20_000# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ──────────────────────# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同# 一个真值来源)。两种模式共用下面同一段判分逻辑。try:from .prompts import JUDGE_PROMPTexcept ImportError: # pragma: no cover - 容器内独立运行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 可读的清单。"""return "\n".join(f"- id={c['id']} | section={c['section']} | points={c['points']}\n"f" criterion: {c['criterion']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。"""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)12 unmodified lines"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 只是防御。hi, lo = total_positive, total_negativeif hi > lo:normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0normalized = max(-1.0, min(1.0, normalized))else:normalized = 0.0return {"reward": round(normalized, 4),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# ── verdict 解析容错 ──────────────────────────────────────────────────────────# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值# 不含引号,reason 取到最后一个引号即可正确还原。_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 的这个比例即判失败重试(而非接受一份残缺判分)。_SALVAGE_MIN_RATIO = 2 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""解析单个 verdict 对象;严格解析失败时按字段正则抢救。"""try:obj = json.loads(blob)if isinstance(obj, dict) and "id" in obj and "status" in obj:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。��捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。"""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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}")return verdictsdef 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。``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端,容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。"""prompt = JUDGE_PROMPT.format(rubric_text=render_rubric(rubric),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。if result["missing_verdicts"] and attempt < attempts - 1:raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试last_error = excprint(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {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 入口 ─────────────────────────────────────────────────ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt")RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 +诊断信息,让整批评测不因单题判分失败中断。"""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = -1.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=-1.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True})returnresult = 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')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 — 兜底也不许崩溃write_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 012345678910111213141516171819202122232425262728293031323334357 unmodified lines434445464748495051525354555657585960616263646566676869708 unmodified lines798081828384858612 unmodified lines991001011021031041051061071081091101111121131141151161172 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314410 unmodified lines15515615715815916016116216316416516616713 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032049 unmodified lines21421521621721821922022122222322422522622722822923023123223323410 unmodified lines24524624724824925025125225325425525625725825918 unmodified lines2782792802812822832842852862872882892904 unmodified lines2952962972982993003013023033043053063 unmodified lines310311312313314315316"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts arefolded 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 thisfile into ``tests/`` when exporting) import the very same code -- there is exactlyone definition of the scoring rule, and the two paths are not allowed to driftapart.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 itmatches the wrong conclusion named by a negative criterion;- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positivecriteria and ``lo`` the total of the negative ones (the raw score reached when everynegative criterion is triggered and no positive criterion is satisfied). The rawscore 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'sHTTP call lives in ``judge.py``.Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every pathcan be overridden through environment variables, and the defaults follow harbor'sconventions. Any failure anywhere in the grading pipeline writes reward 0 plus``judge_error``; it never crashes."""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: Maximum number of consecutive judge failures before giving up.MAX_JUDGE_ATTEMPTS = 4#: 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# -- 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_PROMPTexcept ImportError: # pragma: no cover - standalone run inside the containersys.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:"""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']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""Fold verdicts into a reward; a criterion with no verdict is ``missing`` andearns 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)12 unmodified lines"points": criterion["points"], "status": status or "missing","earned": earned, "reason": verdict.get("reason", ""),})# 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_negativeif hi > lo:reward = 100.0 * (raw_score - lo) / (hi - lo)reward = max(0.0, min(100.0, reward))else:reward = 0.0return {"reward": round(reward, 2),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# -- 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)#: 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 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""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:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdictobjects one by one.Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving theretry 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 wouldpollute the statistics."""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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"too few verdicts salvaged: {len(verdicts)}/{n_criteria}")return verdictsdef 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]:"""Grade one report: build the prompt -> call the judge -> parse tolerantly ->fold into a reward.``call_judge(prompt) -> str`` is injected by the caller (the local path uses theclient from ``judge.py``, and the container path does the same), so this modulecontains no network code at all. A result with missing criteria is retried whileattempts remain.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),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 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"missing verdicts: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 -- any judge/parse error is retriedlast_error = excprint(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 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")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never anon-zero exit.Harbor treats a non-zero verifier exit as an infrastructure failure of the task, soeverything is funneled into a 0 score plus diagnostics here, keeping a wholeevaluation batch from being interrupted by one task's grading failure.Consumers must detect this case through the ``judge_error`` key and not through thereward value: under the [0, 100] scale, 0 is also the legitimate floor."""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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 0 (the rubric floor) regardless of the# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = 0.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=0.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge config error: {exc}", extra={"judge_config_error": True})returnresult = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH))if result.get("reward") is None:write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 -- even the catch-all must not crashwrite_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 0
1234# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*)ANTHROPIC_AUTH_TOKEN=<your-judge-token>ANTHROPIC_BASE_URL=http://<judge-gateway>:8413/v1ANTHROPIC_MODEL=<judge-model-path-or-id>123456789101112131415161718192021222324252627284 unmodified lines33343536373839404142434445464748495051525354555657588 unmodified lines6768697071727374757677787980818212 unmodified lines959697989910010110210310410510610710810911018 unmodified lines1291301311321331341351361371381391401411423 unmodified lines1461471481491501511523 unmodified lines1561571581591601611621631641651661671681691701711721731745 unmodified lines180181182183184185186187188"""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。"""from __future__ import annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出;#: 判分本身不贵,宁可给足。MAX_TOKENS = 131_072#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。#:#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时,#: 只有真正卡住(网关挂起、连接半开)才触发。TIMEOUT_SEC = 180.0#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``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 调用失败"区分开:配置错误不该重试,重试只会重复失败。"""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。"""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # 心跳/注释等非 JSON 帧if isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用,完整路径由各 API 形态自己拼。"""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif 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]}")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)有容错打捞。events = _iter_sse(f"{base_url}/v1/chat/completions",{"authorization": f"Bearer {token}"},3 unmodified lineschunks = []for event in events:if event.get("error"):raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}")for choice in event.get("choices") or []:content = (choice.get("delta") or {}).get("content")if content:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是#: OpenAI 兼容的 chat/completions,不是 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 身份,供调用与评测缓存共同使用。"""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))}")return {"api": api_name,"base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")),5 unmodified linesdef 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`。显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。"""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)1234567891011121314151617181920212223242526272829303132333435364 unmodified lines41424344454647484950515253545556575859606162636465666768697071728 unmodified lines81828384858687888990919293949596979812 unmodified lines11111211311411511611711811912012112212312412512612718 unmodified lines1461471481491501511521531541551561571581591603 unmodified lines1641651661671681691703 unmodified lines1741751761771781791801811821831841851861871881891901911921935 unmodified lines199200201202203204205206207208209"""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 machineshare one scoring rule while each uses its own gateway.**Credentials are read from environment variables only; no token is ever stored in thecode.** Locally they are injected by ``data_world.envfile`` from the project-root``.env`` (the same credentials used by data_world/dag_factory); inside the harborcontainer they are injected at build or run time (see ``harbor.py``). This moduletherefore provides no built-in "works with zero environment variables" key -- that wouldamount 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 thein-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 wayand 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 pathwith ``/v1`` -- after normalization both can share one variable without stepping on eachother.**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens ofcriteria), and a non-streaming request only returns its first byte once the wholegeneration is done, so both the gateway and the client tend to time out and kill ajudgment that would have succeeded. Under streaming, a timeout means "a gap between twochunks", 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 annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: 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#: 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#: 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 credentials/configuration are missing. ``grade.py`` catches it and writesreward 0 plus diagnostics.Kept distinct from "the judge call failed": a configuration error must not beretried, since retrying only repeats the failure."""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST a streaming request and yield the JSON events found in SSE ``data:`` lines.``timeout`` is handed to the socket, so it measures a single blocking read (the gapbetween chunks) rather than the total duration. Proxies are explicitly disabled:gateways usually live on an internal network, and an egress proxy would make therequest fail outright."""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # heartbeats/comments and other non-JSON framesif isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only thebare host prefix.Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shapethe caller passes works, and each API shape builds its own full path."""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif delta.get("type") == "text_delta":chunks.append(delta.get("text") or "")elif event.get("type") == "error":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:# 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}"},3 unmodified lineschunks = []for event in events:if event.get("error"):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:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 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]:"""Resolve the credential-free judge identity, shared by the call path and theevaluation cache."""api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower()if api_name not in _APIS:raise JudgeConfigError(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")),5 unmodified linesdef 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]:"""Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` whencredentials are missing.Explicit arguments take precedence over environment variables, which lets a CLIoverride things such as ``--judge-model``."""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)
123"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。"""JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n<report>\n{report}\n</report>\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}}'123"""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<report>\n{report}\n</report>\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}}'
12345678910111213141516171819204 unmodified lines25262728293031323334353637383940#!/bin/bash# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑);# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。set -euo pipefailANSWER_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 两处都能跑。TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"export ANSWER_PATH REWARD_PATH DETAILS_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。if [ -f "$TESTS_DIR/judge.env" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -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 源==目标会报错。if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# judge 网关在内网:清掉公网出口代理,否则请求被拦。unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure),# 这里只做最后兜底。set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?123456789101112131415161718192021222324254 unmodified lines303132333435363738394041424344454647#!/bin/bash# 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 pipefailANSWER_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}"# 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_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# 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" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -p "$(dirname "$ANSWER_PATH")"echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH"fi# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with# source == destination fails.if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# 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 itself writes reward.txt + details.json on any failure (write_failure);# this is only the last-resort fallback.set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# 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 <base-image>: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/simpleARG 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 usersRUN chmod -R a+rX /app/data
# Build-time assertion: no canonical-truth material may be present in the environmentRUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ && test -d /app/data12345678910111213141516171819207 unmodified lines28293031323334353637383940414243444546474849505152538 unmodified lines6263646566676812 unmodified lines81828384858687888990919293949596972 unmodified lines10010110210310410510610710810911011111211311411511611711811912012110 unmodified lines13213313413513613713813914014113 unmodified lines1551561571581591601611621631641651661671681691701711721731749 unmodified lines18418518618718818919019119219319419519619719819920020120220310 unmodified lines21421521621721821922022122222318 unmodified lines2422432442452462472482492502512522532544 unmodified lines2592602612622632642652662672682692703 unmodified lines274275276277278279280"""判分: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``,绝不崩溃。"""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: judge 连续失败的重试上限。MAX_JUDGE_ATTEMPTS = 4#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。REPORT_HEAD, REPORT_TAIL = 150_000, 20_000# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ──────────────────────# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同# 一个真值来源)。两种模式共用下面同一段判分逻辑。try:from .prompts import JUDGE_PROMPTexcept ImportError: # pragma: no cover - 容器内独立运行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 可读的清单。"""return "\n".join(f"- id={c['id']} | section={c['section']} | points={c['points']}\n"f" criterion: {c['criterion']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。"""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)12 unmodified lines"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 只是防御。hi, lo = total_positive, total_negativeif hi > lo:normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0normalized = max(-1.0, min(1.0, normalized))else:normalized = 0.0return {"reward": round(normalized, 4),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# ── verdict 解析容错 ──────────────────────────────────────────────────────────# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值# 不含引号,reason 取到最后一个引号即可正确还原。_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 的这个比例即判失败重试(而非接受一份残缺判分)。_SALVAGE_MIN_RATIO = 2 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""解析单个 verdict 对象;严格解析失败时按字段正则抢救。"""try:obj = json.loads(blob)if isinstance(obj, dict) and "id" in obj and "status" in obj:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。��捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。"""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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}")return verdictsdef 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。``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端,容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。"""prompt = JUDGE_PROMPT.format(rubric_text=render_rubric(rubric),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。if result["missing_verdicts"] and attempt < attempts - 1:raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试last_error = excprint(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {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 入口 ─────────────────────────────────────────────────ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt")RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 +诊断信息,让整批评测不因单题判分失败中断。"""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = -1.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=-1.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True})returnresult = 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')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 — 兜底也不许崩溃write_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 012345678910111213141516171819202122232425262728293031323334357 unmodified lines434445464748495051525354555657585960616263646566676869708 unmodified lines798081828384858612 unmodified lines991001011021031041051061071081091101111121131141151161172 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314410 unmodified lines15515615715815916016116216316416516616713 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032049 unmodified lines21421521621721821922022122222322422522622722822923023123223323410 unmodified lines24524624724824925025125225325425525625725825918 unmodified lines2782792802812822832842852862872882892904 unmodified lines2952962972982993003013023033043053063 unmodified lines310311312313314315316"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts arefolded 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 thisfile into ``tests/`` when exporting) import the very same code -- there is exactlyone definition of the scoring rule, and the two paths are not allowed to driftapart.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 itmatches the wrong conclusion named by a negative criterion;- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positivecriteria and ``lo`` the total of the negative ones (the raw score reached when everynegative criterion is triggered and no positive criterion is satisfied). The rawscore 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'sHTTP call lives in ``judge.py``.Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every pathcan be overridden through environment variables, and the defaults follow harbor'sconventions. Any failure anywhere in the grading pipeline writes reward 0 plus``judge_error``; it never crashes."""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: Maximum number of consecutive judge failures before giving up.MAX_JUDGE_ATTEMPTS = 4#: 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# -- 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_PROMPTexcept ImportError: # pragma: no cover - standalone run inside the containersys.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:"""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']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""Fold verdicts into a reward; a criterion with no verdict is ``missing`` andearns 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)12 unmodified lines"points": criterion["points"], "status": status or "missing","earned": earned, "reason": verdict.get("reason", ""),})# 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_negativeif hi > lo:reward = 100.0 * (raw_score - lo) / (hi - lo)reward = max(0.0, min(100.0, reward))else:reward = 0.0return {"reward": round(reward, 2),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# -- 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)#: 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 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""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:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdictobjects one by one.Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving theretry 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 wouldpollute the statistics."""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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"too few verdicts salvaged: {len(verdicts)}/{n_criteria}")return verdictsdef 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]:"""Grade one report: build the prompt -> call the judge -> parse tolerantly ->fold into a reward.``call_judge(prompt) -> str`` is injected by the caller (the local path uses theclient from ``judge.py``, and the container path does the same), so this modulecontains no network code at all. A result with missing criteria is retried whileattempts remain.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),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 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"missing verdicts: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 -- any judge/parse error is retriedlast_error = excprint(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 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")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never anon-zero exit.Harbor treats a non-zero verifier exit as an infrastructure failure of the task, soeverything is funneled into a 0 score plus diagnostics here, keeping a wholeevaluation batch from being interrupted by one task's grading failure.Consumers must detect this case through the ``judge_error`` key and not through thereward value: under the [0, 100] scale, 0 is also the legitimate floor."""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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 0 (the rubric floor) regardless of the# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = 0.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=0.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge config error: {exc}", extra={"judge_config_error": True})returnresult = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH))if result.get("reward") is None:write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 -- even the catch-all must not crashwrite_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 0
1234# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*)ANTHROPIC_AUTH_TOKEN=<your-judge-token>ANTHROPIC_BASE_URL=http://<judge-gateway>:8413/v1ANTHROPIC_MODEL=<judge-model-path-or-id>123456789101112131415161718192021222324252627284 unmodified lines33343536373839404142434445464748495051525354555657588 unmodified lines6768697071727374757677787980818212 unmodified lines959697989910010110210310410510610710810911018 unmodified lines1291301311321331341351361371381391401411423 unmodified lines1461471481491501511523 unmodified lines1561571581591601611621631641651661671681691701711721731745 unmodified lines180181182183184185186187188"""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。"""from __future__ import annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出;#: 判分本身不贵,宁可给足。MAX_TOKENS = 131_072#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。#:#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时,#: 只有真正卡住(网关挂起、连接半开)才触发。TIMEOUT_SEC = 180.0#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``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 调用失败"区分开:配置错误不该重试,重试只会重复失败。"""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。"""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # 心跳/注释等非 JSON 帧if isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用,完整路径由各 API 形态自己拼。"""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif 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]}")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)有容错打捞。events = _iter_sse(f"{base_url}/v1/chat/completions",{"authorization": f"Bearer {token}"},3 unmodified lineschunks = []for event in events:if event.get("error"):raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}")for choice in event.get("choices") or []:content = (choice.get("delta") or {}).get("content")if content:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是#: OpenAI 兼容的 chat/completions,不是 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 身份,供调用与评测缓存共同使用。"""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))}")return {"api": api_name,"base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")),5 unmodified linesdef 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`。显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。"""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)1234567891011121314151617181920212223242526272829303132333435364 unmodified lines41424344454647484950515253545556575859606162636465666768697071728 unmodified lines81828384858687888990919293949596979812 unmodified lines11111211311411511611711811912012112212312412512612718 unmodified lines1461471481491501511521531541551561571581591603 unmodified lines1641651661671681691703 unmodified lines1741751761771781791801811821831841851861871881891901911921935 unmodified lines199200201202203204205206207208209"""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 machineshare one scoring rule while each uses its own gateway.**Credentials are read from environment variables only; no token is ever stored in thecode.** Locally they are injected by ``data_world.envfile`` from the project-root``.env`` (the same credentials used by data_world/dag_factory); inside the harborcontainer they are injected at build or run time (see ``harbor.py``). This moduletherefore provides no built-in "works with zero environment variables" key -- that wouldamount 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 thein-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 wayand 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 pathwith ``/v1`` -- after normalization both can share one variable without stepping on eachother.**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens ofcriteria), and a non-streaming request only returns its first byte once the wholegeneration is done, so both the gateway and the client tend to time out and kill ajudgment that would have succeeded. Under streaming, a timeout means "a gap between twochunks", 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 annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: 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#: 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#: 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 credentials/configuration are missing. ``grade.py`` catches it and writesreward 0 plus diagnostics.Kept distinct from "the judge call failed": a configuration error must not beretried, since retrying only repeats the failure."""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST a streaming request and yield the JSON events found in SSE ``data:`` lines.``timeout`` is handed to the socket, so it measures a single blocking read (the gapbetween chunks) rather than the total duration. Proxies are explicitly disabled:gateways usually live on an internal network, and an egress proxy would make therequest fail outright."""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # heartbeats/comments and other non-JSON framesif isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only thebare host prefix.Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shapethe caller passes works, and each API shape builds its own full path."""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif delta.get("type") == "text_delta":chunks.append(delta.get("text") or "")elif event.get("type") == "error":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:# 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}"},3 unmodified lineschunks = []for event in events:if event.get("error"):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:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 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]:"""Resolve the credential-free judge identity, shared by the call path and theevaluation cache."""api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower()if api_name not in _APIS:raise JudgeConfigError(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")),5 unmodified linesdef 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]:"""Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` whencredentials are missing.Explicit arguments take precedence over environment variables, which lets a CLIoverride things such as ``--judge-model``."""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)
123"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。"""JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n<report>\n{report}\n</report>\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}}'123"""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<report>\n{report}\n</report>\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}}'
12345678910111213141516171819204 unmodified lines25262728293031323334353637383940#!/bin/bash# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑);# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。set -euo pipefailANSWER_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 两处都能跑。TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"export ANSWER_PATH REWARD_PATH DETAILS_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。if [ -f "$TESTS_DIR/judge.env" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -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 源==目标会报错。if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# judge 网关在内网:清掉公网出口代理,否则请求被拦。unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure),# 这里只做最后兜底。set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?123456789101112131415161718192021222324254 unmodified lines303132333435363738394041424344454647#!/bin/bash# 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 pipefailANSWER_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}"# 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_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# 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" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -p "$(dirname "$ANSWER_PATH")"echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH"fi# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with# source == destination fails.if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# 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 itself writes reward.txt + details.json on any failure (write_failure);# this is only the last-resort fallback.set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# 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 <base-image>: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/simpleARG 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 usersRUN chmod -R a+rX /app/data
# Build-time assertion: no canonical-truth material may be present in the environmentRUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ && test -d /app/data12345678910111213141516171819207 unmodified lines28293031323334353637383940414243444546474849505152538 unmodified lines6263646566676812 unmodified lines81828384858687888990919293949596972 unmodified lines10010110210310410510610710810911011111211311411511611711811912012110 unmodified lines13213313413513613713813914014113 unmodified lines1551561571581591601611621631641651661671681691701711721731749 unmodified lines18418518618718818919019119219319419519619719819920020120220310 unmodified lines21421521621721821922022122222318 unmodified lines2422432442452462472482492502512522532544 unmodified lines2592602612622632642652662672682692703 unmodified lines274275276277278279280"""判分: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``,绝不崩溃。"""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: judge 连续失败的重试上限。MAX_JUDGE_ATTEMPTS = 4#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。REPORT_HEAD, REPORT_TAIL = 150_000, 20_000# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ──────────────────────# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同# 一个真值来源)。两种模式共用下面同一段判分逻辑。try:from .prompts import JUDGE_PROMPTexcept ImportError: # pragma: no cover - 容器内独立运行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 可读的清单。"""return "\n".join(f"- id={c['id']} | section={c['section']} | points={c['points']}\n"f" criterion: {c['criterion']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。"""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)12 unmodified lines"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 只是防御。hi, lo = total_positive, total_negativeif hi > lo:normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0normalized = max(-1.0, min(1.0, normalized))else:normalized = 0.0return {"reward": round(normalized, 4),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# ── verdict 解析容错 ──────────────────────────────────────────────────────────# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值# 不含引号,reason 取到最后一个引号即可正确还原。_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 的这个比例即判失败重试(而非接受一份残缺判分)。_SALVAGE_MIN_RATIO = 2 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""解析单个 verdict 对象;严格解析失败时按字段正则抢救。"""try:obj = json.loads(blob)if isinstance(obj, dict) and "id" in obj and "status" in obj:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。��捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。"""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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}")return verdictsdef 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。``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端,容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。"""prompt = JUDGE_PROMPT.format(rubric_text=render_rubric(rubric),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。if result["missing_verdicts"] and attempt < attempts - 1:raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试last_error = excprint(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {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 入口 ─────────────────────────────────────────────────ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt")RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 +诊断信息,让整批评测不因单题判分失败中断。"""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = -1.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=-1.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True})returnresult = 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')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 — 兜底也不许崩溃write_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 012345678910111213141516171819202122232425262728293031323334357 unmodified lines434445464748495051525354555657585960616263646566676869708 unmodified lines798081828384858612 unmodified lines991001011021031041051061071081091101111121131141151161172 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314410 unmodified lines15515615715815916016116216316416516616713 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032049 unmodified lines21421521621721821922022122222322422522622722822923023123223323410 unmodified lines24524624724824925025125225325425525625725825918 unmodified lines2782792802812822832842852862872882892904 unmodified lines2952962972982993003013023033043053063 unmodified lines310311312313314315316"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts arefolded 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 thisfile into ``tests/`` when exporting) import the very same code -- there is exactlyone definition of the scoring rule, and the two paths are not allowed to driftapart.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 itmatches the wrong conclusion named by a negative criterion;- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positivecriteria and ``lo`` the total of the negative ones (the raw score reached when everynegative criterion is triggered and no positive criterion is satisfied). The rawscore 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'sHTTP call lives in ``judge.py``.Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every pathcan be overridden through environment variables, and the defaults follow harbor'sconventions. Any failure anywhere in the grading pipeline writes reward 0 plus``judge_error``; it never crashes."""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: Maximum number of consecutive judge failures before giving up.MAX_JUDGE_ATTEMPTS = 4#: 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# -- 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_PROMPTexcept ImportError: # pragma: no cover - standalone run inside the containersys.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:"""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']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""Fold verdicts into a reward; a criterion with no verdict is ``missing`` andearns 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)12 unmodified lines"points": criterion["points"], "status": status or "missing","earned": earned, "reason": verdict.get("reason", ""),})# 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_negativeif hi > lo:reward = 100.0 * (raw_score - lo) / (hi - lo)reward = max(0.0, min(100.0, reward))else:reward = 0.0return {"reward": round(reward, 2),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# -- 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)#: 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 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""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:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdictobjects one by one.Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving theretry 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 wouldpollute the statistics."""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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"too few verdicts salvaged: {len(verdicts)}/{n_criteria}")return verdictsdef 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]:"""Grade one report: build the prompt -> call the judge -> parse tolerantly ->fold into a reward.``call_judge(prompt) -> str`` is injected by the caller (the local path uses theclient from ``judge.py``, and the container path does the same), so this modulecontains no network code at all. A result with missing criteria is retried whileattempts remain.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),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 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"missing verdicts: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 -- any judge/parse error is retriedlast_error = excprint(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 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")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never anon-zero exit.Harbor treats a non-zero verifier exit as an infrastructure failure of the task, soeverything is funneled into a 0 score plus diagnostics here, keeping a wholeevaluation batch from being interrupted by one task's grading failure.Consumers must detect this case through the ``judge_error`` key and not through thereward value: under the [0, 100] scale, 0 is also the legitimate floor."""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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 0 (the rubric floor) regardless of the# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = 0.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=0.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge config error: {exc}", extra={"judge_config_error": True})returnresult = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH))if result.get("reward") is None:write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 -- even the catch-all must not crashwrite_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 0
1234# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*)ANTHROPIC_AUTH_TOKEN=<your-judge-token>ANTHROPIC_BASE_URL=http://<judge-gateway>:8413/v1ANTHROPIC_MODEL=<judge-model-path-or-id>123456789101112131415161718192021222324252627284 unmodified lines33343536373839404142434445464748495051525354555657588 unmodified lines6768697071727374757677787980818212 unmodified lines959697989910010110210310410510610710810911018 unmodified lines1291301311321331341351361371381391401411423 unmodified lines1461471481491501511523 unmodified lines1561571581591601611621631641651661671681691701711721731745 unmodified lines180181182183184185186187188"""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。"""from __future__ import annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出;#: 判分本身不贵,宁可给足。MAX_TOKENS = 131_072#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。#:#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时,#: 只有真正卡住(网关挂起、连接半开)才触发。TIMEOUT_SEC = 180.0#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``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 调用失败"区分开:配置错误不该重试,重试只会重复失败。"""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。"""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # 心跳/注释等非 JSON 帧if isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用,完整路径由各 API 形态自己拼。"""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif 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]}")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)有容错打捞。events = _iter_sse(f"{base_url}/v1/chat/completions",{"authorization": f"Bearer {token}"},3 unmodified lineschunks = []for event in events:if event.get("error"):raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}")for choice in event.get("choices") or []:content = (choice.get("delta") or {}).get("content")if content:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是#: OpenAI 兼容的 chat/completions,不是 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 身份,供调用与评测缓存共同使用。"""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))}")return {"api": api_name,"base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")),5 unmodified linesdef 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`。显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。"""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)1234567891011121314151617181920212223242526272829303132333435364 unmodified lines41424344454647484950515253545556575859606162636465666768697071728 unmodified lines81828384858687888990919293949596979812 unmodified lines11111211311411511611711811912012112212312412512612718 unmodified lines1461471481491501511521531541551561571581591603 unmodified lines1641651661671681691703 unmodified lines1741751761771781791801811821831841851861871881891901911921935 unmodified lines199200201202203204205206207208209"""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 machineshare one scoring rule while each uses its own gateway.**Credentials are read from environment variables only; no token is ever stored in thecode.** Locally they are injected by ``data_world.envfile`` from the project-root``.env`` (the same credentials used by data_world/dag_factory); inside the harborcontainer they are injected at build or run time (see ``harbor.py``). This moduletherefore provides no built-in "works with zero environment variables" key -- that wouldamount 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 thein-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 wayand 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 pathwith ``/v1`` -- after normalization both can share one variable without stepping on eachother.**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens ofcriteria), and a non-streaming request only returns its first byte once the wholegeneration is done, so both the gateway and the client tend to time out and kill ajudgment that would have succeeded. Under streaming, a timeout means "a gap between twochunks", 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 annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: 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#: 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#: 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 credentials/configuration are missing. ``grade.py`` catches it and writesreward 0 plus diagnostics.Kept distinct from "the judge call failed": a configuration error must not beretried, since retrying only repeats the failure."""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST a streaming request and yield the JSON events found in SSE ``data:`` lines.``timeout`` is handed to the socket, so it measures a single blocking read (the gapbetween chunks) rather than the total duration. Proxies are explicitly disabled:gateways usually live on an internal network, and an egress proxy would make therequest fail outright."""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # heartbeats/comments and other non-JSON framesif isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only thebare host prefix.Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shapethe caller passes works, and each API shape builds its own full path."""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif delta.get("type") == "text_delta":chunks.append(delta.get("text") or "")elif event.get("type") == "error":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:# 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}"},3 unmodified lineschunks = []for event in events:if event.get("error"):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:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 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]:"""Resolve the credential-free judge identity, shared by the call path and theevaluation cache."""api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower()if api_name not in _APIS:raise JudgeConfigError(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")),5 unmodified linesdef 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]:"""Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` whencredentials are missing.Explicit arguments take precedence over environment variables, which lets a CLIoverride things such as ``--judge-model``."""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)
123"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。"""JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n<report>\n{report}\n</report>\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}}'123"""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<report>\n{report}\n</report>\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}}'
12345678910111213141516171819204 unmodified lines25262728293031323334353637383940#!/bin/bash# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑);# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。set -euo pipefailANSWER_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 两处都能跑。TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"export ANSWER_PATH REWARD_PATH DETAILS_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。if [ -f "$TESTS_DIR/judge.env" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -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 源==目标会报错。if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# judge 网关在内网:清掉公网出口代理,否则请求被拦。unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure),# 这里只做最后兜底。set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?123456789101112131415161718192021222324254 unmodified lines303132333435363738394041424344454647#!/bin/bash# 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 pipefailANSWER_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}"# 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_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# 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" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -p "$(dirname "$ANSWER_PATH")"echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH"fi# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with# source == destination fails.if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# 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 itself writes reward.txt + details.json on any failure (write_failure);# this is only the last-resort fallback.set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# 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 <base-image>: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/simpleARG 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 usersRUN chmod -R a+rX /app/data
# Build-time assertion: no canonical-truth material may be present in the environmentRUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ && test -d /app/data12345678910111213141516171819207 unmodified lines28293031323334353637383940414243444546474849505152538 unmodified lines6263646566676812 unmodified lines81828384858687888990919293949596972 unmodified lines10010110210310410510610710810911011111211311411511611711811912012110 unmodified lines13213313413513613713813914014113 unmodified lines1551561571581591601611621631641651661671681691701711721731749 unmodified lines18418518618718818919019119219319419519619719819920020120220310 unmodified lines21421521621721821922022122222318 unmodified lines2422432442452462472482492502512522532544 unmodified lines2592602612622632642652662672682692703 unmodified lines274275276277278279280"""判分: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``,绝不崩溃。"""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: judge 连续失败的重试上限。MAX_JUDGE_ATTEMPTS = 4#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。REPORT_HEAD, REPORT_TAIL = 150_000, 20_000# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ──────────────────────# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同# 一个真值来源)。两种模式共用下面同一段判分逻辑。try:from .prompts import JUDGE_PROMPTexcept ImportError: # pragma: no cover - 容器内独立运行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 可读的清单。"""return "\n".join(f"- id={c['id']} | section={c['section']} | points={c['points']}\n"f" criterion: {c['criterion']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。"""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)12 unmodified lines"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 只是防御。hi, lo = total_positive, total_negativeif hi > lo:normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0normalized = max(-1.0, min(1.0, normalized))else:normalized = 0.0return {"reward": round(normalized, 4),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# ── verdict 解析容错 ──────────────────────────────────────────────────────────# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值# 不含引号,reason 取到最后一个引号即可正确还原。_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 的这个比例即判失败重试(而非接受一份残缺判分)。_SALVAGE_MIN_RATIO = 2 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""解析单个 verdict 对象;严格解析失败时按字段正则抢救。"""try:obj = json.loads(blob)if isinstance(obj, dict) and "id" in obj and "status" in obj:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。��捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。"""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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}")return verdictsdef 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。``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端,容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。"""prompt = JUDGE_PROMPT.format(rubric_text=render_rubric(rubric),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。if result["missing_verdicts"] and attempt < attempts - 1:raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试last_error = excprint(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {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 入口 ─────────────────────────────────────────────────ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt")RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 +诊断信息,让整批评测不因单题判分失败中断。"""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = -1.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=-1.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True})returnresult = 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')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 — 兜底也不许崩溃write_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 012345678910111213141516171819202122232425262728293031323334357 unmodified lines434445464748495051525354555657585960616263646566676869708 unmodified lines798081828384858612 unmodified lines991001011021031041051061071081091101111121131141151161172 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314410 unmodified lines15515615715815916016116216316416516616713 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032049 unmodified lines21421521621721821922022122222322422522622722822923023123223323410 unmodified lines24524624724824925025125225325425525625725825918 unmodified lines2782792802812822832842852862872882892904 unmodified lines2952962972982993003013023033043053063 unmodified lines310311312313314315316"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts arefolded 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 thisfile into ``tests/`` when exporting) import the very same code -- there is exactlyone definition of the scoring rule, and the two paths are not allowed to driftapart.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 itmatches the wrong conclusion named by a negative criterion;- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positivecriteria and ``lo`` the total of the negative ones (the raw score reached when everynegative criterion is triggered and no positive criterion is satisfied). The rawscore 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'sHTTP call lives in ``judge.py``.Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every pathcan be overridden through environment variables, and the defaults follow harbor'sconventions. Any failure anywhere in the grading pipeline writes reward 0 plus``judge_error``; it never crashes."""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: Maximum number of consecutive judge failures before giving up.MAX_JUDGE_ATTEMPTS = 4#: 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# -- 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_PROMPTexcept ImportError: # pragma: no cover - standalone run inside the containersys.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:"""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']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""Fold verdicts into a reward; a criterion with no verdict is ``missing`` andearns 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)12 unmodified lines"points": criterion["points"], "status": status or "missing","earned": earned, "reason": verdict.get("reason", ""),})# 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_negativeif hi > lo:reward = 100.0 * (raw_score - lo) / (hi - lo)reward = max(0.0, min(100.0, reward))else:reward = 0.0return {"reward": round(reward, 2),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# -- 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)#: 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 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""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:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdictobjects one by one.Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving theretry 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 wouldpollute the statistics."""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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"too few verdicts salvaged: {len(verdicts)}/{n_criteria}")return verdictsdef 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]:"""Grade one report: build the prompt -> call the judge -> parse tolerantly ->fold into a reward.``call_judge(prompt) -> str`` is injected by the caller (the local path uses theclient from ``judge.py``, and the container path does the same), so this modulecontains no network code at all. A result with missing criteria is retried whileattempts remain.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),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 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"missing verdicts: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 -- any judge/parse error is retriedlast_error = excprint(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 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")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never anon-zero exit.Harbor treats a non-zero verifier exit as an infrastructure failure of the task, soeverything is funneled into a 0 score plus diagnostics here, keeping a wholeevaluation batch from being interrupted by one task's grading failure.Consumers must detect this case through the ``judge_error`` key and not through thereward value: under the [0, 100] scale, 0 is also the legitimate floor."""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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 0 (the rubric floor) regardless of the# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = 0.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=0.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge config error: {exc}", extra={"judge_config_error": True})returnresult = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH))if result.get("reward") is None:write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 -- even the catch-all must not crashwrite_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 0
1234# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*)ANTHROPIC_AUTH_TOKEN=<your-judge-token>ANTHROPIC_BASE_URL=http://<judge-gateway>:8413/v1ANTHROPIC_MODEL=<judge-model-path-or-id>123456789101112131415161718192021222324252627284 unmodified lines33343536373839404142434445464748495051525354555657588 unmodified lines6768697071727374757677787980818212 unmodified lines959697989910010110210310410510610710810911018 unmodified lines1291301311321331341351361371381391401411423 unmodified lines1461471481491501511523 unmodified lines1561571581591601611621631641651661671681691701711721731745 unmodified lines180181182183184185186187188"""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。"""from __future__ import annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出;#: 判分本身不贵,宁可给足。MAX_TOKENS = 131_072#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。#:#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时,#: 只有真正卡住(网关挂起、连接半开)才触发。TIMEOUT_SEC = 180.0#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``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 调用失败"区分开:配置错误不该重试,重试只会重复失败。"""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。"""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # 心跳/注释等非 JSON 帧if isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用,完整路径由各 API 形态自己拼。"""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif 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]}")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)有容错打捞。events = _iter_sse(f"{base_url}/v1/chat/completions",{"authorization": f"Bearer {token}"},3 unmodified lineschunks = []for event in events:if event.get("error"):raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}")for choice in event.get("choices") or []:content = (choice.get("delta") or {}).get("content")if content:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是#: OpenAI 兼容的 chat/completions,不是 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 身份,供调用与评测缓存共同使用。"""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))}")return {"api": api_name,"base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")),5 unmodified linesdef 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`。显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。"""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)1234567891011121314151617181920212223242526272829303132333435364 unmodified lines41424344454647484950515253545556575859606162636465666768697071728 unmodified lines81828384858687888990919293949596979812 unmodified lines11111211311411511611711811912012112212312412512612718 unmodified lines1461471481491501511521531541551561571581591603 unmodified lines1641651661671681691703 unmodified lines1741751761771781791801811821831841851861871881891901911921935 unmodified lines199200201202203204205206207208209"""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 machineshare one scoring rule while each uses its own gateway.**Credentials are read from environment variables only; no token is ever stored in thecode.** Locally they are injected by ``data_world.envfile`` from the project-root``.env`` (the same credentials used by data_world/dag_factory); inside the harborcontainer they are injected at build or run time (see ``harbor.py``). This moduletherefore provides no built-in "works with zero environment variables" key -- that wouldamount 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 thein-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 wayand 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 pathwith ``/v1`` -- after normalization both can share one variable without stepping on eachother.**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens ofcriteria), and a non-streaming request only returns its first byte once the wholegeneration is done, so both the gateway and the client tend to time out and kill ajudgment that would have succeeded. Under streaming, a timeout means "a gap between twochunks", 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 annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: 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#: 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#: 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 credentials/configuration are missing. ``grade.py`` catches it and writesreward 0 plus diagnostics.Kept distinct from "the judge call failed": a configuration error must not beretried, since retrying only repeats the failure."""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST a streaming request and yield the JSON events found in SSE ``data:`` lines.``timeout`` is handed to the socket, so it measures a single blocking read (the gapbetween chunks) rather than the total duration. Proxies are explicitly disabled:gateways usually live on an internal network, and an egress proxy would make therequest fail outright."""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # heartbeats/comments and other non-JSON framesif isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only thebare host prefix.Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shapethe caller passes works, and each API shape builds its own full path."""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif delta.get("type") == "text_delta":chunks.append(delta.get("text") or "")elif event.get("type") == "error":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:# 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}"},3 unmodified lineschunks = []for event in events:if event.get("error"):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:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 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]:"""Resolve the credential-free judge identity, shared by the call path and theevaluation cache."""api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower()if api_name not in _APIS:raise JudgeConfigError(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")),5 unmodified linesdef 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]:"""Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` whencredentials are missing.Explicit arguments take precedence over environment variables, which lets a CLIoverride things such as ``--judge-model``."""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)
123"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。"""JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n<report>\n{report}\n</report>\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}}'123"""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<report>\n{report}\n</report>\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}}'
12345678910111213141516171819204 unmodified lines25262728293031323334353637383940#!/bin/bash# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑);# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。set -euo pipefailANSWER_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 两处都能跑。TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"export ANSWER_PATH REWARD_PATH DETAILS_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。if [ -f "$TESTS_DIR/judge.env" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -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 源==目标会报错。if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# judge 网关在内网:清掉公网出口代理,否则请求被拦。unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure),# 这里只做最后兜底。set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?123456789101112131415161718192021222324254 unmodified lines303132333435363738394041424344454647#!/bin/bash# 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 pipefailANSWER_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}"# 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_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# 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" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -p "$(dirname "$ANSWER_PATH")"echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH"fi# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with# source == destination fails.if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# 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 itself writes reward.txt + details.json on any failure (write_failure);# this is only the last-resort fallback.set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# 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 <base-image>: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/simpleARG 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 usersRUN chmod -R a+rX /app/data
# Build-time assertion: no canonical-truth material may be present in the environmentRUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ && test -d /app/data12345678910111213141516171819207 unmodified lines28293031323334353637383940414243444546474849505152538 unmodified lines6263646566676812 unmodified lines81828384858687888990919293949596972 unmodified lines10010110210310410510610710810911011111211311411511611711811912012110 unmodified lines13213313413513613713813914014113 unmodified lines1551561571581591601611621631641651661671681691701711721731749 unmodified lines18418518618718818919019119219319419519619719819920020120220310 unmodified lines21421521621721821922022122222318 unmodified lines2422432442452462472482492502512522532544 unmodified lines2592602612622632642652662672682692703 unmodified lines274275276277278279280"""判分: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``,绝不崩溃。"""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: judge 连续失败的重试上限。MAX_JUDGE_ATTEMPTS = 4#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。REPORT_HEAD, REPORT_TAIL = 150_000, 20_000# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ──────────────────────# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同# 一个真值来源)。两种模式共用下面同一段判分逻辑。try:from .prompts import JUDGE_PROMPTexcept ImportError: # pragma: no cover - 容器内独立运行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 可读的清单。"""return "\n".join(f"- id={c['id']} | section={c['section']} | points={c['points']}\n"f" criterion: {c['criterion']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。"""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)12 unmodified lines"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 只是防御。hi, lo = total_positive, total_negativeif hi > lo:normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0normalized = max(-1.0, min(1.0, normalized))else:normalized = 0.0return {"reward": round(normalized, 4),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# ── verdict 解析容错 ──────────────────────────────────────────────────────────# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值# 不含引号,reason 取到最后一个引号即可正确还原。_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 的这个比例即判失败重试(而非接受一份残缺判分)。_SALVAGE_MIN_RATIO = 2 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""解析单个 verdict 对象;严格解析失败时按字段正则抢救。"""try:obj = json.loads(blob)if isinstance(obj, dict) and "id" in obj and "status" in obj:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。��捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。"""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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}")return verdictsdef 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。``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端,容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。"""prompt = JUDGE_PROMPT.format(rubric_text=render_rubric(rubric),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。if result["missing_verdicts"] and attempt < attempts - 1:raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试last_error = excprint(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {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 入口 ─────────────────────────────────────────────────ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt")RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 +诊断信息,让整批评测不因单题判分失败中断。"""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = -1.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=-1.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True})returnresult = 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')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 — 兜底也不许崩溃write_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 012345678910111213141516171819202122232425262728293031323334357 unmodified lines434445464748495051525354555657585960616263646566676869708 unmodified lines798081828384858612 unmodified lines991001011021031041051061071081091101111121131141151161172 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314410 unmodified lines15515615715815916016116216316416516616713 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032049 unmodified lines21421521621721821922022122222322422522622722822923023123223323410 unmodified lines24524624724824925025125225325425525625725825918 unmodified lines2782792802812822832842852862872882892904 unmodified lines2952962972982993003013023033043053063 unmodified lines310311312313314315316"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts arefolded 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 thisfile into ``tests/`` when exporting) import the very same code -- there is exactlyone definition of the scoring rule, and the two paths are not allowed to driftapart.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 itmatches the wrong conclusion named by a negative criterion;- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positivecriteria and ``lo`` the total of the negative ones (the raw score reached when everynegative criterion is triggered and no positive criterion is satisfied). The rawscore 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'sHTTP call lives in ``judge.py``.Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every pathcan be overridden through environment variables, and the defaults follow harbor'sconventions. Any failure anywhere in the grading pipeline writes reward 0 plus``judge_error``; it never crashes."""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: Maximum number of consecutive judge failures before giving up.MAX_JUDGE_ATTEMPTS = 4#: 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# -- 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_PROMPTexcept ImportError: # pragma: no cover - standalone run inside the containersys.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:"""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']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""Fold verdicts into a reward; a criterion with no verdict is ``missing`` andearns 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)12 unmodified lines"points": criterion["points"], "status": status or "missing","earned": earned, "reason": verdict.get("reason", ""),})# 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_negativeif hi > lo:reward = 100.0 * (raw_score - lo) / (hi - lo)reward = max(0.0, min(100.0, reward))else:reward = 0.0return {"reward": round(reward, 2),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# -- 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)#: 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 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""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:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdictobjects one by one.Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving theretry 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 wouldpollute the statistics."""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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"too few verdicts salvaged: {len(verdicts)}/{n_criteria}")return verdictsdef 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]:"""Grade one report: build the prompt -> call the judge -> parse tolerantly ->fold into a reward.``call_judge(prompt) -> str`` is injected by the caller (the local path uses theclient from ``judge.py``, and the container path does the same), so this modulecontains no network code at all. A result with missing criteria is retried whileattempts remain.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),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 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"missing verdicts: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 -- any judge/parse error is retriedlast_error = excprint(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 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")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never anon-zero exit.Harbor treats a non-zero verifier exit as an infrastructure failure of the task, soeverything is funneled into a 0 score plus diagnostics here, keeping a wholeevaluation batch from being interrupted by one task's grading failure.Consumers must detect this case through the ``judge_error`` key and not through thereward value: under the [0, 100] scale, 0 is also the legitimate floor."""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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 0 (the rubric floor) regardless of the# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = 0.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=0.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge config error: {exc}", extra={"judge_config_error": True})returnresult = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH))if result.get("reward") is None:write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 -- even the catch-all must not crashwrite_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 0
1234# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*)ANTHROPIC_AUTH_TOKEN=<your-judge-token>ANTHROPIC_BASE_URL=http://<judge-gateway>:8413/v1ANTHROPIC_MODEL=<judge-model-path-or-id>123456789101112131415161718192021222324252627284 unmodified lines33343536373839404142434445464748495051525354555657588 unmodified lines6768697071727374757677787980818212 unmodified lines959697989910010110210310410510610710810911018 unmodified lines1291301311321331341351361371381391401411423 unmodified lines1461471481491501511523 unmodified lines1561571581591601611621631641651661671681691701711721731745 unmodified lines180181182183184185186187188"""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。"""from __future__ import annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: judge 输出上限。judge 常在 verdicts 前长篇推理,给小了会把 JSON 截断成非法输出;#: 判分本身不贵,宁可给足。MAX_TOKENS = 131_072#: 流式读取的空档超时(秒):两个 chunk 之间超过它才算卡死。#:#: 因为是流式,这里不是"整段生成的总时长"——模型持续吐字就一直不算超时,#: 只有真正卡住(网关挂起、连接半开)才触发。TIMEOUT_SEC = 180.0#: 环境变量名:judge 专用(``JUDGE_*``)优先,否则回落到项目通用的 ``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 调用失败"区分开:配置错误不该重试,重试只会重复失败。"""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} 未配置,请设置 {' 或 '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST 一个流式请求,逐个 yield SSE ``data:`` 里的 JSON 事件。``timeout`` 传给 socket,因此它衡量的是单次读阻塞(chunk 间空档)而非总时长。显式禁用代理:网关多在内网,公网出口代理会让请求直接失败。"""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # 心跳/注释等非 JSON 帧if isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""剥掉 base_url 末尾的 ``/v1``、``/anthropic`` 等后缀,只留下裸 host 前缀。与 ``data_world.sdk.ClaudeRunner`` 的归一化同理:调用方给什么形态都能用,完整路径由各 API 形态自己拼。"""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif 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]}")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)有容错打捞。events = _iter_sse(f"{base_url}/v1/chat/completions",{"authorization": f"Bearer {token}"},3 unmodified lineschunks = []for event in events:if event.get("error"):raise RuntimeError(f"judge 流式错误: {str(event['error'])[:200]}")for choice in event.get("choices") or []:content = (choice.get("delta") or {}).get("content")if content:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 默认 API 形态:项目内网关(``.env`` 里的 ``ANTHROPIC_BASE_URL``)是#: OpenAI 兼容的 chat/completions,不是 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 身份,供调用与评测缓存共同使用。"""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))}")return {"api": api_name,"base_url": normalize_base(base_url or _require(_BASE_URL_KEYS, "base_url")),5 unmodified linesdef 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`。显式入参优先于环境变量,便于 CLI 用 ``--judge-model`` 之类覆盖。"""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)1234567891011121314151617181920212223242526272829303132333435364 unmodified lines41424344454647484950515253545556575859606162636465666768697071728 unmodified lines81828384858687888990919293949596979812 unmodified lines11111211311411511611711811912012112212312412512612718 unmodified lines1461471481491501511521531541551561571581591603 unmodified lines1641651661671681691703 unmodified lines1741751761771781791801811821831841851861871881891901911921935 unmodified lines199200201202203204205206207208209"""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 machineshare one scoring rule while each uses its own gateway.**Credentials are read from environment variables only; no token is ever stored in thecode.** Locally they are injected by ``data_world.envfile`` from the project-root``.env`` (the same credentials used by data_world/dag_factory); inside the harborcontainer they are injected at build or run time (see ``harbor.py``). This moduletherefore provides no built-in "works with zero environment variables" key -- that wouldamount 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 thein-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 wayand 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 pathwith ``/v1`` -- after normalization both can share one variable without stepping on eachother.**Everything is streamed (SSE).** Judge output can be long (a rubric has dozens ofcriteria), and a non-streaming request only returns its first byte once the wholegeneration is done, so both the gateway and the client tend to time out and kill ajudgment that would have succeeded. Under streaming, a timeout means "a gap between twochunks", 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 annotations4 unmodified linesimport urllib.requestfrom typing import Any, Callable, Dict, Iterator, Optional#: 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#: 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#: 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 credentials/configuration are missing. ``grade.py`` catches it and writesreward 0 plus diagnostics.Kept distinct from "the judge call failed": a configuration error must not beretried, since retrying only repeats the failure."""8 unmodified linesdef _require(keys: tuple[str, ...], what: str) -> str:value = _first_env(keys)if not value:raise JudgeConfigError(f"judge {what} not configured; set {' or '.join(keys)}")return valuedef _iter_sse(url: str, headers: Dict[str, str], payload: Dict[str, Any],timeout: float) -> Iterator[Dict[str, Any]]:"""POST a streaming request and yield the JSON events found in SSE ``data:`` lines.``timeout`` is handed to the socket, so it measures a single blocking read (the gapbetween chunks) rather than the total duration. Proxies are explicitly disabled:gateways usually live on an internal network, and an egress proxy would make therequest fail outright."""request = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"),12 unmodified linestry:event = json.loads(data)except json.JSONDecodeError:continue # heartbeats/comments and other non-JSON framesif isinstance(event, dict):yield eventdef normalize_base(url: str) -> str:"""Strip a trailing ``/v1``, ``/anthropic`` (etc.) from base_url, leaving only thebare host prefix.Same idea as the normalization in ``data_world.sdk.ClaudeRunner``: whichever shapethe caller passes works, and each API shape builds its own full path."""normalized = (url or "").rstrip("/")for suffix in ("/v1/anthropic", "/anthropic", "/v1"):18 unmodified linesif delta.get("type") == "text_delta":chunks.append(delta.get("text") or "")elif event.get("type") == "error":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:# 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}"},3 unmodified lineschunks = []for event in events:if event.get("error"):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:3 unmodified lines_APIS: Dict[str, Any] = {"anthropic": _call_anthropic, "openai": _call_openai}#: 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]:"""Resolve the credential-free judge identity, shared by the call path and theevaluation cache."""api_name = (api or os.environ.get("JUDGE_API") or DEFAULT_API).strip().lower()if api_name not in _APIS:raise JudgeConfigError(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")),5 unmodified linesdef 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]:"""Build ``call_judge(prompt) -> str``; raises :class:`JudgeConfigError` whencredentials are missing.Explicit arguments take precedence over environment variables, which lets a CLIoverride things such as ``--judge-model``."""identity = resolve_judge_identity(api=api, base_url=base_url, model=model,timeout=timeout)
123"""判分提示词(由 task/harbor.py 从 task/prompts.py 自动生成,勿手改)。"""JUDGE_PROMPT = '你是一名严格、公正的数据分析报告评审。下面给你一份评分细则(rubric)和一份待评报告。\n请逐条判定报告是否满足每个评分点。\n\n[评分细则]\n{rubric_text}\n\n[待评报告({report_path})]\n<report>\n{report}\n</report>\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}}'123"""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<report>\n{report}\n</report>\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}}'
12345678910111213141516171819204 unmodified lines25262728293031323334353637383940#!/bin/bash# Data-World harbor verifier 入口:判 /app/answer.txt,产物 reward.txt + details.json。# judge 凭据由同目录 judge.env 提供(见下方 source 逻辑);# 任何失败都兜底写 reward 0 并 exit 0——verifier 非零退出会被 harbor 当作基础设施故障。set -euo pipefailANSWER_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 两处都能跑。TESTS_DIR="${TESTS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"export ANSWER_PATH REWARD_PATH DETAILS_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# judge 凭据随任务目录走(评测平台没有运行期注入通道,见 judge.env)。if [ -f "$TESTS_DIR/judge.env" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -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 源==目标会报错。if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# judge 网关在内网:清掉公网出口代理,否则请求被拦。unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY || true# grade.py 自身在任何失败下都会写 reward.txt + details.json(write_failure),# 这里只做最后兜底。set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?123456789101112131415161718192021222324254 unmodified lines303132333435363738394041424344454647#!/bin/bash# 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 pipefailANSWER_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}"# 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_PATHexport RUBRIC_PATH="${RUBRIC_PATH:-$TESTS_DIR/rubric.json}"# 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" ]; thenset -a; . "$TESTS_DIR/judge.env"; set +afi4 unmodified linesmkdir -p "$(dirname "$ANSWER_PATH")"echo "[verifier] $ANSWER_PATH missing or empty after the agent run. Placeholder for artifact retention only." > "$ANSWER_PATH"fi# The runner may already have copied ANSWER_PATH into ARTIFACT_DIR; cp with# source == destination fails.if [ "$ANSWER_PATH" != "$ARTIFACT_DIR/answer.txt" ]; thencp -f "$ANSWER_PATH" "$ARTIFACT_DIR/answer.txt"fi# 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 itself writes reward.txt + details.json on any failure (write_failure);# this is only the last-resort fallback.set +epython3 "$TESTS_DIR/grade.py" 2>&1status=$?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# 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 <base-image>: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/simpleARG 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 usersRUN chmod -R a+rX /app/data
# Build-time assertion: no canonical-truth material may be present in the environmentRUN test ! -e /app/WORLD.md && test ! -e /app/dag.json && test ! -e /app/.build \ && test -d /app/data12345678910111213141516171819207 unmodified lines28293031323334353637383940414243444546474849505152538 unmodified lines6263646566676812 unmodified lines81828384858687888990919293949596972 unmodified lines10010110210310410510610710810911011111211311411511611711811912012110 unmodified lines13213313413513613713813914014113 unmodified lines1551561571581591601611621631641651661671681691701711721731749 unmodified lines18418518618718818919019119219319419519619719819920020120220310 unmodified lines21421521621721821922022122222318 unmodified lines2422432442452462472482492502512522532544 unmodified lines2592602612622632642652662672682692703 unmodified lines274275276277278279280"""判分: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``,绝不崩溃。"""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: judge 连续失败的重试上限。MAX_JUDGE_ATTEMPTS = 4#: 报告过长时的截断窗口(judge 上下文有限;头部含结论与方法,尾部含局限与建议)。REPORT_HEAD, REPORT_TAIL = 150_000, 20_000# ── 独立运行(容器 verifier)与包内导入(本机评测)两种模式 ──────────────────────# 容器里本文件被拷成 /tests/grade.py,没有 task 包可 import;此时从同目录的# judge_prompt.py 取(``harbor.py`` 导出时由 prompts.JUDGE_PROMPT 生成,仍是同# 一个真值来源)。两种模式共用下面同一段判分逻辑。try:from .prompts import JUDGE_PROMPTexcept ImportError: # pragma: no cover - 容器内独立运行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 可读的清单。"""return "\n".join(f"- id={c['id']} | section={c['section']} | points={c['points']}\n"f" criterion: {c['criterion']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""按 verdict 折算 reward;缺条记 ``missing`` 且不得分(由调用方决定是否重试)。"""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)12 unmodified lines"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 只是防御。hi, lo = total_positive, total_negativeif hi > lo:normalized = 2.0 * (raw_score - lo) / (hi - lo) - 1.0normalized = max(-1.0, min(1.0, normalized))else:normalized = 0.0return {"reward": round(normalized, 4),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# ── verdict 解析容错 ──────────────────────────────────────────────────────────# judge 的两类典型坏输出:长推理导致 JSON 被截断(尾部对象残缺)、reason 里引用# 报告原话时放了未转义的 ASCII 直引号(整体 json.loads 必挂)。verdict 对象是扁平# 的(无嵌套花括号),可逐个正则捞出;坏对象再走字段级抢救——id/status 是枚举值# 不含引号,reason 取到最后一个引号即可正确还原。_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 的这个比例即判失败重试(而非接受一份残缺判分)。_SALVAGE_MIN_RATIO = 2 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""解析单个 verdict 对象;严格解析失败时按字段正则抢救。"""try:obj = json.loads(blob)if isinstance(obj, dict) and "id" in obj and "status" in obj:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""先严格解析 ``{"verdicts": [...]}``;失败则逐条打捞 verdict 对象。��捞数量不足 criteria 的 2/3 时抛 ValueError,交由调用方重试——宁可重判也不接受一份大面积缺条的结果(缺条会被 :func:`score` 静默记 0,污染统计)。"""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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}")return verdictsdef 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。``call_judge(prompt) -> str`` 由调用方注入(本机走 ``judge.py`` 的客户端,容器内同理),本模块因此不含任何网络代码。缺条且还有重试机会时重试。judge 连续失败返回 ``{"reward": None, "judge_error": ...}``——判分基础设施故障与真实 0 分是两件事,不能混为一谈污染统计与 RL 数据。"""prompt = JUDGE_PROMPT.format(rubric_text=render_rubric(rubric),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 缺条会被 score 静默记 0,不能当正常结果接受:还有重试机会就重试。if result["missing_verdicts"] and attempt < attempts - 1:raise ValueError(f"verdicts 缺条: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 — 任何 judge/解析异常都重试last_error = excprint(f"[grade] judge 第 {attempt + 1}/{attempts} 次失败: {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 入口 ─────────────────────────────────────────────────ANSWER_PATH = Path(os.environ.get("ANSWER_PATH") or "/app/answer.txt")RUBRIC_PATH = Path(os.environ.get("RUBRIC_PATH") or "/tests/rubric.json")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""判分链路失败:reward 0 + details 带 ``judge_error``,绝不非零退出。harbor 把 verifier 的非零退出当作任务基础设施故障;此处统一兜底成 0 分 +诊断信息,让整批评测不因单题判分失败中断。"""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = -1.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=-1.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge 配置错误: {exc}", extra={"judge_config_error": True})returnresult = 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')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 — 兜底也不许崩溃write_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 012345678910111213141516171819202122232425262728293031323334357 unmodified lines434445464748495051525354555657585960616263646566676869708 unmodified lines798081828384858612 unmodified lines991001011021031041051061071081091101111121131141151161172 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314410 unmodified lines15515615715815916016116216316416516616713 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032049 unmodified lines21421521621721821922022122222322422522622722822923023123223323410 unmodified lines24524624724824925025125225325425525625725825918 unmodified lines2782792802812822832842852862872882892904 unmodified lines2952962972982993003013023033043053063 unmodified lines310311312313314315316"""Grading: an LLM judge gives a per-criterion verdict, and the verdicts arefolded 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 thisfile into ``tests/`` when exporting) import the very same code -- there is exactlyone definition of the scoring rule, and the two paths are not allowed to driftapart.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 itmatches the wrong conclusion named by a negative criterion;- ``reward = 100 * (raw - lo) / (hi - lo)``, where ``hi`` is the total of the positivecriteria and ``lo`` the total of the negative ones (the raw score reached when everynegative criterion is triggered and no positive criterion is satisfied). The rawscore 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'sHTTP call lives in ``judge.py``.Command-line entry point (used by the harbor verifier): ``python3 grade.py``. Every pathcan be overridden through environment variables, and the defaults follow harbor'sconventions. Any failure anywhere in the grading pipeline writes reward 0 plus``judge_error``; it never crashes."""from __future__ import annotations7 unmodified linesfrom pathlib import Pathfrom typing import Any, Dict, List, Optional#: Maximum number of consecutive judge failures before giving up.MAX_JUDGE_ATTEMPTS = 4#: 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# -- 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_PROMPTexcept ImportError: # pragma: no cover - standalone run inside the containersys.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:"""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']}"8 unmodified linesdef score(rubric: Dict[str, Any], verdicts: List[Any]) -> Dict[str, Any]:"""Fold verdicts into a reward; a criterion with no verdict is ``missing`` andearns 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)12 unmodified lines"points": criterion["points"], "status": status or "missing","earned": earned, "reason": verdict.get("reason", ""),})# 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_negativeif hi > lo:reward = 100.0 * (raw_score - lo) / (hi - lo)reward = max(0.0, min(100.0, reward))else:reward = 0.0return {"reward": round(reward, 2),"raw_score": raw_score,"total_positive": total_positive,"total_negative": total_negative,2 unmodified lines}# -- 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)#: 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 / 3def _salvage_verdict(blob: str) -> Optional[Dict[str, Any]]:"""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:10 unmodified linesdef parse_verdicts(text: str, n_criteria: int) -> List[Any]:"""Try a strict ``{"verdicts": [...]}`` parse first; otherwise salvage verdictobjects one by one.Raises ValueError when fewer than 2/3 of the criteria were salvaged, leaving theretry 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 wouldpollute the statistics."""stripped = text.strip()if stripped.startswith("```"):13 unmodified linesfor 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"too few verdicts salvaged: {len(verdicts)}/{n_criteria}")return verdictsdef 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]:"""Grade one report: build the prompt -> call the judge -> parse tolerantly ->fold into a reward.``call_judge(prompt) -> str`` is injected by the caller (the local path uses theclient from ``judge.py``, and the container path does the same), so this modulecontains no network code at all. A result with missing criteria is retried whileattempts remain.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),9 unmodified lineson_raw(text)verdicts = parse_verdicts(text, n_criteria)result = score(rubric, verdicts)# 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"missing verdicts: {result['missing_verdicts']}")return resultexcept Exception as exc: # noqa: BLE001 -- any judge/parse error is retriedlast_error = excprint(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 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")10 unmodified linesdef write_failure(reason: str, extra: Optional[Dict[str, Any]] = None) -> None:"""Grading pipeline failure: reward 0 plus ``judge_error`` in the details; never anon-zero exit.Harbor treats a non-zero verifier exit as an infrastructure failure of the task, soeverything is funneled into a 0 score plus diagnostics here, keeping a wholeevaluation batch from being interrupted by one task's grading failure.Consumers must detect this case through the ``judge_error`` key and not through thereward value: under the [0, 100] scale, 0 is also the legitimate floor."""result: Dict[str, Any] = {"reward": 0, "judge_error": reason, "criteria": []}if extra:18 unmodified linesif 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 0 (the rubric floor) regardless of the# negative share -- deliberate uniform penalty, easy for RL to learn.result = score(rubric, [])result["reward"] = 0.0result["blank"] = blank_reasonwrite_reward(result)print(f"[grade] blank submission ({blank_reason}): reward=0.0 "f"(rubric blank would be {result['raw_score']})")return4 unmodified linestry:call_judge = judge.make_judge()except judge.JudgeConfigError as exc:write_failure(f"judge config error: {exc}", extra={"judge_config_error": True})returnresult = judge_report(rubric, report_text, call_judge, report_path=str(ANSWER_PATH))if result.get("reward") is None:write_failure(f"judge failed {MAX_JUDGE_ATTEMPTS} times in a row: {result.get('judge_error')}")returnwrite_reward(result)print(f"[grade] reward={result['reward']} "3 unmodified linesdef main() -> int:try:_grade_container()except Exception: # noqa: BLE001 -- even the catch-all must not crashwrite_failure(f"grader crashed: {traceback.format_exc()[-500:]}")return 0
1234# 判分 judge 网关凭据(test.sh 启动时 source;judge.py 回落读取 ANTHROPIC_*)ANTHROPIC_AUTH_TOKEN=<your-judge-token>ANTHROPIC_BASE_URL=http://<judge-gateway>:8413/v1ANTHROPIC_MODEL=<judge-model-path-or-id>dataworld-p002876-consequence-1/tests/grade.py+99-63
dataworld-p002876-consequence-1/tests/judge.envAdded+4
dataworld-p002876-consequence-1/tests/judge.py+72-51
dataworld-p002876-consequence-1/tests/judge_prompt.py+1-1
dataworld-p002876-consequence-1/tests/test.sh+17-10
dataworld-p004607-cause-2/environment/DockerfileAdded+64
dataworld-p004607-cause-2/tests/grade.py+99-63
dataworld-p004607-cause-2/tests/judge.envAdded+4
dataworld-p004607-cause-2/tests/judge.py+72-51
dataworld-p004607-cause-2/tests/judge_prompt.py+1-1
dataworld-p004607-cause-2/tests/test.sh+17-10
dataworld-p004607-consequence-2/environment/DockerfileAdded+64
dataworld-p004607-consequence-2/tests/grade.py+99-63
dataworld-p004607-consequence-2/tests/judge.envAdded+4
dataworld-p004607-consequence-2/tests/judge.py+72-51
dataworld-p004607-consequence-2/tests/judge_prompt.py+1-1
dataworld-p004607-consequence-2/tests/test.sh+17-10
dataworld-p006499-cause-2/environment/DockerfileAdded+64
dataworld-p006499-cause-2/tests/grade.py+99-63
dataworld-p006499-cause-2/tests/judge.envAdded+4
dataworld-p006499-cause-2/tests/judge.py+72-51
dataworld-p006499-cause-2/tests/judge_prompt.py+1-1
dataworld-p006499-cause-2/tests/test.sh+17-10
dataworld-p006499-consequence-2/environment/DockerfileAdded+64
dataworld-p006499-consequence-2/tests/grade.py+99-63
dataworld-p006499-consequence-2/tests/judge.envAdded+4
dataworld-p006499-consequence-2/tests/judge.py+72-51
dataworld-p006499-consequence-2/tests/judge_prompt.py+1-1
dataworld-p006499-consequence-2/tests/test.sh+17-10
dataworld-p006632-cause-1/environment/DockerfileAdded+64
dataworld-p006632-cause-1/tests/grade.py+99-63
dataworld-p006632-cause-1/tests/judge.envAdded+4
dataworld-p006632-cause-1/tests/judge.py+72-51
dataworld-p006632-cause-1/tests/judge_prompt.py+1-1
dataworld-p006632-cause-1/tests/test.sh+17-10
dataworld-p006632-consequence-2/environment/DockerfileAdded+64
dataworld-p006632-consequence-2/tests/grade.py+99-63
dataworld-p006632-consequence-2/tests/judge.envAdded+4
dataworld-p006632-consequence-2/tests/judge.py+72-51
dataworld-p006632-consequence-2/tests/judge_prompt.py+1-1
dataworld-p006632-consequence-2/tests/test.sh+17-10
dataworld-p006802-cause-2/environment/DockerfileAdded+64
dataworld-p006802-cause-2/tests/grade.py+99-63
dataworld-p006802-cause-2/tests/judge.envAdded+4
dataworld-p006802-cause-2/tests/judge.py+72-51
dataworld-p006802-cause-2/tests/judge_prompt.py+1-1
dataworld-p006802-cause-2/tests/test.sh+17-10
dataworld-p006802-consequence-2/environment/DockerfileAdded+64
dataworld-p006802-consequence-2/tests/grade.py+99-63
dataworld-p006802-consequence-2/tests/judge.envAdded+4