Coverage for fastblocks / adapters / templates / _performance_optimizer.py: 82%
141 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""Performance optimizer for FastBlocks template rendering."""
3import operator
4import time
5from collections import defaultdict, deque
6from contextlib import suppress
7from dataclasses import dataclass, field
8from typing import Any
9from uuid import UUID
11from oneiric.core.resolution import Resolver
13# Migration from ACB to Oneiric
14depends = Resolver()
17@dataclass
18class PerformanceMetrics:
19 """Performance metrics for template rendering."""
21 render_time: float
22 cache_hit: bool
23 template_size: int
24 context_size: int
25 fragment_count: int = 0
26 memory_usage: int = 0
27 concurrent_renders: int = 1
30@dataclass
31class PerformanceStats:
32 """Aggregated performance statistics."""
34 total_renders: int = 0
35 avg_render_time: float = 0.0
36 cache_hit_ratio: float = 0.0
37 slowest_templates: dict[str, float] = field(default_factory=dict)
38 fastest_templates: dict[str, float] = field(default_factory=dict)
39 memory_peak: int = 0
40 concurrent_peak: int = 0
43class PerformanceOptimizer:
44 """Template rendering performance optimizer."""
46 # Required ACB 0.19.0+ metadata
47 MODULE_ID: UUID = UUID("01937d87-b123-4567-89ab-123456789def")
48 MODULE_STATUS: str = "stable"
50 def __init__(self) -> None:
51 """Initialize performance optimizer."""
52 self.metrics_history: deque[dict[str, Any]] = deque(maxlen=1000)
53 self.template_stats: dict[str, list[float]] = defaultdict(list)
54 self.cache_stats: dict[str, int] = defaultdict(int)
55 self.concurrent_renders: int = 0
56 self.optimization_enabled: bool = True
58 # Register with ACB
59 with suppress(Exception):
60 depends.set(self)
62 def record_render(self, template_name: str, metrics: PerformanceMetrics) -> None:
63 """Record template rendering metrics."""
64 if not self.optimization_enabled:
65 return
67 # Store metrics
68 self.metrics_history.append(
69 {"template": template_name, "timestamp": time.time(), "metrics": metrics}
70 )
72 # Update template-specific stats
73 self.template_stats[template_name].append(metrics.render_time)
75 # Update cache stats
76 cache_key = f"{template_name}_cache"
77 if metrics.cache_hit:
78 self.cache_stats[f"{cache_key}_hits"] += 1
79 else:
80 self.cache_stats[f"{cache_key}_misses"] += 1
82 # Track concurrent renders
83 self.concurrent_renders = max(
84 self.concurrent_renders, metrics.concurrent_renders
85 )
87 def get_performance_stats(self) -> PerformanceStats:
88 """Get aggregated performance statistics."""
89 if not self.metrics_history:
90 return PerformanceStats()
92 total_renders = len(self.metrics_history)
93 total_render_time = sum(
94 entry["metrics"].render_time for entry in self.metrics_history
95 )
96 avg_render_time = total_render_time / total_renders
98 # Cache hit ratio
99 total_hits = sum(
100 count for key, count in self.cache_stats.items() if key.endswith("_hits")
101 )
102 total_requests = sum(self.cache_stats.values())
103 cache_hit_ratio = total_hits / total_requests if total_requests > 0 else 0.0
105 # Template performance analysis
106 slowest_templates: dict[str, Any] = {}
107 fastest_templates: dict[str, Any] = {}
109 for template, times in self.template_stats.items():
110 if times:
111 avg_time = sum(times) / len(times)
112 if len(slowest_templates) < 5:
113 slowest_templates[template] = avg_time
114 elif avg_time > min(slowest_templates.values()):
115 # Replace slowest if this is slower
116 min_key = min(
117 slowest_templates.items(), key=operator.itemgetter(1)
118 )[0]
119 del slowest_templates[min_key]
120 slowest_templates[template] = avg_time
122 if len(fastest_templates) < 5:
123 fastest_templates[template] = avg_time
124 elif avg_time < max(fastest_templates.values()):
125 # Replace fastest if this is faster
126 max_key = max(
127 fastest_templates.items(), key=operator.itemgetter(1)
128 )[0]
129 del fastest_templates[max_key]
130 fastest_templates[template] = avg_time
132 return PerformanceStats(
133 total_renders=total_renders,
134 avg_render_time=avg_render_time,
135 cache_hit_ratio=cache_hit_ratio,
136 slowest_templates=slowest_templates,
137 fastest_templates=fastest_templates,
138 concurrent_peak=self.concurrent_renders,
139 )
141 def get_optimization_recommendations(self) -> list[str]:
142 """Get performance optimization recommendations."""
143 recommendations = []
144 stats = self.get_performance_stats()
146 # Cache optimization
147 if stats.cache_hit_ratio < 0.7:
148 recommendations.append(
149 f"Cache hit ratio is {stats.cache_hit_ratio:.1%}. "
150 "Consider increasing cache TTL or improving cache keys."
151 )
153 # Slow template analysis
154 if stats.avg_render_time > 0.1: # 100ms
155 recommendations.append(
156 f"Average render time is {stats.avg_render_time:.3f}s. "
157 "Consider template optimization or caching strategies."
158 )
160 # Identify problematic templates
161 for template, avg_time in stats.slowest_templates.items():
162 if avg_time > 0.2: # 200ms
163 recommendations.append(
164 f"Template '{template}' averages {avg_time:.3f}s. "
165 "Consider breaking into fragments or optimizing logic."
166 )
168 # Concurrent rendering
169 if stats.concurrent_peak > 50:
170 recommendations.append(
171 f"Peak concurrent renders: {stats.concurrent_peak}. "
172 "Consider implementing render queuing or rate limiting."
173 )
175 return recommendations
177 async def optimize_render_context(
178 self, template_name: str, context: dict[str, Any]
179 ) -> dict[str, Any]:
180 """Optimize render context for better performance."""
181 if not self.optimization_enabled:
182 return context
184 optimized_context = context.copy()
186 # Historical performance analysis
187 if template_name in self.template_stats:
188 avg_time = sum(self.template_stats[template_name]) / len(
189 self.template_stats[template_name]
190 )
192 # For slow templates, optimize context
193 if avg_time > 0.1:
194 # Limit large collections (iterate over copy to avoid RuntimeError)
195 items_to_process = list(optimized_context.items())
196 for key, value in items_to_process:
197 if isinstance(value, list | tuple) and len(value) > 100:
198 optimized_context[f"{key}_paginated"] = True
199 optimized_context[f"{key}_total"] = len(value)
200 optimized_context[key] = value[:50] # Paginate large lists
202 # Convert complex objects to simpler representations
203 elif hasattr(value, "__dict__") and len(value.__dict__) > 20:
204 optimized_context[f"{key}_summary"] = True
206 return optimized_context
208 def should_enable_streaming(self, template_name: str, context_size: int) -> bool:
209 """Determine if streaming should be enabled for this render."""
210 if not self.optimization_enabled:
211 return False
213 # Enable streaming for large contexts
214 if context_size > 50000: # 50KB
215 return True
217 # Historical analysis
218 if template_name in self.template_stats:
219 times = self.template_stats[template_name]
220 if times and max(times) > 0.5: # 500ms
221 return True
223 return False
225 def get_optimal_cache_ttl(self, template_name: str) -> int:
226 """Get optimal cache TTL for a template."""
227 if not self.optimization_enabled:
228 return 300 # Default 5 minutes
230 # Analysis based on template usage patterns
231 if template_name in self.template_stats:
232 times = self.template_stats[template_name]
233 if times:
234 avg_time = sum(times) / len(times)
236 # Slower templates get longer cache TTL
237 if avg_time > 0.2:
238 return 1800 # 30 minutes
239 elif avg_time > 0.1:
240 return 900 # 15 minutes
242 return 300 # 5 minutes
244 return 300
246 def clear_stats(self) -> None:
247 """Clear all performance statistics."""
248 self.metrics_history.clear()
249 self.template_stats.clear()
250 self.cache_stats.clear()
251 self.concurrent_renders = 0
253 def export_metrics(self) -> dict[str, Any]:
254 """Export metrics for external monitoring."""
255 stats = self.get_performance_stats()
257 return {
258 "performance_stats": {
259 "total_renders": stats.total_renders,
260 "avg_render_time": stats.avg_render_time,
261 "cache_hit_ratio": stats.cache_hit_ratio,
262 "concurrent_peak": stats.concurrent_peak,
263 },
264 "template_performance": {
265 "slowest": stats.slowest_templates,
266 "fastest": stats.fastest_templates,
267 },
268 "recommendations": self.get_optimization_recommendations(),
269 "timestamp": time.time(),
270 }
273# Global performance optimizer instance
274_performance_optimizer = None
277def get_performance_optimizer() -> PerformanceOptimizer:
278 """Get global performance optimizer instance."""
279 global _performance_optimizer
280 if _performance_optimizer is None:
281 _performance_optimizer = PerformanceOptimizer()
282 return _performance_optimizer
285# Migration status indicator
286_using_oneiric = True