maydan-hf-rl-sampler / scripts /run_reference_and_tests.py
Maydanlabs's picture
Publish licensed ten-task Maydan HF RL sampler
6a48320 verified
Raw History Blame Contribute Delete
12.8 kB
#!/usr/bin/env python3
from __future__ import annotations
import hashlib
import os
import shutil
import sqlite3
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TASKS = sorted((ROOT / "tasks").glob("maydan-gosi-f11-*"))
def env_for(task: Path, live: Path | None = None) -> dict:
env = os.environ.copy()
env["PYTHONDONTWRITEBYTECODE"] = "1"
env["PYTHONPATH"] = f"{task / 'environment'}{os.pathsep}{env.get('PYTHONPATH', '')}"
if live is not None:
env["MAYDAN_MINI_LIVE_DB"] = str(live)
else:
env["VERIFIER_LOG_DIR"] = str(task / "logs" / "verifier")
return env
def run(args: list[str], task: Path, live: Path | None = None, check: bool = True) -> subprocess.CompletedProcess:
return subprocess.run(args, cwd=task, env=env_for(task, live), check=check, text=True, capture_output=True)
def reset_task(task: Path) -> Path:
seed = task / "environment/data/seed.db"
live = task / "environment/data/live.db"
if live.exists():
live.unlink()
shutil.copyfile(seed, live)
return live
def import_verifier(task: Path):
sys.path.insert(0, str(task / "environment"))
try:
from maydan_mini.verifier import expected_rows, verify # type: ignore
return expected_rows, verify
finally:
sys.modules.pop("maydan_mini.verifier", None)
sys.modules.pop("maydan_mini.db", None)
sys.modules.pop("maydan_mini", None)
sys.path.remove(str(task / "environment"))
def expected_for(task: Path, live: Path) -> list[dict]:
expected_rows, _verify = import_verifier(task)
conn = sqlite3.connect(live)
conn.row_factory = sqlite3.Row
try:
return expected_rows(conn)
finally:
conn.close()
def verify_task(task: Path, live: Path) -> dict:
_expected_rows, verify = import_verifier(task)
return verify(live)
def stage_all(task: Path, live: Path, rows: list[dict]) -> None:
for item in rows:
run([
sys.executable, "-m", "maydan_mini.actions", "stage",
"--employee-id", str(item["batch_employee_id"]),
"--cohort", item["selected_cohort"],
"--base", str(item["contribution_base_halalas"]),
"--employer-rate-bps", str(item["employer_rate_bps"]),
"--employee-rate-bps", str(item["employee_rate_bps"]),
"--employer-amount", str(item["employer_amount_halalas"]),
"--employee-amount", str(item["employee_amount_halalas"]),
], task, live)
def expect_fail(name: str, task: Path, fn) -> None:
with tempfile.TemporaryDirectory(prefix=f"maydan-f11-{name}-") as d:
live = Path(d) / "live.db"
shutil.copyfile(task / "environment/data/seed.db", live)
fn(task, live)
result = verify_task(task, live)
if result["pass"]:
raise AssertionError(f"{task.name} {name} unexpectedly passed")
print(f"ok negative {task.name} {name}: {result['reason']}")
def missing_finalization(task: Path, live: Path) -> None:
stage_all(task, live, expected_for(task, live))
def wrong_branch_selection(task: Path, live: Path) -> None:
rows = expected_for(task, live)
non_saudi = next(i for i, row in enumerate(rows) if row["selected_cohort"] == "non_saudi_oh_only")
rows[non_saudi] = {**rows[non_saudi], "selected_cohort": "legacy_saudi", "employer_rate_bps": 1175, "employee_rate_bps": 975}
base = rows[non_saudi]["contribution_base_halalas"]
rows[non_saudi]["employer_amount_halalas"] = (base * 1175 * 2 + 10_000) // 20_000
rows[non_saudi]["employee_amount_halalas"] = (base * 975 * 2 + 10_000) // 20_000
stage_all(task, live, rows)
run([sys.executable, "-m", "maydan_mini.actions", "finalize", "--batch-id", "1"], task, live)
def cohort_contract_check(task: Path) -> None:
rows = expected_for(task, task / "environment/data/seed.db")
by_cohort = {row["selected_cohort"]: row for row in rows}
required = {"new_saudi", "legacy_saudi", "non_saudi_oh_only"}
if set(by_cohort) != required:
raise AssertionError(f"{task.name} expected cohort coverage changed: {sorted(by_cohort)}")
with tempfile.TemporaryDirectory(prefix="maydan-f11-cohort-contract-") as d:
live = Path(d) / "live.db"
shutil.copyfile(task / "environment/data/seed.db", live)
for cohort in sorted(required):
item = by_cohort[cohort]
run([
sys.executable, "-m", "maydan_mini.actions", "stage",
"--employee-id", str(item["batch_employee_id"]),
"--cohort", item["selected_cohort"],
"--base", str(item["contribution_base_halalas"]),
"--employer-rate-bps", str(item["employer_rate_bps"]),
"--employee-rate-bps", str(item["employee_rate_bps"]),
"--employer-amount", str(item["employer_amount_halalas"]),
"--employee-amount", str(item["employee_amount_halalas"]),
], task, live)
bad = run([
sys.executable, "-m", "maydan_mini.actions", "stage",
"--employee-id", str(rows[0]["batch_employee_id"]),
"--cohort", "saudi_new",
"--base", str(rows[0]["contribution_base_halalas"]),
"--employer-rate-bps", str(rows[0]["employer_rate_bps"]),
"--employee-rate-bps", str(rows[0]["employee_rate_bps"]),
"--employer-amount", str(rows[0]["employer_amount_halalas"]),
"--employee-amount", str(rows[0]["employee_amount_halalas"]),
], task, live, check=False)
if bad.returncode == 0 or "invalid choice" not in bad.stderr or "new_saudi" not in bad.stderr:
raise AssertionError(f"{task.name} invalid cohort was not clearly rejected")
finalize = run([sys.executable, "-m", "maydan_mini.actions", "finalize", "--batch-id", "1"], task, live, check=False)
if finalize.returncode == 0 or "every employee must be staged" not in finalize.stderr:
raise AssertionError(f"{task.name} invalid cohort path still reached finalization")
def direct_database_write(task: Path, live: Path) -> None:
rows = expected_for(task, live)
conn = sqlite3.connect(live)
try:
for item in rows:
conn.execute(
"""
INSERT INTO gosi_contribution_results(
batch_employee_id, selected_cohort, contribution_base_halalas,
employer_rate_bps, employee_rate_bps, employer_amount_halalas,
employee_amount_halalas, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, 'DIRECT')
""",
(
item["batch_employee_id"], item["selected_cohort"], item["contribution_base_halalas"],
item["employer_rate_bps"], item["employee_rate_bps"],
item["employer_amount_halalas"], item["employee_amount_halalas"],
),
)
conn.execute("UPDATE gosi_batches SET status='finalized', finalized_at='DIRECT' WHERE id=1")
conn.commit()
finally:
conn.close()
def forge_audit_direct_database_write(task: Path, live: Path) -> None:
rows = expected_for(task, live)
conn = sqlite3.connect(live)
try:
for item in rows:
conn.execute(
"""
INSERT INTO gosi_contribution_results(
batch_employee_id, selected_cohort, contribution_base_halalas,
employer_rate_bps, employee_rate_bps, employer_amount_halalas,
employee_amount_halalas, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, 'FORGED')
""",
(
item["batch_employee_id"], item["selected_cohort"], item["contribution_base_halalas"],
item["employer_rate_bps"], item["employee_rate_bps"],
item["employer_amount_halalas"], item["employee_amount_halalas"],
),
)
conn.execute(
"INSERT INTO audit_events(ts, action, entity_type, entity_id, before_json, after_json) VALUES('FORGED','stage_gosi_contribution','gosi_batch_employees',?,'{}','{}')",
(item["batch_employee_id"],),
)
conn.execute("UPDATE gosi_batches SET status='finalized', finalized_at='FORGED' WHERE id=1")
conn.execute("INSERT INTO audit_events(ts, action, entity_type, entity_id, before_json, after_json) VALUES('FORGED','finalize_gosi_batch','gosi_batches',1,'{}','{}')")
conn.commit()
finally:
conn.close()
def source_table_tamper(task: Path, live: Path) -> None:
rows = expected_for(task, live)
conn = sqlite3.connect(live)
try:
conn.execute("UPDATE payroll_evidence SET basic_wage_halalas=basic_wage_halalas+1 WHERE batch_employee_id=1")
conn.commit()
finally:
conn.close()
stage_all(task, live, rows)
run([sys.executable, "-m", "maydan_mini.actions", "finalize", "--batch-id", "1"], task, live)
def source_query_check(task: Path) -> None:
with tempfile.TemporaryDirectory(prefix="maydan-f11-query-sources-") as d:
live = Path(d) / "live.db"
shutil.copyfile(task / "environment/data/seed.db", live)
employment = run([sys.executable, "-m", "maydan_mini.inspect", "employment", "--employee-id", "1"], task, live).stdout
history = run([sys.executable, "-m", "maydan_mini.inspect", "history", "--employee-id", "1"], task, live).stdout
payroll = run([sys.executable, "-m", "maydan_mini.inspect", "payroll", "--employee-id", "1"], task, live).stdout
if "nationality_code" not in employment or "has_pre_2024_07_03_period" not in history or "basic_wage_halalas" not in payroll:
raise AssertionError(f"{task.name} separate source query surfaces are incomplete")
def checker_replacement_detected(task: Path) -> None:
verifier = task / "environment/maydan_mini/verifier.py"
original = verifier.read_text(encoding="utf-8")
try:
verifier.write_text("print('tampered verifier')\n", encoding="utf-8")
live = reset_task(task)
result = run(["bash", "tests/test.sh"], task, live, check=False)
if result.returncode == 0 or "verifier integrity check failed" not in (result.stdout + result.stderr):
raise AssertionError(f"{task.name} checker replacement was not detected")
finally:
verifier.write_text(original, encoding="utf-8")
def no_expected_answer_file(task: Path) -> None:
forbidden = []
for path in task.rglob("*"):
if path.is_file() and any(token in path.name.lower() for token in ("expected", "answer", "solution_state")):
forbidden.append(str(path.relative_to(task)))
if forbidden:
raise AssertionError(f"{task.name} readable expected-answer files present: {forbidden}")
def reference_solution(task: Path) -> None:
live = reset_task(task)
run(["bash", "solution/solve.sh"], task)
result = run(["bash", "tests/test.sh"], task)
print(result.stdout.strip().splitlines()[-1])
verified = verify_task(task, live)
if not verified["pass"]:
raise AssertionError(f"{task.name} reference solution did not pass")
shutil.rmtree(task / "logs", ignore_errors=True)
if live.exists():
live.unlink()
def main() -> int:
if len(TASKS) != 10:
raise AssertionError(f"expected 10 independent F11 tasks, found {len(TASKS)}")
for task in TASKS:
source_query_check(task)
no_expected_answer_file(task)
cohort_contract_check(task)
reference_solution(task)
expect_fail("missing-finalization", task, missing_finalization)
expect_fail("wrong-branch-selection", task, wrong_branch_selection)
expect_fail("direct-database-write", task, direct_database_write)
expect_fail("source-table-tamper", task, source_table_tamper)
# This deliberately demonstrates the concrete local-helper boundary:
# if the attacker can write exact result rows and forge the audit table,
# the in-DB verifier cannot distinguish it without framework isolation.
with tempfile.TemporaryDirectory(prefix="maydan-f11-forged-audit-") as d:
live = Path(d) / "live.db"
shutil.copyfile(task / "environment/data/seed.db", live)
forge_audit_direct_database_write(task, live)
forged = verify_task(task, live)
print(f"boundary {task.name} forged-audit-direct-db pass={forged['pass']} reason={forged['reason']}")
checker_replacement_detected(task)
print("ok: 10 independent F11 reference solutions and local negative tests completed")
return 0
if __name__ == "__main__":
raise SystemExit(main())