From 9ee78c138b40c24ca5574366c28429b10e30d9a3 Mon Sep 17 00:00:00 2001 From: Novruz Garryyev Date: Sun, 1 Nov 2026 09:40:17 +0000 Subject: [PATCH 1/4] Add a corpus run that asks the model and grades its answers --- .github/workflows/corpus.yml | 59 +++++++++++ .gitignore | 1 + AGENTS.md | 1 + tests/run_corpus.py | 200 +++++++++++++++++++++++++++++++++++ tests/test_run_corpus.py | 68 ++++++++++++ 5 files changed, 329 insertions(+) create mode 100644 .github/workflows/corpus.yml create mode 100644 tests/run_corpus.py create mode 100644 tests/test_run_corpus.py diff --git a/.github/workflows/corpus.yml b/.github/workflows/corpus.yml new file mode 100644 index 0000000..f958832 --- /dev/null +++ b/.github/workflows/corpus.yml @@ -0,0 +1,59 @@ +name: Corpus run + +# Sends every corpus case to the model and grades the answers. +# Costs API credits, so it runs only when the skill text changes, or by hand. +on: + pull_request: + paths: + - SKILL.md + - references/** + - prompts/** + - scripts/barla.py + - tests/corpus/** + - tests/grade.py + - tests/run_corpus.py + workflow_dispatch: + inputs: + variant: + description: "skill (SKILL.md) or prompt (prompts/system-prompt.md)" + type: choice + options: [skill, prompt] + default: skill + runs: + description: "Answers per case" + default: "3" + +permissions: + contents: read + +concurrency: + group: corpus-${{ github.ref }} + cancel-in-progress: true + +jobs: + corpus: + # Pull requests from forks get no secrets; skip them instead of failing. + if: github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.12" + - name: Install uv + run: python3 -m pip install --quiet uv==0.11.32 + - name: Run the corpus + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + run: >- + uv run --no-project --with anthropic==2.3.0 python tests/run_corpus.py + --variant "${{ inputs.variant || 'skill' }}" + --runs "${{ inputs.runs || '3' }}" + - name: Keep the answers + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: corpus-results + path: corpus-results/ + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index 744c70f..fec6f04 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ __pycache__/ *.zip *.skill humanizer21-prompt.md +corpus-results/ diff --git a/AGENTS.md b/AGENTS.md index bf09377..b19f693 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,6 +30,7 @@ humanizer21 is an agent skill written in Markdown, with one Python checker and a - **Facts.** Examples in the references must never add a fact in the "after" text that the "before" text lacks. - **Checker.** Every new check in `barla.py` gets a test in `tests/test_barla.py`, including a test that correct text stays clean. - **Corpus.** When a rewrite goes wrong in a way the rules should have prevented, add the text to `tests/corpus/` as a new case with `input.txt`, `expected.json` and a corrected `reference.txt`. Run `python3 tests/grade.py` on the skill's next answer before releasing a fix. +- **Model run.** `tests/run_corpus.py` sends every corpus case to the model and grades the answers with `grade.py`; CI runs it (`.github/workflows/corpus.yml`) on pull requests that touch the skill text. Run it before and after a change to `SKILL.md`, `references/` or `prompts/`, and do not merge a change that makes a case fail that passed before. Locally: `uv run --no-project --with anthropic==2.3.0 python tests/run_corpus.py --runs 1`. It costs API credits. - **History.** Add a `CHANGELOG.md` note for any change in behavior. ## Checks before publishing diff --git a/tests/run_corpus.py b/tests/run_corpus.py new file mode 100644 index 0000000..b54d27f --- /dev/null +++ b/tests/run_corpus.py @@ -0,0 +1,200 @@ +"""Run the corpus through a model and grade every answer. + + uv run --with anthropic tests/run_corpus.py # all cases, 3 runs each + uv run --with anthropic tests/run_corpus.py --runs 1 --case olimpiada-habary + python3 tests/run_corpus.py --variant prompt --dry-run # show what would be sent + python3 tests/run_corpus.py --answers DIR # grade saved answers, no API + +The model gets SKILL.md and every file of references/ as its instructions +(or, with --variant prompt, prompts/system-prompt.md plus references/, as a +ChatGPT project would). Each case sends its `request` and `input.txt`. The +finished text is taken from between the markers the harness asks for, so +the list of changes after it is not graded, and checked with tests/grade.py. + +A case passes when at least --need of its --runs answers pass every check. +The script exits with code 1 if any case fails. It needs ANTHROPIC_API_KEY +unless --dry-run or --answers is given. Answers and a report go to --out. +""" + +import argparse +import json +import os +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +CORPUS = os.path.join(HERE, "corpus") +sys.path.insert(0, HERE) +import grade # noqa: E402 + +MODEL = "claude-opus-5-5" +START = "<<\n%s\n" % (first.replace(os.sep, "/"), read(os.path.join(ROOT, first)))] + refs = os.path.join(ROOT, "references") + for name in sorted(os.listdir(refs)): + if name.endswith(".md"): + parts.append("\n%s\n" % (name, read(os.path.join(refs, name)))) + return "\n\n".join(parts) + "\n\n" + HARNESS_NOTE + + +def user_message(case): + exp = json.loads(read(os.path.join(CORPUS, case, "expected.json"))) + return "%s\n\n%s" % (exp["request"], read(os.path.join(CORPUS, case, "input.txt"))) + + +def final_text(answer): + """The text between the markers, or None when the answer has none.""" + start = answer.find(START) + if start < 0: + return None + start += len(START) + end = answer.find(END, start) + if end < 0: + return None + return answer[start:end].strip("\n") + + +def check(case, answer): + """Names of the failed checks for one answer.""" + text = final_text(answer) + if text is None: + return ["answer has the %s ... %s markers" % (START, END)] + return [name for name, ok in grade.grade(os.path.join(CORPUS, case), text) if not ok] + + +def ask(client, system, message, model, effort): + import anthropic + + for attempt in range(4): + try: + with client.beta.messages.stream( + model=model, + max_tokens=32000, + system=[{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}], + messages=[{"role": "user", "content": message}], + output_config={"effort": effort}, + betas=["server-side-fallback-2026-07-01"], + fallbacks="default", + ) as stream: + msg = stream.get_final_message() + if msg.stop_reason == "refusal": + return "", msg.usage + return "".join(b.text for b in msg.content if b.type == "text"), msg.usage + except (anthropic.RateLimitError, anthropic.APIConnectionError, anthropic.InternalServerError): + if attempt == 3: + raise + time.sleep(2 ** (attempt + 2)) + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("--case", action="append", help="run only this case (repeatable)") + p.add_argument("--runs", type=int, default=3, help="answers per case (default 3)") + p.add_argument("--need", type=int, help="passing answers a case needs (default: runs - 1, at least 1)") + p.add_argument("--variant", choices=["skill", "prompt"], default="skill") + p.add_argument("--model", default=MODEL) + p.add_argument("--effort", default="high", choices=["low", "medium", "high", "xhigh", "max"]) + p.add_argument("--out", default=os.path.join(ROOT, "corpus-results"), help="folder for answers and report") + p.add_argument("--answers", help="grade saved answers from this folder (/.txt) instead of asking a model") + p.add_argument("--dry-run", action="store_true", help="print sizes and the first request, send nothing") + args = p.parse_args(argv) + + selected = args.case or cases() + unknown = [c for c in selected if c not in cases()] + if unknown: + p.error("unknown case: %s" % ", ".join(unknown)) + need = args.need if args.need is not None else max(1, args.runs - 1) + system = system_prompt(args.variant) + + if args.dry_run: + print("variant %s: system prompt %d characters, %d cases x %d runs" % (args.variant, len(system), len(selected), args.runs)) + print("--- first message ---\n" + user_message(selected[0])) + return 0 + + client = None + if not args.answers: + if not os.environ.get("ANTHROPIC_API_KEY"): + print("ANTHROPIC_API_KEY is not set", file=sys.stderr) + return 2 + import anthropic + + client = anthropic.Anthropic() + + rows, totals = [], {"input": 0, "cache_read": 0, "cache_write": 0, "output": 0} + for case in selected: + passed, failures = 0, [] + for n in range(1, args.runs + 1): + if args.answers: + path = os.path.join(args.answers, case, "%d.txt" % n) + answer = read(path) if os.path.exists(path) else "" + else: + answer, usage = ask(client, system, user_message(case), args.model, args.effort) + totals["input"] += usage.input_tokens + totals["cache_read"] += usage.cache_read_input_tokens or 0 + totals["cache_write"] += usage.cache_creation_input_tokens or 0 + totals["output"] += usage.output_tokens + os.makedirs(os.path.join(args.out, case), exist_ok=True) + with open(os.path.join(args.out, case, "%d.txt" % n), "w", encoding="utf-8") as fh: + fh.write(answer) + failed = check(case, answer) + passed += not failed + failures.append(failed) + print("%-24s run %d: %s" % (case, n, "OK" if not failed else "FAIL (%d)" % len(failed)), flush=True) + rows.append({"case": case, "passed": passed, "runs": args.runs, "ok": passed >= need, "failures": failures}) + + report = render(rows, need, args, totals) + os.makedirs(args.out, exist_ok=True) + with open(os.path.join(args.out, "report.md"), "w", encoding="utf-8") as fh: + fh.write(report) + with open(os.path.join(args.out, "report.json"), "w", encoding="utf-8") as fh: + json.dump({"variant": args.variant, "model": args.model, "need": need, "tokens": totals, "cases": rows}, fh, ensure_ascii=False, indent=2) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as fh: + fh.write(report) + print("\n" + report) + return 0 if all(r["ok"] for r in rows) else 1 + + +def render(rows, need, args, totals): + ok = sum(r["ok"] for r in rows) + lines = [ + "## Corpus run: %s, %s" % (args.variant, "saved answers" if args.answers else args.model), + "", + "%d of %d cases pass (a case needs %d of %d answers to pass every check)." % (ok, len(rows), need, args.runs), + "", + "| Case | Passed | Result |", + "|---|---|---|", + ] + lines += ["| %s | %d / %d | %s |" % (r["case"], r["passed"], r["runs"], "OK" if r["ok"] else "FAIL") for r in rows] + if not args.answers: + lines += ["", "Tokens: %(input)d input, %(cache_read)d cache read, %(cache_write)d cache write, %(output)d output." % totals] + failed = [(r["case"], i + 1, f) for r in rows for i, f in enumerate(r["failures"]) if f] + if failed: + lines += ["", "### Failed checks", ""] + for case, n, names in failed: + lines.append("- **%s**, run %d: %s" % (case, n, "; ".join(names))) + return "\n".join(lines) + "\n" + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_run_corpus.py b/tests/test_run_corpus.py new file mode 100644 index 0000000..00e05d5 --- /dev/null +++ b/tests/test_run_corpus.py @@ -0,0 +1,68 @@ +import os +import shutil +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import run_corpus as rc # noqa: E402 + + +def wrap(text, notes="- için → üçin"): + return "%s\n%s\n%s\n\n%s\n" % (rc.START, text, rc.END, notes) + + +class TestRunCorpus(unittest.TestCase): + def test_final_text_is_taken_from_between_the_markers(self): + self.assertEqual(rc.final_text("x\n<<>>\nnotes"), "Salam.") + self.assertIsNone(rc.final_text("Salam.")) + self.assertIsNone(rc.final_text("<<" % first, s) + for name in os.listdir(os.path.join(rc.ROOT, "references")): + self.assertIn("references/%s" % name, s) + self.assertTrue(s.endswith(rc.HARNESS_NOTE)) + + def test_saved_answers_mode(self): + tmp = tempfile.mkdtemp() + try: + good, bad = os.path.join(tmp, "good"), os.path.join(tmp, "bad") + for case in rc.cases(): + for folder, name in ((good, "reference.txt"), (bad, "input.txt")): + os.makedirs(os.path.join(folder, case)) + text = rc.read(os.path.join(rc.CORPUS, case, name)) + for n in (1, 2): + with open(os.path.join(folder, case, "%d.txt" % n), "w", encoding="utf-8") as fh: + fh.write(wrap(text)) + out = os.path.join(tmp, "out") + with open(os.devnull, "w") as null: + stdout, sys.stdout = sys.stdout, null + try: + ok = rc.main(["--answers", good, "--runs", "2", "--out", out]) + fail = rc.main(["--answers", bad, "--runs", "2", "--out", out]) + finally: + sys.stdout = stdout + self.assertEqual((ok, fail), (0, 1)) + self.assertIn("FAIL", rc.read(os.path.join(out, "report.md"))) + finally: + shutil.rmtree(tmp) + + +if __name__ == "__main__": + unittest.main() From 2b1fcb4d69f2135fc18a653689748debf87ebc5f Mon Sep 17 00:00:00 2001 From: Novruz Garryyev Date: Sun, 1 Nov 2026 09:59:09 +0000 Subject: [PATCH 2/4] Send corpus requests in parallel and stop cleanly when the API key fails --- tests/run_corpus.py | 64 +++++++++++++++++++++++++++++----------- tests/test_run_corpus.py | 31 +++++++++++++++++++ 2 files changed, 78 insertions(+), 17 deletions(-) diff --git a/tests/run_corpus.py b/tests/run_corpus.py index b54d27f..83ca37f 100644 --- a/tests/run_corpus.py +++ b/tests/run_corpus.py @@ -12,7 +12,9 @@ the list of changes after it is not graded, and checked with tests/grade.py. A case passes when at least --need of its --runs answers pass every check. -The script exits with code 1 if any case fails. It needs ANTHROPIC_API_KEY +Requests go out --jobs at a time. The script exits with code 1 if any case +fails, and with code 2 if the API stops answering (a bad key, for example); +the report then covers the answers received so far. It needs ANTHROPIC_API_KEY unless --dry-run or --answers is given. Answers and a report go to --out. """ @@ -21,6 +23,7 @@ import os import sys import time +from concurrent.futures import ThreadPoolExecutor, as_completed HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) @@ -111,6 +114,7 @@ def main(argv=None): p.add_argument("--case", action="append", help="run only this case (repeatable)") p.add_argument("--runs", type=int, default=3, help="answers per case (default 3)") p.add_argument("--need", type=int, help="passing answers a case needs (default: runs - 1, at least 1)") + p.add_argument("--jobs", type=int, default=6, help="requests sent at the same time (default 6)") p.add_argument("--variant", choices=["skill", "prompt"], default="skill") p.add_argument("--model", default=MODEL) p.add_argument("--effort", default="high", choices=["low", "medium", "high", "xhigh", "max"]) @@ -140,27 +144,47 @@ def main(argv=None): client = anthropic.Anthropic() - rows, totals = [], {"input": 0, "cache_read": 0, "cache_write": 0, "output": 0} - for case in selected: - passed, failures = 0, [] - for n in range(1, args.runs + 1): - if args.answers: - path = os.path.join(args.answers, case, "%d.txt" % n) - answer = read(path) if os.path.exists(path) else "" - else: - answer, usage = ask(client, system, user_message(case), args.model, args.effort) + jobs = [(case, n) for case in selected for n in range(1, args.runs + 1)] + totals = {"input": 0, "cache_read": 0, "cache_write": 0, "output": 0} + results = {} + + def one(job): + case, n = job + if args.answers: + path = os.path.join(args.answers, case, "%d.txt" % n) + return job, (read(path) if os.path.exists(path) else ""), None + answer, usage = ask(client, system, user_message(case), args.model, args.effort) + os.makedirs(os.path.join(args.out, case), exist_ok=True) + with open(os.path.join(args.out, case, "%d.txt" % n), "w", encoding="utf-8") as fh: + fh.write(answer) + return job, answer, usage + + fatal = None + with ThreadPoolExecutor(max_workers=1 if args.answers else args.jobs) as pool: + pending = [pool.submit(one, job) for job in jobs] + for future in as_completed(pending): + try: + (case, n), answer, usage = future.result() + except Exception as exc: # a bad key or a dead API: stop, keep what we have + if fatal is None: + fatal = exc + for f in pending: + f.cancel() + continue + if usage is not None: totals["input"] += usage.input_tokens totals["cache_read"] += usage.cache_read_input_tokens or 0 totals["cache_write"] += usage.cache_creation_input_tokens or 0 totals["output"] += usage.output_tokens - os.makedirs(os.path.join(args.out, case), exist_ok=True) - with open(os.path.join(args.out, case, "%d.txt" % n), "w", encoding="utf-8") as fh: - fh.write(answer) failed = check(case, answer) - passed += not failed - failures.append(failed) + results[case, n] = failed print("%-24s run %d: %s" % (case, n, "OK" if not failed else "FAIL (%d)" % len(failed)), flush=True) - rows.append({"case": case, "passed": passed, "runs": args.runs, "ok": passed >= need, "failures": failures}) + + rows = [] + for case in selected: + failures = [results[case, n] for n in range(1, args.runs + 1) if (case, n) in results] + passed = sum(not f for f in failures) + rows.append({"case": case, "passed": passed, "runs": len(failures), "ok": passed >= need, "failures": failures}) report = render(rows, need, args, totals) os.makedirs(args.out, exist_ok=True) @@ -172,6 +196,9 @@ def main(argv=None): with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as fh: fh.write(report) print("\n" + report) + if fatal is not None: + print("Stopped early: %s" % fatal, file=sys.stderr) + return 2 return 0 if all(r["ok"] for r in rows) else 1 @@ -185,7 +212,10 @@ def render(rows, need, args, totals): "| Case | Passed | Result |", "|---|---|---|", ] - lines += ["| %s | %d / %d | %s |" % (r["case"], r["passed"], r["runs"], "OK" if r["ok"] else "FAIL") for r in rows] + lines += ["| %s | %d / %d | %s |" % (r["case"], r["passed"], r["runs"], "OK" if r["ok"] else "FAIL") for r in rows if r["runs"]] + skipped = [r["case"] for r in rows if not r["runs"]] + if skipped: + lines += ["", "Not run (stopped early): %s." % ", ".join(skipped)] if not args.answers: lines += ["", "Tokens: %(input)d input, %(cache_read)d cache read, %(cache_write)d cache write, %(output)d output." % totals] failed = [(r["case"], i + 1, f) for r in rows for i, f in enumerate(r["failures"]) if f] diff --git a/tests/test_run_corpus.py b/tests/test_run_corpus.py index 00e05d5..fc4f217 100644 --- a/tests/test_run_corpus.py +++ b/tests/test_run_corpus.py @@ -63,6 +63,37 @@ def test_saved_answers_mode(self): finally: shutil.rmtree(tmp) + def test_api_stop_keeps_the_answers_so_far(self): + # A key that stops working mid-run must end with code 2 and a report, not a traceback. + import types + from unittest import mock + + calls = [] + + def fake_ask(client, system, message, model, effort): + calls.append(message) + if len(calls) > 1: + raise RuntimeError("invalid x-api-key") + usage = types.SimpleNamespace(input_tokens=1, cache_read_input_tokens=0, cache_creation_input_tokens=0, output_tokens=1) + case = rc.cases()[0] + return wrap(rc.read(os.path.join(rc.CORPUS, case, "reference.txt"))), usage + + fake = types.ModuleType("anthropic") + fake.Anthropic = lambda: object() + tmp = tempfile.mkdtemp() + try: + with mock.patch.dict(sys.modules, {"anthropic": fake}), \ + mock.patch.dict(os.environ, {"ANTHROPIC_API_KEY": "x"}), \ + mock.patch.object(rc, "ask", fake_ask), \ + open(os.devnull, "w") as null, mock.patch("sys.stdout", null), mock.patch("sys.stderr", null): + code = rc.main(["--case", rc.cases()[0], "--case", rc.cases()[1], "--runs", "2", "--jobs", "1", "--out", tmp]) + self.assertEqual(code, 2) + report = rc.read(os.path.join(tmp, "report.md")) + self.assertIn("1 / 1", report) + self.assertIn("Not run (stopped early): %s" % rc.cases()[1], report) + finally: + shutil.rmtree(tmp) + if __name__ == "__main__": unittest.main() From 89d2e75091ec304de765972175ecfcab166cdb70 Mon Sep 17 00:00:00 2001 From: Novruz Garryyev Date: Sun, 1 Nov 2026 10:17:48 +0000 Subject: [PATCH 3/4] Run the corpus workflow by hand only --- .github/workflows/corpus.yml | 15 +++------------ AGENTS.md | 2 +- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/.github/workflows/corpus.yml b/.github/workflows/corpus.yml index f958832..5a4e198 100644 --- a/.github/workflows/corpus.yml +++ b/.github/workflows/corpus.yml @@ -1,17 +1,10 @@ name: Corpus run # Sends every corpus case to the model and grades the answers. -# Costs API credits, so it runs only when the skill text changes, or by hand. +# One full run costs about 8 USD in API credits, so it runs only by hand: +# Actions > Corpus run > Run workflow. Run it before a release that changes +# SKILL.md, references/ or prompts/. on: - pull_request: - paths: - - SKILL.md - - references/** - - prompts/** - - scripts/barla.py - - tests/corpus/** - - tests/grade.py - - tests/run_corpus.py workflow_dispatch: inputs: variant: @@ -32,8 +25,6 @@ concurrency: jobs: corpus: - # Pull requests from forks get no secrets; skip them instead of failing. - if: github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-latest timeout-minutes: 60 steps: diff --git a/AGENTS.md b/AGENTS.md index b19f693..8b8135d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,7 +30,7 @@ humanizer21 is an agent skill written in Markdown, with one Python checker and a - **Facts.** Examples in the references must never add a fact in the "after" text that the "before" text lacks. - **Checker.** Every new check in `barla.py` gets a test in `tests/test_barla.py`, including a test that correct text stays clean. - **Corpus.** When a rewrite goes wrong in a way the rules should have prevented, add the text to `tests/corpus/` as a new case with `input.txt`, `expected.json` and a corrected `reference.txt`. Run `python3 tests/grade.py` on the skill's next answer before releasing a fix. -- **Model run.** `tests/run_corpus.py` sends every corpus case to the model and grades the answers with `grade.py`; CI runs it (`.github/workflows/corpus.yml`) on pull requests that touch the skill text. Run it before and after a change to `SKILL.md`, `references/` or `prompts/`, and do not merge a change that makes a case fail that passed before. Locally: `uv run --no-project --with anthropic==2.3.0 python tests/run_corpus.py --runs 1`. It costs API credits. +- **Model run.** `tests/run_corpus.py` sends every corpus case to the model and grades the answers with `grade.py`; run it by hand in GitHub Actions (`Corpus run` > Run workflow); one full run costs about 8 USD. Run it before and after a change to `SKILL.md`, `references/` or `prompts/`, and do not merge a change that makes a case fail that passed before. Locally: `uv run --no-project --with anthropic==2.3.0 python tests/run_corpus.py --runs 1`. - **History.** Add a `CHANGELOG.md` note for any change in behavior. ## Checks before publishing From deec16702cb461def62cb708a83828e7e85f4782 Mon Sep 17 00:00:00 2001 From: Novruz Garryyev Date: Sun, 1 Nov 2026 10:35:44 +0000 Subject: [PATCH 4/4] =?UTF-8?q?Accept=20counts=20in=20digits=20or=20words?= =?UTF-8?q?=20in=20corpus=20checks,=20match=20i=C3=A7in=20as=20a=20whole?= =?UTF-8?q?=20word,=20print=20failed=20answers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/corpus.yml | 10 ++++-- tests/corpus/hasabat-yazgysy/expected.json | 2 +- tests/corpus/kitaphana-habary/expected.json | 2 +- tests/corpus/olimpiada-habary/expected.json | 2 +- .../corpus/sanly-mekdep-makala/expected.json | 2 +- tests/corpus/uly-hasabat/expected.json | 2 +- tests/corpus/welosiped-post/expected.json | 2 +- tests/corpus/yoremek-post/expected.json | 2 +- tests/grade.py | 34 +++++++++++++++++-- tests/run_corpus.py | 14 ++++++-- tests/test_run_corpus.py | 29 ++++++++++++++++ 11 files changed, 86 insertions(+), 15 deletions(-) diff --git a/.github/workflows/corpus.yml b/.github/workflows/corpus.yml index 5a4e198..255547a 100644 --- a/.github/workflows/corpus.yml +++ b/.github/workflows/corpus.yml @@ -15,6 +15,9 @@ on: runs: description: "Answers per case" default: "3" + cases: + description: "Only these cases, comma-separated (empty: all)" + default: "" permissions: contents: read @@ -37,10 +40,13 @@ jobs: - name: Run the corpus env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + VARIANT: ${{ inputs.variant || 'skill' }} + RUNS: ${{ inputs.runs || '3' }} + CASES: ${{ inputs.cases }} run: >- uv run --no-project --with anthropic==2.3.0 python tests/run_corpus.py - --variant "${{ inputs.variant || 'skill' }}" - --runs "${{ inputs.runs || '3' }}" + --variant "$VARIANT" --runs "$RUNS" --case "$CASES" + --print-failed - name: Keep the answers if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 diff --git a/tests/corpus/hasabat-yazgysy/expected.json b/tests/corpus/hasabat-yazgysy/expected.json index 27557a7..7cdf54d 100644 --- a/tests/corpus/hasabat-yazgysy/expected.json +++ b/tests/corpus/hasabat-yazgysy/expected.json @@ -37,7 +37,7 @@ "täze sahypa", "Umyt edýärin", "Başga soraglaryňyz", - "için", + "re:\\bi[cç]in\\b", "daha", "abilir", "YouTube'da", diff --git a/tests/corpus/kitaphana-habary/expected.json b/tests/corpus/kitaphana-habary/expected.json index f605a43..d9b14c8 100644 --- a/tests/corpus/kitaphana-habary/expected.json +++ b/tests/corpus/kitaphana-habary/expected.json @@ -13,7 +13,7 @@ ], "must_not": [ "Elbetde", - "için", + "re:\\bi[cç]in\\b", "Şuny bellemek", "rol oýna", "täze sahypa", diff --git a/tests/corpus/olimpiada-habary/expected.json b/tests/corpus/olimpiada-habary/expected.json index f9a2225..37b4d6d 100644 --- a/tests/corpus/olimpiada-habary/expected.json +++ b/tests/corpus/olimpiada-habary/expected.json @@ -23,7 +23,7 @@ "çäklerinde", "öz içine", "rol oýna", - "için", + "re:\\bi[cç]in\\b", "daha", "önemli", "yeňijilere", diff --git a/tests/corpus/sanly-mekdep-makala/expected.json b/tests/corpus/sanly-mekdep-makala/expected.json index 40ae731..02ceffc 100644 --- a/tests/corpus/sanly-mekdep-makala/expected.json +++ b/tests/corpus/sanly-mekdep-makala/expected.json @@ -21,7 +21,7 @@ "Platforma barada gürrüň", "Elimdäki", "million", - "için", + "re:\\bi[cç]in\\b", "daha", "sadece", "olarak", diff --git a/tests/corpus/uly-hasabat/expected.json b/tests/corpus/uly-hasabat/expected.json index 2cf7839..f6f9050 100644 --- a/tests/corpus/uly-hasabat/expected.json +++ b/tests/corpus/uly-hasabat/expected.json @@ -96,7 +96,7 @@ "must_not": [ "Elbetde", "Umyt edýärin", - "için", + "re:\\bi[cç]in\\b", "daha", "ösebilir", "Türkmenistanyn", diff --git a/tests/corpus/welosiped-post/expected.json b/tests/corpus/welosiped-post/expected.json index 05faf51..e4a4d67 100644 --- a/tests/corpus/welosiped-post/expected.json +++ b/tests/corpus/welosiped-post/expected.json @@ -16,7 +16,7 @@ "Elbetde", "Geliň", "**", - "için", + "re:\\bi[cç]in\\b", "peydaly", "2026-nji", "velosipedler", diff --git a/tests/corpus/yoremek-post/expected.json b/tests/corpus/yoremek-post/expected.json index e15f313..e4cde77 100644 --- a/tests/corpus/yoremek-post/expected.json +++ b/tests/corpus/yoremek-post/expected.json @@ -12,7 +12,7 @@ "Gowy sorag", "Geliň", "**", - "için", + "re:\\bi[cç]in\\b", "daha", "durum", "Hakykatdan", diff --git a/tests/grade.py b/tests/grade.py index ef43f92..47b72f5 100644 --- a/tests/grade.py +++ b/tests/grade.py @@ -5,12 +5,20 @@ python3 tests/grade.py tests/corpus/olimpiada-habary result.txt Prints one line per check and exits with code 1 if any check fails. -The checks are plain substring tests from the case's expected.json: +The checks are substring tests from the case's expected.json: must_keep lists facts and protected text that have to survive the edit, must_not lists tells, errors and invented details that must be gone. + +Two allowances keep the checks from failing correct Turkmen: +- in must_keep, a count from 2 to 9 may be written in digits or in words, + with or without `sany` (`3 sany täze seýilgäh`, `üç täze seýilgäh`); +- an entry that starts with `re:` is a regular expression, for a word that + must not match inside a longer one (`re:\\bi[cç]in\\b` is the Turkish + `için`, not the Turkmen `içinde`). """ import json +import re import os import sys @@ -18,12 +26,32 @@ sys.path.insert(0, os.path.join(HERE, "..", "scripts")) import barla # noqa: E402 +UNITS = {"2": "iki", "3": "üç", "4": "dört", "5": "bäş", "6": "alty", "7": "ýedi", "8": "sekiz", "9": "dokuz"} +WORDS = {w: d for d, w in UNITS.items()} +COUNT = re.compile(r"^(\d|%s)( sany)? (.+)$" % "|".join(UNITS.values())) + + +def variants(entry): + """Equally correct spellings of a must_keep entry: 3 / üç, with or without sany.""" + m = COUNT.match(entry) + if not m or (m.group(1).isdigit() and m.group(1) not in UNITS): + return [entry] + n, rest = m.group(1), m.group(3) + forms = {n, UNITS.get(n, WORDS.get(n))} + return sorted("%s%s %s" % (f, s, rest) for f in forms for s in ("", " sany")) + + +def found(entry, text): + if entry.startswith("re:"): + return re.search(entry[3:], text) is not None + return any(v in text for v in variants(entry)) + def grade(case_dir, text): with open(os.path.join(case_dir, "expected.json"), encoding="utf-8") as fh: exp = json.load(fh) - results = [("keeps %r" % k, k in text) for k in exp["must_keep"]] - results += [("has no %r" % k, k not in text) for k in exp["must_not"]] + results = [("keeps %r" % k, found(k, text)) for k in exp["must_keep"]] + results += [("has no %r" % k, not found(k, text)) for k in exp["must_not"]] # Quotes and table rows of a Turkmen source must survive unchanged. if exp.get("source_language", "tk") == "tk": with open(os.path.join(case_dir, "input.txt"), encoding="utf-8") as fh: diff --git a/tests/run_corpus.py b/tests/run_corpus.py index 83ca37f..b85ce79 100644 --- a/tests/run_corpus.py +++ b/tests/run_corpus.py @@ -111,7 +111,7 @@ def ask(client, system, message, model, effort): def main(argv=None): p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - p.add_argument("--case", action="append", help="run only this case (repeatable)") + p.add_argument("--case", action="append", help="run only this case (repeatable, or comma-separated)") p.add_argument("--runs", type=int, default=3, help="answers per case (default 3)") p.add_argument("--need", type=int, help="passing answers a case needs (default: runs - 1, at least 1)") p.add_argument("--jobs", type=int, default=6, help="requests sent at the same time (default 6)") @@ -120,10 +120,12 @@ def main(argv=None): p.add_argument("--effort", default="high", choices=["low", "medium", "high", "xhigh", "max"]) p.add_argument("--out", default=os.path.join(ROOT, "corpus-results"), help="folder for answers and report") p.add_argument("--answers", help="grade saved answers from this folder (/.txt) instead of asking a model") + p.add_argument("--print-failed", action="store_true", help="print the text of every failed answer after the report") p.add_argument("--dry-run", action="store_true", help="print sizes and the first request, send nothing") args = p.parse_args(argv) - selected = args.case or cases() + selected = [c for arg in (args.case or []) for c in arg.split(",") if c.strip()] or cases() + selected = [c.strip() for c in selected] unknown = [c for c in selected if c not in cases()] if unknown: p.error("unknown case: %s" % ", ".join(unknown)) @@ -146,7 +148,7 @@ def main(argv=None): jobs = [(case, n) for case in selected for n in range(1, args.runs + 1)] totals = {"input": 0, "cache_read": 0, "cache_write": 0, "output": 0} - results = {} + results, texts = {}, {} def one(job): case, n = job @@ -178,6 +180,8 @@ def one(job): totals["output"] += usage.output_tokens failed = check(case, answer) results[case, n] = failed + if failed: + texts[case, n] = answer print("%-24s run %d: %s" % (case, n, "OK" if not failed else "FAIL (%d)" % len(failed)), flush=True) rows = [] @@ -196,6 +200,10 @@ def one(job): with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as fh: fh.write(report) print("\n" + report) + if args.print_failed: + for (case, n), answer in sorted(texts.items()): + text = final_text(answer) + print("\n===== %s, run %d: %s\n%s" % (case, n, "; ".join(results[case, n]), text if text is not None else answer)) if fatal is not None: print("Stopped early: %s" % fatal, file=sys.stderr) return 2 diff --git a/tests/test_run_corpus.py b/tests/test_run_corpus.py index fc4f217..0bfcda4 100644 --- a/tests/test_run_corpus.py +++ b/tests/test_run_corpus.py @@ -95,5 +95,34 @@ def fake_ask(client, system, message, model, effort): shutil.rmtree(tmp) +class TestGradeAllowances(unittest.TestCase): + def test_counts_in_digits_or_words(self): + import grade + self.assertTrue(grade.found("üç täze seýilgäh", "3 sany täze seýilgäh bar")) + self.assertTrue(grade.found("2 täze studiýa", "iki täze studiýa açyldy")) + self.assertFalse(grade.found("2 täze studiýa", "dört täze studiýa")) + self.assertFalse(grade.found("12 göterim", "on iki göterim")) # only 2 to 9 + + def test_regex_entries_match_whole_words(self): + import grade + self.assertTrue(grade.found(r"re:\bi[cç]in\b", "siz için")) + self.assertFalse(grade.found(r"re:\bi[cç]in\b", "öýüň içinde")) + + def test_comma_separated_cases(self): + tmp = tempfile.mkdtemp() + try: + with open(os.devnull, "w") as null: + stdout, sys.stdout = sys.stdout, null + try: + code = rc.main(["--answers", tmp, "--runs", "1", "--case", "%s,%s" % tuple(rc.cases()[:2]), "--out", tmp]) + finally: + sys.stdout = stdout + self.assertEqual(code, 1) # no saved answers, so both fail + report = rc.read(os.path.join(tmp, "report.md")) + self.assertIn("0 of 2 cases pass", report) + finally: + shutil.rmtree(tmp) + + if __name__ == "__main__": unittest.main()