Spaces:
Sleeping
Sleeping
Add bug-first pipeline behind legacy feature flag
Browse filesFiles changed (5)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Bug-first challenge pipeline feature behind an explicit environment flag."""
from __future__ import annotations
import astimport osfrom collections.abc import Callable
from architect.graph import build_graph
PIPELINE_ENV = "CHALLENGE_PIPELINE"LEGACY_PIPELINE = "legacy"BUG_FIRST_PIPELINE = "bug_first"
def get_challenge_pipeline_variant() -> str: variant = os.getenv(PIPELINE_ENV, LEGACY_PIPELINE).strip().lower() return variant if variant in {LEGACY_PIPELINE, BUG_FIRST_PIPELINE} else LEGACY_PIPELINE
def build_selected_graph(progress_callback: Callable[[int, str], None] | None = None): variant = get_challenge_pipeline_variant() if variant == BUG_FIRST_PIPELINE: # Bug-first implementation is added separately after replay coverage. return build_graph(progress_callback=progress_callback) return build_graph(progress_callback=progress_callback)
def validate_challenge_contract(result: dict) -> tuple[bool, str]: public_tests = result.get("public_tests") or [] secret_tests = result.get("secret_tests") or [] if len(public_tests) < 5: return False, "Bug-first pipeline requires at least 5 public tests" if len(secret_tests) < 5: return False, "Bug-first pipeline requires at least 5 secret tests"
target_file = str(result.get("target_file") or "") sabotaged_code = str(result.get("sabotaged_code") or "") if not target_file or not sabotaged_code: return False, "Bug-first pipeline requires a target file and sabotaged source"
try: ast.parse(sabotaged_code) except SyntaxError as exc: return False, f"Generated source is syntactically invalid: {exc}"
return True, ""248 unmodified lines249250251252253254248 unmodified linesfor bug in bugs_with_testsfor test_case in bug.get("secret_tests", [])]def _build_multi_bug_test_file(bugs: list, test_type: str = "public") -> str:"""Build a test file with separate sections for each bug."""248 unmodified lines249250251252253254255256257258259260261262248 unmodified linesfor bug in bugs_with_testsfor test_case in bug.get("secret_tests", [])]if os.getenv("CHALLENGE_PIPELINE", "legacy").strip().lower() == "bug_first":public_count = len(state["public_tests"])secret_count = len(state["secret_tests"])if public_count < 5:raise RuntimeError(f"Bug-first pipeline requires at least 5 public tests; got {public_count}")if secret_count < 5:raise RuntimeError(f"Bug-first pipeline requires at least 5 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."""
1486 unmodified lines14871488148914901491149218 unmodified lines1511151215131514151515161486 unmodified linesreturn total_tests > 0 and detecting_tests >= (total_tests + 1) // 2def _sabotage_one_helper(bug_func_name: str,current_source: str,18 unmodified linesReturns (buggy_source, data_dict) or (None, None) on failure."""func_source, start_line, end_line = _extract_function_source(current_source, bug_func_name)prompt_supplements = prompt_supplements or {}test_rule = prompt_supplements.get("test_generation", {})1486 unmodified lines148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161318 unmodified lines1632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551486 unmodified linesreturn total_tests > 0 and detecting_tests >= (total_tests + 1) // 2def _bug_first_sabotage_one_helper(bug_func_name: str,current_source: str,surface_func_name: str,surface_source: str,instructions: str,llm,indirect_mode: bool,call_chain: list[str] | None = None,previous_bugs: list[str] | None = None,target_nesting: int = 3,file_path: str | None = None,debug_mode: bool = False,prompt_supplements: dict[str, dict[str, Any]] | None = None,failure_events: list[dict[str, Any]] | None = None,) -> tuple[str, dict] | tuple[None, None]:"""Bug-first variant: propose one bug, then generate 12-16 cases and require 5/5 public/secret detection."""func_source, start_line, end_line = _extract_function_source(current_source, bug_func_name)prompt_supplements = prompt_supplements or {}bug_rule = prompt_supplements.get("bug_injection", {})bug_instructions = str(bug_rule.get("instructions") or "") if isinstance(bug_rule, dict) else ""bug_revision = bug_rule.get("revision") if isinstance(bug_rule, dict) else Nonetest_rule = prompt_supplements.get("test_generation", {})test_instructions = str(test_rule.get("instructions") or "") if isinstance(test_rule, dict) else ""test_revision = test_rule.get("revision") if isinstance(test_rule, dict) else Noneattempted_bugs: list[str] = []for bug_attempt in range(1, 4):buggy_func_dict = _inject_bug_into_function(func_source=func_source,func_name=bug_func_name,llm=llm,attempted_bugs=attempted_bugs,test_cases=[],original_results={},debug_mode=debug_mode,require_internal_change=bug_attempt <= 2,prompt_supplement=bug_instructions,prompt_revision=bug_revision,failure_events=failure_events,retry_feedback="Generate a complete function with one meaningful behavioral logic defect.",)if buggy_func_dict is None:_record_generation_failure(failure_events, stage="bug_injection", failure_code="no_valid_bug_output", prompt_key="bug_injection", prompt_revision=bug_revision, attempt_number=bug_attempt)continuesabotaged_func = buggy_func_dict["sabotaged_function_code"]bug_description = buggy_func_dict.get("bug_description", "")if bug_description:attempted_bugs.append(bug_description)if _has_only_case_changes(func_source, sabotaged_func):_record_generation_failure(failure_events, stage="bug_validation", failure_code="cosmetic_only_change", prompt_key="bug_injection", prompt_revision=bug_revision, attempt_number=bug_attempt)continuelines = current_source.splitlines(keepends=True)candidate_source = "".join(lines[:start_line]) + sabotaged_func + "\n" + "".join(lines[end_line:])try:ast.parse(candidate_source)except SyntaxError as exc:_record_generation_failure(failure_events, stage="bug_validation", failure_code="invalid_module_syntax", prompt_key="bug_injection", prompt_revision=bug_revision, attempt_number=bug_attempt, error_detail=str(exc))continuetest_data = _generate_tests_for_function(func_source=func_source,func_name=bug_func_name,surface_func_name=surface_func_name,surface_source=surface_source,llm=llm,indirect_mode=indirect_mode,debug_mode=debug_mode,prompt_supplement=test_instructions,prompt_revision=test_revision,failure_events=failure_events,)test_cases = test_data.get("test_cases", []) if test_data else []if len(test_cases) < 10:_record_generation_failure(failure_events, stage="test_generation", failure_code="too_few_test_cases", prompt_key="test_generation", prompt_revision=test_revision, attempt_number=bug_attempt, valid_test_count=len(test_cases), total_test_count=10)continueoriginal_results = _execute_tests_on_source(current_source, surface_func_name, test_data, file_path=file_path, debug_mode=debug_mode)buggy_results = _execute_tests_on_source(candidate_source, surface_func_name, test_data, file_path=file_path, debug_mode=debug_mode)valid_cases = []detecting_cases = []for test in test_cases:args_text = test.get("args", "") or test.get("test_args", "")original = original_results.get(args_text)buggy = buggy_results.get(args_text)if not args_text or not original or not buggy:continueoriginal_ok, original_value = originalbuggy_ok, buggy_value = buggyif not original_ok or not buggy_ok:continuevalid_cases.append({**test, "expected": original_value, "expected_is_repr": True})if original_value != buggy_value:detecting_cases.append({**test, "expected": original_value, "expected_is_repr": True})if len(detecting_cases) < 10:_record_generation_failure(failure_events, stage="bug_validation", failure_code="insufficient_detection", prompt_key="bug_injection", prompt_revision=bug_revision, attempt_number=bug_attempt, valid_test_count=len(detecting_cases), total_test_count=10)continuepublic_tests = detecting_cases[:5]secret_tests = detecting_cases[5:10]return candidate_source, {"test_cases": valid_cases,"detecting_tests": detecting_cases,"public_tests": public_tests,"secret_tests": secret_tests,"bug_description": bug_description,"_debug_func_name": bug_func_name,"_debug_start_line": start_line,"_debug_end_line": end_line,"_debug_func_source": func_source,"_debug_sabot_func": sabotaged_func,"_debug_tests_summary": f"{len(detecting_cases)} tests detect bug",}return None, Nonedef _sabotage_one_helper(bug_func_name: str,current_source: str,18 unmodified linesReturns (buggy_source, data_dict) or (None, None) on failure."""if os.getenv("CHALLENGE_PIPELINE", "legacy").strip().lower() == "bug_first":return _bug_first_sabotage_one_helper(bug_func_name=bug_func_name,current_source=current_source,surface_func_name=surface_func_name,surface_source=surface_source,instructions=instructions,llm=llm,indirect_mode=indirect_mode,call_chain=call_chain,previous_bugs=previous_bugs,target_nesting=target_nesting,file_path=file_path,debug_mode=debug_mode,prompt_supplements=prompt_supplements,failure_events=failure_events,)func_source, start_line, end_line = _extract_function_source(current_source, bug_func_name)prompt_supplements = prompt_supplements or {}test_rule = prompt_supplements.get("test_generation", {})
335 unmodified lines3363373383393403413423 unmodified lines34634734834935035135261 unmodified lines414415416417418419335 unmodified linesgeneration_id: str | None = None,) -> str:"""Run the architect graph and persist its result into a challenge workspace."""from architect.graph import build_graphfrom architect.repo_cloner import WORKSPACES_DIRclone_path = ""3 unmodified linesfrom supabase_generation_prompts import load_generation_prompt_supplementsgraph = build_graph(progress_callback=progress_callback)initial_state = {"github_url": github_url,"nesting_level": nesting_level,61 unmodified lines"nesting_level": nesting_level,"refactoring_enabled": refactoring_enabled,"debug_mode": debug_mode,"bug_description": result.get("bug_description", ""),"detailed_explanation": result.get("detailed_explanation", ""),"challenge_summary": result.get("challenge_summary", ""),335 unmodified lines3363373383393403413423 unmodified lines34634734834935035135235361 unmodified lines415416417418419420421335 unmodified linesgeneration_id: str | None = None,) -> str:"""Run the architect graph and persist its result into a challenge workspace."""from architect.bug_first_pipeline import build_selected_graph, get_challenge_pipeline_variantfrom architect.repo_cloner import WORKSPACES_DIRclone_path = ""3 unmodified linesfrom supabase_generation_prompts import load_generation_prompt_supplementspipeline_variant = get_challenge_pipeline_variant()graph = build_selected_graph(progress_callback=progress_callback)initial_state = {"github_url": github_url,"nesting_level": nesting_level,61 unmodified lines"nesting_level": nesting_level,"refactoring_enabled": refactoring_enabled,"debug_mode": debug_mode,"pipeline_variant": pipeline_variant,"bug_description": result.get("bug_description", ""),"detailed_explanation": result.get("detailed_explanation", ""),"challenge_summary": result.get("challenge_summary", ""),
359 unmodified lines360361362363364365359 unmodified linesassert "only modified the return value" in retry_messages[1].contentdef test_test_argument_parser_rejects_executable_expressions():import tempfilefrom pathlib import Path359 unmodified lines360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423359 unmodified linesassert "only modified the return value" in retry_messages[1].contentdef test_bug_first_variant_flags_fail_closed_and_validates_contract():import osfrom unittest.mock import patchfrom architect.bug_first_pipeline import get_challenge_pipeline_variant, validate_challenge_contractwith patch.dict(os.environ, {"CHALLENGE_PIPELINE": "unknown"}, clear=False):assert get_challenge_pipeline_variant() == "legacy"valid_result = {"target_file": "sample.py","sabotaged_code": "def target(value):\n return 0\n","public_tests": [{"args": f"({i},)"} for i in range(5)],"secret_tests": [{"args": f"({i + 5},)"} for i in range(5)],}assert validate_challenge_contract(valid_result) == (True, "")missing_secret = {**valid_result, "secret_tests": valid_result["secret_tests"][:4]}valid, reason = validate_challenge_contract(missing_secret)assert not validassert "5 secret" in reasondef test_bug_first_helper_requires_ten_detecting_tests():from architect.saboteur import _bug_first_sabotage_one_helpercurrent = "def target(value):\n return value\n"buggy = "def target(value):\n return 0\n"test_cases = [{"args": f"({i},)", "correct_output": str(i)} for i in range(16)]with patch("architect.saboteur._inject_bug_into_function",return_value={"sabotaged_function_code": buggy, "bug_description": "Returns zero."},), patch("architect.saboteur._generate_tests_for_function",return_value={"test_cases": test_cases},), patch("architect.saboteur._execute_tests_on_source",side_effect=lambda source, _name, _data, **_kwargs: {case["args"]: (True, "0" if "return 0" in source else str(ast.literal_eval(case["args"])[0]))for case in test_cases},):candidate, data = _bug_first_sabotage_one_helper(bug_func_name="target",current_source=current,surface_func_name="target",surface_source="",instructions="",llm=object(),indirect_mode=False,)assert candidate is not Noneassert data is not Noneassert len(data["public_tests"]) == 5assert len(data["secret_tests"]) == 5def test_test_argument_parser_rejects_executable_expressions():import tempfilefrom pathlib import Path
architect/bug_first_pipeline.pyAdded+48
architect/challenge_deployer.py+8
architect/saboteur.py+139
challenge_runtime.py+4-2
test_saboteur_generated_test_validation.py+58