Coverage for fastblocks / actions / gather / strategies.py: 60%

161 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""Gather strategies for error handling, caching, and parallelization.""" 

2 

3import asyncio 

4import typing as t 

5from enum import Enum 

6from pathlib import Path 

7 

8from oneiric.core.resolution import Resolver 

9 

10# Migration from ACB to Oneiric 

11depends = Resolver() 

12 

13# ACB compatibility imports - these will be migrated in future phases 

14try: 

15 # MIGRATED: Removed ACB import - debug import debug 

16 pass 

17except ImportError: 

18 # Fallback for Oneiric-only mode 

19 def debug(msg: str) -> None: 

20 """Debug function fallback.""" 

21 print(f"[DEBUG] {msg}") 

22 

23 

24class ErrorStrategy(Enum): 

25 FAIL_FAST = "fail_fast" 

26 COLLECT_ERRORS = "collect_errors" 

27 IGNORE_ERRORS = "ignore_errors" 

28 PARTIAL_SUCCESS = "partial_success" 

29 

30 

31class CacheStrategy(Enum): 

32 NO_CACHE = "no_cache" 

33 MEMORY_CACHE = "memory_cache" 

34 PERSISTENT = "persistent" 

35 

36 

37class GatherStrategy: 

38 def __init__( 

39 self, 

40 *, 

41 parallel: bool = True, 

42 max_concurrent: int = 10, 

43 timeout: float = 30.0, 

44 error_strategy: ErrorStrategy = ErrorStrategy.PARTIAL_SUCCESS, 

45 cache_strategy: CacheStrategy = CacheStrategy.MEMORY_CACHE, 

46 retry_attempts: int = 2, 

47 retry_delay: float = 0.1, 

48 ) -> None: 

49 self.parallel = parallel 

50 self.max_concurrent = max_concurrent 

51 self.timeout = timeout 

52 self.error_strategy = error_strategy 

53 self.cache_strategy = cache_strategy 

54 self.retry_attempts = retry_attempts 

55 self.retry_delay = retry_delay 

56 

57 

58_memory_cache: dict[str, t.Any] = {} 

59 

60 

61class GatherResult: 

62 def __init__( 

63 self, 

64 *, 

65 success: list[t.Any] | None = None, 

66 errors: list[Exception] | None = None, 

67 cache_key: str | None = None, 

68 ) -> None: 

69 self.success = success if success is not None else [] 

70 self.errors = errors if errors is not None else [] 

71 self.cache_key = cache_key 

72 self.total_attempts = len(self.success) + len(self.errors) 

73 

74 @property 

75 def is_success(self) -> bool: 

76 return len(self.success) > 0 

77 

78 @property 

79 def is_partial(self) -> bool: 

80 return len(self.success) > 0 and len(self.errors) > 0 

81 

82 @property 

83 def is_failure(self) -> bool: 

84 return len(self.success) == 0 and len(self.errors) > 0 

85 

86 

87async def gather_with_strategy( 

88 tasks: list[t.Coroutine[t.Any, t.Any, t.Any]], 

89 strategy: GatherStrategy, 

90 cache_key: str | None = None, 

91) -> GatherResult: 

92 if cached_result := _check_cache(cache_key, strategy): 

93 return cached_result 

94 

95 success_results, error_results = await _execute_tasks_with_strategy(tasks, strategy) 

96 

97 _handle_gather_errors(error_results, success_results, strategy) 

98 

99 result = GatherResult( 

100 success=success_results, 

101 errors=error_results, 

102 cache_key=cache_key, 

103 ) 

104 

105 _cache_result_if_needed(result, cache_key, strategy) 

106 

107 return result 

108 

109 

110def _check_cache( 

111 cache_key: str | None, 

112 strategy: GatherStrategy, 

113) -> GatherResult | None: 

114 if cache_key and strategy.cache_strategy != CacheStrategy.NO_CACHE: 

115 if cached_result := _memory_cache.get(cache_key): 

116 debug(f"Cache hit for {cache_key}") 

117 return t.cast(GatherResult, cached_result) 

118 return None 

119 

120 

121async def _execute_tasks_with_strategy( 

122 tasks: list[t.Coroutine[t.Any, t.Any, t.Any]], 

123 strategy: GatherStrategy, 

124) -> tuple[list[t.Any], list[Exception]]: 

125 if strategy.parallel and len(tasks) > 1: 

126 return await _execute_tasks_parallel(tasks, strategy) 

127 return await _execute_tasks_sequential(tasks, strategy) 

128 

129 

130async def _execute_tasks_parallel( 

131 tasks: list[t.Coroutine[t.Any, t.Any, t.Any]], 

132 strategy: GatherStrategy, 

133) -> tuple[list[t.Any], list[Exception]]: 

134 success_results = [] 

135 error_results = [] 

136 semaphore = asyncio.Semaphore(strategy.max_concurrent) 

137 

138 async def execute_with_semaphore(task: t.Coroutine[t.Any, t.Any, t.Any]) -> t.Any: 

139 async with semaphore: 

140 return await _execute_with_retry(task, strategy) 

141 

142 try: 

143 results = await asyncio.wait_for( 

144 asyncio.gather( 

145 *[execute_with_semaphore(task) for task in tasks], 

146 return_exceptions=True, 

147 ), 

148 timeout=strategy.timeout, 

149 ) 

150 

151 for result in results: 

152 if isinstance(result, Exception): 

153 error_results.append(result) 

154 else: 

155 success_results.append(result) 

156 

157 except TimeoutError as e: 

158 error_results.append(e) 

159 

160 return success_results, error_results 

161 

162 

163async def _execute_tasks_sequential( 

164 tasks: list[t.Coroutine[t.Any, t.Any, t.Any]], 

165 strategy: GatherStrategy, 

166) -> tuple[list[t.Any], list[Exception]]: 

167 success_results = [] 

168 error_results = [] 

169 

170 for task in tasks: 

171 try: 

172 result = await asyncio.wait_for( 

173 _execute_with_retry(task, strategy), 

174 timeout=strategy.timeout, 

175 ) 

176 success_results.append(result) 

177 

178 except Exception as e: 

179 error_results.append(e) 

180 if strategy.error_strategy == ErrorStrategy.FAIL_FAST: 

181 break 

182 

183 return success_results, error_results 

184 

185 

186def _handle_gather_errors( 

187 error_results: list[Exception], 

188 success_results: list[t.Any], 

189 strategy: GatherStrategy, 

190) -> None: 

191 if error_results: 

192 debug(f"Gathering completed with {len(error_results)} errors") 

193 

194 if strategy.error_strategy == ErrorStrategy.FAIL_FAST: 

195 raise error_results[0] 

196 if strategy.error_strategy == ErrorStrategy.COLLECT_ERRORS: 

197 if not success_results: 

198 msg = f"All gathering operations failed: {error_results}" 

199 raise Exception(msg) 

200 

201 

202def _cache_result_if_needed( 

203 result: GatherResult, 

204 cache_key: str | None, 

205 strategy: GatherStrategy, 

206) -> None: 

207 if cache_key and strategy.cache_strategy == CacheStrategy.MEMORY_CACHE: 

208 _memory_cache[cache_key] = result 

209 debug(f"Cached result for {cache_key}") 

210 

211 

212async def _execute_with_retry( 

213 task: t.Coroutine[t.Any, t.Any, t.Any], 

214 strategy: GatherStrategy, 

215) -> t.Any: 

216 for attempt in range(strategy.retry_attempts + 1): 

217 try: 

218 return await task 

219 except Exception as e: 

220 if attempt == strategy.retry_attempts: 

221 raise 

222 

223 debug(f"Retry attempt {attempt + 1} after error: {e}") 

224 await asyncio.sleep(strategy.retry_delay * (attempt + 1)) 

225 

226 msg = "Should not reach here" 

227 raise RuntimeError(msg) 

228 

229 

230async def gather_modules( 

231 module_patterns: list[str], 

232 strategy: GatherStrategy | None = None, 

233 cache_key: str | None = None, 

234) -> GatherResult: 

235 if strategy is None: 

236 strategy = GatherStrategy() 

237 

238 tasks: list[t.Coroutine[t.Any, t.Any, t.Any]] = [ 

239 _import_module_safe(pattern) for pattern in module_patterns 

240 ] 

241 

242 return await gather_with_strategy(tasks, strategy, cache_key) 

243 

244 

245async def _import_module_safe(module_path: str) -> t.Any: 

246 from importlib import import_module 

247 

248 if module_path.startswith("."): 

249 base_module = "fastblocks" 

250 module_path = base_module + module_path 

251 debug(f"Importing module: {module_path}") 

252 try: 

253 return import_module(module_path) 

254 except ModuleNotFoundError as e: 

255 debug(f"Module not found: {module_path} - {e}") 

256 raise 

257 except Exception as e: 

258 debug(f"Error importing {module_path}: {e}") 

259 raise 

260 

261 

262async def gather_files( 

263 file_patterns: list[str], 

264 base_path: Path | None = None, 

265 strategy: GatherStrategy | None = None, 

266 cache_key: str | None = None, 

267) -> GatherResult: 

268 if strategy is None: 

269 strategy = GatherStrategy() 

270 

271 if base_path is None: 

272 # MIGRATED: Removed ACB import - using Oneiric equivalent 

273 

274 base_path = Path(root_path) 

275 

276 tasks: list[t.Coroutine[t.Any, t.Any, t.Any]] = [ 

277 _find_files_safe(pattern, base_path) for pattern in file_patterns 

278 ] 

279 

280 return await gather_with_strategy(tasks, strategy, cache_key) 

281 

282 

283async def _find_files_safe(pattern: str, base_path: Path) -> list[Path]: 

284 from anyio import Path as AsyncPath 

285 

286 async_base = AsyncPath(base_path) 

287 try: 

288 if "*" in pattern: 

289 async_files = [ 

290 f async for f in async_base.rglob(pattern) if await f.is_file() 

291 ] 

292 files = [Path(f) for f in async_files] 

293 else: 

294 file_path = async_base / pattern 

295 files = [Path(file_path)] if await file_path.exists() else [] 

296 debug(f"Found {len(files)} files for pattern: {pattern}") 

297 return files 

298 except Exception as e: 

299 debug(f"Error finding files for pattern {pattern}: {e}") 

300 raise 

301 

302 

303def clear_cache(cache_key: str | None = None) -> None: 

304 if cache_key: 

305 _memory_cache.pop(cache_key, None) 

306 debug(f"Cleared cache for {cache_key}") 

307 else: 

308 _memory_cache.clear() 

309 debug("Cleared all cache") 

310 

311 

312def get_cache_info() -> dict[str, t.Any]: 

313 return { 

314 "total_entries": len(_memory_cache), 

315 "cache_keys": list(_memory_cache.keys()), 

316 "memory_usage": sum(len(str(v)) for v in _memory_cache.values()), 

317 } 

318 

319 

320# Migration status indicator 

321# Note: Partial migration - ACB debug system still in use 

322_using_oneiric = True # Oneiric resolver available 

323_requires_further_migration = True # ACB debug system needs migration