legacy-code-challenge-v2 / architect /challenge_deployer.py
refaelz's picture
Use baseline-aware scoring for ten challenge tests
1a0c29d
Raw History Blame Contribute Delete
25.2 kB
import ast
import inspect
import json
import os
import re
import stat
from typing import Any
from architect.state import ArchitectState
from architect.private_artifacts import ensure_private_workspace_dir
_RUNTIME_ADDRESS_RE = re.compile(r"(?<= at )0x[0-9a-fA-F]+(?=>)")
def _normalize_runtime_repr(value: str) -> str:
value = _RUNTIME_ADDRESS_RE.sub("0x<address>", value)
try:
result = ast.literal_eval(value)
if not isinstance(result, str):
return value
profile = json.loads(result)
except (ValueError, SyntaxError, TypeError, json.JSONDecodeError):
return value
if not isinstance(profile, dict) or "_eco_version" not in profile or not isinstance(profile.get("python"), dict):
return value
def stabilize(item, key=None):
if key == "_eco_version":
return item
if isinstance(item, dict):
return {name: stabilize(child, name) for name, child in item.items()}
if isinstance(item, list):
return [stabilize(child) for child in item]
if isinstance(item, bool):
return False
if isinstance(item, int):
return 0
if isinstance(item, float):
return 0.0
if isinstance(item, str):
return "<runtime>"
return item
indent_match = re.search(r"\n([ \t]*)\"", result)
indent = len(indent_match.group(1).expandtabs()) if indent_match else None
normalized = json.dumps(stabilize(profile), sort_keys=True, indent=indent)
return repr(normalized)
def _short_test_value(value, other, limit: int = 64) -> str:
text = value if isinstance(value, str) else repr(value)
other_text = other if isinstance(other, str) else repr(other)
difference = 0
while difference < min(len(text), len(other_text)) and text[difference] == other_text[difference]:
difference += 1
start = max(0, difference - limit // 2)
end = min(len(text), start + limit)
excerpt = re.sub(r"\s+", " ", text[start:end])
if start:
excerpt = "..." + excerpt
if end < len(text):
excerpt += "..."
return f"{type(value).__name__} len={len(text)} diff@{difference}: {excerpt!r}"
def _runtime_profile_diagnostic(expected: Any, actual: Any) -> tuple[str, str] | None:
if not isinstance(expected, str) or not isinstance(actual, str):
return None
try:
expected_data = json.loads(expected)
actual_data = json.loads(actual)
except (ValueError, TypeError, json.JSONDecodeError):
return None
if not all(isinstance(item, dict) and "_eco_version" in item and isinstance(item.get("python"), dict)
for item in (expected_data, actual_data)):
return None
volatile = {
"cwd", "guid", "time_utc", "time_utc_offset", "hostfqdn", "hostname", "username",
"uname", "python", "linux_dist_name", "linux_dist_version", "ulimit_soft", "ulimit_hard",
"umask", "cpu_count", "fs_encoding",
}
def stabilize(value, key=None):
if key == "_eco_version":
return value
if key in volatile:
return "<runtime>"
if isinstance(value, dict):
return {name: stabilize(child, name) for name, child in value.items()}
if isinstance(value, list):
return [stabilize(child) for child in value]
return value
def indent_width(value: str) -> int:
content_lines = [line for line in value.splitlines()[1:] if line.strip() not in {"}", "]"}]
return len(content_lines[0]) - len(content_lines[0].lstrip(" ")) if content_lines else 0
expected_stable = stabilize(expected_data)
actual_stable = stabilize(actual_data)
expected_indent = indent_width(expected)
actual_indent = indent_width(actual)
if expected_stable == actual_stable:
return (
f"JSON profile indent={expected_indent}; data matches",
f"JSON profile indent={actual_indent}; data matches",
)
changes: list[tuple[str, Any, Any]] = []
def collect(left, right, path="$", depth=0):
if len(changes) >= 2:
return
if depth > 8:
if left != right:
changes.append((path, left, right))
return
if isinstance(left, dict) and isinstance(right, dict):
for key in sorted(set(left) | set(right)):
if key not in left or key not in right:
changes.append((f"{path}.{key}", left.get(key, "<missing>"), right.get(key, "<missing>")))
else:
collect(left[key], right[key], f"{path}.{key}", depth + 1)
if len(changes) >= 2:
return
elif isinstance(left, list) and isinstance(right, list):
for index in range(max(len(left), len(right))):
collect(left[index] if index < len(left) else "<missing>",
right[index] if index < len(right) else "<missing>", f"{path}[{index}]", depth + 1)
if len(changes) >= 2:
return
elif left != right:
changes.append((path, left, right))
collect(expected_stable, actual_stable)
if not changes:
changes.append(("$", expected_stable, actual_stable))
expected_fields = "; ".join(f"{path}={left!r}" for path, left, _right in changes)
actual_fields = "; ".join(f"{path}={right!r}" for path, _left, right in changes)
return (
f"JSON profile indent={expected_indent}; {expected_fields}",
f"JSON profile indent={actual_indent}; {actual_fields}",
)
def _module_import_path(clone_path: str, target_file: str) -> str:
"""Convert an absolute file path to a dotted module path relative to clone_path."""
rel = os.path.relpath(target_file, clone_path) # e.g. utils/math_utils.py
without_ext = os.path.splitext(rel)[0] # e.g. utils/math_utils
module_path = without_ext.replace(os.sep, ".") # e.g. utils.math_utils
return module_path
def _format_test_args(args_repr: str) -> str:
if not isinstance(args_repr, str) or not args_repr.strip():
raise ValueError("Generated test arguments must be a non-empty Python literal")
args_str = args_repr.strip()
try:
evaluated = ast.literal_eval(args_str)
except (ValueError, SyntaxError, TypeError) as exc:
raise ValueError("Generated test arguments must be a Python literal") from exc
return args_str if isinstance(evaluated, tuple) else f"({args_str},)"
def deploy_challenge(state: ArchitectState) -> ArchitectState:
clone_path = state["clone_path"]
target_file = state["target_file"]
module_path = _module_import_path(clone_path, target_file)
sabotaged_files = state.get("sabotaged_files") or {}
if sabotaged_files:
for rel_path, content in sabotaged_files.items():
abs_path = os.path.join(clone_path, rel_path)
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
with open(abs_path, "w", encoding="utf-8") as f:
f.write(content)
print(f"[deployer] Applied sabotaged file: {abs_path}")
else:
sabotaged_code = state.get("sabotaged_code", "")
if target_file and sabotaged_code:
with open(target_file, "w", encoding="utf-8") as f:
f.write(sabotaged_code)
print(f"[deployer] Applied sabotaged target file: {target_file}")
# Get bug-specific data
all_bug_data = state.get("all_bug_data") or []
bug_specific_tests = state.get("bug_specific_tests") or {}
# If no per-bug data, fall back to old single-bug behavior
if not all_bug_data:
all_bug_data = [{
"function_name": state.get("function_name", "target_func"),
"bug_description": state.get("bug_description", "Unknown bug") # Changed from bug_variant
}]
# Use the global tests
public_tests = state.get("public_tests") or []
secret_tests = state.get("secret_tests") or []
if not public_tests and not secret_tests:
all_tests = state.get("test_cases") or []
if not all_tests:
all_tests = [{"args": state["test_args"], "expected": state["expected_output"]}]
mid = len(all_tests) // 2
public_tests = all_tests[:mid] if mid > 0 else all_tests
secret_tests = all_tests[mid:] if mid > 0 else []
func_name = all_bug_data[0]["function_name"]
bug_specific_tests[func_name] = public_tests + secret_tests
# Split tests for each bug into public/secret
bugs_with_tests = []
for bug in all_bug_data:
func_name = bug["function_name"]
all_tests = bug_specific_tests.get(func_name) or []
# Skip bugs with no tests (shouldn't happen, but be safe)
if not all_tests:
continue
if os.getenv("CHALLENGE_PIPELINE", "bug_first").strip().lower() == "bug_first":
public = bug.get("public_tests") or []
secret = bug.get("secret_tests") or []
if (
len(public) != 5
or len(secret) != 5
or sum(test.get("detects_bug") is True for test in public) < 3
or sum(test.get("detects_bug") is True for test in secret) < 3
):
raise RuntimeError(f"Bug-first pipeline requires five public and five secret tests with at least three detections each for {func_name}")
else:
baseline_passing = [test for test in all_tests if test.get("detects_bug") is False]
bug_detecting = [test for test in all_tests if test.get("detects_bug") is not False]
if baseline_passing:
public = bug_detecting[:4] + baseline_passing[:1]
secret = bug_detecting[4:9] + baseline_passing[1:2]
else:
public = bug_detecting[:5]
secret = bug_detecting[5:10]
bugs_with_tests.append({
"function_name": func_name,
"bug_description": bug.get("bug_description", ""),
"public_tests": public,
"secret_tests": secret
})
state["public_tests"] = [
{
"function_name": bug["function_name"],
"bug_description": bug.get("bug_description", ""),
**test_case,
}
for bug in bugs_with_tests
for test_case in bug.get("public_tests", [])
]
state["secret_tests"] = [
{
"function_name": bug["function_name"],
"bug_description": bug.get("bug_description", ""),
**test_case,
}
for bug in bugs_with_tests
for test_case in bug.get("secret_tests", [])
]
if os.getenv("CHALLENGE_PIPELINE", "bug_first").strip().lower() == "bug_first":
public_count = len(state["public_tests"])
secret_count = len(state["secret_tests"])
if public_count < 3:
raise RuntimeError(f"Bug-first pipeline requires at least 3 public tests; got {public_count}")
if secret_count < 3:
raise RuntimeError(f"Bug-first pipeline requires at least 3 secret tests; got {secret_count}")
def _build_multi_bug_test_file(bugs: list, test_type: str = "public") -> str:
"""Build a test file with separate sections for each bug."""
# Helper to format test cases
def format_tests(tests):
case_lines = []
for tc in tests:
args_repr = tc.get("args", "()")
exp_value = tc.get("expected") if "expected" in tc else tc.get("correct_output")
comparison_mode = "value"
if tc.get("expected_is_repr"):
exp_repr = repr(_normalize_runtime_repr(str(exp_value)))
comparison_mode = "repr"
elif exp_value is None:
exp_repr = "None"
elif isinstance(exp_value, str):
# Already a string β€” validate it's a valid Python literal
try:
ast.literal_eval(exp_value)
exp_repr = exp_value
except (ValueError, SyntaxError, TypeError):
exp_repr = repr(exp_value)
else:
# Already a Python object (int, list, tuple, bool…)
exp_repr = repr(exp_value)
args_str = _format_test_args(args_repr)
case_lines.append(f" ({args_str}, {exp_repr}, {comparison_mode!r}),")
return "\n".join(case_lines) if case_lines else " # No tests"
# Build imports section
imports = []
for bug in bugs:
func = bug["function_name"]
imports.append(f"from {module_path} import {func}")
imports_str = "\n".join(imports)
# Build test sections for each bug
bug_sections = []
test_functions = []
for i, bug in enumerate(bugs, 1):
func = bug["function_name"]
tests = bug.get(f"{test_type}_tests", [])
bug_desc = bug.get("bug_description", "") # Changed from bug_variant
# Test cases for this bug
cases_literal = format_tests(tests)
# Create test function for this bug
bug_sections.append(
f"# ===== Bug #{i}: {func} =====\n"
f"# {bug_desc}\n"
f"_BUG{i}_TESTS = [\n{cases_literal}\n]\n"
)
test_functions.append(
f"def test_bug{i}():\n"
f" \"\"\"Test Bug #{i}: {func}\"\"\"\n"
f" print(f'\\n===== Testing Bug #{i}: {func} =====')\n"
f" passed = crashed = 0\n"
f" statuses = []\n"
f" details = []\n"
f" for j, (args, expected, comparison_mode) in enumerate(_BUG{i}_TESTS, 1):\n"
f" try:\n"
f" result = globals()[{func!r}](*args)\n"
f" actual = _normalize_runtime_repr(repr(result)) if comparison_mode == 'repr' else result\n"
f" profile_comparison = False\n"
f" if comparison_mode != 'repr' and isinstance(result, str) and isinstance(expected, str):\n"
f" profile_actual = _normalize_runtime_repr(repr(result))\n"
f" profile_expected = _normalize_runtime_repr(repr(expected))\n"
f" if profile_actual != repr(result) or profile_expected != repr(expected):\n"
f" actual, expected = profile_actual, profile_expected\n"
f" profile_comparison = True\n"
f" elif comparison_mode == 'repr':\n"
f" expected = _normalize_runtime_repr(expected)\n"
f" ok = actual == expected\n"
f" status = '[PASS]' if ok else '[FAIL]'\n"
f" passed += ok\n"
f" statuses.append(status.strip('[]'))\n"
f" args_preview = _short_test_value(args, ())\n"
f" actual_preview = _short_test_value(result, expected)\n"
f" if comparison_mode == 'repr' or profile_comparison:\n"
f" expected_preview = _short_test_value(expected, result)\n"
f" else:\n"
f" expected_preview = _short_test_value(expected, result)\n"
f" actual_raw = repr(result) if isinstance(result, str) else repr(result)\n"
f" details.append({{'num': j, 'status': status.strip('[]'), 'function_name': {func!r}, 'args': args_preview, 'expected': expected_preview, 'actual': actual_preview, 'actual_raw': actual_raw}})\n"
f" print(f' Test {{j}}: {{status}} (args={{args_preview}})')\n"
f" if not ok:\n"
f" expected_display = expected\n"
f" if comparison_mode == 'repr' or profile_comparison:\n"
f" try:\n"
f" expected_display = ast.literal_eval(expected)\n"
f" except (ValueError, SyntaxError, TypeError):\n"
f" pass\n"
f" profile_diagnostic = _runtime_profile_diagnostic(expected_display, result)\n"
f" if profile_diagnostic:\n"
f" expected_preview, actual_preview = profile_diagnostic\n"
f" else:\n"
f" expected_preview = _short_test_value(expected_display, result)\n"
f" actual_preview = _short_test_value(result, expected_display)\n"
f" print(f' expected = {{expected_preview}}')\n"
f" print(f' got = {{actual_preview}}')\n"
f" except Exception as exc:\n"
f" crashed += 1\n"
f" statuses.append('CRASH')\n"
f" args_preview = _short_test_value(args, ())\n"
f" details.append({{'num': j, 'status': 'CRASH', 'function_name': {func!r}, 'args': args_preview, 'expected': _short_test_value(expected, None), 'actual': {{'exception': type(exc).__name__, 'message': str(exc)}}}})\n"
f" print(f' Test {{j}}: [CRASH] - {{type(exc).__name__}}: {{exc}}')\n"
f" print(f' args = {{args!r}}')\n"
f" \n"
f" total = len(_BUG{i}_TESTS)\n"
f" return passed, crashed, total, statuses, details\n"
)
# Build main runner
bug_calls = []
for i in range(1, len(bugs) + 1):
bug_calls.append(f" p{i}, c{i}, t{i}, s{i}, d{i} = test_bug{i}()")
total_calc = " + ".join([f"t{i}" for i in range(1, len(bugs) + 1)])
passed_calc = " + ".join([f"p{i}" for i in range(1, len(bugs) + 1)])
crashed_calc = " + ".join([f"c{i}" for i in range(1, len(bugs) + 1)])
status_groups = ", ".join([f"s{i}" for i in range(1, len(bugs) + 1)])
detail_groups = ", ".join([f"d{i}" for i in range(1, len(bugs) + 1)])
main_runner = (
"def run_all_tests():\n"
" \"\"\"Run tests for all bugs.\"\"\"\n"
+ "\n".join(bug_calls) + "\n"
f" \n"
f" total = {total_calc}\n"
f" passed = {passed_calc}\n"
f" crashed = {crashed_calc}\n"
f" statuses = [{status_groups}]\n"
f" detail_groups = [{detail_groups}]\n"
f" per_test = []\n"
f" test_num = 1\n"
f" for group in detail_groups:\n"
f" for detail in group:\n"
f" per_test.append({{'num': test_num, 'status': detail['status'], 'function_name': detail['function_name'], 'args': detail['args'], 'expected': detail['expected'], 'actual': detail['actual']}})\n"
f" test_num += 1\n"
f" broken = total - passed\n"
f" all_passed = total > 0 and passed == total\n"
f" \n"
f" print(f'\\n=========================================')\n"
f" if all_passed:\n"
f" print(f'=== ALL TESTS PASSED ({{passed}}/{{total}}) ===')\n"
f" elif crashed == total:\n"
f" print(f'=== ALL TESTS CRASHED ({{crashed}}/{{total}}) ===')\n"
f" else:\n"
f" print(f'=== {{broken}}/{{total}} tests failed ({{crashed}} crash, {{broken-crashed}} wrong) ===')\n"
f" result = {{'passed': passed, 'total': total, 'all_passed': all_passed, 'per_test': per_test}}\n"
f" print('__CHALLENGE_RESULT__' + json.dumps(result, separators=(',', ':')))\n"
f" return all_passed\n"
)
# Combine everything
return (
"import sys\n"
"import os\n\n"
"import json\n\n"
"import re\n\n"
"import ast\n\n"
"from typing import Any\n\n"
"# Runtime profile comparison and concise diagnostics migration v6\n"
"_RUNTIME_ADDRESS_RE = re.compile(r'(?<= at )0x[0-9a-fA-F]+(?=>)')\n"
+ inspect.getsource(_normalize_runtime_repr)
+ "\n\n"
+ inspect.getsource(_short_test_value)
+ "\n\n"
+ inspect.getsource(_runtime_profile_diagnostic)
+ "\n\n"
"# Ensure UTF-8 output on Windows\n"
"if hasattr(sys.stdout, 'reconfigure'):\n"
" sys.stdout.reconfigure(encoding='utf-8')\n\n"
"# Make the repo root importable (works from workspace root or .metadata/)\n"
"_here = os.path.dirname(os.path.abspath(__file__))\n"
"sys.path.insert(0, _here)\n"
"sys.path.insert(0, os.path.dirname(_here))\n\n"
"sys.path.insert(0, os.getcwd())\n\n"
f"{imports_str}\n\n"
f"# {test_type.upper()} TEST CASES\n\n"
+ "\n".join(bug_sections) + "\n"
+ "\n".join(test_functions) + "\n"
+ main_runner + "\n"
"if __name__ == '__main__':\n"
" run_all_tests()\n"
)
# Store both generated runners outside the student-visible workspace.
private_dir = ensure_private_workspace_dir(clone_path)
challenge_run_path = os.path.join(private_dir, "challenge_run_public.py")
public_content = _build_multi_bug_test_file(bugs_with_tests, "public")
with open(challenge_run_path, "w", encoding="utf-8") as f:
f.write(public_content)
os.chmod(challenge_run_path, 0o600)
total_public = sum(len(b["public_tests"]) for b in bugs_with_tests)
print(f"[deployer] Stored private public-test runner ({total_public} tests across {len(bugs_with_tests)} bugs)")
# Keep secret tests outside the student-visible workspace.
secret_run_path = os.path.join(private_dir, "challenge_run_secret.py")
secret_content = _build_multi_bug_test_file(bugs_with_tests, "secret")
with open(secret_run_path, "w", encoding="utf-8") as f:
f.write(secret_content)
with open(os.path.join(private_dir, "secret_tests.json"), "w", encoding="utf-8") as f:
import json
json.dump({"secret_tests": state["secret_tests"]}, f, ensure_ascii=False)
os.chmod(secret_run_path, 0o600)
os.chmod(os.path.join(private_dir, "secret_tests.json"), 0o600)
total_secret = sum(len(b["secret_tests"]) for b in bugs_with_tests)
print(f"[deployer] Written: {secret_run_path} ({total_secret} secret tests across {len(bugs_with_tests)} bugs)")
# Write detailed explanation for instructor
detailed_path = os.path.join(clone_path, "detailed_explanation.txt")
with open(detailed_path, "w", encoding="utf-8") as f:
f.write(state.get("detailed_explanation", "No detailed explanation available."))
print(f"[deployer] Written: {detailed_path}")
# ── .metadata/ directory ──────────────────────────────────────────────────
# Contains only the sabotaged-file snapshot. Secret tests live outside the workspace.
# Hidden + read-only so students cannot accidentally access or overwrite them.
metadata_dir = os.path.join(clone_path, ".metadata")
os.makedirs(metadata_dir, exist_ok=True)
# Snapshot of every file the saboteur touched
target_file = state.get("target_file", "")
sabotaged_code = state.get("sabotaged_code", "")
snapshot_sources = sabotaged_files or {}
if not snapshot_sources and target_file and sabotaged_code:
rel = os.path.relpath(target_file, clone_path)
snapshot_sources = {rel: sabotaged_code}
for rel_path, content in snapshot_sources.items():
snap_name = rel_path.replace("/", "__").replace("\\", "__")
snap_path = os.path.join(metadata_dir, snap_name)
if os.path.exists(snap_path):
os.chmod(snap_path, stat.S_IWRITE)
with open(snap_path, "w", encoding="utf-8") as f:
f.write(content)
os.chmod(snap_path, stat.S_IREAD | stat.S_IRGRP | stat.S_IROTH)
print(f"[deployer] Snapshot: {snap_path}")
# Hide the whole .metadata directory on Windows
try:
import subprocess as _sp
_sp.run(["attrib", "+H", "+R", metadata_dir], check=False, capture_output=True)
except Exception:
pass
return state