judge.py

acceptance/grader/judge.py

Every string a judge ever sees is built here, so blindness is auditable in one place.

anonymise

str acceptance.grader.judge.anonymise(str answer)

Strip arm, model and run identity from an answer before judging.

acceptance/grader/judge.py:163

Show on the map →

Called by cmd_run, main, score_question, test_anonymise_strips_arm_identity

Calls none

Source · 18 lines
def anonymise(answer: str) -> str:
    """An answer leaks its arm three ways: the runner's header line, a tool-named call, and the
    words "index arm" / "baseline arm" in its own prose.

    WHAT IS NOT SCRUBBED is an answer's own prose about HOW it found something ("the index does
    not resolve that"). Removing it would edit the evidence being judged. That residual leak is
    a stated limitation, not a silent one.

    @brief Remove arm identity.
    @return Anonymised answer.
    @version 1
    """
    text = _HEADER.sub("", answer)
    text = _TOOL.sub(r"a \1 lookup", text)
    text = _GAPS.sub(r"\1Gaps", text)
    return _ARM.sub("this approach", text).strip()

Activity · 4 steps
lines 175–175text = _HEADER.sub("", answer)lines 176–176text = _TOOL.sub(r"a \1 lookup", text)lines 177–177text = _GAPS.sub(r"\1Gaps", text)lines 178–178return _ARM.sub("this approach", text).strip()

Flows

ask

Reply acceptance.grader.judge.ask(str prompt, str model, int timeout=DEFAULT_TIMEOUT, int sample=0)

Version 3 takes sample , so the samples of one vote are cached as distinct calls.

acceptance/grader/judge.py:299

Show on the map →

Called by cmd_run, score_set, test_a_capacity_refusal_is_raised_not_retried, test_a_different_prompt_or_model_is_judged_separately, test_a_failure_is_not_cached, test_a_repeated_call_replays_the_first_verdict, test_a_slow_failure_keeps_the_long_backoff, test_an_instant_failure_backs_off_briefly, test_ask_closes_stdin, test_ask_records_stdout_when_stderr_is_empty, test_ask_retries_transient_failures_but_not_a_missing_binary, test_disabling_the_cache_judges_afresh

2 moretest_the_first_sample_replays_an_entry_written_before_samples_were_keyed, vote

Calls _cache_entry, _is_account_limit, _took_no_api_time

Source · 103 lines
def ask(prompt: str, model: str, timeout: int = DEFAULT_TIMEOUT, sample: int = 0) -> Reply:
    """Tool-less and fresh every call, which is what makes repeated calls a variance measurement
    rather than a conversation.

    A timeout and a malformed reply stay distinguishable in the record: they cost a reviewer
    very different things, and lumping them together is how marks the judge never ruled on once
    got counted as failures.

    @brief One judge call.
    @return Reply.
    @version 4
    """
    argv = [
        "claude",
        "-p",
        prompt,
        "--model",
        model,
        "--output-format",
        "json",
        "--allowedTools",
        "",
    ]
    ## RETRIED WITH BACKOFF, because the observed failure is TRANSIENT CAPACITY rather than a
    ## broken call. Measured: three cells came back 85-100% unruled — EVERY call failing, not
    ## some — and the identical call succeeded minutes later with no code change. A judge that
    ## degrades under sustained load gets worse exactly as a grid gets bigger, which is when
    ## unruled marks do the most damage.
    ##
    ## Bounded rather than indefinite: a genuinely broken invocation must still surface as an
    ## error instead of hanging a run. A missing binary is not retried at all, since it will not
    ## fix itself and would burn the whole budget.
    entry = _cache_entry(prompt, model, sample)
    if entry is not None and entry.is_file():
        try:
            ## A CACHED ERROR IS NEVER REPLAYED. Only verdicts are stored, so a transient capacity
            ## failure cannot become permanent — it retries on the next pass, as it should.
            return Reply(text=str(json.loads(entry.read_text("utf-8"))["text"]))
        except (OSError, ValueError, KeyError):
            pass

    last = Reply(error="no attempt made")
    fast = False
    for attempt in range(ASK_ATTEMPTS):
        if attempt:
            time.sleep((FAST_BACKOFF_SECONDS if fast else ASK_BACKOFF_SECONDS) * attempt)
        try:
            ## STDIN EXPLICITLY CLOSED. The CLI warns "no stdin data received in 3s,
            ## proceeding without it" when it inherits an idle stdin, and the same call
            ## measured 8.9s with stdin inherited against 3.4s from /dev/null. A COST fix,
            ## not a correctness one — stdin was tested as a suspect for the rc=1 failures
            ## and cleared, both forms succeed. But this grid makes ~2,244 judge calls, so a
            ## few seconds each is hours of a grade spent waiting for input that never comes.
            done = subprocess.run(
                argv,
                capture_output=True,
                text=True,
                timeout=timeout,
                check=False,
                stdin=subprocess.DEVNULL,
            )
        except subprocess.TimeoutExpired as exc:
            last = Reply(error=f"timeout after {timeout}s: {exc}")
            continue
        except OSError as exc:
            return Reply(error=f"transport: {exc}")
        if done.returncode != 0:
            ## STDOUT TOO, NOT JUST STDERR. Measured on the weekend grid: seven cells recorded
            ## "rc=1 after 3 attempt(s):" with NOTHING after the colon, because the CLI puts its
            ## explanation on stdout and only the empty stderr was kept. A recorded reason that
            ## says only "it failed" is the tally this field replaced.
            whole = f"{done.stderr}\n{done.stdout}"
            if _is_account_limit(whole):
                raise JudgeCapacityError(
                    f"the judge is out of capacity, so this pass would record holes rather "
                    f"than verdicts:\n{whole.strip()[:300]}\n"
                    f"Nothing is wrong with the rubric or the answers. Wait for capacity and "
                    f"re-run `grade` — grading is additive, so the passes already written stand "
                    f"and the rest fill in."
                )
            ## A ZERO-DURATION FAILURE NEVER REACHED THE SERVER, so the next attempt comes
            ## quickly; a call that took real time and failed is worth the long wait.
            fast = _took_no_api_time(done.stdout)
            detail = (done.stderr.strip() or done.stdout.strip())[:300]
            last = Reply(error=f"rc={done.returncode} after {attempt + 1} attempt(s): {detail}")
            continue
        try:
            reply = Reply(text=str(json.loads(done.stdout).get("result") or ""))
            if entry is not None:
                ## WRITTEN ONLY ON SUCCESS, and tolerantly: a cache that cannot be written must
                ## not fail a grading pass that otherwise worked.
                try:
                    entry.write_text(
                        json.dumps({"model": model, "text": reply.text}, indent=2), "utf-8"
                    )
                except OSError:
                    pass
            return reply
        except (json.JSONDecodeError, AttributeError) as exc:
            last = Reply(error=f"unparseable envelope: {exc}")
    return last

Activity · 38 steps
lines 311–321argv = [ "claude", "-p", prompt, "--model", model, "--output-format", "json", "--allowedTools", "", ]lines 331–331entry = _cache_entry(prompt, model, sample)lines 332–332◇ if entry is not None and entry.is_file()lines 333–333trylines 336–336return Reply(text=str(json.loads(entry.read_text("utf-8"))["text"]))lines 337–337except (OSError, ValueError, KeyError)lines 338–338passlines 340–340last = Reply(error="no attempt made")lines 341–341fast = Falselines 342–342◇ for attempt in range(ASK_ATTEMPTS)lines 343–343◇ if attemptlines 344–344time.sleep((FAST_BACKOFF_SECONDS if fast else ASK_BACKOFF_SECONDS) * attempt)lines 345–345trylines 352–359done = subprocess.run( argv, capture_output=True, text=True, timeout=timeout, check=False, stdin=subprocess.DEVNULL, )lines 360–360except subprocess.TimeoutExpired as exclines 361–361last = Reply(error=f"timeout after {timeout}s: {exc}")lines 362–362continuelines 363–363except OSError as exclines 364–364return Reply(error=f"transport: {exc}")lines 365–365◇ if done.returncode != 0lines 370–370whole = f"{done.stderr}\n{done.stdout}"lines 371–371◇ if _is_account_limit(whole)lines 372–378raise JudgeCapacityError( f"the judge is out of capacity, so this pass would record holes rather " f"than verdicts:\n{whole.strip()[:300]}\n" f"Nothing is wrong with the rubric or the answers. Wait for capacity and " f"re-run `grade` — grading is additive, so the passes already written stand " f"and the rest fill in." )lines 381–381fast = _took_no_api_time(done.stdout)lines 382–382detail = (done.stderr.strip() or done.stdout.strip())[:300]lines 383–383last = Reply(error=f"rc={done.returncode} after {attempt + 1} attempt(s): {detail}")lines 384–384continuelines 385–385trylines 386–386reply = Reply(text=str(json.loads(done.stdout).get("result") or ""))lines 387–387◇ if entry is not Nonelines 390–390trylines 391–393entry.write_text( json.dumps({"model": model, "text": reply.text}, indent=2), "utf-8" )lines 394–394except OSErrorlines 395–395passlines 396–396return replylines 397–397except (json.JSONDecodeError, AttributeError) as exclines 398–398last = Reply(error=f"unparseable envelope: {exc}")lines 399–399return last

Flows

read_verdict

str | None acceptance.grader.judge.read_verdict(str text)

Pull the verdict token out of a judge reply.

acceptance/grader/judge.py:485

Show on the map →

Called by cmd_run, test_ask_retries_transient_failures_but_not_a_missing_binary, test_read_verdict_takes_the_last_line, vote

Calls none

Source · 15 lines
def read_verdict(text: str) -> str | None:
    """Takes the LAST `VERDICT:` line. A judge that shows a verdict and then revises it has
    revised it; taking the first would score the discarded one.

    @brief Extract a verdict.
    @return Token or None.
    @version 1
    """
    found = re.findall(r"^\s*VERDICT:\s*([A-Z_]+)\s*$", text, re.MULTILINE)
    if not found:
        return None
    token = found[-1].strip().upper()
    return token if token in VERDICTS else None

Activity · 5 steps
lines 493–493found = re.findall(r"^\s*VERDICT:\s*([A-Z_]+)\s*$", text, re.MULTILINE)lines 494–494◇ if not foundlines 495–495return Nonelines 496–496token = found[-1].strip().upper()lines 497–497return token if token in VERDICTS else None

Flows

verdict_prompt

str acceptance.grader.judge.verdict_prompt(str mark_text, str answer)

Build the per-mark verdict prompt.

acceptance/grader/judge.py:407

Show on the map →

Called by cmd_run, main, test_verdict_prompt_carries_only_the_mark_and_the_answer, vote

Calls none

Source · 41 lines
def verdict_prompt(mark_text: str, answer: str) -> str:
    """QUOTE COMES BEFORE VERDICT, and that order is load-bearing. Asked for the verdict first,
    a judge commits and only then produces evidence, with no retrieval step in between — which
    is how a reply reads `VERDICT: MISS / QUOTE: NONE` against text sitting in the paragraph it
    was grading.

    @brief Verdict prompt.
    @return Prompt.
    @version 1
    """
    width = max(len(v) for v in VERDICTS)
    rules = "\n".join(f"{v:<{width}} — {_RULES[v]}" for v in VERDICTS)
    return f"""You are grading ONE checklist item from a frozen grading key against a candidate
answer about a software codebase. You have NO access to the codebase; judge only whether the
ANSWER demonstrates the item. Do not reward the answer for being good in general — judge THIS
item and nothing else.

CHECKLIST ITEM:
{mark_text}

CANDIDATE ANSWER:
<<<ANSWER
{answer}
ANSWER>>>

Verdicts:
{rules}

SEARCH THE ANSWER FIRST, THEN DECIDE — in that order. Scan the whole answer, including its
tables, bullets, headings and parenthetical asides, for the substance of the item. Write the
quote down BEFORE you settle the verdict. If you find the substance the verdict is HIT and you
must not then talk yourself out of it on grounds of wording, prominence or arrangement.
QUOTE: NONE with VERDICT: HIT is a contradiction; so is quoting the item's substance and then
answering MISS.

Reply with EXACTLY ONE of these blocks, as the LAST thing in your reply:
QUOTE: <short verbatim quote from the answer carrying the item's substance, or NONE>
VERDICT: <one of {", ".join(VERDICTS)}>
WHY: <one line>"""

Activity · 3 steps
lines 417–417width = max(len(v) for v in VERDICTS)lines 418–418rules = "\n".join(f"{v:<{width}} — {_RULES[v]}" for v in VERDICTS)lines 419–445return f"""You are grading ONE checklist item from a frozen grading key against a candidate answer about a software codebase. You have NO access to the codebase; judge only whether the ANSWER demonstrates the item. Do not reward the answer for being good in general — judge THIS item and nothing else. CHECKLIST ITEM: {mark_text} CANDIDATE ANSWER: <<<ANSWER {answer} ANSWER>>> Verdicts: {rules} SEARCH THE ANSWER FIRST, THEN DECIDE — in that order. Scan the whole answer, including its tables, bullets, headings and parenthetical asides, for the substance of the item. Write the quote down BEFORE you settle the verdict. If you find the substance the verdict is HIT and you must not then talk yourself out of it on grounds of wording, prominence or arrangement. QUOTE: NONE with VERDICT: HIT is a contradiction; so is quoting the item's substance and then answering MISS. Reply with EXACTLY ONE of these blocks, as the LAST thing in your reply: QUOTE: <short verbatim quote from the answer carrying the item's substance, or NONE> VERDICT: <one of {", ".join(VERDICTS)}> WHY: <one line>"""

Flows