deepdesk-bench / dev /mutation_tests_03.py
qrlow's picture
feat: publish SnD Floaters benchmark
25d68e6 verified
Raw History Blame Contribute Delete
5.98 kB
#!/usr/bin/env python3
"""Discrimination tests for the snd-floaters 03-schedule-update grader.
Mutates the oracle workbook into known-bad variants and checks that the
scorer applies the designed penalties / check failures. Tasks 03 and 04 share
byte-identical graders and answer keys through sync_assets.py, so testing task
03 covers both.
Requires openpyxl (3.1.5, same as the task image):
pip install openpyxl==3.1.5
python3 snd-floaters/dev/mutation_tests_03.py
Note: openpyxl drops cached formula values on save, so every mutant also
loses numerical-balance points that read formula caches. Assertions target
only the intended penalty/check behavior, not the total score. Mutant
workbooks go to a temp directory; set MUTANT_OUT to keep them.
"""
from __future__ import annotations
import json
import os
import sys
import tempfile
from pathlib import Path
import openpyxl
SUITE = Path(__file__).resolve().parents[1]
TASK = SUITE / "03-schedule-update"
ANSWER = TASK / "solution" / "European_Gas_SnD_Answer.xlsx"
KEY = TASK / "tests" / "answer_key.json"
SCORER = TASK / "tests" / "score_submission.py"
OUT = Path(os.environ.get("MUTANT_OUT", tempfile.mkdtemp(prefix="snd03-mutants-")))
sys.path.insert(0, str(SCORER.parent))
import score_submission # noqa: E402
def find_row_by_value(ws, col: str, needle: str, lo: int, hi: int) -> int | None:
for row in range(lo, hi + 1):
if str(ws[f"{col}{row}"].value or "").strip().lower() == needle:
return row
return None
def first_empty_row(ws, cols: tuple[str, ...], lo: int, hi: int) -> int:
for row in range(lo, hi + 1):
if all(ws[f"{c}{row}"].value in (None, "") for c in cols):
return row
raise RuntimeError("no empty row")
def mutate(name: str, fn) -> Path:
wb = openpyxl.load_workbook(ANSWER)
fn(wb)
path = OUT / f"{name}.xlsx"
wb.save(path)
return path
def m_post_cutoff(wb):
"""Cite obs-802 (received after the 12:00 UTC cutoff) in the Update Log."""
ws = wb["Update Log"]
row = find_row_by_value(ws, "B", "cargo-1001", 7, 37)
assert row, "cargo-1001 log row not found"
ws[f"M{row}"] = f"{ws[f'M{row}'].value}; obs-802"
def m_include_unresolved(wb):
"""Add cargo-1001 to the schedule as an included leg."""
ws = wb["LNG Schedule"]
row = first_empty_row(ws, ("A", "B"), 8, 37)
ws[f"A{row}"] = "leg-1001-a"
ws[f"B{row}"] = "cargo-1001"
ws[f"D{row}"] = "FR-DKK"
ws[f"F{row}"] = 500.0
ws[f"G{row}"] = 1.0
ws[f"H{row}"] = "Yes"
ws[f"O{row}"] = "obs-1001"
def m_hardcode_h6(wb):
"""Replace the Monthly S&D LNG formula with a hardcoded number."""
wb["Monthly S&D"]["H6"] = 218.936678614098
def m_duplicate_701(wb):
"""Add a second included leg for cargo-701 (no split evidence)."""
ws = wb["LNG Schedule"]
row = first_empty_row(ws, ("A", "B"), 8, 37)
ws[f"A{row}"] = "leg-701-b"
ws[f"B{row}"] = "cargo-701"
ws[f"D{row}"] = "BE-ZEE"
ws[f"F{row}"] = 500.0
ws[f"G{row}"] = 1.0
ws[f"H{row}"] = "Yes"
ws[f"O{row}"] = "obs-703"
def m_drop_unresolved_log(wb):
"""Delete the cargo-1001 row from the Update Log entirely."""
ws = wb["Update Log"]
row = find_row_by_value(ws, "B", "cargo-1001", 7, 37)
assert row, "cargo-1001 log row not found"
for col in "BCDEFGHIJKLMNO":
ws[f"{col}{row}"] = None
def m_break_schedule_helper(wb):
"""Hardcode a schedule helper cell that should stay formula-driven."""
wb["LNG Schedule"]["J8"] = 42.0
def m_wrong_terminal(wb):
"""Corrupt one expected leg's terminal (partial operational credit)."""
ws = wb["LNG Schedule"]
row = find_row_by_value(ws, "A", "leg-201-a", 8, 37)
assert row, "leg-201-a not found"
ws[f"D{row}"] = "FR-DKK"
CASES = {
"post_cutoff": (m_post_cutoff, lambda r: (
any(p["id"] == "post_cutoff_evidence_used" for p in r["penalties"])
and r["critical_failure"] and not r["passed"]
and r["categories"]["provenance_and_cutoff"]["score"] < 20.0
)),
"include_unresolved": (m_include_unresolved, lambda r: (
any(p["id"] == "unresolved_cargo_included" for p in r["penalties"])
and r["critical_failure"] and not r["passed"]
)),
"hardcode_h6": (m_hardcode_h6, lambda r: (
any(p["id"] == "lng_output_hardcoded" for p in r["penalties"])
and not r["categories"]["workbook_integrity"]["checks"]["monthly_lng_formula"]
)),
"duplicate_701": (m_duplicate_701, lambda r: (
any(p["id"] == "duplicate_cargo_counted_twice" for p in r["penalties"])
)),
"drop_unresolved_log": (m_drop_unresolved_log, lambda r: (
r["categories"]["uncertainty_handling"]["score"] == 0.0
)),
"break_schedule_helper": (m_break_schedule_helper, lambda r: (
not r["categories"]["workbook_integrity"]["checks"]["schedule_helpers_preserved"]
)),
"wrong_terminal": (m_wrong_terminal, lambda r: (
not any(
d["leg_id"] == "leg-201-a" and d["checks"].get("terminal")
for d in r["categories"]["operational_schedule"]["leg_details"]
)
)),
}
def main() -> int:
failures = 0
for name, (mutate_fn, check) in CASES.items():
path = mutate(name, mutate_fn)
report = score_submission.score_submission(path, KEY)
ok = bool(check(report))
penalty_ids = [p["id"] for p in report["penalties"]]
print(f"{'PASS' if ok else 'FAIL'} {name:22s} score={report['score']:6.2f} "
f"passed={report['passed']} penalties={penalty_ids}")
if not ok:
failures += 1
debug = OUT / f"{name}.report.json"
debug.write_text(json.dumps(report, indent=2) + "\n")
print(f" report written to {debug}")
print(f"\n{len(CASES) - failures}/{len(CASES)} discrimination tests passed "
f"(mutants in {OUT})")
return 1 if failures else 0
if __name__ == "__main__":
sys.exit(main())