Coverage for /Users/les/Projects/crackerjack/crackerjack/agents/performance_agent.py: 0%
285 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import ast
2import operator
3import typing as t
4from contextlib import suppress
5from pathlib import Path
7from .base import (
8 FixResult,
9 Issue,
10 IssueType,
11 SubAgent,
12 agent_registry,
13)
16class PerformanceAgent(SubAgent):
17 def get_supported_types(self) -> set[IssueType]:
18 return {IssueType.PERFORMANCE}
20 async def can_handle(self, issue: Issue) -> float:
21 if issue.type == IssueType.PERFORMANCE:
22 return 0.85
23 return 0.0
25 async def analyze_and_fix(self, issue: Issue) -> FixResult:
26 self.log(f"Analyzing performance issue: {issue.message}")
28 validation_result = self._validate_performance_issue(issue)
29 if validation_result:
30 return validation_result
32 if issue.file_path is None:
33 return FixResult(
34 success=False,
35 confidence=0.0,
36 remaining_issues=["No file path provided for performance issue"],
37 )
39 file_path = Path(issue.file_path)
41 try:
42 return await self._process_performance_optimization(file_path)
43 except Exception as e:
44 return self._create_performance_error_result(e)
46 def _validate_performance_issue(self, issue: Issue) -> FixResult | None:
47 if not issue.file_path:
48 return FixResult(
49 success=False,
50 confidence=0.0,
51 remaining_issues=["No file path specified for performance issue"],
52 )
54 file_path = Path(issue.file_path)
55 if not file_path.exists():
56 return FixResult(
57 success=False,
58 confidence=0.0,
59 remaining_issues=[f"File not found: {file_path}"],
60 )
62 return None
64 async def _process_performance_optimization(self, file_path: Path) -> FixResult:
65 content = self.context.get_file_content(file_path)
66 if not content:
67 return FixResult(
68 success=False,
69 confidence=0.0,
70 remaining_issues=[f"Could not read file: {file_path}"],
71 )
73 performance_issues = self._detect_performance_issues(content, file_path)
75 if not performance_issues:
76 return FixResult(
77 success=True,
78 confidence=0.7,
79 recommendations=["No performance issues detected"],
80 )
82 return self._apply_and_save_optimizations(
83 file_path,
84 content,
85 performance_issues,
86 )
88 def _apply_and_save_optimizations(
89 self,
90 file_path: Path,
91 content: str,
92 issues: list[dict[str, t.Any]],
93 ) -> FixResult:
94 optimized_content = self._apply_performance_optimizations(content, issues)
96 if optimized_content == content:
97 return self._create_no_optimization_result()
99 success = self.context.write_file_content(file_path, optimized_content)
100 if not success:
101 return FixResult(
102 success=False,
103 confidence=0.0,
104 remaining_issues=[f"Failed to write optimized file: {file_path}"],
105 )
107 return FixResult(
108 success=True,
109 confidence=0.8,
110 fixes_applied=[
111 f"Optimized {len(issues)} performance issues",
112 "Applied algorithmic improvements",
113 ],
114 files_modified=[str(file_path)],
115 recommendations=["Test performance improvements with benchmarks"],
116 )
118 def _create_no_optimization_result(self) -> FixResult:
119 return FixResult(
120 success=False,
121 confidence=0.6,
122 remaining_issues=["Could not automatically optimize performance"],
123 recommendations=[
124 "Manual optimization required",
125 "Consider algorithm complexity improvements",
126 "Review data structure choices",
127 "Profile code execution for bottlenecks",
128 ],
129 )
131 def _create_performance_error_result(self, error: Exception) -> FixResult:
132 return FixResult(
133 success=False,
134 confidence=0.0,
135 remaining_issues=[f"Error processing file: {error}"],
136 )
138 def _detect_performance_issues(
139 self,
140 content: str,
141 file_path: Path,
142 ) -> list[dict[str, t.Any]]:
143 issues: list[dict[str, t.Any]] = []
145 with suppress(SyntaxError):
146 tree = ast.parse(content)
148 issues.extend(self._detect_nested_loops(tree))
150 issues.extend(self._detect_inefficient_list_ops(content, tree))
152 issues.extend(self._detect_repeated_operations(content, tree))
154 issues.extend(self._detect_string_inefficiencies(content))
156 return issues
158 def _detect_nested_loops(self, tree: ast.AST) -> list[dict[str, t.Any]]:
159 issues: list[dict[str, t.Any]] = []
161 class NestedLoopAnalyzer(ast.NodeVisitor):
162 def __init__(self) -> None:
163 self.loop_stack: list[tuple[str, ast.AST]] = []
164 self.nested_loops: list[dict[str, t.Any]] = []
166 def visit_For(self, node: ast.For) -> None:
167 self.loop_stack.append(("for", node))
168 if len(self.loop_stack) > 1:
169 self.nested_loops.append(
170 {
171 "line_number": node.lineno,
172 "type": "nested_for_loop",
173 "depth": len(self.loop_stack),
174 "node": node,
175 },
176 )
177 self.generic_visit(node)
178 self.loop_stack.pop()
180 def visit_While(self, node: ast.While) -> None:
181 self.loop_stack.append(("while", node))
182 if len(self.loop_stack) > 1:
183 self.nested_loops.append(
184 {
185 "line_number": node.lineno,
186 "type": "nested_while_loop",
187 "depth": len(self.loop_stack),
188 "node": node,
189 },
190 )
191 self.generic_visit(node)
192 self.loop_stack.pop()
194 analyzer = NestedLoopAnalyzer()
195 analyzer.visit(tree)
197 if analyzer.nested_loops:
198 issues.append(
199 {
200 "type": "nested_loops",
201 "instances": analyzer.nested_loops,
202 "suggestion": "Consider flattening loops or using more efficient algorithms",
203 },
204 )
206 return issues
208 def _detect_inefficient_list_ops(
209 self,
210 content: str,
211 tree: ast.AST,
212 ) -> list[dict[str, t.Any]]:
213 issues: list[dict[str, t.Any]] = []
214 content.split("\n")
216 class ListOpAnalyzer(ast.NodeVisitor):
217 def __init__(self) -> None:
218 self.in_loop = False
219 self.list_ops: list[dict[str, t.Any]] = []
221 def visit_For(self, node: ast.For) -> None:
222 old_in_loop = self.in_loop
223 self.in_loop = True
224 self.generic_visit(node)
225 self.in_loop = old_in_loop
227 def visit_While(self, node: ast.While) -> None:
228 old_in_loop = self.in_loop
229 self.in_loop = True
230 self.generic_visit(node)
231 self.in_loop = old_in_loop
233 def visit_AugAssign(self, node: ast.AugAssign) -> None:
234 if self.in_loop and isinstance(node.op, ast.Add):
235 if isinstance(node.value, ast.List):
236 self.list_ops.append(
237 {
238 "line_number": node.lineno,
239 "type": "list_concat_in_loop",
240 "pattern": "list += [item]",
241 },
242 )
243 self.generic_visit(node)
245 analyzer = ListOpAnalyzer()
246 analyzer.visit(tree)
248 if analyzer.list_ops:
249 issues.append(
250 {
251 "type": "inefficient_list_operations",
252 "instances": analyzer.list_ops,
253 "suggestion": "Use list.append() or collect items first, then extend",
254 },
255 )
257 return issues
259 def _detect_repeated_operations(
260 self,
261 content: str,
262 tree: ast.AST,
263 ) -> list[dict[str, t.Any]]:
264 lines = content.split("\n")
265 repeated_calls = self._find_expensive_operations_in_loops(lines)
267 return self._create_repeated_operations_issues(repeated_calls)
269 def _find_expensive_operations_in_loops(
270 self,
271 lines: list[str],
272 ) -> list[dict[str, t.Any]]:
273 repeated_calls: list[dict[str, t.Any]] = []
274 expensive_patterns = self._get_expensive_operation_patterns()
276 for i, line in enumerate(lines):
277 stripped = line.strip()
278 if self._contains_expensive_operation(stripped, expensive_patterns):
279 if self._is_in_loop_context(lines, i):
280 repeated_calls.append(self._create_operation_record(i, stripped))
282 return repeated_calls
284 def _get_expensive_operation_patterns(self) -> tuple[str, ...]:
285 return (
286 ".exists()",
287 ".read_text()",
288 ".glob(",
289 ".rglob(",
290 "Path(",
291 "len(",
292 ".get(",
293 )
295 def _contains_expensive_operation(
296 self,
297 line: str,
298 patterns: tuple[str, ...],
299 ) -> bool:
300 return any(pattern in line for pattern in patterns)
302 def _is_in_loop_context(self, lines: list[str], line_index: int) -> bool:
303 context_start = max(0, line_index - 5)
304 context_lines = lines[context_start : line_index + 1]
306 loop_keywords = ("for ", "while ")
307 return any(
308 any(keyword in ctx_line for keyword in loop_keywords)
309 for ctx_line in context_lines
310 )
312 def _create_operation_record(
313 self,
314 line_index: int,
315 content: str,
316 ) -> dict[str, t.Any]:
317 return {
318 "line_number": line_index + 1,
319 "content": content,
320 "type": "expensive_operation_in_loop",
321 }
323 def _create_repeated_operations_issues(
324 self,
325 repeated_calls: list[dict[str, t.Any]],
326 ) -> list[dict[str, t.Any]]:
327 if len(repeated_calls) >= 2:
328 return [
329 {
330 "type": "repeated_expensive_operations",
331 "instances": repeated_calls,
332 "suggestion": "Cache expensive operations outside loops",
333 },
334 ]
335 return []
337 def _detect_string_inefficiencies(self, content: str) -> list[dict[str, t.Any]]:
338 issues: list[dict[str, t.Any]] = []
339 lines = content.split("\n")
341 string_concat_in_loop: list[dict[str, t.Any]] = []
343 for i, line in enumerate(lines):
344 stripped = line.strip()
345 if "+=" in stripped and any(quote in stripped for quote in ('"', "'")):
346 context_start = max(0, i - 5)
347 context_lines = lines[context_start : i + 1]
349 loop_keywords = ("for ", "while ")
350 if any(
351 any(keyword in ctx_line for keyword in loop_keywords)
352 for ctx_line in context_lines
353 ):
354 string_concat_in_loop.append(
355 {
356 "line_number": i + 1,
357 "content": stripped,
358 },
359 )
361 if len(string_concat_in_loop) >= 2:
362 issues.append(
363 {
364 "type": "string_concatenation_in_loop",
365 "instances": string_concat_in_loop,
366 "suggestion": 'Use list.append() and "".join() for string building',
367 },
368 )
370 return issues
372 def _apply_performance_optimizations(
373 self,
374 content: str,
375 issues: list[dict[str, t.Any]],
376 ) -> str:
377 lines = content.split("\n")
378 modified = False
380 for issue in issues:
381 if issue["type"] == "inefficient_list_operations":
382 lines, changed = self._fix_list_operations(lines, issue)
383 modified = modified or changed
384 elif issue["type"] == "string_concatenation_in_loop":
385 lines, changed = self._fix_string_concatenation(lines, issue)
386 modified = modified or changed
387 elif issue["type"] == "repeated_expensive_operations":
388 lines, changed = self._fix_repeated_operations(lines, issue)
389 modified = modified or changed
391 return "\n".join(lines) if modified else content
393 def _fix_list_operations(
394 self,
395 lines: list[str],
396 issue: dict[str, t.Any],
397 ) -> tuple[list[str], bool]:
398 modified = False
400 instances = sorted(
401 issue["instances"],
402 key=operator.itemgetter("line_number"),
403 reverse=True,
404 )
406 for instance in instances:
407 line_idx = instance["line_number"] - 1
408 if line_idx < len(lines):
409 original_line = t.cast(str, lines[line_idx])
411 import re
413 pattern = r"(\s*)(\w+)\s*\+=\s*\[([^]]+)\]"
414 match = re.match(pattern, original_line)
416 if match:
417 indent, var_name, item_expr = match.groups()
418 optimized_line = f"{indent}{var_name}.append({item_expr})"
419 lines[line_idx] = optimized_line
420 modified = True
422 comment = (
423 f"{indent}# Performance: Changed += [item] to .append(item)"
424 )
425 lines.insert(line_idx, comment)
427 return lines, modified
429 def _fix_string_concatenation(
430 self,
431 lines: list[str],
432 issue: dict[str, t.Any],
433 ) -> tuple[list[str], bool]:
434 var_groups = self._group_concatenation_instances(lines, issue["instances"])
435 return self._apply_concatenation_optimizations(lines, var_groups)
437 def _group_concatenation_instances(
438 self,
439 lines: list[str],
440 instances: list[dict[str, t.Any]],
441 ) -> dict[str, list[dict[str, t.Any]]]:
442 var_groups: dict[str, list[dict[str, t.Any]]] = {}
444 for instance in instances:
445 line_info = self._parse_concatenation_line(lines, instance)
446 if line_info:
447 var_name = line_info["var_name"]
448 if var_name not in var_groups:
449 var_groups[var_name] = []
450 var_groups[var_name].append(line_info)
452 return var_groups
454 def _parse_concatenation_line(
455 self,
456 lines: list[str],
457 instance: dict[str, t.Any],
458 ) -> dict[str, t.Any] | None:
459 line_idx = instance["line_number"] - 1
460 if line_idx >= len(lines):
461 return None
463 original_line = t.cast(str, lines[line_idx])
465 import re
467 pattern = r"(\s*)(\w+)\s*\+=\s*(.+)"
468 match = re.match(pattern, original_line)
470 if match:
471 indent, var_name, expr = match.groups()
472 return {
473 "line_idx": line_idx,
474 "indent": indent,
475 "var_name": var_name,
476 "expr": expr.strip(),
477 "original_line": original_line,
478 }
479 return None
481 def _apply_concatenation_optimizations(
482 self,
483 lines: list[str],
484 var_groups: dict[str, list[dict[str, t.Any]]],
485 ) -> tuple[list[str], bool]:
486 modified = False
488 for var_name, instances in var_groups.items():
489 if instances:
490 first_instance = instances[0]
491 loop_start = self._find_loop_start(lines, first_instance["line_idx"])
493 if loop_start is not None:
494 optimization_applied = self._apply_string_building_optimization(
495 lines, var_name, instances, loop_start
496 )
497 modified = modified or optimization_applied
499 return lines, modified
501 def _find_loop_start(self, lines: list[str], start_idx: int) -> int | None:
502 for i in range(start_idx, -1, -1):
503 line = lines[i].strip()
504 if line.startswith(("for ", "while ")):
505 return i
507 if line.startswith(("def ", "class ")):
508 break
509 return None
511 def _apply_string_building_optimization(
512 self,
513 lines: list[str],
514 var_name: str,
515 instances: list[dict[str, t.Any]],
516 loop_start: int,
517 ) -> bool:
518 if not instances:
519 return False
521 first_instance = instances[0]
522 indent = first_instance["indent"]
524 init_line_idx = self._find_variable_initialization(lines, var_name, loop_start)
525 if init_line_idx is not None:
526 self._transform_string_initialization(
527 lines, init_line_idx, var_name, indent
528 )
529 self._replace_concatenations_with_appends(
530 lines, instances, var_name, indent
531 )
532 self._add_join_after_loop(lines, var_name, indent, loop_start)
533 return True
535 return False
537 def _find_variable_initialization(
538 self,
539 lines: list[str],
540 var_name: str,
541 loop_start: int,
542 ) -> int | None:
543 search_start = max(0, loop_start - 10)
545 for i in range(loop_start - 1, search_start - 1, -1):
546 line = lines[i].strip()
547 if f"{var_name} =" in line and '""' in line:
548 return i
549 return None
551 def _transform_string_initialization(
552 self,
553 lines: list[str],
554 init_line_idx: int,
555 var_name: str,
556 indent: str,
557 ) -> None:
558 lines[init_line_idx] = (
559 f"{indent}{var_name}_parts = [] # Performance: Use list for string building"
560 )
562 def _replace_concatenations_with_appends(
563 self,
564 lines: list[str],
565 instances: list[dict[str, t.Any]],
566 var_name: str,
567 indent: str,
568 ) -> None:
569 for instance in instances:
570 line_idx = instance["line_idx"]
571 expr = instance["expr"]
572 lines[line_idx] = f"{indent}{var_name}_parts.append({expr})"
574 def _add_join_after_loop(
575 self,
576 lines: list[str],
577 var_name: str,
578 indent: str,
579 loop_start: int,
580 ) -> None:
581 loop_end = self._find_loop_end(lines, loop_start)
582 if loop_end is not None:
583 join_line = f"{indent}{var_name} = ''.join({var_name}_parts) # Performance: Join string parts"
584 lines.insert(loop_end + 1, join_line)
586 def _find_loop_end(self, lines: list[str], loop_start: int) -> int | None:
587 if loop_start >= len(lines):
588 return None
590 loop_indent = len(lines[loop_start]) - len(lines[loop_start].lstrip())
592 for i in range(loop_start + 1, len(lines)):
593 line = lines[i]
594 if line.strip() == "":
595 continue
597 current_indent = len(line) - len(line.lstrip())
598 if current_indent <= loop_indent:
599 return i - 1
601 return len(lines) - 1
603 def _fix_repeated_operations(
604 self,
605 lines: list[str],
606 issue: dict[str, t.Any],
607 ) -> tuple[list[str], bool]:
608 modified = False
610 for instance in issue["instances"]:
611 line_idx = instance["line_number"] - 1
612 if line_idx < len(lines):
613 original_line = t.cast(str, lines[line_idx])
614 indent_level = len(original_line) - len(original_line.lstrip())
615 indent_str = " " * indent_level
617 comment = f"{indent_str}# Performance: Consider caching this expensive operation outside the loop"
618 lines.insert(line_idx, comment)
619 modified = True
621 return lines, modified
624agent_registry.register(PerformanceAgent)