Spaces:
Runtime error
Runtime error
File size: 21,977 Bytes
6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d e8d92f9 6e5766d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 | """
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
@dataclass
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
@dataclass
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,
),
}
|