star_v1 / scripts /star /eval /_common.py
pourasrp's picture
STAR v1 release
c921540 verified
Raw History Blame Contribute Delete
22.8 kB
"""Shared constants and helpers for the STAR evaluation tools (star/eval/).
NOTHING in here tokenizes, renders a chat or truncates: that is star/scoring/tokenize_common.py and only
that file (charter rule 4). This module only CALLS it (`get_tokenizer`, `encode_ids`).
PRE-DECLARED EVALUATION CONSTANTS (written 2026-10-09 BEFORE any rollout exists; charter rule 8).
They are recorded in every RUN_MANIFEST. Changing one after a result has been read invalidates the run.
Items marked PROPOSED were chosen by the builder, not by the user, and need the user's ratification
before the first real rollout is read.
"""
from __future__ import annotations
import hashlib
import importlib.util
import json
import os
import re
import sys
import time
import types
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1] # project root (contains star/)
STAR = ROOT / "star"
SPLIT_DIR = STAR / "labelling" / "split"
VERIFIED_MINI_JSON = SPLIT_DIR / "verified_mini_canonical.json"
TIER2_IDS = SPLIT_DIR / "tier2_nll_ids.txt"
TIER2_IDS_SHA = SPLIT_DIR / "tier2_nll_ids.sha256"
TIER2_FULL_IDS = SPLIT_DIR / "tier2_full_ids.txt" # user 2026-10-11 (plan.md GATE OUTCOME RULING item 5): the evaluated set; TIER2_IDS is its reported 100-id subset
TIER2_FULL_IDS_SHA = SPLIT_DIR / "tier2_full_ids.sha256"
DETECTOR_PATH = STAR / "detector" / "detector.py"
FROZEN_DETECTOR_SHA = "379909386b67c2891173c96554956f540cb765c577f4161e60592a6f72dca033" # v3, plan.md
RESULTS_DIR = STAR / "artifacts" / "results"
sys.path.insert(0, str(STAR / "scoring")) # tokenize_common
# ----------------------------------------------------------------------------- pre-declared constants
ARMS = ("A0", "A1", "A2", "A4", "A5", "A5-corr") # plan.md "RESUME + USER INSTRUCTIONS 2026-10-11" item 1
SEEDS = (42,) # RATIFIED 2026-10-09: seed 42 for all arms. 43/44 are opt-in (--seeds 42 43 44) only if a second-seed round is funded
OPTIONAL_SEEDS = (43, 44)
# TURN_CAP is deliberately NOT a constant: NOT ratified. tier1_rollout.py --turn-cap is required and recorded in the manifest.
PROMPT_MAX_LENGTH = 16384 # = training window (head 2048 + tail 14336) via tokenize_common.encode_prompt
MAX_NEW_TOKENS = 2048 # RATIFIED 2026-10-09. per assistant turn
MIN_MAX_MODEL_LEN = PROMPT_MAX_LENGTH + MAX_NEW_TOKENS # vLLM must be launched with --max-model-len >= this (18432)
SAMPLING = {"temperature": 0.7, "top_p": 0.8, "top_k": 20} # RATIFIED 2026-10-09
STOP = ["</function>"] # one tool call per turn (SWE-Lego preamble: "Only call one function at a time")
OBS_MAX_CHARS = 8000 # RATIFIED 2026-10-09. middle-clip of tool output
CMD_TIMEOUT_DEFAULT, CMD_TIMEOUT_MAX = 120, 600
REPO_DIR = "/testbed" # SWE-bench instance images keep the repo here (SWE-Lego used /workspace/<repo>__<ver>)
PY_INTERP = "/opt/miniconda3/envs/testbed/bin/python"
CONDA_ACTIVATE = "source /opt/miniconda3/bin/activate && conda activate testbed && "
HUMANEVALFIX_SEED = 42 # greedy (temperature 0); the seed is recorded, not used for sampling
HUMANEVALFIX_MAX_NEW = 1024
T1_STRINGS_FILE = HERE / "t1_rejection_strings.json"
TIER1_DISCLOSURE = "chroot runner, no network namespace; outbound attempts audited by trajectory scan." # beside EVERY Tier-1 table/number (user 2026-10-10)
# The runner's name, exactly as the user pre-declared it (2026-10-10). Used in every Tier-1 table header and manifest.
RUNNER_NAME = "a minimal bash+editor agent loop modelled on mini-SWE-agent (ours; not the upstream package)"
RUNNER_FILES = ("tier1_rollout.py", "_tools.py")
RUNNER_FILES_CHROOT = ("chroot_runtime.py", "chroot_grade.py")
def runner_hashes(chroot: bool) -> dict:
"""sha256 of the runner code, computed NOW (at run time): tier1_rollout.py and _tools.py always; chroot_runtime.py and
chroot_grade.py when the chroot runner is used."""
names = RUNNER_FILES + (RUNNER_FILES_CHROOT if chroot else ())
return {n: sha256_file(HERE / n) for n in names}
def uses_chroot(rollout_root=None, grade_dir=None) -> bool:
"""True iff the Tier-1 numbers come from the chroot runner: a RUN_MANIFEST with env_runner.kind == 'chroot' under the
rollout root, or a CHROOT_RUN_MANIFEST.json under the grade dir."""
if rollout_root and Path(rollout_root).exists():
for p in Path(rollout_root).glob("*/seed*/RUN_MANIFEST.json"):
try:
if ((json.loads(p.read_text(encoding="utf-8")).get("env_runner") or {}).get("kind")) == "chroot":
return True
except (ValueError, OSError):
pass
return bool(grade_dir and Path(grade_dir).exists() and any(Path(grade_dir).glob("*/work/CHROOT_RUN_MANIFEST.json")))
def tier1_footer(chroot: bool) -> list[str]:
"""The lines printed under EVERY Tier-1 table: runner name, the network disclosure, and the runner-code hashes."""
h = runner_hashes(chroot)
return [f"runner: {RUNNER_NAME}", TIER1_DISCLOSURE,
"runner code sha256 (computed at run time): " + "; ".join(f"{k}={v}" for k, v in h.items())]
def tier1_meta(chroot: bool) -> dict:
return {"runner_name": RUNNER_NAME, "runner_sha256": runner_hashes(chroot), "tier1_disclosure": TIER1_DISCLOSURE,
"chroot_runner": chroot}
SCAFFOLD_MISMATCH = (
"MISMATCH RECORDED (plan.md sprint item 5): SWE-Lego's published 42.2% Verified used the OpenHands scaffold; "
f"this evaluation uses {RUNNER_NAME} (star/eval/tier1_rollout.py: bash + str_replace_editor tools, "
"SWE-Lego tool-call text format). Resolve rates here are NOT comparable to 42.2%. Additionally the eval "
"prompt is not the training prompt (P1 limitation): same stub system message and same task-prompt structure, "
"but repo path /testbed instead of /workspace/<repo>__<ver>, one tool call per turn enforced by a stop "
"sequence, tool-observation strings re-implemented by this harness.")
STUB_TASK_TEMPLATE = """<uploaded_files>
{repo_path}
</uploaded_files>
I've uploaded a python code repository in the directory {repo_path}. Consider the following issue description:
<issue_description>
{issue}
</issue_description>
Can you help me implement the necessary changes to the repository so that the requirements specified in the <issue_description> are met?
I've already taken care of all changes to any of the test files described in the <issue_description>. This means you DON'T have to modify the testing logic or any of the tests in any way!
Also the development Python environment is already set up for you (i.e., all dependencies already installed), so you don't need to install other packages.
Your task is to make the minimal changes to non-test files in the {repo_path} directory to ensure the <issue_description> is satisfied.
Follow these phases to resolve the issue:
Phase 1. READING: read the problem and reword it in clearer terms
1.1 If there are code or config snippets. Express in words any best practices or conventions in them.
1.2 Hightlight message errors, method names, variables, file names, stack traces, and technical details.
1.3 Explain the problem in clear terms.
1.4 Enumerate the steps to reproduce the problem.
1.5 Hightlight any best practices to take into account when testing and fixing the issue
Phase 2. RUNNING: install and run the tests on the repository
2.1 Follow the readme
2.2 Install the environment and anything needed
2.2 Iterate and figure out how to run the tests
Phase 3. EXPLORATION: find the files that are related to the problem and possible solutions
3.1 Use `grep` to search for relevant methods, classes, keywords and error messages.
3.2 Identify all files related to the problem statement.
3.3 Propose the methods and files to fix the issue and explain why.
3.4 From the possible file locations, select the most likely location to fix the issue.
Phase 4. TEST CREATION: before implementing any fix, create a script to reproduce and verify the issue.
4.1 Look at existing test files in the repository to understand the test format/structure.
4.2 Create a minimal reproduction script that reproduces the located issue.
4.3 Run the reproduction script to confirm you are reproducing the issue.
4.4 Adjust the reproduction script as necessary.
Phase 5. FIX ANALYSIS: state clearly the problem and how to fix it
5.1 State clearly what the problem is.
5.2 State clearly where the problem is located.
5.3 State clearly how the test reproduces the issue.
5.4 State clearly the best practices to take into account in the fix.
5.5 State clearly how to fix the problem.
Phase 6. FIX IMPLEMENTATION: Edit the source code to implement your chosen solution.
6.1 Make minimal, focused changes to fix the issue.
Phase 7. VERIFICATION: Test your implementation thoroughly.
7.1 Run your reproduction script to verify the fix works.
7.2 Add edge cases to your test script to ensure comprehensive coverage.
7.3 Run existing tests related to the modified code to ensure you haven't broken anything.
8. FINAL REVIEW: Carefully re-read the problem description and compare your changes with the base commit {base_commit}.
8.1 Ensure you've fully addressed all requirements.
8.2 Run any tests in the repository related to:
8.2.1 The issue you are fixing
8.2.2 The files you modified
8.2.3 The functions you changed
8.3 If any tests fail, revise your implementation until all tests pass
Be thorough in your exploration, testing, and reasoning. It's fine if your thinking process is lengthy - quality and completeness are more important than brevity."""
# ----------------------------------------------------------------------------- small utilities
def sha256_file(p: str | Path) -> str:
h = hashlib.sha256()
with open(p, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def sha256_text(s: str) -> str:
return hashlib.sha256(s.encode("utf-8")).hexdigest()
def write_json_atomic(path: str | Path, obj: Any) -> None:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(obj, indent=1, ensure_ascii=False, sort_keys=True), encoding="utf-8")
os.replace(tmp, path)
def now_utc() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def script_hashes() -> dict[str, str]:
"""Hashes of every star/eval/*.py and of the two upstream files this package depends on."""
out = {p.name: sha256_file(p) for p in sorted(HERE.glob("*.py"))}
out["tokenize_common.py"] = sha256_file(STAR / "scoring" / "tokenize_common.py")
out["detector.py"] = sha256_file(DETECTOR_PATH)
return out
def swebench_image(instance_id: str) -> str:
"""Public per-instance image on Docker Hub (namespace `swebench`; '__' -> '_1776_'), as the swebench
harness (namespace=swebench) names them."""
return f"docker.io/swebench/sweb.eval.x86_64.{instance_id.replace('__', '_1776_')}:latest".lower()
def mini_ids() -> list[str]:
ids = json.loads(VERIFIED_MINI_JSON.read_text())["instance_ids"]
assert len(ids) == 50 and len(set(ids)) == 50
return ids
# ----------------------------------------------------------------------------- tokenizer (the ONE path)
def get_tokenizer(test_tokenizer_dir: str | None = None):
"""Return (tok, info). Real runs: tokenize_common.load_tokenizer() (pinned Qwen3-8B revision, local cache).
`test_tokenizer_dir` is for the LOCAL TESTS ONLY (a tiny fixture tokenizer with a Qwen-style template); the
info dict then says kind='TEST_FIXTURE' and every manifest carries it, so a fixture can never pass as real."""
import tokenize_common as tc
if test_tokenizer_dir:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(test_tokenizer_dir)
assert tok.is_fast and tok.chat_template
return tok, {"kind": "TEST_FIXTURE", "dir": str(test_tokenizer_dir),
"tokenizer.json_sha256": sha256_file(Path(test_tokenizer_dir) / "tokenizer.json"),
"chat_template_sha256": sha256_text(tok.chat_template)}
if Path("/home/jl_fs/hf_cache").exists(): # same cache convention as star/scoring/score_base_loss.py
os.environ.setdefault("HF_HOME", "/home/jl_fs/hf_cache")
os.environ.setdefault("HF_HUB_OFFLINE", "1")
tok = tc.load_tokenizer()
info = {"kind": "REAL"}
info.update(tc.tokenizer_fingerprint(tok))
return tok, info
def encode_prompt_ids(messages, tok, max_length: int = PROMPT_MAX_LENGTH) -> list[int]:
"""Inference-side prompt: tokenize_common.encode_prompt (stub system, official template + generation prompt,
head+tail RIGHT-END-KEEPING truncation)."""
import tokenize_common as tc
return [int(x) for x in tc.encode_prompt(messages, tok, max_length)]
# ----------------------------------------------------------------------------- frozen detector
_DET: dict[str, Any] = {}
def load_detector():
"""Import star/detector/detector.py by path, after asserting its sha256 == the frozen v3 hash. Never edited.
The file imports pyarrow at top level but only uses it in load_real_resolved()/main(); if pyarrow is not
installed (this laptop) a placeholder module is registered so the import succeeds. Recorded in
`pyarrow_stubbed` (no detector function we call touches it)."""
if "mod" in _DET:
assert_detector_unchanged()
return _DET["mod"]
assert_detector_unchanged()
stubbed = False
try:
import pyarrow # noqa: F401
except ImportError:
sys.modules["pyarrow"] = types.ModuleType("pyarrow")
stubbed = True
spec = importlib.util.spec_from_file_location("star_frozen_detector", DETECTOR_PATH)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
_DET["mod"], _DET["pyarrow_stubbed"] = mod, stubbed
return mod
def detector_window(det) -> int:
"""The 'within k steps' window of spec S8.2, taken FROM the frozen detector: the `window = N` literal inside
detector.detect_t5 (the detector's own repeat window, 3). The detector has no module-level constant, so the
literal is read from the function source; exactly one match is required. No separate k exists in star/eval."""
import inspect
ms = re.findall(r"^\s*window\s*=\s*(\d+)\s*$", inspect.getsource(det.detect_t5), re.M)
if len(ms) != 1:
raise RuntimeError(f"expected exactly one `window = N` in detector.detect_t5, found {ms}")
return int(ms[0])
def assert_detector_unchanged() -> str:
got = sha256_file(DETECTOR_PATH)
if got != FROZEN_DETECTOR_SHA:
raise RuntimeError(f"detector.py sha256 {got} != frozen {FROZEN_DETECTOR_SHA}; refusing to run")
return got
def detector_info() -> dict[str, Any]:
return {"detector_path": str(DETECTOR_PATH), "detector_sha256": assert_detector_unchanged(),
"frozen_sha256": FROZEN_DETECTOR_SHA, "pyarrow_stubbed": bool(_DET.get("pyarrow_stubbed", False))}
# ----------------------------------------------------------------------------- recovery spans (as in star/probe/expand_run_v3.py)
def extract_events(det, messages: list[dict], extra: list[dict] | None = None) -> dict[str, Any]:
"""Run the frozen detectors and build recovery spans with EXACTLY the rule of star/probe/expand_run_v3.py
(the code that produced events.jsonl): failure turn = the observation turn (T6: the correction turn);
span_start = next assistant turn after it; span_end = last assistant turn before the next failure of ANY type
that lies after span_start, else the last assistant turn. Turn numbers are the detector's (build_turns).
Events without an assistant turn after the signal have no span: listed in `no_span`, never dropped silently."""
result = det.detect_all(messages)
turns, m2t = det.build_turns(messages)
asst = [t["turn"] for t in turns if t["label"] == "assistant"]
turn2msg = {t["turn"]: t["msg_index"] for t in turns}
raw = []
skipped = 0
for typ, evs in result.items():
for e in evs:
if typ == "T6":
a_t, c_t = m2t.get(e["anchor_msg"]), m2t.get(e["correction_msg"])
if a_t is None or c_t is None:
skipped += 1
continue
raw.append({"type": typ, "failure_turn": c_t, "anchor_turn": a_t})
else:
o_t = m2t.get(e["obs_msg"])
if o_t is None:
skipped += 1
continue
raw.append({"type": typ, "failure_turn": o_t, "anchor_turn": o_t})
for e in extra or []: # events of a type the frozen detector does not have (T1, only if confirmed): {type, obs_msg}
o_t = m2t.get(e["obs_msg"])
if o_t is None:
skipped += 1
else:
raw.append({"type": e["type"], "failure_turn": o_t, "anchor_turn": o_t})
raw.sort(key=lambda r: (r["failure_turn"], r["type"]))
fail_turns = sorted(r["failure_turn"] for r in raw)
events, no_span = [], []
for r in raw:
after = [t for t in asst if t > r["failure_turn"]]
if not after:
no_span.append(r)
continue
s0 = after[0]
later = [x for x in fail_turns if x > s0]
if later:
before = [t for t in asst if t < min(later)]
s1 = before[-1] if before else s0
else:
s1 = asst[-1]
if s1 < s0:
s1 = s0
events.append({**r, "span_start": s0, "span_end": s1,
"span_start_msg": turn2msg[s0], "span_end_msg": turn2msg[s1]})
return {"events": events, "no_span": no_span, "skipped_unmapped": skipped,
"fail_turns": fail_turns, "assistant_turns": asst, "turns": turns, "turn2msg": turn2msg}
# ----------------------------------------------------------------------------- tool-call parsing (detector's own regexes)
def parse_first_call(text: str) -> tuple[str, dict[str, str]] | None:
"""First `<function=NAME>...</function>` in an assistant message -> (name, params). One leading and one
trailing newline of a parameter value are removed (the preamble's own example shows values written that way)."""
det = load_detector()
m = det.TOOL_CALL_RE.search(text)
if not m:
return None
params = {}
for k, v in det.PARAM_RE.findall(m.group(2)):
if v.startswith("\n"):
v = v[1:]
if v.endswith("\n"):
v = v[:-1]
params[k] = v
return m.group(1), params
def normalise_ws(s: str) -> str:
return " ".join(s.split())
# ----------------------------------------------------------------------------- vLLM OpenAI-compatible client
class EndpointError(RuntimeError):
pass
def complete(endpoint: str, model: str, prompt_ids: list[int], *, max_tokens: int, seed: int | None,
sampling: dict[str, float], stop: list[str] | None, retries: int = 3, timeout: float = 900.0) -> dict:
"""POST {endpoint}/completions with a TOKEN-ID prompt (so tokenization is exactly tokenize_common's). Returns
{text, finish_reason, completion_tokens, prompt_tokens}. Raises EndpointError after `retries` failures; the
caller records the task as errored (a missing run is reported missing, never filled)."""
body: dict[str, Any] = {"model": model, "prompt": prompt_ids, "max_tokens": max_tokens, **sampling}
if seed is not None:
body["seed"] = int(seed)
if stop:
body["stop"] = stop
body["include_stop_str_in_output"] = True
data = json.dumps(body).encode()
last = None
for k in range(retries):
try:
req = urllib.request.Request(endpoint.rstrip("/") + "/completions", data=data,
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=timeout) as r:
j = json.loads(r.read())
ch = j["choices"][0]
return {"text": ch["text"], "finish_reason": ch.get("finish_reason"),
"completion_tokens": int(j["usage"]["completion_tokens"]),
"prompt_tokens": int(j["usage"]["prompt_tokens"])}
except (urllib.error.URLError, TimeoutError, KeyError, ValueError, ConnectionError) as e:
last = e
time.sleep(min(2 ** k, 8))
raise EndpointError(f"{endpoint}: {type(last).__name__}: {last}")
# ----------------------------------------------------------------------------- Verified-mini rows
def load_mini_rows(rows_jsonl: str | None = None, require_all: bool | None = None) -> dict[str, dict]:
"""Rows of MariusHobbhahn/swe-bench-verified-mini (problem_statement, base_commit, test_patch, FAIL_TO_PASS,
PASS_TO_PASS, ...) keyed by instance_id; asserts the id set equals the canonical 50-id file.
`rows_jsonl` (tests / offline) bypasses `datasets` and drops the all-50 requirement (require_all defaults to
`not rows_jsonl`); the caller then records the rows file path/sha in its manifest."""
if rows_jsonl:
rows = [json.loads(l) for l in Path(rows_jsonl).read_text(encoding="utf-8").splitlines() if l.strip()]
else:
from datasets import load_dataset
rows = [dict(r) for r in load_dataset("MariusHobbhahn/swe-bench-verified-mini", split="test")]
by = {r["instance_id"]: r for r in rows}
want = set(mini_ids())
if require_all is None:
require_all = not rows_jsonl
if require_all and set(by) != want:
raise RuntimeError(f"verified-mini rows differ from canonical ids: only-rows={sorted(set(by) - want)[:3]} "
f"only-canonical={sorted(want - set(by))[:3]}")
for r in by.values():
for k in ("FAIL_TO_PASS", "PASS_TO_PASS"):
if isinstance(r[k], str):
r[k] = json.loads(r[k])
return by
def build_task_messages(row: dict) -> list[dict]:
import tokenize_common as tc
user = STUB_TASK_TEMPLATE.format(repo_path=REPO_DIR, issue=row["problem_statement"].strip(),
base_commit=row["base_commit"])
assert "EXECUTION RESULT" not in user, "task prompt would be mistaken for an observation by the detector"
return [{"role": "system", "content": tc.STUB_TEXT}, {"role": "user", "content": user}]
def read_manifest_ids(path: Path) -> list[str]:
return [l.strip() for l in Path(path).read_text(encoding="utf-8").splitlines() if l.strip() and not l.startswith("#")]