Spaces:
Paused

yaz / src /shared /performance.py
anaselamr's picture
fix(collaboration): production-ready collaboration fixes — all 19 engines
0743ddc
Raw History Blame Contribute Delete
9.02 kB
"""
Performance monitoring and metrics collection
Tracks query execution times, API response times, and resource usage
"""
import threading
import time
from collections import defaultdict, deque
from datetime import UTC, datetime, timedelta, timezone
from functools import wraps
from typing import Callable, ClassVar, Dict, List, Optional
import structlog
logger = structlog.get_logger(__name__)
class PerformanceMonitor:
"""
Thread-safe performance monitoring with rolling window statistics
"""
_metrics = defaultdict(
lambda: { # type: ignore[name-defined, index, return-value, var-annotated]
"count": 0,
"total_time": 0.0,
"min_time": float("inf"),
"max_time": 0.0,
"recent_times": deque(maxlen=100), # Last 100 executions
}
)
_lock = threading.Lock()
_slow_queries: ClassVar[deque] = deque(maxlen=50) # Last 50 slow queries
@classmethod
def record_execution(cls, operation: str, duration: float, details: dict | None = None):
"""Record execution time for an operation"""
with cls._lock:
metrics = cls._metrics[operation]
metrics["count"] += 1 # type: ignore[misc, operator, valid-type]
metrics["total_time"] += duration # type: ignore[misc, operator, valid-type]
metrics["min_time"] = min(metrics["min_time"], duration) # type: ignore[call-arg, call-overload, no-redef]
metrics["max_time"] = max(metrics["max_time"], duration) # type: ignore[call-arg, call-overload, no-redef]
metrics["recent_times"].append(duration) # type: ignore[attr-defined]
# Track slow queries (>1 second)
if duration > 1.0:
cls._slow_queries.append(
{
"operation": operation,
"duration": duration,
"timestamp": datetime.now(UTC).isoformat(),
"details": details or {},
}
)
logger.warning(f"Slow operation detected: {operation} took {duration:.2f}s")
@classmethod
def get_stats(cls, operation: str | None = None) -> dict:
"""Get performance statistics"""
with cls._lock:
if operation:
if operation not in cls._metrics:
return {}
metrics = cls._metrics[operation]
recent = list(metrics["recent_times"]) # type: ignore[call-arg, call-overload, no-redef]
return {
"operation": operation,
"count": metrics["count"],
"total_time": round(metrics["total_time"], 2), # type: ignore[call-arg, call-overload, no-redef]
"avg_time": (
round(metrics["total_time"] / metrics["count"], 3)
if metrics["count"] > 0
else 0
), # type: ignore[misc, operator, valid-type]
"min_time": (
round(metrics["min_time"], 3) if metrics["min_time"] != float("inf") else 0
), # type: ignore[call-arg, call-overload, no-redef]
"max_time": round(metrics["max_time"], 3), # type: ignore[call-arg, call-overload, no-redef]
"recent_avg": round(sum(recent) / len(recent), 3) if recent else 0,
}
# Return all operations
return {
op: {
"count": m["count"],
"avg_time": round(m["total_time"] / m["count"], 3) if m["count"] > 0 else 0, # type: ignore[misc, operator, valid-type]
"max_time": round(m["max_time"], 3), # type: ignore[call-arg, call-overload, no-redef]
}
for op, m in cls._metrics.items()
}
@classmethod
def get_slow_queries(cls) -> list[dict]:
"""Get recent slow queries"""
with cls._lock:
return list(cls._slow_queries)
@classmethod
def get_top_operations(cls, limit: int = 10) -> list[dict]:
"""Get top operations by total time"""
with cls._lock:
operations = []
for op, metrics in cls._metrics.items():
operations.append(
{
"operation": op,
"total_time": round(metrics["total_time"], 2), # type: ignore[call-arg, call-overload, no-redef]
"count": metrics["count"],
"avg_time": (
round(metrics["total_time"] / metrics["count"], 3)
if metrics["count"] > 0
else 0
), # type: ignore[misc, operator, valid-type]
}
)
# Sort by total time descending
operations.sort(key=lambda x: x["total_time"], reverse=True)
return operations[:limit]
@classmethod
def reset_stats(cls):
"""Reset all statistics"""
with cls._lock:
cls._metrics.clear()
cls._slow_queries.clear()
logger.info("Performance statistics reset")
def monitor_performance(operation_name: str, slow_threshold: float = 1.0):
"""
Decorator to monitor function performance
Usage:
@monitor_performance("get_inventory_item", slow_threshold=0.5)
def get_item(self, item_id):
...
"""
def decorator(func: Callable) -> Callable:
@wraps(func)
def sync_wrapper(*args, **kwargs):
start = time.time()
try:
result = func(*args, **kwargs)
return result
finally:
duration = time.time() - start
PerformanceMonitor.record_execution(
operation_name,
duration,
details={"args_count": len(args), "kwargs_count": len(kwargs)},
)
if duration > slow_threshold:
logger.warning(
f"Operation {operation_name} exceeded threshold: "
f"{duration:.2f}s > {slow_threshold}s"
)
@wraps(func)
async def async_wrapper(*args, **kwargs):
start = time.time()
try:
result = await func(*args, **kwargs)
return result
finally:
duration = time.time() - start
PerformanceMonitor.record_execution(
operation_name,
duration,
details={"args_count": len(args), "kwargs_count": len(kwargs)},
)
if duration > slow_threshold:
logger.warning(
f"Operation {operation_name} exceeded threshold: "
f"{duration:.2f}s > {slow_threshold}s"
)
# Return appropriate wrapper based on function type
import asyncio
if asyncio.iscoroutinefunction(func):
return async_wrapper
return sync_wrapper
return decorator
class QueryPerformanceTracker:
"""Track database query performance"""
@staticmethod
def track_query(query_type: str, table_name: str):
"""Decorator for tracking query performance"""
def decorator(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args, **kwargs):
operation = f"query:{query_type}:{table_name}"
start = time.time()
try:
result = func(*args, **kwargs)
return result
finally:
duration = time.time() - start
PerformanceMonitor.record_execution(operation, duration)
return wrapper
return decorator
# Middleware-compatible timing function
def time_operation(operation_name: str) -> float:
"""
Context manager for timing operations
Usage:
with time_operation("my_operation"):
# do work
"""
class TimingContext:
def __init__(self, op_name: str):
self.op_name = op_name
self.start = None
def __enter__(self):
self.start = time.time() # type: ignore[arg-type, assignment]
return self
def __exit__(self, exc_type, exc_val, exc_tb):
duration = time.time() - self.start # type: ignore[misc, operator, valid-type]
PerformanceMonitor.record_execution(self.op_name, duration)
return False
return TimingContext(operation_name) # type: ignore[name-defined, index, return-value, var-annotated]
# Export utilities
__all__ = [
"PerformanceMonitor",
"monitor_performance",
"QueryPerformanceTracker",
"time_operation",
]