File size: 15,997 Bytes
a21d9ae
 
 
 
 
 
 
 
 
 
 
5e92b80
a21d9ae
 
 
 
5e92b80
a21d9ae
 
 
 
 
 
 
5e92b80
a21d9ae
 
 
5e92b80
a21d9ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e92b80
a21d9ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c51832
a21d9ae
 
 
 
 
8c51832
 
 
 
5e92b80
8c51832
 
 
 
 
 
 
 
 
 
 
 
 
 
a21d9ae
 
5e92b80
a21d9ae
 
 
 
5e92b80
a21d9ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e92b80
a21d9ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c51832
a21d9ae
 
 
 
 
8c51832
 
 
 
5e92b80
8c51832
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1939cbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a21d9ae
 
5e92b80
a21d9ae
 
 
 
5e92b80
a21d9ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e92b80
a21d9ae
 
 
 
5e92b80
a21d9ae
 
 
 
 
 
 
 
 
5e92b80
a21d9ae
 
 
 
5e92b80
a21d9ae
 
 
 
 
 
 
 
 
 
 
 
 
8c51832
 
 
 
5e92b80
8c51832
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a23e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1939cbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a21d9ae
 
5e92b80
a21d9ae
 
 
 
 
 
 
7a23e48
 
a21d9ae
 
 
 
5e92b80
a21d9ae
 
 
 
 
 
 
 
 
5e92b80
a21d9ae
 
 
 
 
 
 
 
 
 
5e92b80
a21d9ae
 
5e92b80
 
a21d9ae
 
 
 
 
 
 
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
from typing import Dict, Any, List
from environment.models import CodeContext, TaskMetadata


class TaskDefinitions:

    TASK_ALIASES = {
        "bug_detection_easy": "bug_detection_easy_1",
        "bug_detection_medium": "memory_leak_medium_1",
        "bug_detection_hard": "security_hard_1",
    }

    EASY_TASKS = [
        {
            "task_id": "bug_detection_easy_1",
            "task_name": "Division by Zero",
            "difficulty": "easy",
            "description": "Find the division by zero vulnerability in the calculate_average function",
            "code_diff": """def calculate_average(numbers):
    total = sum(numbers)
    return total / len(numbers)""",
            "surrounding_code": """class StatisticsCalculator:
    def __init__(self):
        self.results = []

    def calculate_average(self, numbers):
        total = sum(numbers)
        return total / len(numbers)

    def add_result(self, value):
        self.results.append(value)""",
            "file_path": "statistics.py",
            "language": "python",
            "line_count": 3,
            "expected_issues": [
                {
                    "line": 3,
                    "type": "division_by_zero",
                    "severity": "high",
                    "description": "No check for empty list before division"
                }
            ]
        },
        {
            "task_id": "bug_detection_easy_2",
            "task_name": "Off-by-One Error",
            "difficulty": "easy",
            "description": "Find the off-by-one error in the array iteration",
            "code_diff": """def process_items(items):
    for i in range(len(items)):
        item = items[i]
        next_item = items[i + 1]
        process_pair(item, next_item)""",
            "surrounding_code": """def process_items(items):
    for i in range(len(items)):
        item = items[i]
        next_item = items[i + 1]
        process_pair(item, next_item)
    return True""",
            "file_path": "processor.py",
            "language": "python",
            "line_count": 4,
            "expected_issues": [
                {
                    "line": 3,
                    "type": "index_error",
                    "severity": "medium",
                    "description": "Index out of bounds when i is the last element"
                }
            ]
        },
        {
            "task_id": "approve_easy_3",
            "task_name": "Approve Safe Refactor",
            "difficulty": "easy",
            "description": "No issues expected: approve this small readability refactor",
            "code_diff": """def normalize_name(name):
    cleaned = name.strip()
    return cleaned.lower()""",
            "surrounding_code": """def normalize_name(name):
    cleaned = name.strip()
    return cleaned.lower()

def format_username(user):
    return normalize_name(user.name)""",
            "file_path": "string_utils.py",
            "language": "python",
            "line_count": 3,
            "expected_issues": []
        }
    ]

    MEDIUM_TASKS = [
        {
            "task_id": "memory_leak_medium_1",
            "task_name": "File Handle Leak",
            "difficulty": "medium",
            "description": "Find the memory leak where file handles are not properly closed",
            "code_diff": """def read_files(file_list):
    contents = []
    for filename in file_list:
        f = open(filename, 'r')
        data = f.read()
        contents.append(data)
    return contents""",
            "surrounding_code": """import os

def read_files(file_list):
    contents = []
    for filename in file_list:
        f = open(filename, 'r')
        data = f.read()
        contents.append(data)
    return contents

def write_output(data, filename):
    with open(filename, 'w') as f:
        f.write(data)""",
            "file_path": "file_handler.py",
            "language": "python",
            "line_count": 6,
            "expected_issues": [
                {
                    "line": 4,
                    "type": "resource_leak",
                    "severity": "high",
                    "description": "File not closed after reading"
                }
            ]
        },
        {
            "task_id": "performance_medium_2",
            "task_name": "Inefficient String Concatenation",
            "difficulty": "medium",
            "description": "Find the performance issue with string concatenation in a loop",
            "code_diff": """def build_string(items):
    result = ""
    for item in items:
        result = result + item + ","
    return result[:-1]""",
            "surrounding_code": """def build_string(items):
    result = ""
    for item in items:
        result = result + item + ","
    return result[:-1]

def format_output(data):
    return build_string(data)""",
            "file_path": "string_builder.py",
            "language": "python",
            "line_count": 4,
            "expected_issues": [
                {
                    "line": 3,
                    "type": "performance",
                    "severity": "medium",
                    "description": "Inefficient string concatenation in loop"
                }
            ]
        },
        {
            "task_id": "approve_medium_3",
            "task_name": "Approve Safe Query Helper",
            "difficulty": "medium",
            "description": "No issues expected: approve this query helper cleanup",
            "code_diff": """def build_user_query(limit):
    safe_limit = max(1, int(limit))
    return \"SELECT id, name FROM users LIMIT ?\", [safe_limit]""",
            "surrounding_code": """def build_user_query(limit):
    safe_limit = max(1, int(limit))
    return \"SELECT id, name FROM users LIMIT ?\", [safe_limit]

def run_user_query(db, limit):
    query, params = build_user_query(limit)
    return db.execute(query, params)""",
            "file_path": "query_builder.py",
            "language": "python",
            "line_count": 3,
            "expected_issues": []
        },
        {
            "task_id": "type_safety_medium_4",
            "task_name": "Type Safety: Optional Arithmetic",
            "difficulty": "medium",
            "description": "Find the type safety issue where Optional[int] can be None during arithmetic",
            "code_diff": """from typing import Optional\n\ndef increment(value: Optional[int]) -> int:\n    return value + 1""",
            "surrounding_code": """from typing import Optional\n\ndef increment(value: Optional[int]) -> int:\n    return value + 1\n\ndef safe_increment(value: Optional[int]) -> int:\n    return increment(value)""",
            "file_path": "type_utils.py",
            "language": "python",
            "line_count": 4,
            "expected_issues": [
                {
                    "line": 4,
                    "type": "type_safety",
                    "severity": "medium",
                    "description": "Optional[int] may be None, causing runtime TypeError",
                }
            ]
        },
        {
            "task_id": "javascript_medium_5",
            "task_name": "JavaScript: Undefined Access",
            "difficulty": "medium",
            "description": "Find the JavaScript bug where user can be undefined before property access",
            "code_diff": """function getUserName(user) {\n  return user.name.trim();\n}""",
            "surrounding_code": """function getUserName(user) {\n  return user.name.trim();\n}\n\nfunction formatUser(user) {\n  return getUserName(user).toLowerCase();\n}""",
            "file_path": "user.js",
            "language": "javascript",
            "line_count": 3,
            "expected_issues": [
                {
                    "line": 2,
                    "type": "null_access",
                    "severity": "medium",
                    "description": "user may be undefined and property access can throw",
                }
            ]
        }
    ]

    HARD_TASKS = [
        {
            "task_id": "security_hard_1",
            "task_name": "SQL Injection Vulnerability",
            "difficulty": "hard",
            "description": "Find the SQL injection vulnerability in the database query",
            "code_diff": """def get_user_data(user_id):
    query = f"SELECT * FROM users WHERE id = {user_id}"
    return database.execute(query)""",
            "surrounding_code": """import database

def get_user_data(user_id):
    query = f"SELECT * FROM users WHERE id = {user_id}"
    return database.execute(query)

def get_all_users():
    return database.execute("SELECT * FROM users")""",
            "file_path": "user_repository.py",
            "language": "python",
            "line_count": 3,
            "expected_issues": [
                {
                    "line": 2,
                    "type": "sql_injection",
                    "severity": "critical",
                    "description": "SQL injection vulnerability from string interpolation"
                }
            ]
        },
        {
            "task_id": "race_condition_hard_2",
            "task_name": "Race Condition",
            "difficulty": "hard",
            "description": "Find the race condition in the thread-safe counter",
            "code_diff": """class Counter:
    def __init__(self):
        self.count = 0

    def increment(self):
        current = self.count
        self.count = current + 1
        return self.count""",
            "surrounding_code": """import threading

class Counter:
    def __init__(self):
        self.count = 0

    def increment(self):
        current = self.count
        self.count = current + 1
        return self.count

    def get_count(self):
        return self.count""",
            "file_path": "counter.py",
            "language": "python",
            "line_count": 7,
            "expected_issues": [
                {
                    "line": 6,
                    "type": "race_condition",
                    "severity": "high",
                    "description": "Non-atomic increment operation"
                }
            ]
        },
        {
            "task_id": "approve_hard_3",
            "task_name": "Approve Thread-Safe Counter",
            "difficulty": "hard",
            "description": "No issues expected: approve this lock-based concurrency fix",
            "code_diff": """class Counter:
    def __init__(self):
        self.count = 0
        self._lock = threading.Lock()

    def increment(self):
        with self._lock:
            self.count += 1
            return self.count""",
            "surrounding_code": """import threading

class Counter:
    def __init__(self):
        self.count = 0
        self._lock = threading.Lock()

    def increment(self):
        with self._lock:
            self.count += 1
            return self.count""",
            "file_path": "counter.py",
            "language": "python",
            "line_count": 9,
            "expected_issues": []
        },
        {
            "task_id": "adversarial_hard_4",
            "task_name": "Adversarial: Safe SQL Builder",
            "difficulty": "hard",
            "description": "No issues expected: query text looks suspicious but uses parameterized execution safely",
            "code_diff": """def find_user(database, user_id):
    query = \"SELECT * FROM users WHERE id = ?\"
    params = [int(user_id)]
    return database.execute(query, params)""",
            "surrounding_code": """def find_user(database, user_id):
    query = \"SELECT * FROM users WHERE id = ?\"
    params = [int(user_id)]
    return database.execute(query, params)

def find_all_users(database):
    return database.execute(\"SELECT * FROM users\")""",
            "file_path": "user_repository.py",
            "language": "python",
            "line_count": 4,
            "expected_issues": []
        },
        {
            "task_id": "concurrency_hard_5",
            "task_name": "Concurrency: Async Await Misuse",
            "difficulty": "hard",
            "description": "Find async misuse where created tasks are never awaited",
            "code_diff": """import asyncio\n\nasync def process_all(items, worker):\n    for item in items:\n        asyncio.create_task(worker(item))\n    return True""",
            "surrounding_code": """import asyncio\n\nasync def process_all(items, worker):\n    for item in items:\n        asyncio.create_task(worker(item))\n    return True\n\nasync def run(items, worker):\n    return await process_all(items, worker)""",
            "file_path": "async_processor.py",
            "language": "python",
            "line_count": 6,
            "expected_issues": [
                {
                    "line": 5,
                    "type": "async_misuse",
                    "severity": "high",
                    "description": "Tasks are created but never awaited or gathered",
                }
            ]
        },
        {
            "task_id": "dependency_injection_hard_6",
            "task_name": "Dependency Injection: Tight Coupling",
            "difficulty": "hard",
            "description": "Find design issue where service constructs hardcoded dependency internally",
            "code_diff": """class PaymentService:\n    def __init__(self):\n        self.gateway = StripeGateway()\n\n    def charge(self, amount):\n        return self.gateway.charge(amount)""",
            "surrounding_code": """class PaymentService:\n    def __init__(self):\n        self.gateway = StripeGateway()\n\n    def charge(self, amount):\n        return self.gateway.charge(amount)\n\nclass StripeGateway:\n    def charge(self, amount):\n        return True""",
            "file_path": "payment_service.py",
            "language": "python",
            "line_count": 6,
            "expected_issues": [
                {
                    "line": 3,
                    "type": "dependency_injection",
                    "severity": "medium",
                    "description": "Hardcoded dependency prevents testability and inversion of control",
                }
            ]
        }
    ]

    @classmethod
    def get_task(cls, task_id: str) -> Dict[str, Any]:
        canonical_task_id = cls.TASK_ALIASES.get(task_id, task_id)
        all_tasks = cls.EASY_TASKS + cls.MEDIUM_TASKS + cls.HARD_TASKS
        for task in all_tasks:
            if task["task_id"] == canonical_task_id:
                return task
        available = ", ".join(t["task_id"] for t in all_tasks)
        raise KeyError(f"Unknown task_id '{task_id}'. Available task IDs: {available}")

    @classmethod
    def get_all_tasks(cls) -> List[Dict[str, Any]]:
        return cls.EASY_TASKS + cls.MEDIUM_TASKS + cls.HARD_TASKS

    @classmethod
    def get_tasks_by_difficulty(cls, difficulty: str) -> List[Dict[str, Any]]:
        if difficulty == "easy":
            return cls.EASY_TASKS
        elif difficulty == "medium":
            return cls.MEDIUM_TASKS
        elif difficulty == "hard":
            return cls.HARD_TASKS
        return []

    @classmethod
    def create_code_context(cls, task_data: Dict[str, Any]) -> CodeContext:
        return CodeContext(
            file_path=task_data["file_path"],
            file_extension=task_data["file_path"].split(".")[-1],
            code_diff=task_data["code_diff"],
            surrounding_code=task_data["surrounding_code"],
            language=task_data["language"],
            line_count=task_data["line_count"]
        )

    @classmethod
    def create_task_metadata(cls, task_data: Dict[str, Any]) -> TaskMetadata:
        difficulty = task_data.get("difficulty", "easy")

        return TaskMetadata(
            task_id=task_data["task_id"],
            task_name=task_data["task_name"],
            difficulty=difficulty,
            description=task_data["description"],
            expected_issues=task_data.get("expected_issues", [])
        )