Coverage for /Users/les/Projects/crackerjack/crackerjack/executors/async_hook_executor.py: 0%
177 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 asyncio
2import time
3import typing as t
4from dataclasses import dataclass
5from pathlib import Path
7from rich.console import Console
9from crackerjack.config.hooks import HookDefinition, HookStrategy, RetryPolicy
10from crackerjack.models.task import HookResult
11from crackerjack.services.logging import LoggingContext, get_logger
14@dataclass
15class AsyncHookExecutionResult:
16 strategy_name: str
17 results: list[HookResult]
18 total_duration: float
19 success: bool
20 concurrent_execution: bool = True
21 cache_hits: int = 0
22 cache_misses: int = 0
23 performance_gain: float = 0.0
25 @property
26 def failed_count(self) -> int:
27 return sum(1 for r in self.results if r.status == "failed")
29 @property
30 def passed_count(self) -> int:
31 return sum(1 for r in self.results if r.status == "passed")
33 @property
34 def cache_hit_rate(self) -> float:
35 total_requests = self.cache_hits + self.cache_misses
36 return (self.cache_hits / total_requests * 100) if total_requests > 0 else 0.0
38 @property
39 def performance_summary(self) -> dict[str, t.Any]:
40 return {
41 "total_hooks": len(self.results),
42 "passed": self.passed_count,
43 "failed": self.failed_count,
44 "duration_seconds": round(self.total_duration, 2),
45 "concurrent": self.concurrent_execution,
46 "cache_hits": self.cache_hits,
47 "cache_misses": self.cache_misses,
48 "cache_hit_rate_percent": round(self.cache_hit_rate, 1),
49 "performance_gain_percent": round(self.performance_gain, 1),
50 }
53class AsyncHookExecutor:
54 def __init__(
55 self,
56 console: Console,
57 pkg_path: Path,
58 max_concurrent: int = 4,
59 timeout: int = 300,
60 quiet: bool = False,
61 ) -> None:
62 self.console = console
63 self.pkg_path = pkg_path
64 self.max_concurrent = max_concurrent
65 self.timeout = timeout
66 self.quiet = quiet
67 self.logger = get_logger("crackerjack.async_hook_executor")
69 self._semaphore = asyncio.Semaphore(max_concurrent)
71 async def execute_strategy(
72 self,
73 strategy: HookStrategy,
74 ) -> AsyncHookExecutionResult:
75 with LoggingContext(
76 "async_hook_strategy",
77 strategy_name=strategy.name,
78 hook_count=len(strategy.hooks),
79 ):
80 start_time = time.time()
81 self.logger.info(
82 "Starting async hook strategy execution",
83 strategy=strategy.name,
84 hooks=len(strategy.hooks),
85 parallel=strategy.parallel,
86 max_workers=getattr(strategy, "max_workers", self.max_concurrent),
87 )
89 self._print_strategy_header(strategy)
91 estimated_sequential = sum(
92 getattr(hook, "timeout", 30) for hook in strategy.hooks
93 )
95 if strategy.parallel and len(strategy.hooks) > 1:
96 results = await self._execute_parallel(strategy)
97 else:
98 results = await self._execute_sequential(strategy)
100 if strategy.retry_policy != RetryPolicy.NONE:
101 results = await self._handle_retries(strategy, results)
103 total_duration = time.time() - start_time
104 success = all(r.status == "passed" for r in results)
105 performance_gain = max(
106 0,
107 ((estimated_sequential - total_duration) / estimated_sequential) * 100,
108 )
110 self.logger.info(
111 "Async hook strategy completed",
112 strategy=strategy.name,
113 success=success,
114 duration_seconds=round(total_duration, 2),
115 performance_gain_percent=round(performance_gain, 1),
116 passed=sum(1 for r in results if r.status == "passed"),
117 failed=sum(1 for r in results if r.status == "failed"),
118 errors=sum(1 for r in results if r.status in ("timeout", "error")),
119 )
121 if not self.quiet:
122 self._print_summary(strategy, results, success, performance_gain)
124 return AsyncHookExecutionResult(
125 strategy_name=strategy.name,
126 results=results,
127 total_duration=total_duration,
128 success=success,
129 performance_gain=performance_gain,
130 )
132 def _print_strategy_header(self, strategy: HookStrategy) -> None:
133 self.console.print("\n" + "-" * 80)
134 if strategy.name == "fast":
135 self.console.print(
136 "[bold bright_cyan]🔍 HOOKS[/ bold bright_cyan] [bold bright_white]Running code quality checks (async)[/ bold bright_white]",
137 )
138 elif strategy.name == "comprehensive":
139 self.console.print(
140 "[bold bright_cyan]🔍 HOOKS[/ bold bright_cyan] [bold bright_white]Running comprehensive quality checks (async)[/ bold bright_white]",
141 )
142 else:
143 self.console.print(
144 f"[bold bright_cyan]🔍 HOOKS[/ bold bright_cyan] [bold bright_white]Running {strategy.name} hooks (async)[/ bold bright_white]",
145 )
146 self.console.print("-" * 80 + "\n")
148 async def _execute_sequential(self, strategy: HookStrategy) -> list[HookResult]:
149 results: list[HookResult] = []
150 for hook in strategy.hooks:
151 result = await self._execute_single_hook(hook)
152 results.append(result)
153 self._display_hook_result(result)
154 return results
156 async def _execute_parallel(self, strategy: HookStrategy) -> list[HookResult]:
157 results: list[HookResult] = []
159 formatting_hooks = [
160 h for h in strategy.hooks if getattr(h, "is_formatting", False)
161 ]
162 other_hooks = [
163 h for h in strategy.hooks if not getattr(h, "is_formatting", False)
164 ]
166 for hook in formatting_hooks:
167 result = await self._execute_single_hook(hook)
168 results.append(result)
169 self._display_hook_result(result)
171 if other_hooks:
172 tasks = [self._execute_single_hook(hook) for hook in other_hooks]
173 parallel_results = await asyncio.gather(*tasks, return_exceptions=True)
175 for i, result in enumerate(parallel_results):
176 if isinstance(result, Exception):
177 hook = other_hooks[i]
178 error_result = HookResult(
179 id=getattr(hook, "name", f"hook_{i}"),
180 name=getattr(hook, "name", f"hook_{i}"),
181 status="error",
182 duration=0.0,
183 issues_found=[str(result)],
184 stage=hook.stage.value,
185 )
186 results.append(error_result)
187 self._display_hook_result(error_result)
188 else:
189 hook_result = t.cast("HookResult", result)
190 results.append(hook_result)
191 self._display_hook_result(hook_result)
193 return results
195 async def _execute_single_hook(self, hook: HookDefinition) -> HookResult:
196 async with self._semaphore:
197 return await self._run_hook_subprocess(hook)
199 async def _run_hook_subprocess(self, hook: HookDefinition) -> HookResult:
200 start_time = time.time()
202 try:
203 cmd = hook.get_command() if hasattr(hook, "get_command") else [str(hook)]
204 timeout_val = getattr(hook, "timeout", self.timeout)
206 self.logger.debug(
207 "Starting hook execution",
208 hook=hook.name,
209 command=" ".join(cmd),
210 timeout=timeout_val,
211 )
213 process = await asyncio.create_subprocess_exec(
214 *cmd,
215 cwd=self.pkg_path,
216 stdout=asyncio.subprocess.PIPE,
217 stderr=asyncio.subprocess.PIPE,
218 )
220 try:
221 stdout, stderr = await asyncio.wait_for(
222 process.communicate(),
223 timeout=timeout_val,
224 )
225 except TimeoutError:
226 process.kill()
227 await process.wait()
228 duration = time.time() - start_time
230 self.logger.warning(
231 "Hook execution timed out",
232 hook=hook.name,
233 timeout=timeout_val,
234 duration_seconds=round(duration, 2),
235 )
237 return HookResult(
238 id=hook.name,
239 name=hook.name,
240 status="timeout",
241 duration=duration,
242 issues_found=[f"Hook timed out after {duration: .1f}s"],
243 stage=hook.stage.value,
244 )
246 duration = time.time() - start_time
247 output_text = (
248 (stdout.decode() + stderr.decode()) if stdout and stderr else ""
249 )
250 return_code = process.returncode if process.returncode is not None else -1
251 parsed_output = self._parse_hook_output(return_code, output_text)
253 status = "passed" if return_code == 0 else "failed"
255 self.logger.info(
256 "Hook execution completed",
257 hook=hook.name,
258 status=status,
259 duration_seconds=round(duration, 2),
260 return_code=process.returncode,
261 files_processed=parsed_output.get("files_processed", 0),
262 issues_count=len(parsed_output.get("issues", [])),
263 )
265 return HookResult(
266 id=parsed_output.get("hook_id", hook.name),
267 name=hook.name,
268 status=status,
269 duration=duration,
270 files_processed=parsed_output.get("files_processed", 0),
271 issues_found=parsed_output.get("issues", []),
272 stage=hook.stage.value,
273 )
275 except Exception as e:
276 duration = time.time() - start_time
277 self.logger.exception(
278 "Hook execution failed with exception",
279 hook=hook.name,
280 error=str(e),
281 error_type=type(e).__name__,
282 duration_seconds=round(duration, 2),
283 )
284 return HookResult(
285 id=hook.name,
286 name=hook.name,
287 status="error",
288 duration=duration,
289 issues_found=[str(e)],
290 stage=hook.stage.value,
291 )
293 def _parse_hook_output(self, returncode: int, output: str) -> dict[str, t.Any]:
294 return {
295 "hook_id": None,
296 "exit_code": returncode,
297 "files_processed": 0,
298 "issues": [],
299 "raw_output": output,
300 }
302 def _display_hook_result(self, result: HookResult) -> None:
303 dots = "." * (60 - len(result.name))
304 status_text = "Passed" if result.status == "passed" else "Failed"
305 status_color = "green" if result.status == "passed" else "red"
307 self.console.print(
308 f"{result.name}{dots}[{status_color}]{status_text}[/{status_color}]",
309 )
311 if result.status != "passed" and result.issues_found:
312 for issue in result.issues_found:
313 if issue and "raw_output" not in issue:
314 self.console.print(issue)
316 async def _handle_retries(
317 self,
318 strategy: HookStrategy,
319 results: list[HookResult],
320 ) -> list[HookResult]:
321 if strategy.retry_policy == RetryPolicy.FORMATTING_ONLY:
322 return await self._retry_formatting_hooks(strategy, results)
323 if strategy.retry_policy == RetryPolicy.ALL_HOOKS:
324 return await self._retry_all_hooks(strategy, results)
325 return results
327 async def _retry_formatting_hooks(
328 self,
329 strategy: HookStrategy,
330 results: list[HookResult],
331 ) -> list[HookResult]:
332 formatting_hooks_failed: set[str] = set()
334 for i, result in enumerate(results):
335 hook = strategy.hooks[i]
336 if getattr(hook, "is_formatting", False) and result.status == "failed":
337 formatting_hooks_failed.add(hook.name)
339 if not formatting_hooks_failed:
340 return results
342 retry_tasks = [self._execute_single_hook(hook) for hook in strategy.hooks]
343 retry_results = await asyncio.gather(*retry_tasks, return_exceptions=True)
345 updated_results: list[HookResult] = []
346 for i, (prev_result, new_result) in enumerate(
347 zip(results, retry_results, strict=False)
348 ):
349 if isinstance(new_result, Exception):
350 hook = strategy.hooks[i]
351 error_result = HookResult(
352 id=hook.name,
353 name=hook.name,
354 status="error",
355 duration=prev_result.duration,
356 issues_found=[str(new_result)],
357 stage=hook.stage.value,
358 )
359 updated_results.append(error_result)
360 else:
361 hook_result = t.cast("HookResult", new_result)
362 hook_result.duration += prev_result.duration
363 updated_results.append(hook_result)
365 self._display_hook_result(updated_results[-1])
367 return updated_results
369 async def _retry_all_hooks(
370 self,
371 strategy: HookStrategy,
372 results: list[HookResult],
373 ) -> list[HookResult]:
374 failed_indices = [i for i, r in enumerate(results) if r.status == "failed"]
376 if not failed_indices:
377 return results
379 updated_results = results.copy()
380 retry_tasks: list[t.Awaitable[HookResult]] = []
381 retry_indices: list[int] = []
383 for i in failed_indices:
384 hook = strategy.hooks[i]
385 retry_tasks.append(self._execute_single_hook(hook))
386 retry_indices.append(i)
388 retry_results = await asyncio.gather(*retry_tasks, return_exceptions=True)
390 for result_idx, new_result in zip(retry_indices, retry_results, strict=False):
391 prev_result = results[result_idx]
393 if isinstance(new_result, Exception):
394 hook = strategy.hooks[result_idx]
395 error_result = HookResult(
396 id=hook.name,
397 name=hook.name,
398 status="error",
399 duration=prev_result.duration,
400 issues_found=[str(new_result)],
401 stage=hook.stage.value,
402 )
403 updated_results[result_idx] = error_result
404 else:
405 hook_result = t.cast("HookResult", new_result)
406 hook_result.duration += prev_result.duration
407 updated_results[result_idx] = hook_result
409 self._display_hook_result(updated_results[result_idx])
411 return updated_results
413 def _print_summary(
414 self,
415 strategy: HookStrategy,
416 results: list[HookResult],
417 success: bool,
418 performance_gain: float,
419 ) -> None:
420 if success:
421 self.console.print(
422 f"[green]✅[/ green] {strategy.name.title()} hooks passed: {len(results)} / {len(results)} "
423 f"(async, {performance_gain: .1f} % faster)",
424 )
425 else:
426 failed_count = sum(1 for r in results if r.status == "failed")
427 error_count = sum(1 for r in results if r.status in ("timeout", "error"))
428 self.console.print(
429 f"[red]❌[/ red] {strategy.name.title()} hooks failed: {failed_count} failed, {error_count} errors "
430 f"(async, {performance_gain: .1f} % faster)",
431 )