Spaces:
Runtime error
Runtime error
Download tasks.py from Krsnapriya/CodeReviewEnv-Elite: direct link, hf CLI and curl.
- Browser
- Download file 22 kB
-
https://huggingface.co/spaces/Krsnapriya/CodeReviewEnv-Elite/resolve/main/tasks.py
- Command line
-
hf download hf://spaces/Krsnapriya/CodeReviewEnv-Elite/tasks.py
-
curl -L -o tasks.py https://huggingface.co/spaces/Krsnapriya/CodeReviewEnv-Elite/resolve/main/tasks.py
22 kB
| """ | |
| Task definitions for CodeReviewEnv-RX. | |
| Multi-file tasks with confidence/ambiguity, call graphs, and 6 difficulty levels. | |
| Each task contains realistic Python code across one or more files with intentional | |
| bugs, style violations, and optimization opportunities for the agent to detect. | |
| """ | |
| from dataclasses import dataclass, field | |
| from typing import List, Dict, Optional | |
| class Issue: | |
| """Represents a single issue in the code.""" | |
| file: str # Which file this issue is in | |
| line: int # 1-indexed line number | |
| issue_type: str # "bug", "style", "optimization" | |
| description: str # Human-readable description | |
| severity: str = "high" # "high", "medium", "low" | |
| confidence: float = 1.0 # 1.0 = definite bug, 0.5 = ambiguous, 0.0 = trap | |
| cascade_lines: List[int] = field(default_factory=list) | |
| is_root_cause: bool = False # True if this is a cross-file root cause | |
| class Task: | |
| """A code review task supporting multi-file codebases.""" | |
| name: str | |
| level: str | |
| description: str | |
| files: Dict[str, str] # {filename: code_content} | |
| issues: List[Issue] # Required issues (must-find) | |
| optional_issues: List[Issue] # Bonus issues | |
| call_graph: Dict[str, List[str]] = field(default_factory=dict) # {func: [calls]} | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # EASY TASK: Single file, 2 clear bugs | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| EASY_FILES = { | |
| "main.py": '''\ | |
| def calculate_discount(price, discount_percent): | |
| """Apply a percentage discount to the given price.""" | |
| if discount_percent > 1.0: | |
| raise ValueError("Discount must be between 0 and 1") | |
| final_price = price + price * discount_percent # BUG: should subtract, not add | |
| return final_price | |
| def format_price(price): | |
| """Format price as a string with 2 decimal places.""" | |
| return "$" + str(round(price)) # BUG: round() without ndigits loses decimals | |
| ''' | |
| } | |
| EASY_ISSUES = [ | |
| Issue(file="main.py", line=5, issue_type="bug", | |
| description="Operator error: uses + instead of - for discount calculation", | |
| severity="high", confidence=1.0, cascade_lines=[6]), | |
| Issue(file="main.py", line=10, issue_type="bug", | |
| description="round() called without ndigits=2, loses decimal precision", | |
| severity="medium", confidence=1.0), | |
| ] | |
| EASY_OPTIONAL = [] | |
| EASY_GRAPH = { | |
| "calculate_discount": [], | |
| "format_price": [], | |
| } | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # MEDIUM TASK: Multiple functions with interdependent bugs + style | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| MEDIUM_FILES = { | |
| "main.py": '''\ | |
| import os | |
| def read_config(filepath): | |
| """Read a configuration file and return key-value pairs.""" | |
| config = {} | |
| f = open(filepath, "r") # BUG: file handle never closed (resource leak) | |
| for line in f: | |
| key, value = line.strip().split("=") # BUG: no error handling for malformed lines | |
| config[key] = value | |
| return config | |
| def get_setting(config, key): | |
| """Retrieve a setting, return None if missing.""" | |
| return config[key] # BUG: should use .get(key) to avoid KeyError | |
| def apply_settings(filepath): | |
| """Load config and apply settings.""" | |
| config = read_config(filepath) | |
| timeout = int(get_setting(config, "timeout")) | |
| return timeout | |
| ''' | |
| } | |
| MEDIUM_ISSUES = [ | |
| Issue(file="main.py", line=6, issue_type="bug", | |
| description="File handle opened but never closed β resource leak", | |
| severity="high", confidence=1.0, cascade_lines=[20, 21]), | |
| Issue(file="main.py", line=8, issue_type="bug", | |
| description="No error handling for malformed config lines (missing '=')", | |
| severity="medium", confidence=1.0, cascade_lines=[9]), | |
| Issue(file="main.py", line=15, issue_type="bug", | |
| description="Direct dict access instead of .get() β raises KeyError on missing keys", | |
| severity="high", confidence=1.0, cascade_lines=[21]), | |
| ] | |
| MEDIUM_OPTIONAL = [ | |
| Issue(file="main.py", line=1, issue_type="style", | |
| description="Unused import 'os'", | |
| severity="low", confidence=1.0), | |
| Issue(file="main.py", line=6, issue_type="optimization", | |
| description="Should use context manager (with statement) for file I/O", | |
| severity="low", confidence=1.0), | |
| ] | |
| MEDIUM_GRAPH = { | |
| "apply_settings": ["read_config", "get_setting"], | |
| "read_config": [], | |
| "get_setting": [], | |
| } | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # HARD TASK: Multi-function with subtle logic, cascading errors | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| HARD_FILES = { | |
| "main.py": '''\ | |
| from typing import List, Optional | |
| def normalize_scores(scores: List[float]) -> List[float]: | |
| """Normalize scores to 0-1 range using min-max scaling.""" | |
| min_score = min(scores) | |
| max_score = max(scores) | |
| return [(s - min_score) / (max_score - min_score) for s in scores] # BUG: ZeroDivisionError | |
| def compute_weighted_average(values: List[float], weights: List[float]) -> float: | |
| """Compute weighted average of values.""" | |
| total = sum(v * w for v, w in zip(values, weights)) # BUG: zip silently truncates | |
| return total / sum(weights) # BUG: ZeroDivisionError if all weights are 0 | |
| def find_outliers(data: List[float], threshold: float = 2.0) -> List[float]: | |
| """Find outliers using z-score method.""" | |
| mean = sum(data) / len(data) # BUG: ZeroDivisionError on empty list | |
| variance = sum((x - mean) ** 2 for x in data) / len(data) | |
| std_dev = variance ** 0.5 | |
| return [x for x in data if abs(x - mean) / std_dev > threshold] # BUG: ZeroDivisionError | |
| def analyze_dataset(scores: List[float], weights: List[float]) -> dict: | |
| """Full analysis pipeline.""" | |
| normalized = normalize_scores(scores) | |
| avg = compute_weighted_average(normalized, weights) | |
| outliers = find_outliers(normalized) | |
| return { | |
| "normalized": normalized, | |
| "weighted_average": avg, | |
| "outliers": outliers, | |
| "summary": f"Processed {len(scores)} scores, found {len(outliers)} outliers" | |
| } | |
| ''' | |
| } | |
| HARD_ISSUES = [ | |
| Issue(file="main.py", line=7, issue_type="bug", | |
| description="ZeroDivisionError when all scores are equal (max == min)", | |
| severity="high", confidence=1.0, cascade_lines=[22, 23]), | |
| Issue(file="main.py", line=11, issue_type="bug", | |
| description="zip() silently truncates mismatched-length lists", | |
| severity="high", confidence=1.0, cascade_lines=[23]), | |
| Issue(file="main.py", line=12, issue_type="bug", | |
| description="ZeroDivisionError if sum of weights is 0", | |
| severity="high", confidence=1.0, cascade_lines=[23]), | |
| Issue(file="main.py", line=16, issue_type="bug", | |
| description="ZeroDivisionError on empty input list", | |
| severity="high", confidence=1.0, cascade_lines=[24]), | |
| Issue(file="main.py", line=19, issue_type="bug", | |
| description="ZeroDivisionError if standard deviation is 0", | |
| severity="medium", confidence=1.0, cascade_lines=[24]), | |
| ] | |
| HARD_OPTIONAL = [ | |
| Issue(file="main.py", line=1, issue_type="style", | |
| description="Optional imported but never used", | |
| severity="low", confidence=1.0), | |
| Issue(file="main.py", line=11, issue_type="optimization", | |
| description="Could use numpy for vectorized weighted average", | |
| severity="low", confidence=1.0), | |
| Issue(file="main.py", line=17, issue_type="optimization", | |
| description="Variance computed with second pass; could use online algorithm", | |
| severity="low", confidence=1.0), | |
| ] | |
| HARD_GRAPH = { | |
| "analyze_dataset": ["normalize_scores", "compute_weighted_average", "find_outliers"], | |
| "normalize_scores": [], | |
| "compute_weighted_average": [], | |
| "find_outliers": [], | |
| } | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # SECURITY TASK: Vulnerability detection in authentication | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| SECURITY_FILES = { | |
| "main.py": '''\ | |
| import hashlib | |
| import sqlite3 | |
| def authenticate(username, password): | |
| """Authenticate a user against the database.""" | |
| conn = sqlite3.connect("users.db") | |
| cursor = conn.cursor() | |
| query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'" # BUG: SQL injection | |
| cursor.execute(query) | |
| result = cursor.fetchone() | |
| conn.close() | |
| return result is not None | |
| def hash_password(password): | |
| """Hash a password for storage.""" | |
| return hashlib.md5(password.encode()).hexdigest() # BUG: MD5 is cryptographically broken | |
| def check_admin(user_role): | |
| """Check if user has admin privileges.""" | |
| if user_role == "admin" or user_role == "ADMIN": | |
| return True | |
| return False | |
| def load_user_file(username): | |
| """Load user profile from file.""" | |
| filepath = f"/data/profiles/{username}.json" # BUG: path traversal | |
| with open(filepath, "r") as f: | |
| return f.read() | |
| API_KEY = "sk-prod-12345abcdef" # BUG: hardcoded secret | |
| ''' | |
| } | |
| SECURITY_ISSUES = [ | |
| Issue(file="main.py", line=8, issue_type="bug", | |
| description="SQL injection vulnerability", | |
| severity="high", confidence=1.0, cascade_lines=[9, 10, 11]), | |
| Issue(file="main.py", line=16, issue_type="bug", | |
| description="MD5 is cryptographically broken", | |
| severity="high", confidence=1.0), | |
| Issue(file="main.py", line=24, issue_type="bug", | |
| description="Path traversal vulnerability", | |
| severity="high", confidence=1.0, cascade_lines=[25]), | |
| Issue(file="main.py", line=28, issue_type="bug", | |
| description="Hardcoded API key/secret in source code", | |
| severity="high", confidence=1.0), | |
| ] | |
| SECURITY_OPTIONAL = [ | |
| Issue(file="main.py", line=19, issue_type="style", | |
| description="Case-insensitive comparison should use .lower()", | |
| severity="low", confidence=1.0), | |
| Issue(file="main.py", line=6, issue_type="optimization", | |
| description="Database connection should use context manager", | |
| severity="low", confidence=1.0), | |
| ] | |
| SECURITY_GRAPH = { | |
| "authenticate": [], | |
| "hash_password": [], | |
| "check_admin": [], | |
| "load_user_file": [], | |
| } | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CONCURRENCY TASK: Race conditions, deadlocks | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| CONCURRENCY_FILES = { | |
| "main.py": '''\ | |
| import threading | |
| import time | |
| balance = 0 | |
| lock_a = threading.Lock() | |
| lock_b = threading.Lock() | |
| def deposit(amount): | |
| """Deposit money into the account.""" | |
| global balance | |
| current = balance | |
| time.sleep(0.01) | |
| balance = current + amount # BUG: race condition | |
| def withdraw(amount): | |
| """Withdraw money from the account.""" | |
| global balance | |
| if balance >= amount: | |
| time.sleep(0.01) | |
| balance -= amount # BUG: TOCTOU race | |
| return balance | |
| def transfer_a_to_b(): | |
| """Transfer from account A to B.""" | |
| lock_a.acquire() | |
| time.sleep(0.01) | |
| lock_b.acquire() # BUG: potential deadlock | |
| lock_b.release() | |
| lock_a.release() | |
| def transfer_b_to_a(): | |
| """Transfer from account B to A.""" | |
| lock_b.acquire() | |
| time.sleep(0.01) | |
| lock_a.acquire() # BUG: deadlock β opposite order | |
| lock_a.release() | |
| lock_b.release() | |
| shared_list = [] | |
| def append_item(item): | |
| """Append an item to the shared list.""" | |
| shared_list.append(item) # BUG: not thread-safe | |
| ''' | |
| } | |
| CONCURRENCY_ISSUES = [ | |
| Issue(file="main.py", line=13, issue_type="bug", | |
| description="Race condition: read-modify-write without lock", | |
| severity="high", confidence=1.0), | |
| Issue(file="main.py", line=20, issue_type="bug", | |
| description="TOCTOU race: check and update not atomic", | |
| severity="high", confidence=1.0), | |
| Issue(file="main.py", line=26, issue_type="bug", | |
| description="Deadlock risk: lock ordering conflict", | |
| severity="high", confidence=1.0, cascade_lines=[27, 28]), | |
| Issue(file="main.py", line=34, issue_type="bug", | |
| description="Deadlock: acquires locks in reverse order", | |
| severity="high", confidence=1.0, cascade_lines=[35, 36]), | |
| Issue(file="main.py", line=41, issue_type="bug", | |
| description="Shared mutable list without lock", | |
| severity="medium", confidence=1.0), | |
| ] | |
| CONCURRENCY_OPTIONAL = [ | |
| Issue(file="main.py", line=4, issue_type="style", | |
| description="Global mutable state should be encapsulated", | |
| severity="low", confidence=1.0), | |
| Issue(file="main.py", line=11, issue_type="optimization", | |
| description="time.sleep() is a code smell β use lock-based sync", | |
| severity="low", confidence=1.0), | |
| ] | |
| CONCURRENCY_GRAPH = { | |
| "deposit": [], | |
| "withdraw": [], | |
| "transfer_a_to_b": [], | |
| "transfer_b_to_a": [], | |
| "append_item": [], | |
| } | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # HARD-RX TASK: Multi-file with cross-file bugs, call tracing, | |
| # ambiguous issues, and traps | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| HARD_RX_FILES = { | |
| "main.py": '''\ | |
| from data_loader import load_dataset | |
| from processor import process_pipeline | |
| from reporter import generate_report | |
| def run_analysis(filepath, config): | |
| """Main entry point for the analysis pipeline.""" | |
| data = load_dataset(filepath) | |
| processed = process_pipeline(data, config) | |
| report = generate_report(processed) | |
| return report | |
| ''', | |
| "data_loader.py": '''\ | |
| import json | |
| def load_dataset(filepath): | |
| """Load and parse a JSON dataset.""" | |
| with open(filepath) as f: | |
| raw = f.read() | |
| data = json.loads(raw) | |
| if "records" not in data: | |
| return [] # BUG: silently returns empty instead of raising error | |
| records = data["records"] | |
| return records | |
| def validate_record(record): | |
| """Validate a single data record.""" | |
| required = ["id", "value", "timestamp"] | |
| for key in required: | |
| if key not in record: | |
| return False # BUG: returns False but caller never checks return value | |
| return True | |
| ''', | |
| "processor.py": '''\ | |
| from data_loader import validate_record | |
| def process_pipeline(records, config): | |
| """Process all records through the pipeline.""" | |
| results = [] | |
| threshold = config.get("threshold", 0) # BUG: default 0 instead of None causes wrong filtering | |
| for record in records: | |
| validate_record(record) # BUG: return value ignored β invalid records pass through | |
| value = transform(record["value"], threshold) | |
| results.append({"id": record["id"], "result": value}) | |
| return results | |
| def transform(value, threshold): | |
| """Apply transformation with threshold filtering.""" | |
| if value > threshold: | |
| adjusted = value / (value - threshold) # BUG: ZeroDivisionError when value == threshold | |
| return round(adjusted, 2) | |
| return 0 | |
| ''', | |
| "reporter.py": '''\ | |
| def generate_report(results): | |
| """Generate a summary report from processed results.""" | |
| total = len(results) | |
| values = [r["result"] for r in results] | |
| average = sum(values) / total # BUG: ZeroDivisionError if results is empty | |
| top_result = max(values) # BUG: ValueError on empty sequence | |
| return { | |
| "total_records": total, | |
| "average_result": average, | |
| "top_result": top_result, | |
| "status": "complete" | |
| } | |
| ''' | |
| } | |
| HARD_RX_ISSUES = [ | |
| # data_loader.py bugs | |
| Issue(file="data_loader.py", line=9, issue_type="bug", | |
| description="Silently returns empty list instead of raising error on missing 'records' key", | |
| severity="high", confidence=1.0, cascade_lines=[], | |
| is_root_cause=True), | |
| Issue(file="data_loader.py", line=17, issue_type="bug", | |
| description="Returns False but callers never check the return value", | |
| severity="medium", confidence=0.7), | |
| # processor.py bugs | |
| Issue(file="processor.py", line=6, issue_type="bug", | |
| description="Default threshold=0 causes incorrect filtering behavior", | |
| severity="medium", confidence=0.5), # ambiguous β could be intentional | |
| Issue(file="processor.py", line=8, issue_type="bug", | |
| description="validate_record() return value ignored β invalid records pass through", | |
| severity="high", confidence=1.0, cascade_lines=[9, 10], | |
| is_root_cause=True), | |
| Issue(file="processor.py", line=15, issue_type="bug", | |
| description="ZeroDivisionError when value == threshold", | |
| severity="high", confidence=1.0, cascade_lines=[]), | |
| # reporter.py bugs | |
| Issue(file="reporter.py", line=5, issue_type="bug", | |
| description="ZeroDivisionError if results list is empty", | |
| severity="high", confidence=1.0, cascade_lines=[6]), | |
| Issue(file="reporter.py", line=6, issue_type="bug", | |
| description="ValueError: max() on empty sequence", | |
| severity="high", confidence=1.0), | |
| ] | |
| HARD_RX_OPTIONAL = [ | |
| Issue(file="main.py", line=5, issue_type="style", | |
| description="Function docstring is vague β should specify expected types", | |
| severity="low", confidence=0.3), # trap-like: very ambiguous | |
| Issue(file="processor.py", line=10, issue_type="optimization", | |
| description="List append in loop β could use list comprehension", | |
| severity="low", confidence=1.0), | |
| Issue(file="reporter.py", line=4, issue_type="optimization", | |
| description="values list could be computed lazily with generator", | |
| severity="low", confidence=1.0), | |
| ] | |
| HARD_RX_GRAPH = { | |
| "run_analysis": ["load_dataset", "process_pipeline", "generate_report"], | |
| "load_dataset": [], | |
| "validate_record": [], | |
| "process_pipeline": ["validate_record", "transform"], | |
| "transform": [], | |
| "generate_report": [], | |
| } | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # TASK REGISTRY | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def get_tasks() -> Dict[str, Task]: | |
| """Return all registered tasks keyed by difficulty level.""" | |
| return { | |
| "easy": Task( | |
| name="Discount Calculator Review", | |
| level="easy", | |
| description="Review a simple discount calculator with 2 clear bugs.", | |
| files=EASY_FILES, | |
| issues=EASY_ISSUES, | |
| optional_issues=EASY_OPTIONAL, | |
| call_graph=EASY_GRAPH, | |
| ), | |
| "medium": Task( | |
| name="Config Parser Review", | |
| level="medium", | |
| description="Review a config file parser with resource leaks and missing error handling.", | |
| files=MEDIUM_FILES, | |
| issues=MEDIUM_ISSUES, | |
| optional_issues=MEDIUM_OPTIONAL, | |
| call_graph=MEDIUM_GRAPH, | |
| ), | |
| "hard": Task( | |
| name="Data Analysis Pipeline Review", | |
| level="hard", | |
| description="Review a multi-function data analysis pipeline with cascading bugs.", | |
| files=HARD_FILES, | |
| issues=HARD_ISSUES, | |
| optional_issues=HARD_OPTIONAL, | |
| call_graph=HARD_GRAPH, | |
| ), | |
| "security": Task( | |
| name="Auth System Security Audit", | |
| level="security", | |
| description="Audit authentication system for SQL injection, broken crypto, and more.", | |
| files=SECURITY_FILES, | |
| issues=SECURITY_ISSUES, | |
| optional_issues=SECURITY_OPTIONAL, | |
| call_graph=SECURITY_GRAPH, | |
| ), | |
| "concurrency": Task( | |
| name="Concurrent Banking System Review", | |
| level="concurrency", | |
| description="Review multi-threaded banking system for race conditions and deadlocks.", | |
| files=CONCURRENCY_FILES, | |
| issues=CONCURRENCY_ISSUES, | |
| optional_issues=CONCURRENCY_OPTIONAL, | |
| call_graph=CONCURRENCY_GRAPH, | |
| ), | |
| "hard_rx": Task( | |
| name="Multi-File Pipeline Debugging", | |
| level="hard_rx", | |
| description="Debug a 4-file data pipeline with cross-file bugs, ambiguous issues, call tracing, and root-cause analysis.", | |
| files=HARD_RX_FILES, | |
| issues=HARD_RX_ISSUES, | |
| optional_issues=HARD_RX_OPTIONAL, | |
| call_graph=HARD_RX_GRAPH, | |
| ), | |
| } | |