Spaces:
Sleeping
Sleeping
Store challenge generation audit telemetry
Browse filesFiles changed (3)
53 unmodified lines545556575859472 unmodified lines5325335345355365376 unmodified lines5445455465475485491 unmodified line55155255355455555655744 unmodified lines60260360460560660760860961061161253 unmodified linesfail_submission_score_review,)from supabase_history import HistoryStoreError, get_instructor_dashboard, get_student_historyfrom supabase_course_access import (CourseAccessStoreError,get_access_request,472 unmodified linesif job is None or session is None:returnjob.status = "running"_set_challenge_job_progress(job, 2, "Checking challenge setup")try:if not payload.round_id:6 unmodified linestimer_minutes = int(round_info.get("timer_minutes", 0))else:with llm_api_key_context(captured_api_key):workspace_path = create_challenge(github_url=payload.github_url,nesting_level=payload.nesting_level,1 unmodified linerefactoring_enabled=payload.refactoring_enabled,debug_mode=payload.debug_mode,workspace_id=workspace_id,progress_callback=lambda progress, message: _set_challenge_job_progress(job, progress, message),generation_id=job_id,)timer_minutes = payload.timer_minutes44 unmodified linesjob.status = "completed"job.progress = 100job.message = "Challenge ready"except Exception as exc:logger.exception("Challenge generation failed for job %s", job_id)job.error = llm_quota_error_message(exc) or f"Challenge generation failed ({type(exc).__name__}). Check the server logs and try again."job.message = "Challenge setup failed"job.status = "failed"finally:with session.thread_lock:if session.active_job_id == job_id:53 unmodified lines54555657585960472 unmodified lines5335345355365375385395405415425435445455465475485495505515526 unmodified lines5595605615625635645655665675685691 unmodified line57157257357457557657744 unmodified lines62262362462562662762862963063163263363463563663763863964064164264364464564664764864953 unmodified linesfail_submission_score_review,)from supabase_history import HistoryStoreError, get_instructor_dashboard, get_student_historyfrom supabase_generation_prompts import record_generation_event, record_generation_runfrom supabase_course_access import (CourseAccessStoreError,get_access_request,472 unmodified linesif job is None or session is None:returnjob.status = "running"started_monotonic = time.monotonic()record_generation_run(job_id,course_id=_course_id(),source="round" if payload.round_id else "personal",github_url=payload.github_url,nesting_level=payload.nesting_level,num_bugs=payload.num_bugs,refactoring_enabled=payload.refactoring_enabled,timer_minutes=payload.timer_minutes,status="running",progress_max=2,)record_generation_event(job_id, "challenge_job", "started", 2, "Checking challenge setup")_set_challenge_job_progress(job, 2, "Checking challenge setup")try:if not payload.round_id:6 unmodified linestimer_minutes = int(round_info.get("timer_minutes", 0))else:with llm_api_key_context(captured_api_key):def generation_progress(progress: int, message: str) -> None:_set_challenge_job_progress(job, progress, message)record_generation_event(job_id, "architect", "progress", progress, message)record_generation_run(job_id, status="running", progress_max=max(job.progress, progress))workspace_path = create_challenge(github_url=payload.github_url,nesting_level=payload.nesting_level,1 unmodified linerefactoring_enabled=payload.refactoring_enabled,debug_mode=payload.debug_mode,workspace_id=workspace_id,progress_callback=generation_progress,generation_id=job_id,)timer_minutes = payload.timer_minutes44 unmodified linesjob.status = "completed"job.progress = 100job.message = "Challenge ready"record_generation_event(job_id, "challenge_job", "completed", 100, "Challenge ready")record_generation_run(job_id,status="completed",duration_ms=max(0, int((time.monotonic() - started_monotonic) * 1000)),progress_max=100,metadata={"workspace_id": workspace_id, "round_id": payload.round_id or ""},)except Exception as exc:logger.exception("Challenge generation failed for job %s", job_id)job.error = llm_quota_error_message(exc) or f"Challenge generation failed ({type(exc).__name__}). Check the server logs and try again."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,status="failed",duration_ms=max(0, int((time.monotonic() - started_monotonic) * 1000)),error_type=type(exc).__name__,error_message=str(exc)[:2000],progress_max=job.progress,)finally:with session.thread_lock:if session.active_job_id == job_id:
13 unmodified lines14151617181997 unmodified lines11711811912013 unmodified lineslogger = logging.getLogger("legacy_generation_prompts")PROMPTS_TABLE = "challenge_generation_prompt_rules"FAILURES_TABLE = "challenge_generation_failures"PROMPT_KEYS = {"function_selection", "test_generation", "bug_injection"}97 unmodified lineswith urlopen(request, timeout=5):returnexcept (HTTPError, TimeoutError, URLError, OSError, TypeError, ValueError) as exc:logger.warning("Generation failure telemetry unavailable: %s", type(exc).__name__)13 unmodified lines141516171819202197 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919013 unmodified lineslogger = logging.getLogger("legacy_generation_prompts")PROMPTS_TABLE = "challenge_generation_prompt_rules"FAILURES_TABLE = "challenge_generation_failures"RUNS_TABLE = "challenge_generation_runs"EVENTS_TABLE = "challenge_generation_events"PROMPT_KEYS = {"function_selection", "test_generation", "bug_injection"}97 unmodified lineswith urlopen(request, timeout=5):returnexcept (HTTPError, TimeoutError, URLError, OSError, TypeError, ValueError) as exc:logger.warning("Generation failure telemetry unavailable: %s", type(exc).__name__)def record_generation_run(generation_id: str, **fields: dict) -> None:configured = _configuration()if not configured or not generation_id:returnurl, key = configuredmetadata = fields.pop("metadata", {})if not isinstance(metadata, dict):metadata = {}blocked = ("api_key", "secret", "password", "authorization", "token", "source_code", "code")safe_metadata = {}for key_name, value in metadata.items():if any(marker in str(key_name).lower() for marker in blocked):continuesafe_metadata[str(key_name)[:80]] = str(value)[:10000]row = {"generation_id": str(generation_id)[:80]}for field in ("course_id", "source", "github_url", "nesting_level", "num_bugs", "refactoring_enabled", "timer_minutes", "status", "duration_ms", "error_type", "error_message", "progress_max"):if field in fields:value = fields[field]if field in {"github_url", "error_type", "error_message", "course_id", "source", "status"}:value = str(value)[:2000] if value is not None else Noneelif field == "progress_max":value = max(0, min(100, int(value or 0)))row[field] = valueif safe_metadata:row["metadata"] = safe_metadataquery = urlencode({"on_conflict": "generation_id"})request = Request(f"{url}/rest/v1/{RUNS_TABLE}?{query}",data=json.dumps(row).encode("utf-8"),headers=_headers(key, prefer="resolution=merge-duplicates,return=minimal"),method="POST",)try:with urlopen(request, timeout=5):returnexcept (HTTPError, TimeoutError, URLError, OSError, TypeError, ValueError) as exc:logger.warning("Generation run telemetry unavailable: %s", type(exc).__name__)def record_generation_event(generation_id: str, stage: str, event_type: str, progress: int | None = None, message: str = "", payload: dict | None = None) -> None:configured = _configuration()if not configured or not generation_id:returnurl, key = configuredsafe_payload = payload if isinstance(payload, dict) else {}blocked = ("api_key", "secret", "password", "authorization", "token", "source_code", "code")safe_payload = {str(key_name)[:80]: str(value)[:10000] for key_name, value in safe_payload.items() if not any(marker in str(key_name).lower() for marker in blocked)}row = {"generation_id": str(generation_id)[:80],"stage": str(stage)[:60],"event_type": str(event_type)[:40],"progress": max(0, min(100, int(progress))) if progress is not None else None,"message": str(message)[:500] or None,"payload": safe_payload,}request = Request(f"{url}/rest/v1/{EVENTS_TABLE}",data=json.dumps(row).encode("utf-8"),headers=_headers(key),method="POST",)try:with urlopen(request, timeout=5):returnexcept (HTTPError, TimeoutError, URLError, OSError, TypeError, ValueError) as exc:logger.warning("Generation event telemetry unavailable: %s", type(exc).__name__)
815 unmodified lines816817818815 unmodified linesalter table public.challenge_generation_failures enable row level security;revoke all on table public.challenge_generation_failures from public, anon, authenticated;grant select, insert on table public.challenge_generation_failures to service_role;815 unmodified lines816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857815 unmodified linesalter table public.challenge_generation_failures enable row level security;revoke all on table public.challenge_generation_failures from public, anon, authenticated;grant select, insert on table public.challenge_generation_failures to service_role;create table if not exists public.challenge_generation_runs (generation_id text primary key,course_id text not null default 'local',source text not null check (source in ('personal', 'round')),github_url text,nesting_level integer,num_bugs integer,refactoring_enabled boolean,timer_minutes integer,status text not null check (status in ('running', 'completed', 'failed')),started_at timestamptz not null default now(),finished_at timestamptz,duration_ms integer,error_type text,error_message text,progress_max integer not null default 0,metadata jsonb not null default '{}'::jsonb,updated_at timestamptz not null default now());alter table public.challenge_generation_runs enable row level security;revoke all on table public.challenge_generation_runs from public, anon, authenticated;grant select, insert, update on table public.challenge_generation_runs to service_role;create table if not exists public.challenge_generation_events (event_id uuid primary key default gen_random_uuid(),generation_id text not null,stage text not null,event_type text not null,progress integer,message text,payload jsonb not null default '{}'::jsonb,created_at timestamptz not null default now());create index if not exists challenge_generation_events_generation_idxon public.challenge_generation_events (generation_id, created_at desc);alter table public.challenge_generation_events enable row level security;revoke all on table public.challenge_generation_events from public, anon, authenticated;grant select, insert on table public.challenge_generation_events to service_role;
backend/app.py+38-1
supabase_generation_prompts.py+71-1
supabase_schema.sql+39