Download src/monitoring/query_profiler.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/monitoring/query_profiler.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/monitoring/query_profiler.py
-
curl -L -o query_profiler.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/monitoring/query_profiler.py
12.3 kB
| """ | |
| YAZ Care Platform - Database Query Performance Profiler | |
| Real-time query monitoring, slow query detection, and optimization recommendations | |
| """ | |
| import hashlib | |
| import threading | |
| import time | |
| from collections import defaultdict | |
| from dataclasses import dataclass, field | |
| from datetime import UTC, datetime, timedelta, timezone | |
| from typing import Any, Dict, List, Optional | |
| import structlog | |
| logger = structlog.get_logger(__name__) | |
| class QueryMetrics: | |
| """Metrics for a database query""" | |
| query_hash: str | |
| query_text: str | |
| execution_count: int = 0 | |
| total_duration: float = 0.0 | |
| min_duration: float = float("inf") | |
| max_duration: float = 0.0 | |
| avg_duration: float = 0.0 | |
| p95_duration: float = 0.0 | |
| p99_duration: float = 0.0 | |
| error_count: int = 0 | |
| last_execution: datetime | None = None | |
| durations: list[float] = field(default_factory=list) | |
| def record_execution(self, duration: float, error: bool = False): | |
| """Record a query execution""" | |
| self.execution_count += 1 | |
| self.total_duration += duration | |
| self.min_duration = min(self.min_duration, duration) | |
| self.max_duration = max(self.max_duration, duration) | |
| self.avg_duration = self.total_duration / self.execution_count | |
| self.last_execution = datetime.now(UTC) | |
| if error: | |
| self.error_count += 1 | |
| # Keep last 1000 durations for percentile calculation | |
| self.durations.append(duration) | |
| if len(self.durations) > 1000: | |
| self.durations.pop(0) | |
| # Calculate percentiles | |
| if self.durations: | |
| sorted_durations = sorted(self.durations) | |
| self.p95_duration = sorted_durations[int(len(sorted_durations) * 0.95)] | |
| self.p99_duration = sorted_durations[int(len(sorted_durations) * 0.99)] | |
| class QueryProfiler: | |
| """ | |
| Database query profiler for performance monitoring | |
| Features: | |
| - Real-time query tracking | |
| - Slow query detection (>1s) | |
| - Query deduplication by hash | |
| - Performance metrics (min, max, avg, p95, p99) | |
| - Optimization recommendations | |
| - N+1 query detection | |
| """ | |
| def __init__(self, slow_query_threshold: float = 1.0): | |
| self.slow_query_threshold = slow_query_threshold # seconds | |
| self.queries: dict[str, QueryMetrics] = {} | |
| self.lock = threading.Lock() | |
| self.total_queries = 0 | |
| self.total_slow_queries = 0 | |
| self.start_time = datetime.now(UTC) | |
| def _hash_query(self, query: str) -> str: | |
| """Generate hash for query deduplication""" | |
| # Normalize query (remove extra whitespace, lowercase) | |
| normalized = " ".join(query.lower().split()) | |
| return hashlib.md5(normalized.encode()).hexdigest()[:16] | |
| def profile_query(self, query: str, duration: float, error: bool = False): | |
| """Profile a database query execution""" | |
| query_hash = self._hash_query(query) | |
| with self.lock: | |
| self.total_queries += 1 | |
| if duration >= self.slow_query_threshold: | |
| self.total_slow_queries += 1 | |
| logger.warning("🐌 Slow query detected (%.3fs): %s", duration, query[:200]) | |
| if query_hash not in self.queries: | |
| self.queries[query_hash] = QueryMetrics( | |
| query_hash=query_hash, | |
| query_text=query[:500], # Store truncated query | |
| ) | |
| self.queries[query_hash].record_execution(duration, error) | |
| def get_slow_queries(self, limit: int = 10) -> list[QueryMetrics]: | |
| """Get slowest queries by average duration""" | |
| with self.lock: | |
| sorted_queries = sorted( | |
| self.queries.values(), key=lambda q: q.avg_duration, reverse=True | |
| ) | |
| return sorted_queries[:limit] | |
| def get_frequent_queries(self, limit: int = 10) -> list[QueryMetrics]: | |
| """Get most frequently executed queries""" | |
| with self.lock: | |
| sorted_queries = sorted( | |
| self.queries.values(), key=lambda q: q.execution_count, reverse=True | |
| ) | |
| return sorted_queries[:limit] | |
| def get_error_queries(self) -> list[QueryMetrics]: | |
| """Get queries with errors""" | |
| with self.lock: | |
| return [q for q in self.queries.values() if q.error_count > 0] | |
| def get_statistics(self) -> dict[str, Any]: | |
| """Get overall query statistics""" | |
| with self.lock: | |
| if not self.queries: | |
| return { | |
| "total_queries": 0, | |
| "unique_queries": 0, | |
| "slow_queries": 0, | |
| "error_rate": 0.0, | |
| "uptime_seconds": 0, | |
| } | |
| all_durations = [] | |
| for query in self.queries.values(): | |
| all_durations.extend(query.durations) | |
| sorted_durations = sorted(all_durations) if all_durations else [0] | |
| uptime = (datetime.now(UTC) - self.start_time).total_seconds() | |
| return { | |
| "total_queries": self.total_queries, | |
| "unique_queries": len(self.queries), | |
| "slow_queries": self.total_slow_queries, | |
| "slow_query_percentage": ( | |
| self.total_slow_queries / self.total_queries * 100 | |
| if self.total_queries > 0 | |
| else 0 | |
| ), | |
| "queries_per_second": self.total_queries / uptime if uptime > 0 else 0, | |
| "avg_duration": sum(all_durations) / len(all_durations) if all_durations else 0, | |
| "p95_duration": sorted_durations[int(len(sorted_durations) * 0.95)], | |
| "p99_duration": sorted_durations[int(len(sorted_durations) * 0.99)], | |
| "total_errors": sum(q.error_count for q in self.queries.values()), | |
| "error_rate": ( | |
| sum(q.error_count for q in self.queries.values()) / self.total_queries * 100 | |
| if self.total_queries > 0 | |
| else 0 | |
| ), | |
| "uptime_seconds": uptime, | |
| } | |
| def generate_recommendations(self) -> list[dict[str, str]]: | |
| """Generate optimization recommendations based on query patterns""" | |
| recommendations = [] | |
| with self.lock: | |
| # Check for N+1 queries | |
| frequent_queries = self.get_frequent_queries(5) | |
| for query in frequent_queries: | |
| if query.execution_count > 100 and "WHERE" in query.query_text.upper(): | |
| recommendations.append( | |
| { | |
| "type": "n+1_query", | |
| "severity": "high", | |
| "query_hash": query.query_hash, | |
| "message": f"Potential N+1 query detected (executed {query.execution_count} times). Consider using JOIN or eager loading.", | |
| "query": query.query_text[:200], | |
| } | |
| ) | |
| # Check for missing indexes | |
| slow_queries = self.get_slow_queries(5) | |
| for query in slow_queries: | |
| if "WHERE" in query.query_text.upper() and query.avg_duration > 0.5: | |
| recommendations.append( | |
| { | |
| "type": "missing_index", | |
| "severity": "medium", | |
| "query_hash": query.query_hash, | |
| "message": f"Slow query with WHERE clause (avg: {query.avg_duration:.3f}s). Consider adding indexes.", | |
| "query": query.query_text[:200], | |
| } | |
| ) | |
| # Check for full table scans | |
| for query in self.queries.values(): | |
| query_upper = query.query_text.upper() | |
| if ( | |
| "SELECT *" in query_upper or "SELECT COUNT(*)" in query_upper | |
| ) and query.avg_duration > 0.3: | |
| recommendations.append( | |
| { | |
| "type": "full_table_scan", | |
| "severity": "medium", | |
| "query_hash": query.query_hash, | |
| "message": f"Potential full table scan (avg: {query.avg_duration:.3f}s). Consider selecting specific columns or adding WHERE clause.", | |
| "query": query.query_text[:200], | |
| } | |
| ) | |
| # Check for error-prone queries | |
| error_queries = self.get_error_queries() | |
| for query in error_queries: | |
| if query.error_count > 5: | |
| recommendations.append( | |
| { | |
| "type": "error_prone", | |
| "severity": "high", | |
| "query_hash": query.query_hash, | |
| "message": f"Query has failed {query.error_count} times. Investigate query logic and constraints.", | |
| "query": query.query_text[:200], | |
| } | |
| ) | |
| return recommendations | |
| def reset_statistics(self): | |
| """Reset all profiling statistics""" | |
| with self.lock: | |
| self.queries.clear() | |
| self.total_queries = 0 | |
| self.total_slow_queries = 0 | |
| self.start_time = datetime.now(UTC) | |
| logger.info("Query profiler statistics reset") | |
| def export_metrics(self) -> dict[str, Any]: | |
| """Export metrics for Prometheus""" | |
| stats = self.get_statistics() | |
| slow_queries = self.get_slow_queries(10) | |
| frequent_queries = self.get_frequent_queries(10) | |
| return { | |
| "statistics": stats, | |
| "slow_queries": [ | |
| { | |
| "query_hash": q.query_hash, | |
| "query": q.query_text[:200], | |
| "avg_duration": q.avg_duration, | |
| "p95_duration": q.p95_duration, | |
| "execution_count": q.execution_count, | |
| } | |
| for q in slow_queries | |
| ], | |
| "frequent_queries": [ | |
| { | |
| "query_hash": q.query_hash, | |
| "query": q.query_text[:200], | |
| "execution_count": q.execution_count, | |
| "avg_duration": q.avg_duration, | |
| } | |
| for q in frequent_queries | |
| ], | |
| "recommendations": self.generate_recommendations(), | |
| } | |
| # Global query profiler instance | |
| query_profiler = QueryProfiler(slow_query_threshold=1.0) | |
| # Context manager for profiling queries | |
| class ProfileQuery: | |
| """Context manager for profiling a database query""" | |
| def __init__(self, query: str, profiler: QueryProfiler = None): # type: ignore[arg-type, assignment] | |
| self.query = query | |
| self.profiler = profiler or query_profiler | |
| self.start_time = None | |
| self.error = False | |
| def __enter__(self): | |
| self.start_time = time.time() # type: ignore[arg-type, assignment] | |
| return self | |
| def __exit__(self, exc_type, exc_val, exc_tb): | |
| duration = time.time() - self.start_time # type: ignore[misc, operator, valid-type] | |
| self.error = exc_type is not None | |
| self.profiler.profile_query(self.query, duration, self.error) | |
| return False # Don't suppress exceptions | |
| # Decorator for profiling functions with queries | |
| def profile_queries(func): | |
| """Decorator to profile all queries in a function""" | |
| def wrapper(*args, **kwargs): | |
| start_time = time.time() | |
| try: | |
| result = func(*args, **kwargs) | |
| duration = time.time() - start_time | |
| if duration > 0.5: | |
| logger.info( | |
| "Function %s took %.3fs (check for N+1 queries)", func.__name__, duration | |
| ) | |
| return result | |
| except Exception as e: | |
| duration = time.time() - start_time | |
| logger.error("Function %s failed after %.3fs: %s", func.__name__, duration, str(e)) | |
| raise | |
| return wrapper | |
| __all__ = ["QueryProfiler", "QueryMetrics", "ProfileQuery", "profile_queries", "query_profiler"] | |