Coverage for fastblocks / actions / sync / cache.py: 41%

275 statements  

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

1"""Cache synchronization and consistency management across layers.""" 

2 

3import typing as t 

4 

5from oneiric.core.resolution import Resolver 

6 

7# Migration from ACB to Oneiric 

8depends = Resolver() 

9 

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

11try: 

12 # MIGRATED: Removed ACB import - debug import debug 

13 pass 

14except ImportError: 

15 # Fallback for Oneiric-only mode 

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

17 """Debug function fallback.""" 

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

19 

20 

21from .strategies import SyncResult, SyncStrategy 

22 

23 

24class CacheSyncResult(SyncResult): 

25 def __init__( 

26 self, 

27 *, 

28 invalidated_keys: list[str] | None = None, 

29 warmed_keys: list[str] | None = None, 

30 cleared_namespaces: list[str] | None = None, 

31 **kwargs: t.Any, 

32 ) -> None: 

33 super().__init__(**kwargs) 

34 self.invalidated_keys = invalidated_keys if invalidated_keys is not None else [] 

35 self.warmed_keys = warmed_keys if warmed_keys is not None else [] 

36 self.cleared_namespaces = ( 

37 cleared_namespaces if cleared_namespaces is not None else [] 

38 ) 

39 

40 

41async def sync_cache( 

42 *, 

43 operation: str = "refresh", 

44 namespaces: list[str] | None = None, 

45 keys: list[str] | None = None, 

46 warm_templates: bool = True, 

47 strategy: SyncStrategy | None = None, 

48) -> CacheSyncResult: 

49 if strategy is None: 

50 strategy = SyncStrategy() 

51 

52 if namespaces is None: 

53 namespaces = ["templates", "bccache", "responses"] 

54 

55 debug(f"Starting cache sync: operation={operation}, namespaces={namespaces}") 

56 

57 result = CacheSyncResult() 

58 

59 try: 

60 # MIGRATED: Removed ACB import - using Oneiric equivalent 

61 

62 cache = await depends.resolve("fastblocks", "cache") 

63 

64 if not cache: 

65 result.errors.append(Exception("Cache adapter not available")) 

66 return result 

67 

68 except Exception as e: 

69 result.errors.append(e) 

70 return result 

71 

72 try: 

73 if operation == "refresh": 

74 await _refresh_cache(cache, namespaces, strategy, result) 

75 elif operation == "invalidate": 

76 await _invalidate_cache(cache, namespaces, keys, strategy, result) 

77 elif operation == "warm": 

78 await _warm_cache(cache, namespaces, strategy, result) 

79 elif operation == "clear": 

80 await _clear_cache(cache, namespaces, strategy, result) 

81 else: 

82 result.errors.append(ValueError(f"Unknown cache operation: {operation}")) 

83 return result 

84 

85 if ( 

86 warm_templates 

87 and operation in ("refresh", "invalidate") 

88 and result.invalidated_keys 

89 ): 

90 await _warm_template_cache(cache, strategy, result) 

91 

92 except Exception as e: 

93 result.errors.append(e) 

94 debug(f"Error in cache sync operation {operation}: {e}") 

95 

96 debug( 

97 f"Cache sync completed: {len(result.invalidated_keys)} invalidated, {len(result.warmed_keys)} warmed", 

98 ) 

99 

100 return result 

101 

102 

103async def _refresh_cache( 

104 cache: t.Any, 

105 namespaces: list[str], 

106 strategy: SyncStrategy, 

107 result: CacheSyncResult, 

108) -> None: 

109 await _invalidate_cache(cache, namespaces, None, strategy, result) 

110 

111 await _warm_cache(cache, namespaces, strategy, result) 

112 

113 

114async def _invalidate_cache( 

115 cache: t.Any, 

116 namespaces: list[str], 

117 keys: list[str] | None, 

118 strategy: SyncStrategy, 

119 result: CacheSyncResult, 

120) -> None: 

121 if strategy.dry_run: 

122 debug("DRY RUN: Would invalidate cache entries") 

123 result.invalidated_keys.append("DRY_RUN_INVALIDATION") 

124 return 

125 

126 if keys: 

127 for key in keys: 

128 try: 

129 await cache.delete(key) 

130 result.invalidated_keys.append(key) 

131 debug(f"Invalidated cache key: {key}") 

132 except Exception as e: 

133 result.errors.append(e) 

134 

135 for namespace in namespaces: 

136 try: 

137 if namespace == "templates": 

138 pattern = "template:*" 

139 deleted_keys = await cache.delete_pattern(pattern) 

140 result.invalidated_keys.extend(deleted_keys or [pattern]) 

141 debug(f"Invalidated template cache: {pattern}") 

142 

143 elif namespace == "bccache": 

144 pattern = "bccache:*" 

145 deleted_keys = await cache.delete_pattern(pattern) 

146 result.invalidated_keys.extend(deleted_keys or [pattern]) 

147 debug(f"Invalidated bytecode cache: {pattern}") 

148 

149 elif namespace == "responses": 

150 pattern = "response:*" 

151 deleted_keys = await cache.delete_pattern(pattern) 

152 result.invalidated_keys.extend(deleted_keys or [pattern]) 

153 debug(f"Invalidated response cache: {pattern}") 

154 

155 elif namespace == "gather": 

156 pattern = "routes:*" 

157 deleted_keys = await cache.delete_pattern(pattern) 

158 result.invalidated_keys.extend(deleted_keys or [pattern]) 

159 

160 pattern = "templates:*" 

161 deleted_keys = await cache.delete_pattern(pattern) 

162 result.invalidated_keys.extend(deleted_keys or [pattern]) 

163 

164 pattern = "middleware:*" 

165 deleted_keys = await cache.delete_pattern(pattern) 

166 result.invalidated_keys.extend(deleted_keys or [pattern]) 

167 

168 debug("Invalidated gather cache") 

169 

170 else: 

171 pattern = f"{namespace}:*" 

172 deleted_keys = await cache.delete_pattern(pattern) 

173 result.invalidated_keys.extend(deleted_keys or [pattern]) 

174 debug(f"Invalidated namespace {namespace}: {pattern}") 

175 

176 except Exception as e: 

177 result.errors.append(e) 

178 debug(f"Error invalidating namespace {namespace}: {e}") 

179 

180 

181async def _warm_cache( 

182 cache: t.Any, 

183 namespaces: list[str], 

184 strategy: SyncStrategy, 

185 result: CacheSyncResult, 

186) -> None: 

187 if strategy.dry_run: 

188 debug("DRY RUN: Would warm cache entries") 

189 result.warmed_keys.append("DRY_RUN_WARMING") 

190 return 

191 

192 for namespace in namespaces: 

193 try: 

194 if namespace == "templates": 

195 await _warm_template_cache(cache, strategy, result) 

196 elif namespace == "responses": 

197 await _warm_response_cache(cache, strategy, result) 

198 elif namespace == "gather": 

199 await _warm_gather_cache(cache, strategy, result) 

200 

201 except Exception as e: 

202 result.errors.append(e) 

203 debug(f"Error warming namespace {namespace}: {e}") 

204 

205 

206async def _clear_cache( 

207 cache: t.Any, 

208 namespaces: list[str], 

209 strategy: SyncStrategy, 

210 result: CacheSyncResult, 

211) -> None: 

212 if strategy.dry_run: 

213 debug("DRY RUN: Would clear cache namespaces") 

214 result.cleared_namespaces.extend(namespaces) 

215 return 

216 

217 for namespace in namespaces: 

218 try: 

219 await cache.clear(namespace) 

220 result.cleared_namespaces.append(namespace) 

221 debug(f"Cleared cache namespace: {namespace}") 

222 

223 except Exception as e: 

224 result.errors.append(e) 

225 debug(f"Error clearing namespace {namespace}: {e}") 

226 

227 

228async def _warm_template_cache( 

229 cache: t.Any, 

230 strategy: SyncStrategy, 

231 result: CacheSyncResult, 

232) -> None: 

233 common_templates = [ 

234 "base.html", 

235 "layout.html", 

236 "index.html", 

237 "404.html", 

238 "500.html", 

239 "login.html", 

240 "dashboard.html", 

241 ] 

242 

243 try: 

244 # MIGRATED: Removed ACB import - using Oneiric equivalent 

245 

246 storage = await depends.resolve("fastblocks", "storage") 

247 

248 if not storage: 

249 debug("Storage not available for template warming") 

250 return 

251 

252 for template_path in common_templates: 

253 try: 

254 if await storage.templates.exists(template_path): 

255 content = await storage.templates.read(template_path) 

256 

257 cache_key = f"template:{template_path}" 

258 await cache.set(cache_key, content, ttl=86400) 

259 result.warmed_keys.append(cache_key) 

260 

261 debug(f"Warmed template cache: {template_path}") 

262 

263 except Exception as e: 

264 debug(f"Error warming template {template_path}: {e}") 

265 

266 except Exception as e: 

267 debug(f"Error in template cache warming: {e}") 

268 

269 

270async def _warm_response_cache( 

271 cache: t.Any, 

272 strategy: SyncStrategy, 

273 result: CacheSyncResult, 

274) -> None: 

275 debug("Response cache warming not implemented - requires HTTP client") 

276 

277 

278async def _warm_gather_cache( 

279 cache: t.Any, 

280 strategy: SyncStrategy, 

281 result: CacheSyncResult, 

282) -> None: 

283 try: 

284 from fastblocks.actions.gather import gather 

285 

286 try: 

287 routes_result = await gather.routes() 

288 if routes_result.total_routes > 0: 

289 result.warmed_keys.append("gather:routes") 

290 debug("Warmed gather routes cache") 

291 except Exception as e: 

292 debug(f"Error warming routes cache: {e}") 

293 

294 try: 

295 templates_result = await gather.templates() 

296 if templates_result.total_components > 0: 

297 result.warmed_keys.append("gather:templates") 

298 debug("Warmed gather templates cache") 

299 except Exception as e: 

300 debug(f"Error warming templates cache: {e}") 

301 

302 try: 

303 middleware_result = await gather.middleware() 

304 if middleware_result.total_middleware > 0: 

305 result.warmed_keys.append("gather:middleware") 

306 debug("Warmed gather middleware cache") 

307 except Exception as e: 

308 debug(f"Error warming middleware cache: {e}") 

309 

310 except Exception as e: 

311 debug(f"Error warming gather cache: {e}") 

312 

313 

314async def invalidate_template_cache( 

315 template_paths: list[str] | None = None, 

316 cache_namespace: str = "templates", 

317) -> dict[str, t.Any]: 

318 result: dict[str, t.Any] = { 

319 "invalidated": [], 

320 "errors": [], 

321 } 

322 

323 try: 

324 # MIGRATED: Removed ACB import - using Oneiric equivalent 

325 

326 cache = await depends.resolve("fastblocks", "cache") 

327 

328 if not cache: 

329 result["errors"].append("Cache adapter not available") 

330 return result 

331 

332 if not template_paths: 

333 pattern = f"{cache_namespace}:*" 

334 deleted_keys = await cache.delete_pattern(pattern) 

335 result["invalidated"].extend(deleted_keys or [pattern]) 

336 else: 

337 for template_path in template_paths: 

338 try: 

339 template_key = f"{cache_namespace}:{template_path}" 

340 await cache.delete(template_key) 

341 result["invalidated"].append(template_key) 

342 

343 bytecode_key = f"bccache:{template_path}" 

344 await cache.delete(bytecode_key) 

345 result["invalidated"].append(bytecode_key) 

346 

347 await cache.delete_pattern(f"{cache_namespace}:*:{template_path}") 

348 await cache.delete_pattern(f"bccache:*:{template_path}") 

349 

350 debug(f"Invalidated cache for template: {template_path}") 

351 

352 except Exception as e: 

353 result["errors"].append(f"{template_path}: {e}") 

354 

355 except Exception as e: 

356 result["errors"].append(str(e)) 

357 debug(f"Error invalidating template cache: {e}") 

358 

359 return result 

360 

361 

362async def get_cache_stats( 

363 namespaces: list[str] | None = None, 

364) -> dict[str, t.Any]: 

365 if namespaces is None: 

366 namespaces = ["templates", "bccache", "responses", "gather"] 

367 

368 stats: dict[str, t.Any] = { 

369 "total_keys": 0, 

370 "namespaces": {}, 

371 "memory_usage": 0, 

372 "hit_rate": 0.0, 

373 "errors": [], 

374 } 

375 

376 try: 

377 cache = await _get_cache_adapter(stats) 

378 if not cache: 

379 return stats 

380 

381 await _collect_cache_info(cache, stats) 

382 await _collect_namespace_stats(cache, namespaces, stats) 

383 

384 except Exception as e: 

385 stats["errors"].append(str(e)) 

386 debug(f"Error getting cache stats: {e}") 

387 

388 return stats 

389 

390 

391async def _get_cache_adapter(stats: dict[str, t.Any]) -> t.Any: 

392 # MIGRATED: Removed ACB import - using Oneiric equivalent 

393 

394 cache = await depends.resolve("fastblocks", "cache") 

395 if not cache: 

396 stats["errors"].append("Cache adapter not available") 

397 return cache 

398 

399 

400async def _collect_cache_info(cache: t.Any, stats: dict[str, t.Any]) -> None: 

401 try: 

402 info = await cache.info() 

403 stats["memory_usage"] = info.get("used_memory", 0) 

404 hits = info.get("keyspace_hits", 0) 

405 misses = info.get("keyspace_misses", 0) 

406 stats["hit_rate"] = hits / max(hits + misses, 1) 

407 except Exception as e: 

408 stats["errors"].append(f"Error getting cache info: {e}") 

409 

410 

411async def _collect_namespace_stats( 

412 cache: t.Any, 

413 namespaces: list[str], 

414 stats: dict[str, t.Any], 

415) -> None: 

416 for namespace in namespaces: 

417 try: 

418 pattern = f"{namespace}:*" 

419 keys = await cache.keys(pattern) 

420 key_count = len(keys) if keys else 0 

421 

422 stats["namespaces"][namespace] = { 

423 "key_count": key_count, 

424 "sample_keys": keys[:5] if keys else [], 

425 } 

426 

427 stats["total_keys"] += key_count 

428 

429 except Exception as e: 

430 stats["errors"].append(f"Error checking namespace {namespace}: {e}") 

431 

432 

433async def optimize_cache( 

434 max_memory_mb: int = 512, 

435 eviction_policy: str = "allkeys-lru", 

436) -> dict[str, t.Any]: 

437 result: dict[str, t.Any] = { 

438 "optimizations": [], 

439 "warnings": [], 

440 "errors": [], 

441 } 

442 

443 try: 

444 cache = await _get_cache_adapter(result) 

445 if not cache: 

446 result["errors"].append("Cache adapter not available") 

447 return result 

448 

449 # Configure memory settings 

450 await _configure_memory_settings(cache, max_memory_mb, eviction_policy, result) 

451 

452 # Analyze cache stats and generate warnings 

453 await _analyze_cache_stats(result) 

454 

455 except Exception as e: 

456 result["errors"].append(str(e)) 

457 debug(f"Error optimizing cache: {e}") 

458 

459 return result 

460 

461 

462async def _configure_memory_settings( 

463 cache: t.Any, max_memory_mb: int, eviction_policy: str, result: dict[str, t.Any] 

464) -> None: 

465 """Configure cache memory settings.""" 

466 try: 

467 max_memory_bytes = max_memory_mb * 1024 * 1024 

468 await cache.config_set("maxmemory", max_memory_bytes) 

469 result["optimizations"].append(f"Set max memory to {max_memory_mb}MB") 

470 except Exception as e: 

471 result["errors"].append(f"Error setting max memory: {e}") 

472 

473 try: 

474 await cache.config_set("maxmemory-policy", eviction_policy) 

475 result["optimizations"].append(f"Set eviction policy to {eviction_policy}") 

476 except Exception as e: 

477 result["errors"].append(f"Error setting eviction policy: {e}") 

478 

479 

480async def _analyze_cache_stats(result: dict[str, t.Any]) -> None: 

481 """Analyze cache statistics and generate warnings.""" 

482 stats = await get_cache_stats() 

483 

484 if stats["hit_rate"] < 0.8: 

485 result["warnings"].append(f"Low cache hit rate: {stats['hit_rate']:.2%}") 

486 

487 if stats["total_keys"] > 10000: 

488 result["warnings"].append(f"High key count: {stats['total_keys']}") 

489 

490 for namespace, info in stats["namespaces"].items(): 

491 if info["key_count"] > 5000: 

492 result["warnings"].append( 

493 f"Namespace {namespace} has {info['key_count']} keys", 

494 ) 

495 

496 

497def get_cache_sync_summary(result: CacheSyncResult) -> dict[str, t.Any]: 

498 return { 

499 "invalidated_count": len(result.invalidated_keys), 

500 "warmed_count": len(result.warmed_keys), 

501 "cleared_namespaces": len(result.cleared_namespaces), 

502 "errors": len(result.errors), 

503 "success": len(result.errors) == 0, 

504 "operation_summary": { 

505 "invalidated": result.invalidated_keys[:10], 

506 "warmed": result.warmed_keys[:10], 

507 "cleared": result.cleared_namespaces, 

508 }, 

509 } 

510 

511 

512# Migration status indicator 

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

514_using_oneiric = True # Oneiric resolver available 

515_requires_further_migration = True # ACB debug system needs migration