Spaces:
Sleeping
Sleeping
Generate tests before injecting challenge bugs
Browse filesFiles changed (2)
1659 unmodified lines16601661166216631664166516663 unmodified lines167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169715 unmodified lines171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174022 unmodified lines1763176417651766176717681097 unmodified lines28662867286828692870287140 unmodified lines291229132914291529162917291829192920292120 unmodified lines294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129821659 unmodified linesfailure_events: list[dict[str, Any]] | None = None,progress_callback=None,) -> tuple[str, dict] | tuple[None, None]:"""Bug-first variant: propose one bug, then generate 10 cases and require 3/3 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", {})3 unmodified linestest_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):if progress_callback:progress_callback(32 + (bug_attempt - 1) * 2, f"Proposing bug candidate (attempt {bug_attempt}/3)")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 one complete, syntax-valid function with a deterministic logical defect. ""No test cases are supplied yet: the next stage will generate 10 cases, with at least ""6 detecting the defect (at least 3 public and 3 secret) and the remaining cases serving ""as regression guards. No case may crash. Choose a broadly observable change."),)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)15 unmodified lines_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 + "\nPIPELINE OVERRIDE: Generate EXACTLY 10 distinct test cases.").strip(),prompt_revision=test_revision,failure_events=failure_events,target_test_count=10,min_accepted_test_count=10,progress_callback=progress_callback,progress_start=38,)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 = []22 unmodified linesif len(valid_cases) < 10 or len(detecting_cases) < 6:_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=6)continuepublic_detecting_count = min(5, max(3, (len(detecting_cases) + 1) // 2))1097 unmodified linesreturn []requested_funcs = min(n_funcs, len(candidates))# Step 2: Use GPT to select best functions for bug injectionprint(f"[picker] Found {len(candidates)} candidate functions, asking GPT to select best {requested_funcs}...")40 unmodified lines# Validate selectionsvalid_names = {name for name, _ in candidates}selected = [name for name in selected if name in valid_names]if selected:print(f"[picker] GPT selected: {selected[:requested_funcs]}")return selected[:requested_funcs]else:_record_generation_failure(20 unmodified lines# Step 3: Fallback to rule-based scoring if GPT failsprint("[picker] Using fallback AST-based complexity scoring...")scored: list[tuple[int, str]] = []for name, code in candidates:# Score based on complexityscore = 0try:func_tree = ast.parse(code)for child in ast.walk(func_tree):if isinstance(child, ast.Constant) and isinstance(child.value, (int, float, str)):score += 2if isinstance(child, (ast.For, ast.While)):score += 3if isinstance(child, ast.If):score += 2if isinstance(child, ast.Return):score += 2if isinstance(child, ast.BinOp):score += 2if isinstance(child, ast.ListComp):score += 3if isinstance(child, ast.Compare):score += 1if isinstance(child, ast.Attribute):score -= 1 # Discourage class methodsexcept:score = 0if score > 0:scored.append((score, name))# Sort by score and take top candidatesscored.sort(key=lambda x: x[0], reverse=True)top_candidates = scored[:min(max(requested_funcs * 3, 8), len(scored))]random.shuffle(top_candidates)return [name for _, name in top_candidates[:requested_funcs]]def saboteur_init(state: ArchitectState) -> ArchitectState:1659 unmodified lines16601661166216631664166516663 unmodified lines16701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174415 unmodified lines17601761176217631764176522 unmodified lines17881789179017911792179317941795179617971097 unmodified lines28952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293340 unmodified lines297429752976297729782979298029812982298329842985298620 unmodified lines30073008300930103011301230131659 unmodified linesfailure_events: list[dict[str, Any]] | None = None,progress_callback=None,) -> tuple[str, dict] | tuple[None, None]:"""Generate ten valid cases first, then inject a bug designed to fail at least six."""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", {})3 unmodified linestest_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 Noneif progress_callback:progress_callback(32, "Generating ten tests on the original function")test_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 + "\nPIPELINE OVERRIDE: Generate EXACTLY 10 distinct test cases.").strip(),prompt_revision=test_revision,failure_events=failure_events,target_test_count=10,min_accepted_test_count=10,progress_callback=progress_callback,progress_start=32,)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=1,valid_test_count=len(test_cases), total_test_count=10,)return None, Noneoriginal_results = _execute_tests_on_source(current_source, surface_func_name, test_data, file_path=file_path, debug_mode=debug_mode)runnable_tests = [test for test in test_casesif (test.get("args") or test.get("test_args"))and (original_results.get(test.get("args") or test.get("test_args")) or (False, ""))[0]]if len(runnable_tests) < 10:_record_generation_failure(failure_events, stage="test_execution", failure_code="too_few_runnable_tests",prompt_key="test_generation", prompt_revision=test_revision, attempt_number=1,valid_test_count=len(runnable_tests), total_test_count=10,)return None, Nonetest_data = {**test_data, "test_cases": runnable_tests}original_results = {test.get("args") or test.get("test_args"): original_results[test.get("args") or test.get("test_args")]for test in runnable_tests}attempted_bugs: list[str] = []retry_feedback = ("Inject a deterministic logical defect that changes the outputs for at least 6 of the 10 supplied tests. ""The original outputs are provided. Preserve a valid signature and ensure all ten calls still execute.")for bug_attempt in range(1, 4):if progress_callback:progress_callback(52 + (bug_attempt - 1) * 2, f"Designing a test-detectable bug (attempt {bug_attempt}/3)")buggy_func_dict = _inject_bug_into_function(func_source=func_source,func_name=bug_func_name,llm=llm,attempted_bugs=attempted_bugs,test_cases=runnable_tests,original_results=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=retry_feedback,)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)15 unmodified lines_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))continuebuggy_results = _execute_tests_on_source(candidate_source, surface_func_name, test_data, file_path=file_path, debug_mode=debug_mode)valid_cases = []22 unmodified linesif len(valid_cases) < 10 or len(detecting_cases) < 6:_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=6)retry_feedback = (f"The previous bug changed only {len(detecting_cases)} of the 10 supplied test outputs. ""Choose a broader behavioral change that changes at least 6, while keeping all tests executable.")continuepublic_detecting_count = min(5, max(3, (len(detecting_cases) + 1) // 2))1097 unmodified linesreturn []requested_funcs = min(n_funcs, len(candidates))def ast_ranked_names(functions: list[tuple[str, str]], limit: int) -> list[str]:scored: list[tuple[int, str]] = []for name, code in functions:score = 0try:func_tree = ast.parse(code)for child in ast.walk(func_tree):if isinstance(child, ast.Constant) and isinstance(child.value, (int, float, str)):score += 2if isinstance(child, (ast.For, ast.While)):score += 3if isinstance(child, ast.If):score += 2if isinstance(child, ast.Return):score += 2if isinstance(child, ast.BinOp):score += 2if isinstance(child, ast.ListComp):score += 3if isinstance(child, ast.Compare):score += 1if isinstance(child, ast.Attribute):score -= 1except (SyntaxError, TypeError):continueif score > 0:scored.append((score, name))scored.sort(key=lambda item: item[0], reverse=True)shortlist = scored[:min(max(limit * 3, 8), len(scored))]random.shuffle(shortlist)return [name for _, name in shortlist[:limit]]# Step 2: Use GPT to select best functions for bug injectionprint(f"[picker] Found {len(candidates)} candidate functions, asking GPT to select best {requested_funcs}...")40 unmodified lines# Validate selectionsvalid_names = {name for name, _ in candidates}selected = list(dict.fromkeys(name for name in selected if name in valid_names))if selected:if len(selected) < requested_funcs:remaining = [(name, code) for name, code in candidates if name not in selected]selected.extend(ast_ranked_names(remaining, requested_funcs - len(selected)))print(f"[picker] GPT selected and AST-filled: {selected[:requested_funcs]}")return selected[:requested_funcs]else:_record_generation_failure(20 unmodified lines# Step 3: Fallback to rule-based scoring if GPT failsprint("[picker] Using fallback AST-based complexity scoring...")return ast_ranked_names(candidates, requested_funcs)def saboteur_init(state: ArchitectState) -> ArchitectState:
308 unmodified lines309310311312313314196 unmodified lines5115125135145155165171 unmodified line51952052152252352452573 unmodified lines59960060160260360460518 unmodified lines624625626627628629308 unmodified linesassert _pick_simple_functions(source, 1, llm=object()) == []def test_sabotage_validator_rejects_case_only_ast_changes():original = 'def normalize(value):\n return value == "ready"\n'case_only = 'def normalize(Value):\n return Value == "READY"\n'196 unmodified linesstate = {"candidate_files": paths,"target_file": paths[0],"num_bugs": 1,"nesting_level": 1,"refactoring_enabled": False,"debug_mode": False,1 unmodified linewith patch.dict("os.environ", {"CHALLENGE_PIPELINE": "legacy"}), patch("architect.saboteur.get_llm", return_value=object()), patch("architect.saboteur._pick_simple_functions", side_effect=[["first"], ["second", "third"]]), patch("architect.saboteur.random.shuffle"), patch("architect.saboteur._try_exec", side_effect=lambda code, *_args, **_kwargs: (True, "bug" if ("return value + 1" in str(code) or "return helper(value) + 2" in str(code) or "return helper(value)+2" in str(code)) else "original")), patch("architect.saboteur._sabotage_one_helper", side_effect=fake_sabotage):result = saboteur_init(state)73 unmodified lineswith 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(18 unmodified linesassert sum(test["detects_bug"] for test in data["public_tests"]) >= 3assert sum(test["detects_bug"] for test in data["secret_tests"]) >= 3assert sum(not test["detects_bug"] for test in data["public_tests"] + data["secret_tests"]) == 4def test_test_argument_parser_rejects_executable_expressions():308 unmodified lines309310311312313314315316317318319320321322323324325326327328329330331332333334196 unmodified lines5315325335345355365371 unmodified line53954054154254354454554654754854955055173 unmodified lines62562662762862963063118 unmodified lines650651652653654655656657658308 unmodified linesassert _pick_simple_functions(source, 1, llm=object()) == []def test_candidate_picker_fills_partial_model_selection_with_ast_candidates():source = "\n\n".join(f"def {name}(value):\n"" result = value\n"" if result > 2:\n"" result = result - 1\n"" result = result + 3\n"" return result"for name in ("first", "second", "third"))response = SimpleNamespace(content='{"selected_functions": ["first"]}')llm = Mock(invoke=Mock(return_value=response))selected = _pick_simple_functions(source, 3, llm)assert len(selected) == 3assert selected[0] == "first"assert set(selected) == {"first", "second", "third"}def test_sabotage_validator_rejects_case_only_ast_changes():original = 'def normalize(value):\n return value == "ready"\n'case_only = 'def normalize(Value):\n return Value == "READY"\n'196 unmodified linesstate = {"candidate_files": paths,"target_file": paths[0],"num_bugs": 2,"nesting_level": 1,"refactoring_enabled": False,"debug_mode": False,1 unmodified linewith patch.dict("os.environ", {"CHALLENGE_PIPELINE": "legacy"}), patch("architect.saboteur.get_llm", return_value=object()), patch("architect.saboteur._pick_simple_functions", side_effect=[["first"], ["second", "third"]]), patch("architect.saboteur.random.shuffle"), patch("architect.saboteur._try_exec", side_effect=lambda code, func_name, *_args, **_kwargs: (True,"bug" if any(candidate in _extract_function_source(str(code), func_name)[0]for candidate in ("return value + 1", "return helper(value) + 2", "return helper(value)+2")) else "original",)), patch("architect.saboteur._sabotage_one_helper", side_effect=fake_sabotage):result = saboteur_init(state)73 unmodified lineswith patch("architect.saboteur._inject_bug_into_function",return_value={"sabotaged_function_code": buggy, "bug_description": "Returns zero."},) as inject_bug, patch("architect.saboteur._generate_tests_for_function",return_value={"test_cases": test_cases},), patch(18 unmodified linesassert sum(test["detects_bug"] for test in data["public_tests"]) >= 3assert sum(test["detects_bug"] for test in data["secret_tests"]) >= 3assert sum(not test["detects_bug"] for test in data["public_tests"] + data["secret_tests"]) == 4assert len(inject_bug.call_args.kwargs["test_cases"]) == 10assert len(inject_bug.call_args.kwargs["original_results"]) == 10assert all(result[0] for result in inject_bug.call_args.kwargs["original_results"].values())def test_test_argument_parser_rejects_executable_expressions():
architect/saboteur.py+100-69
test_saboteur_generated_test_validation.py+32-3