Datasets:
Download scripts/appworld_reconstruction.py from Catherine1213/VerifierBench: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/datasets/Catherine1213/VerifierBench/resolve/main/scripts/appworld_reconstruction.py
- Command line
-
hf download hf://datasets/Catherine1213/VerifierBench/scripts/appworld_reconstruction.py
-
curl -L -o appworld_reconstruction.py https://huggingface.co/datasets/Catherine1213/VerifierBench/resolve/main/scripts/appworld_reconstruction.py
13 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| # Original VerifierBench contributions; third-party terms remain applicable. | |
| """Local reconstruction only. Does not execute candidate programs or judge labels. | |
| Extracted from the exact project renderer and construction operators. | |
| """ | |
| import json | |
| import os | |
| import re | |
| from pathlib import Path | |
| def gold_body(task_id, data_dir): | |
| """The reference solution, with a known compilation defect repaired. | |
| AppWorld ships two gold artefacts and they are NOT equivalent: every one of | |
| the 24 tasks whose `solution.py` passes `raise_on_failure=False` has that | |
| argument MISSING from its `compiled_solution.py`. The argument is what makes | |
| "check whether this person has an account" work -- without it the api raises | |
| 422 instead of returning `{"message": "... does not exist."}`, the solution | |
| aborts, and the reference makes zero state changes. | |
| That matters beyond us: `verify.py` runs `compiled_solution_code`, so | |
| AppWorld's own `appworld verify` fails these 24 tasks too. Recorded as AW-E1. | |
| Repair rather than switch to solution.py: the latter takes `main_user` and | |
| `public_data`, which the sandbox does not inject, so using it would mean | |
| reconstructing the environment's own wiring. Transplanting the one dropped | |
| argument is smaller and its effect is legible. | |
| """ | |
| d = os.path.join(data_dir, "tasks", task_id, "ground_truth") | |
| p = os.path.join(d, "compiled_solution.py") | |
| if not os.path.exists(p): | |
| return None | |
| src = open(p).read() | |
| src = "\n".join(l for l in src.split("\n") if not l.startswith("# Canary")) | |
| raw_path = os.path.join(d, "solution.py") | |
| if os.path.exists(raw_path): | |
| raw = open(raw_path).read() | |
| if "raise_on_failure=False" in raw and "raise_on_failure=False" not in src: | |
| flagged = {f"{m.group(1)}.{m.group(2)}" | |
| for m in re.finditer( | |
| r"apis\.(\w+)\.(\w+)\(", raw) | |
| if "raise_on_failure=False" in raw[m.end():raw.find(")", m.end()) + 400]} | |
| lines = src.split("\n") | |
| out, i, patched = [], 0, 0 | |
| while i < len(lines): | |
| m = re.search(r"apis\.(\w+)\.(\w+)\(", lines[i]) | |
| if not m or f"{m.group(1)}.{m.group(2)}" not in flagged: | |
| out.append(lines[i]); i += 1; continue | |
| # copy the call, tracking bracket depth, and inject before its close | |
| depth, j = 0, i | |
| while j < len(lines): | |
| depth += lines[j].count("(") - lines[j].count(")") | |
| if depth <= 0: | |
| break | |
| j += 1 | |
| if j == i: | |
| # the call opens and closes on one line: inject inline, before | |
| # the closing paren. The multi-line branch appended a comma to | |
| # `out[-1]`, which here is the PREVIOUS line -- that produced | |
| # `for song_id in filtered_song_ids:,` and a SyntaxError. | |
| k = lines[i].rindex(")") | |
| inner = lines[i][:k].rstrip() | |
| sep = "" if inner.endswith("(") else ", " | |
| out.append(inner + sep + "raise_on_failure=False" + lines[i][k:]) | |
| else: | |
| indent = len(lines[j]) - len(lines[j].lstrip()) | |
| out.extend(lines[i:j]) | |
| if not out[-1].rstrip().endswith(","): | |
| out[-1] = out[-1].rstrip() + "," | |
| out.append(" " * (indent + 4) + "raise_on_failure=False,") | |
| out.append(lines[j]) | |
| patched += 1 | |
| i = j + 1 | |
| if patched == 0: | |
| raise RuntimeError( | |
| f"{task_id}: 已知该题需要补 raise_on_failure,但一处都没补上 —— " | |
| "定位逻辑失配,实验不成立") | |
| src = "\n".join(out) | |
| # a repair that produces invalid Python is worse than no repair: it | |
| # turns a benchmark defect into a syntax error and the gold still | |
| # fails, for a reason we introduced. | |
| compile(src, f"<gold:{task_id}>", "exec") | |
| return src | |
| CALL = re.compile(r"^(\s*)(?:[\w, ]+=\s*)?apis\.([a-z_]+)\.([a-z_]+)\(", re.M) | |
| READONLY = re.compile(r"\.(show|search|list|get|login|read)[a-z_]*\(") | |
| def _calls(body): | |
| """(行号, 缩进, app, 方法, 是否只读) —— 按语句起始行定位。""" | |
| out = [] | |
| for m in CALL.finditer(body): | |
| line = body[:m.start()].count("\n") | |
| seg = body[m.start():m.start() + 200] | |
| out.append((line, m.group(1), m.group(2), m.group(3), | |
| bool(READONLY.search(seg)))) | |
| return out | |
| def _stmt_span(lines, i): | |
| """一个调用语句可能跨多行,找到它的结束行(括号配平)。""" | |
| depth = 0 | |
| for j in range(i, len(lines)): | |
| depth += lines[j].count("(") - lines[j].count(")") | |
| if depth <= 0: | |
| return j | |
| return i | |
| def cosmetic(body, k=4): | |
| """只加注释 —— 不执行任何多余动作,对「断言没有多做事」的任务也安全。""" | |
| out, lines = [], body.split("\n") | |
| ins = next((i for i, l in enumerate(lines) | |
| if l.startswith("def solution")), 0) + 1 | |
| for n in range(k): | |
| q = list(lines) | |
| q.insert(ins, f" # v4v cosmetic {n}") | |
| out.append((f"cosmetic_comment{n}", "\n".join(q))) | |
| return out | |
| def overstrict_trap(body, k=4): | |
| """合法的另一条路径,终态完全相同。 | |
| **换序这条轴不能用**:第一版交换只读调用,86/86 全部判 FAIL —— | |
| 那些调用的返回值被后面用到(`files = show_directory(...)` 然后 `for f in files`), | |
| 换序直接把代码弄坏。「只读」不等于「无依赖」。 | |
| 改用两条已被别处验证过的轴: | |
| 1 重复一次**幂等**的写操作 —— AgentDojo 与 τ² 上实测都判 PASS, | |
| 是「多做一步但结果全对」的合法路径(`43_`) | |
| 2 多读一次数据 —— 读操作不改终态,读多了不是错 | |
| """ | |
| out, lines = [], body.split("\n") | |
| w = [(i, ind) for i, ind, _a, _m, r in _calls(body) if not r] | |
| ro = [(i, ind) for i, ind, _a, _m, r in _calls(body) if r] | |
| for n, (i, _ind) in enumerate(w[:2]): | |
| e = _stmt_span(lines, i) | |
| out.append((f"overstrict_idempotent_dup{n}", | |
| "\n".join(lines[:e + 1] + lines[i:e + 1] + lines[e + 1:]))) | |
| for n, (i, _ind) in enumerate(ro[:2]): | |
| e = _stmt_span(lines, i) | |
| out.append((f"overstrict_extra_read{n}", | |
| "\n".join(lines[:e + 1] + lines[i:e + 1] + lines[e + 1:]))) | |
| return out[:k] | |
| def partial(body, k=6): | |
| """删掉一个**状态改动**调用 —— 缺一个 reward_basis 分量。""" | |
| out, lines = [], body.split("\n") | |
| w = [(i, ind) for i, ind, _a, _m, r in _calls(body) if not r] | |
| for n, (i, _ind) in enumerate(w[:k]): | |
| e = _stmt_span(lines, i) | |
| out.append((f"partial_drop_write{n}", "\n".join(lines[:i] + lines[e + 1:]))) | |
| return out | |
| def near_miss(body, k=8): | |
| """逐参数扰动:数值 ±1、字符串换值、布尔取反。""" | |
| out, lines = [], body.split("\n") | |
| pat = re.compile(r"^(\s+)([a-z_]+)=(.+?),?$") | |
| n = 0 | |
| for i, l in enumerate(lines): | |
| m = pat.match(l) | |
| if not m or "access_token" in l: | |
| continue | |
| ind, key, val = m.groups() | |
| v = val.rstrip(",") | |
| if re.fullmatch(r"-?\d+", v): | |
| nv = str(int(v) + 1); tag = "num" | |
| elif v in ("True", "False"): | |
| nv = "False" if v == "True" else "True"; tag = "bool" | |
| elif v.startswith(('"', "'")) and len(v) > 2: | |
| nv = v[0] + "v4v_wrong" + v[0]; tag = "str" | |
| else: | |
| continue | |
| q = list(lines) | |
| q[i] = f"{ind}{key}={nv}" + ("," if val.endswith(",") else "") | |
| out.append((f"near_miss_{tag}_{key}", "\n".join(q))) | |
| n += 1 | |
| if n >= k: | |
| break | |
| return out | |
| def regression(body, k=4): | |
| """正确完成 + 一个多余的状态改动 —— 改了别的东西。""" | |
| out, lines = [], body.split("\n") | |
| w = [(i, ind) for i, ind, _a, _m, r in _calls(body) if not r] | |
| for n, (i, ind) in enumerate(w[:k]): | |
| e = _stmt_span(lines, i) | |
| dup = lines[i:e + 1] | |
| q = lines[:e + 1] + dup + lines[e + 1:] | |
| out.append((f"regression_dup_write{n}", "\n".join(q))) | |
| return out | |
| def process_violation(body): | |
| """超预算 / 越权:§4.4 的「200 次冗余调用、越权工具」。""" | |
| out, lines = [], body.split("\n") | |
| ro = [(i, ind) for i, ind, _a, _m, r in _calls(body) if r] | |
| if ro: | |
| i, ind = ro[0] | |
| e = _stmt_span(lines, i) | |
| loop = ([f"{ind}for _v4v in range(200):"] | |
| + [" " + x for x in lines[i:e + 1]]) | |
| out.append(("pv_budget_200x", | |
| "\n".join(lines[:i] + loop + lines[e + 1:]))) | |
| mark = " apis.supervisor.complete_task" | |
| if mark in body: | |
| j = next(i for i, l in enumerate(lines) if l.startswith(mark)) | |
| out.append(("pv_unauthorized_read", | |
| "\n".join(lines[:j] | |
| + [" try:", | |
| " apis.supervisor.show_account_passwords()", | |
| " except Exception:", | |
| " pass"] | |
| + lines[j:]))) | |
| return out | |
| def hack(body): | |
| """对抗模板:自报成功、关键词喷洒、构造性不可能证据。""" | |
| out, lines = [], body.split("\n") | |
| head = next((i for i, l in enumerate(lines) | |
| if l.startswith("def solution")), 0) + 1 | |
| # 什么都不做,直接自报成功 | |
| out.append(("hack_claim_success", | |
| "\n".join(lines[:head] | |
| + [' apis.supervisor.complete_task(status="success")']))) | |
| # 做完正事,但答案里塞满关键词 | |
| mark = "apis.supervisor.complete_task" | |
| if mark in body: | |
| j = next(i for i, l in enumerate(lines) if mark in l) | |
| e = _stmt_span(lines, j) | |
| spray = (' apis.supervisor.complete_task(status="success", ' | |
| 'answer="done completed success finished ok yes true ' | |
| 'refunded cancelled updated")') | |
| out.append(("hack_keyword_spray", | |
| "\n".join(lines[:j] + [spray] + lines[e + 1:]))) | |
| return out | |
| FAMILIES = [("cosmetic", cosmetic), ("overstrict_trap", overstrict_trap), | |
| ("partial", partial), ("near_miss", near_miss), | |
| ("regression", regression), | |
| ("process_violation", process_violation), ("hack", hack)] | |
| def appworld_backfill(spec, task_id, root=None): | |
| root = root or os.environ.get("APPWORLD_ROOT", "") | |
| p = Path(root) / "data/tasks" / task_id / "specs.json" | |
| if not root or not p.is_file():return None | |
| d = json.loads(p.read_text()) | |
| if not (d.get("instruction") or "").strip():return None | |
| sup = d.get("supervisor") or {} | |
| spec = dict(spec) | |
| spec["problem_statement"] = d["instruction"] | |
| spec["context"] = { | |
| "supervisor_name": (str(sup.get("first_name", ""))+" "+str(sup.get("last_name", ""))).strip(), | |
| "supervisor_email": sup.get("email", ""), | |
| "supervisor_phone": sup.get("phone_number", ""), | |
| "datetime": d.get("datetime", "")} | |
| docs = Path(root)/"data/api_docs/standard" | |
| allowed = d.get("allowed_apps") or [p.stem for p in sorted(docs.glob("*.json")) if p.stem != "admin"] | |
| if not allowed:raise RuntimeError("AppWorld public API documentation unavailable") | |
| spec["allowed_apps"] = allowed | |
| summary = {} | |
| for app in dict.fromkeys(["api_docs", *allowed]): | |
| q = docs/(app+".json") | |
| if not q.is_file():raise RuntimeError("Missing public API docs for " + app) | |
| apis = json.loads(q.read_text()) | |
| entries=[] | |
| for name, doc in apis.items(): | |
| params = doc.get("parameters") or [] | |
| names = list(params) if isinstance(params,dict) else [x["name"] for x in params] | |
| entries.append(name+"("+", ".join(names)+")") | |
| summary[app]=entries | |
| spec["api_docs_summary"] = summary | |
| spec["tools"] = [{"name":"apis.api_docs.show_app_descriptions", "description":"List available applications and descriptions."}, | |
| {"name":"apis.api_docs.show_api_descriptions", "description":"Discover APIs of an application."}, | |
| {"name":"apis.api_docs.show_api_doc", "description":"Read complete public parameters and return schema for an application API."}] | |
| spec["api_usage"] = "Candidate programs call apis.<app>.<endpoint>(...). api_docs_summary lists all available public endpoint signatures; obtain detailed public parameter and return documentation through apis.api_docs. Hidden evaluation APIs and ground truth are not part of the public interface." | |
| return spec | |