Spaces:
Sleeping
Sleeping
Persist generation failure categories for prompt learning
Browse filesFiles changed (4)
57 unmodified lines58596061626364618 unmodified lines68368468568668768814 unmodified lines70370470570670770857 unmodified lines)from supabase_history import HistoryStoreError, get_feedback, get_instructor_dashboard, get_instructor_round_attempts, get_round_export, get_student_history, save_feedbackfrom supabase_comprehension import ComprehensionStoreError, get_submission_comprehension, save_comprehension_answer, save_comprehension_gradefrom supabase_generation_prompts import record_generation_event, record_generation_runfrom supabase_course_access import (CourseAccessStoreError,get_access_request,618 unmodified linesjob.error = llm_quota_error_message(exc) or _challenge_job_error_message(exc)job.message = "Challenge setup failed"job.status = "failed"record_generation_event(job_id, "challenge_job", "failed", job.progress, job.message, {"error_type": type(exc).__name__})record_generation_run(job_id,14 unmodified linesdetail = str(exc).strip()if detail:return f"Challenge generation failed: {detail[:500]}"return f"Challenge generation failed ({type(exc).__name__}). Check the server logs and try again."57 unmodified lines58596061626364618 unmodified lines68368468568668768868969069169269369469569669769869970070170214 unmodified lines71771871972072172272372472572672757 unmodified lines)from supabase_history import HistoryStoreError, get_feedback, get_instructor_dashboard, get_instructor_round_attempts, get_round_export, get_student_history, save_feedbackfrom supabase_comprehension import ComprehensionStoreError, get_submission_comprehension, save_comprehension_answer, save_comprehension_gradefrom supabase_generation_prompts import record_generation_event, record_generation_failures, record_generation_runfrom supabase_course_access import (CourseAccessStoreError,get_access_request,618 unmodified linesjob.error = llm_quota_error_message(exc) or _challenge_job_error_message(exc)job.message = "Challenge setup failed"job.status = "failed"failure_code = ("requested_bug_count_not_met"if isinstance(exc, RuntimeError) and str(exc).startswith("Failed to inject ")else "challenge_runtime_error")try:record_generation_failures(job_id, [{"stage": "challenge_generation","failure_code": failure_code,"prompt_key": "bug_injection" if failure_code == "requested_bug_count_not_met" else None,"attempt_number": 1,}])except Exception:logger.warning("Challenge failure category could not be persisted")record_generation_event(job_id, "challenge_job", "failed", job.progress, job.message, {"error_type": type(exc).__name__})record_generation_run(job_id,14 unmodified linesdetail = str(exc).strip()if detail:return f"Challenge generation failed: {detail[:500]}"if isinstance(exc, RuntimeError) and str(exc).startswith("Failed to inject "):return ("Challenge generation could not find a bug with enough valid tests in this repository. ""Try again or choose a repository with simpler, deterministic Python functions.")return f"Challenge generation failed ({type(exc).__name__}). Check the server logs and try again."
214 unmodified lines215216217218219220142 unmodified lines363364365366367368214 unmodified linesapi._challenge_job_error_message(ValueError("Generated challenge target file is unavailable")),"Challenge generation failed: Generated challenge target file is unavailable",)def setUp(self):self.progress_upload = self.enterContext(patch.object(api, "upload_challenge_progress_to_supabase", return_value=(True, "")))142 unmodified linesself.assertEqual(response.status_code, 422)self.assertEqual(api.app.state.jobs, {})def test_github_repository_urls_are_canonicalized_and_spoofing_is_rejected(self):self.assertEqual(api._check_github_url("https://github.com/acme/demo.git/"), "https://github.com/acme/demo")for value in (214 unmodified lines215216217218219220221222223142 unmodified lines366367368369370371372373374375376377378379380381382383384385386387388389390214 unmodified linesapi._challenge_job_error_message(ValueError("Generated challenge target file is unavailable")),"Challenge generation failed: Generated challenge target file is unavailable",)message = api._challenge_job_error_message(RuntimeError("Failed to inject 1 bugs (only got 0) in 4 candidate files"))self.assertIn("enough valid tests", message)self.assertNotIn("RuntimeError", message)def setUp(self):self.progress_upload = self.enterContext(patch.object(api, "upload_challenge_progress_to_supabase", return_value=(True, "")))142 unmodified linesself.assertEqual(response.status_code, 422)self.assertEqual(api.app.state.jobs, {})def test_generation_runtime_error_persists_a_safe_failure_category(self):session = self.add_session()job_id = str(uuid4())job = api.ChallengeJob(job_id=job_id, owner_session_id=session.session_id)api.app.state.jobs[job_id] = jobpayload = api.ChallengeStartRequest(github_url="https://github.com/acme/demo")with patch.object(api, "create_challenge", side_effect=RuntimeError("Failed to inject 1 bugs (only got 0) in 4 candidate files")), patch.object(api, "record_generation_run"), patch.object(api, "record_generation_event"), patch.object(api, "record_generation_failures") as record_failures:api._run_challenge_job(job_id, session.session_id, payload, "test-key")self.assertEqual(job.status, "failed")record_failures.assert_called_once_with(job_id, [{"stage": "challenge_generation","failure_code": "requested_bug_count_not_met","prompt_key": "bug_injection","attempt_number": 1,}])def test_github_repository_urls_are_canonicalized_and_spoofing_is_rejected(self):self.assertEqual(api._check_github_url("https://github.com/acme/demo.git/"), "https://github.com/acme/demo")for value in (
23 unmodified lines242526272829303132333435363738394023 unmodified lines"invalid_json": ("test_generation", "Return only valid JSON matching the exact schema. Do not add markdown or explanatory text."),"bug_crashes_tests": ("bug_injection", "Never use unsafe indexing, missing dict keys, zero division, recursion loops, or state that can raise exceptions."),"insufficient_detection": ("bug_injection", "Choose a broad behavioral logic defect that changes at least half of the supplied test outputs without crashing."),}def build_failure_derived_supplements(failures: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:counts: dict[str, int] = {}for failure in failures:code = str(failure.get("failure_code") or "").strip()if code:counts[code] = counts.get(code, 0) + 1by_prompt: dict[str, list[str]] = {key: [] for key in PROMPT_KEYS}for code, count in counts.items():if count < FAILURE_THRESHOLD:continuerule = FAILURE_SUPPLEMENTS.get(code)23 unmodified lines2425262728293031323334353637383940414243444546474823 unmodified lines"invalid_json": ("test_generation", "Return only valid JSON matching the exact schema. Do not add markdown or explanatory text."),"bug_crashes_tests": ("bug_injection", "Never use unsafe indexing, missing dict keys, zero division, recursion loops, or state that can raise exceptions."),"insufficient_detection": ("bug_injection", "Choose a broad behavioral logic defect that changes at least half of the supplied test outputs without crashing."),"requested_bug_count_not_met": ("bug_injection", "If a candidate does not produce a detectable bug, abandon it and try another deterministic public module-level function. Preserve all ten runnable tests per bug, with at least three detections in each five-test public and secret set; never weaken validation thresholds."),}def build_failure_derived_supplements(failures: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:generations_by_code: dict[str, set[str]] = {}unscoped_counts: dict[str, int] = {}for failure in failures:code = str(failure.get("failure_code") or "").strip()if code:generation_id = str(failure.get("generation_id") or "").strip()if generation_id:generations_by_code.setdefault(code, set()).add(generation_id)else:unscoped_counts[code] = unscoped_counts.get(code, 0) + 1by_prompt: dict[str, list[str]] = {key: [] for key in PROMPT_KEYS}failure_codes = set(generations_by_code) | set(unscoped_counts)for code in failure_codes:count = len(generations_by_code.get(code, set())) + unscoped_counts.get(code, 0)if count < FAILURE_THRESHOLD:continuerule = FAILURE_SUPPLEMENTS.get(code)
119 unmodified lines120121122123124125119 unmodified linesself.assertIn("primitive positional", learned["test_generation"]["instructions"])self.assertIn("unsafe indexing", learned["bug_injection"]["instructions"].lower())def test_event_telemetry_keeps_numeric_token_usage_and_filters_secrets(self):event_payload = {"llm_calls": 4,119 unmodified lines120121122123124125126127128129130131132133134135136137138139140119 unmodified linesself.assertIn("primitive positional", learned["test_generation"]["instructions"])self.assertIn("unsafe indexing", learned["bug_injection"]["instructions"].lower())def test_failure_threshold_counts_distinct_generation_runs(self):failures = [{"generation_id": "same-run", "failure_code": "requested_bug_count_not_met"}for _ in range(3)]self.assertEqual(prompts.build_failure_derived_supplements(failures), {})failures = [{"generation_id": f"run-{number}", "failure_code": "requested_bug_count_not_met"}for number in range(3)]learned = prompts.build_failure_derived_supplements(failures)self.assertIn("bug_injection", learned)self.assertIn("ten runnable tests", learned["bug_injection"]["instructions"])def test_event_telemetry_keeps_numeric_token_usage_and_filters_secrets(self):event_payload = {"llm_calls": 4,
backend/app.py+20-1
backend/test_api.py+22
supabase_generation_prompts.py+11-3
test_supabase_generation_prompts.py+15