Monitoring & Alerting API
The monitoring and alerting system provides comprehensive metrics collection, security violation tracking, and multi-channel alerting for Kailash workflows.
Monitoring and alerting system for Kailash SDK.
Provides comprehensive monitoring for validation failures, security violations, performance metrics, and alerting for critical events. Includes specialized AsyncSQL lock contention monitoring.
- class kailash.monitoring.ValidationMetrics[source]
Bases:
MetricsCollectorMetrics collector for validation operations.
- record_validation_attempt(node_type: str, success: bool, duration_ms: float, cached: bool = False)[source]
Record a validation attempt.
- get_success_rate(time_window: timedelta = datetime.timedelta(seconds=3600)) float[source]
Get validation success rate over time window.
- get_cache_hit_rate(time_window: timedelta = datetime.timedelta(seconds=3600)) float[source]
Get cache hit rate over time window.
- clear_metrics()
Clear all metrics.
- create_metric(name: str, metric_type: MetricType, description: str, unit: str = '') MetricSeries
Create a new metric series.
- Parameters:
name (str) – Metric name
metric_type (MetricType) – Type of metric
description (str) – Description of what this metric measures
unit (str) – Unit of measurement
- Returns:
MetricSeries instance
- Return type:
- get_all_metrics() Dict[str, MetricSeries]
Get all metric series.
- Return type:
- get_metric(name: str) MetricSeries | None
Get a metric series by name.
- Parameters:
name (str)
- Return type:
MetricSeries | None
- increment(name: str, value: int | float = 1, labels: Dict[str, str] | None = None)
Increment a counter metric.
- record_histogram(name: str, value: int | float, labels: Dict[str, str] | None = None)
Record a histogram value.
- class kailash.monitoring.SecurityMetrics[source]
Bases:
MetricsCollectorMetrics collector for security events.
- record_security_violation(violation_type: str, severity: MetricSeverity, source: str, details: Dict[str, Any] | None = None)[source]
Record a security violation.
- record_blocked_connection(source_node: str, target_node: str, reason: str)[source]
Record a blocked connection.
- get_violation_rate(time_window: timedelta = datetime.timedelta(seconds=3600)) float[source]
Get security violation rate per minute.
- get_critical_violations(time_window: timedelta = datetime.timedelta(seconds=3600)) int[source]
Get count of critical violations in time window.
- clear_metrics()
Clear all metrics.
- create_metric(name: str, metric_type: MetricType, description: str, unit: str = '') MetricSeries
Create a new metric series.
- Parameters:
name (str) – Metric name
metric_type (MetricType) – Type of metric
description (str) – Description of what this metric measures
unit (str) – Unit of measurement
- Returns:
MetricSeries instance
- Return type:
- get_all_metrics() Dict[str, MetricSeries]
Get all metric series.
- Return type:
- get_metric(name: str) MetricSeries | None
Get a metric series by name.
- Parameters:
name (str)
- Return type:
MetricSeries | None
- increment(name: str, value: int | float = 1, labels: Dict[str, str] | None = None)
Increment a counter metric.
- record_histogram(name: str, value: int | float, labels: Dict[str, str] | None = None)
Record a histogram value.
- class kailash.monitoring.PerformanceMetrics[source]
Bases:
MetricsCollectorMetrics collector for performance monitoring.
- record_operation(operation: str, duration_ms: float, success: bool)[source]
Record an operation performance.
- update_system_metrics(memory_mb: float, cpu_percent: float, rps: float)[source]
Update system-level metrics.
- get_p95_response_time(time_window: timedelta = datetime.timedelta(seconds=3600)) float | None[source]
Get 95th percentile response time.
- clear_metrics()
Clear all metrics.
- create_metric(name: str, metric_type: MetricType, description: str, unit: str = '') MetricSeries
Create a new metric series.
- Parameters:
name (str) – Metric name
metric_type (MetricType) – Type of metric
description (str) – Description of what this metric measures
unit (str) – Unit of measurement
- Returns:
MetricSeries instance
- Return type:
- get_all_metrics() Dict[str, MetricSeries]
Get all metric series.
- Return type:
- get_metric(name: str) MetricSeries | None
Get a metric series by name.
- Parameters:
name (str)
- Return type:
MetricSeries | None
- increment(name: str, value: int | float = 1, labels: Dict[str, str] | None = None)
Increment a counter metric.
- record_histogram(name: str, value: int | float, labels: Dict[str, str] | None = None)
Record a histogram value.
- class kailash.monitoring.AlertManager(metrics_registry: MetricsRegistry)[source]
Bases:
objectAlert manager for handling alerting rules and notifications.
- Parameters:
metrics_registry (MetricsRegistry)
- __init__(metrics_registry: MetricsRegistry)[source]
Initialize alert manager.
- Parameters:
metrics_registry (MetricsRegistry) – Metrics registry to monitor
- add_rule(rule: AlertRule)[source]
Add an alerting rule.
- Parameters:
rule (AlertRule) – AlertRule to add
- remove_rule(rule_name: str)[source]
Remove an alerting rule.
- Parameters:
rule_name (str) – Name of rule to remove
- add_notification_channel(channel: NotificationChannel)[source]
Add a notification channel.
- Parameters:
channel (NotificationChannel) – NotificationChannel to add
- class kailash.monitoring.AlertRule(name: str, description: str, severity: AlertSeverity, metric_name: str, condition: str, threshold: int | float, time_window: timedelta = datetime.timedelta(seconds=300), evaluation_interval: timedelta = datetime.timedelta(seconds=60), notification_interval: timedelta = datetime.timedelta(seconds=900), labels: Dict[str, str]=<factory>, annotations: Dict[str, str]=<factory>, enabled: bool = True)[source]
Bases:
objectAlert rule configuration.
- Parameters:
- severity: AlertSeverity
- evaluate(metric_series: MetricSeries) bool[source]
Evaluate if alert condition is met.
- Parameters:
metric_series (MetricSeries) – Metric series to evaluate
- Returns:
True if alert condition is met
- Return type:
- __init__(name: str, description: str, severity: AlertSeverity, metric_name: str, condition: str, threshold: int | float, time_window: timedelta = datetime.timedelta(seconds=300), evaluation_interval: timedelta = datetime.timedelta(seconds=60), notification_interval: timedelta = datetime.timedelta(seconds=900), labels: Dict[str, str]=<factory>, annotations: Dict[str, str]=<factory>, enabled: bool = True) None
- class kailash.monitoring.AlertSeverity(value)[source]
Bases:
EnumAlert severity levels.
- INFO = 'info'
- WARNING = 'warning'
- ERROR = 'error'
- CRITICAL = 'critical'
- classmethod __contains__(member)
Return True if member is a member of this enum raises TypeError if member is not an enum member
note: in 3.12 TypeError will no longer be raised, and True will also be returned if member is the value of a member in this enum
- classmethod __getitem__(name)
Return the member matching name.
- classmethod __iter__()
Return members in definition order.
- classmethod __len__()
Return the number of members (no aliases)
- class kailash.monitoring.AsyncSQLMetrics(enabled: bool = True, registry: Any = None)[source]
Bases:
objectPrometheus metrics collector for AsyncSQL lock contention monitoring.
- Parameters:
enabled (bool)
registry (Any)
- __init__(enabled: bool = True, registry: Any = None)[source]
Initialize AsyncSQL metrics collector.
- record_lock_acquisition(pool_key: str, status: str, wait_time: float = 0.0)[source]
Record a lock acquisition event.
- kailash.monitoring.enable_metrics(registry: Any = None) AsyncSQLMetrics[source]
Enable global AsyncSQL metrics collection.
- Parameters:
registry (Any) – Custom Prometheus registry (uses default if None)
- Returns:
The configured metrics instance
- Return type:
- kailash.monitoring.get_global_metrics() AsyncSQLMetrics | None[source]
Get the global AsyncSQL metrics instance.
- Return type:
AsyncSQLMetrics | None
- kailash.monitoring.set_global_metrics(metrics: AsyncSQLMetrics | None)[source]
Set the global AsyncSQL metrics instance.
- Parameters:
metrics (AsyncSQLMetrics | None)
- kailash.monitoring.record_lock_acquisition(pool_key: str, status: str, wait_time: float = 0.0)[source]
Record a lock acquisition event using global metrics.
- kailash.monitoring.record_pool_operation(pool_key: str, operation: str)[source]
Record a pool operation event using global metrics.
- kailash.monitoring.set_active_locks(pool_key: str, count: int)[source]
Update active locks count using global metrics.
- kailash.monitoring.integrate_with_async_sql()[source]
Example of how to integrate metrics with AsyncSQLDatabaseNode.
This would typically be called during AsyncSQL initialization or through a configuration setting.
Metrics Collection
Metrics collection and aggregation for monitoring system.
Provides detailed metrics for validation failures, security violations, and performance monitoring with time-series data collection.
- class kailash.monitoring.metrics.MetricType(value)[source]
Bases:
EnumTypes of metrics collected.
- COUNTER = 'counter'
- GAUGE = 'gauge'
- HISTOGRAM = 'histogram'
- TIMER = 'timer'
- classmethod __contains__(member)
Return True if member is a member of this enum raises TypeError if member is not an enum member
note: in 3.12 TypeError will no longer be raised, and True will also be returned if member is the value of a member in this enum
- classmethod __getitem__(name)
Return the member matching name.
- classmethod __iter__()
Return members in definition order.
- classmethod __len__()
Return the number of members (no aliases)
- class kailash.monitoring.metrics.MetricSeverity(value)[source]
Bases:
EnumSeverity levels for metrics.
- LOW = 'low'
- MEDIUM = 'medium'
- HIGH = 'high'
- CRITICAL = 'critical'
- classmethod __contains__(member)
Return True if member is a member of this enum raises TypeError if member is not an enum member
note: in 3.12 TypeError will no longer be raised, and True will also be returned if member is the value of a member in this enum
- classmethod __getitem__(name)
Return the member matching name.
- classmethod __iter__()
Return members in definition order.
- classmethod __len__()
Return the number of members (no aliases)
- class kailash.monitoring.metrics.MetricPoint(timestamp: datetime, value: int | float, labels: Dict[str, str]=<factory>, metadata: Dict[str, ~typing.Any]=<factory>)[source]
Bases:
objectSingle metric data point.
- Parameters:
- class kailash.monitoring.metrics.MetricSeries(name: str, metric_type: MetricType, description: str, unit: str = '', points: deque = <factory>)[source]
Bases:
objectTime series of metric data points.
- Parameters:
name (str)
metric_type (MetricType)
description (str)
unit (str)
points (deque)
- metric_type: MetricType
- add_point(value: int | float, labels: Dict[str, str] | None = None, metadata: Dict[str, Any] | None = None)[source]
Add a new data point to the series.
- get_average(time_window: timedelta | None = None) float | None[source]
Get average value over time window.
- get_max(time_window: timedelta | None = None) int | float | None[source]
Get maximum value over time window.
- class kailash.monitoring.metrics.MetricsCollector(max_series: int = 100)[source]
Bases:
objectBase metrics collector.
- Parameters:
max_series (int)
- __init__(max_series: int = 100)[source]
Initialize metrics collector.
- Parameters:
max_series (int) – Maximum number of metric series to track
- create_metric(name: str, metric_type: MetricType, description: str, unit: str = '') MetricSeries[source]
Create a new metric series.
- Parameters:
name (str) – Metric name
metric_type (MetricType) – Type of metric
description (str) – Description of what this metric measures
unit (str) – Unit of measurement
- Returns:
MetricSeries instance
- Return type:
- increment(name: str, value: int | float = 1, labels: Dict[str, str] | None = None)[source]
Increment a counter metric.
- set_gauge(name: str, value: int | float, labels: Dict[str, str] | None = None)[source]
Set a gauge metric value.
- record_timer(name: str, duration_ms: float, labels: Dict[str, str] | None = None)[source]
Record a timer metric.
- record_histogram(name: str, value: int | float, labels: Dict[str, str] | None = None)[source]
Record a histogram value.
- get_metric(name: str) MetricSeries | None[source]
Get a metric series by name.
- Parameters:
name (str)
- Return type:
MetricSeries | None
- get_all_metrics() Dict[str, MetricSeries][source]
Get all metric series.
- Return type:
- class kailash.monitoring.metrics.ValidationMetrics[source]
Bases:
MetricsCollectorMetrics collector for validation operations.
- record_validation_attempt(node_type: str, success: bool, duration_ms: float, cached: bool = False)[source]
Record a validation attempt.
- get_success_rate(time_window: timedelta = datetime.timedelta(seconds=3600)) float[source]
Get validation success rate over time window.
- get_cache_hit_rate(time_window: timedelta = datetime.timedelta(seconds=3600)) float[source]
Get cache hit rate over time window.
- clear_metrics()
Clear all metrics.
- create_metric(name: str, metric_type: MetricType, description: str, unit: str = '') MetricSeries
Create a new metric series.
- Parameters:
name (str) – Metric name
metric_type (MetricType) – Type of metric
description (str) – Description of what this metric measures
unit (str) – Unit of measurement
- Returns:
MetricSeries instance
- Return type:
- get_all_metrics() Dict[str, MetricSeries]
Get all metric series.
- Return type:
- get_metric(name: str) MetricSeries | None
Get a metric series by name.
- Parameters:
name (str)
- Return type:
MetricSeries | None
- increment(name: str, value: int | float = 1, labels: Dict[str, str] | None = None)
Increment a counter metric.
- record_histogram(name: str, value: int | float, labels: Dict[str, str] | None = None)
Record a histogram value.
- class kailash.monitoring.metrics.SecurityMetrics[source]
Bases:
MetricsCollectorMetrics collector for security events.
- record_security_violation(violation_type: str, severity: MetricSeverity, source: str, details: Dict[str, Any] | None = None)[source]
Record a security violation.
- record_blocked_connection(source_node: str, target_node: str, reason: str)[source]
Record a blocked connection.
- get_violation_rate(time_window: timedelta = datetime.timedelta(seconds=3600)) float[source]
Get security violation rate per minute.
- get_critical_violations(time_window: timedelta = datetime.timedelta(seconds=3600)) int[source]
Get count of critical violations in time window.
- clear_metrics()
Clear all metrics.
- create_metric(name: str, metric_type: MetricType, description: str, unit: str = '') MetricSeries
Create a new metric series.
- Parameters:
name (str) – Metric name
metric_type (MetricType) – Type of metric
description (str) – Description of what this metric measures
unit (str) – Unit of measurement
- Returns:
MetricSeries instance
- Return type:
- get_all_metrics() Dict[str, MetricSeries]
Get all metric series.
- Return type:
- get_metric(name: str) MetricSeries | None
Get a metric series by name.
- Parameters:
name (str)
- Return type:
MetricSeries | None
- increment(name: str, value: int | float = 1, labels: Dict[str, str] | None = None)
Increment a counter metric.
- record_histogram(name: str, value: int | float, labels: Dict[str, str] | None = None)
Record a histogram value.
- class kailash.monitoring.metrics.PerformanceMetrics[source]
Bases:
MetricsCollectorMetrics collector for performance monitoring.
- record_operation(operation: str, duration_ms: float, success: bool)[source]
Record an operation performance.
- update_system_metrics(memory_mb: float, cpu_percent: float, rps: float)[source]
Update system-level metrics.
- get_p95_response_time(time_window: timedelta = datetime.timedelta(seconds=3600)) float | None[source]
Get 95th percentile response time.
- clear_metrics()
Clear all metrics.
- create_metric(name: str, metric_type: MetricType, description: str, unit: str = '') MetricSeries
Create a new metric series.
- Parameters:
name (str) – Metric name
metric_type (MetricType) – Type of metric
description (str) – Description of what this metric measures
unit (str) – Unit of measurement
- Returns:
MetricSeries instance
- Return type:
- get_all_metrics() Dict[str, MetricSeries]
Get all metric series.
- Return type:
- get_metric(name: str) MetricSeries | None
Get a metric series by name.
- Parameters:
name (str)
- Return type:
MetricSeries | None
- increment(name: str, value: int | float = 1, labels: Dict[str, str] | None = None)
Increment a counter metric.
- record_histogram(name: str, value: int | float, labels: Dict[str, str] | None = None)
Record a histogram value.
- class kailash.monitoring.metrics.MetricsRegistry[source]
Bases:
objectGlobal registry for metrics collectors.
- register_collector(name: str, collector: MetricsCollector)[source]
Register a metrics collector.
- Parameters:
name (str) – Collector name
collector (MetricsCollector) – MetricsCollector instance
- get_collector(name: str) MetricsCollector | None[source]
Get a metrics collector by name.
- Parameters:
name (str) – Collector name
- Returns:
MetricsCollector instance or None
- Return type:
MetricsCollector | None
- get_all_collectors() Dict[str, MetricsCollector][source]
Get all registered collectors.
- Return type:
- kailash.monitoring.metrics.get_metrics_registry() MetricsRegistry[source]
Get the global metrics registry.
- Return type:
- kailash.monitoring.metrics.render_prometheus_exposition(extra_lines: list[str] | None = None) str[source]
Render the unified Prometheus exposition for a
/metricsscrape (#1708).Concatenates, in one OpenMetrics text body:
the custom
MetricsRegistry(validation / security / performance),the
prometheus_clientdefault registry — which includes bothprometheus_client-native instruments (asyncsql, ML) AND the OTel meters bridged in bykailash.observability.configure_observability()’s Prometheus reader, andoptional
extra_lines(e.g. connection-pool metrics).
Before #1708 the server
/metricsexported only (1), so most collected metrics were invisible to Prometheus. Degrades gracefully whenprometheus_clientis not installed (part 2 is skipped).
- kailash.monitoring.metrics.get_validation_metrics() ValidationMetrics[source]
Get the validation metrics collector.
- Return type:
- kailash.monitoring.metrics.get_security_metrics() SecurityMetrics[source]
Get the security metrics collector.
- Return type:
- kailash.monitoring.metrics.get_performance_metrics() PerformanceMetrics[source]
Get the performance metrics collector.
- Return type:
Alert Management
Alerting system for monitoring validation failures and security violations.
Provides configurable alerting rules, notification channels, and alert management for critical events in the Kailash SDK validation system.
- class kailash.monitoring.alerts.AlertSeverity(value)[source]
Bases:
EnumAlert severity levels.
- INFO = 'info'
- WARNING = 'warning'
- ERROR = 'error'
- CRITICAL = 'critical'
- classmethod __contains__(member)
Return True if member is a member of this enum raises TypeError if member is not an enum member
note: in 3.12 TypeError will no longer be raised, and True will also be returned if member is the value of a member in this enum
- classmethod __getitem__(name)
Return the member matching name.
- classmethod __iter__()
Return members in definition order.
- classmethod __len__()
Return the number of members (no aliases)
- class kailash.monitoring.alerts.AlertStatus(value)[source]
Bases:
EnumAlert status.
- PENDING = 'pending'
- FIRING = 'firing'
- RESOLVED = 'resolved'
- SILENCED = 'silenced'
- classmethod __contains__(member)
Return True if member is a member of this enum raises TypeError if member is not an enum member
note: in 3.12 TypeError will no longer be raised, and True will also be returned if member is the value of a member in this enum
- classmethod __getitem__(name)
Return the member matching name.
- classmethod __iter__()
Return members in definition order.
- classmethod __len__()
Return the number of members (no aliases)
- class kailash.monitoring.alerts.Alert(id: str, rule_name: str, severity: AlertSeverity, title: str, description: str, labels: Dict[str, str]=<factory>, annotations: Dict[str, str]=<factory>, status: AlertStatus = AlertStatus.PENDING, created_at: datetime = <factory>, fired_at: datetime | None = None, resolved_at: datetime | None = None, last_notification: datetime | None = None, notification_count: int = 0)[source]
Bases:
objectAlert instance.
- Parameters:
- severity: AlertSeverity
- status: AlertStatus = 'pending'
- should_notify(notification_interval: timedelta) bool[source]
Check if alert should send notification.
- __init__(id: str, rule_name: str, severity: AlertSeverity, title: str, description: str, labels: Dict[str, str]=<factory>, annotations: Dict[str, str]=<factory>, status: AlertStatus = AlertStatus.PENDING, created_at: datetime = <factory>, fired_at: datetime | None = None, resolved_at: datetime | None = None, last_notification: datetime | None = None, notification_count: int = 0) None
- Parameters:
- Return type:
None
- class kailash.monitoring.alerts.AlertRule(name: str, description: str, severity: AlertSeverity, metric_name: str, condition: str, threshold: int | float, time_window: timedelta = datetime.timedelta(seconds=300), evaluation_interval: timedelta = datetime.timedelta(seconds=60), notification_interval: timedelta = datetime.timedelta(seconds=900), labels: Dict[str, str]=<factory>, annotations: Dict[str, str]=<factory>, enabled: bool = True)[source]
Bases:
objectAlert rule configuration.
- Parameters:
- severity: AlertSeverity
- evaluate(metric_series: MetricSeries) bool[source]
Evaluate if alert condition is met.
- Parameters:
metric_series (MetricSeries) – Metric series to evaluate
- Returns:
True if alert condition is met
- Return type:
- __init__(name: str, description: str, severity: AlertSeverity, metric_name: str, condition: str, threshold: int | float, time_window: timedelta = datetime.timedelta(seconds=300), evaluation_interval: timedelta = datetime.timedelta(seconds=60), notification_interval: timedelta = datetime.timedelta(seconds=900), labels: Dict[str, str]=<factory>, annotations: Dict[str, str]=<factory>, enabled: bool = True) None
- class kailash.monitoring.alerts.NotificationChannel[source]
Bases:
ABCBase class for notification channels.
- class kailash.monitoring.alerts.LogNotificationChannel(log_level: str = 'ERROR')[source]
Bases:
NotificationChannelLog-based notification channel.
- Parameters:
log_level (str)
- class kailash.monitoring.alerts.EmailNotificationChannel(smtp_host: str, smtp_port: int, username: str, password: str, from_email: str, to_emails: List[str], use_tls: bool = True)[source]
Bases:
NotificationChannelEmail notification channel.
- Parameters:
- class kailash.monitoring.alerts.SlackNotificationChannel(webhook_url: str, channel: str = '#alerts')[source]
Bases:
NotificationChannelSlack notification channel.
- class kailash.monitoring.alerts.WebhookNotificationChannel(webhook_url: str, headers: Dict[str, str] | None = None)[source]
Bases:
NotificationChannelGeneric webhook notification channel.
- class kailash.monitoring.alerts.AlertManager(metrics_registry: MetricsRegistry)[source]
Bases:
objectAlert manager for handling alerting rules and notifications.
- Parameters:
metrics_registry (MetricsRegistry)
- __init__(metrics_registry: MetricsRegistry)[source]
Initialize alert manager.
- Parameters:
metrics_registry (MetricsRegistry) – Metrics registry to monitor
- notification_channels: List[NotificationChannel]
- add_rule(rule: AlertRule)[source]
Add an alerting rule.
- Parameters:
rule (AlertRule) – AlertRule to add
- remove_rule(rule_name: str)[source]
Remove an alerting rule.
- Parameters:
rule_name (str) – Name of rule to remove
- add_notification_channel(channel: NotificationChannel)[source]
Add a notification channel.
- Parameters:
channel (NotificationChannel) – NotificationChannel to add
Usage Examples
Basic Monitoring Setup
from kailash.monitoring.metrics import get_validation_metrics, get_security_metrics
from kailash.monitoring.alerts import AlertManager, AlertRule, AlertSeverity
from kailash.monitoring.alerts import LogNotificationChannel
# Set up comprehensive monitoring
validation_metrics = get_validation_metrics()
security_metrics = get_security_metrics()
registry = get_metrics_registry()
alert_manager = AlertManager(registry)
# Configure alert rules
alert_manager.add_rule(AlertRule(
name="high_validation_failures",
description="Validation failure rate above 10%",
severity=AlertSeverity.ERROR,
metric_name="validation_failure",
condition="> 5",
threshold=5
))
alert_manager.add_notification_channel(LogNotificationChannel())
alert_manager.start()
Custom Metrics Collection
from kailash.monitoring.metrics import MetricsCollector, MetricType
# Create custom metrics collector
collector = MetricsCollector()
# Create and record metrics
response_time = collector.create_metric(
"api_response_time",
MetricType.TIMER,
"API response time",
"milliseconds"
)
collector.record_timer("api_response_time", 150.5)
collector.increment("api_requests")
collector.set_gauge("active_connections", 42)
Security Monitoring
from kailash.monitoring.metrics import get_security_metrics, MetricSeverity
security_metrics = get_security_metrics()
# Record security violations
security_metrics.record_security_violation(
violation_type="sql_injection_attempt",
severity=MetricSeverity.HIGH,
source="workflow_connection",
details={"query": "malicious_query"}
)
# Check critical violations
critical_count = security_metrics.get_critical_violations()
violation_rate = security_metrics.get_violation_rate()
Performance Monitoring
from kailash.monitoring.metrics import get_performance_metrics
performance_metrics = get_performance_metrics()
# Record operation performance
performance_metrics.record_operation(
operation="workflow_execution",
duration_ms=1250.0,
success=True
)
# Update system metrics
performance_metrics.update_system_metrics(
memory_mb=512.0,
cpu_percent=25.5,
rps=100.0
)
# Get performance statistics
p95_time = performance_metrics.get_p95_response_time()
Connection Validation Monitoring
from kailash.runtime.local import LocalRuntime
from kailash.monitoring.metrics import get_validation_metrics
# Enable connection validation with monitoring
runtime = LocalRuntime(connection_validation="strict")
validation_metrics = get_validation_metrics()
# Execute workflow with monitoring
results, run_id = runtime.execute(workflow.build())
# View validation metrics
success_rate = validation_metrics.get_success_rate()
cache_hit_rate = validation_metrics.get_cache_hit_rate()
print(f"Validation success rate: {success_rate:.2%}")
print(f"Cache hit rate: {cache_hit_rate:.2%}")
Metrics Export
from kailash.monitoring.metrics import get_metrics_registry
registry = get_metrics_registry()
# Export metrics in JSON format
json_metrics = registry.export_metrics("json")
# Export metrics in Prometheus format
prometheus_metrics = registry.export_metrics("prometheus")
print(json_metrics)