1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432"""Service for tracking and managing cleanup metrics.
This service stores metrics about timeout worker operations
(timeouts processed, files cleaned, orphans detected, etc.)
in Redis hashes organized by date.
Additionally provides Prometheus metrics for real-time monitoring
of jobs, queues, and workers.
"""
import logging
from datetime import UTC, datetime, timedelta
from typing import Any
from prometheus_client import Counter, Gauge, Histogram
from ..config import settings
logger = logging.getLogger(__name__)
# Prometheus Metrics for Jobs
jobs_submitted_total = Counter(
"jobs_submitted_total",
"Total jobs submitted",
["source"], # webhook, api, etc.
)
jobs_completed_total = Counter(
"jobs_completed_total",
"Total jobs completed",
["status"], # success, failed, denied
)
job_duration_seconds = Histogram(
"job_duration_seconds",
"Job processing duration",
["stage"], # pii_scan, processing, total
buckets=[10, 30, 60, 120, 300, 600, 1200], # 10s to 20min
)
# Prometheus Metrics for Queues
queue_depth_gauge = Gauge(
"queue_depth",
"Current queue depth",
["queue_name"], # pii_scan, processing, approval_pending
)
# Prometheus Metrics for Workers
worker_active_gauge = Gauge(
"worker_active",
"Worker active status (1=active, 0=stopped)",
["worker_name"], # pii, processing, timeout
)
worker_errors_total = Counter(
"worker_errors_total",
"Worker error count",
["worker_name", "error_type"],
)
worker_jobs_processed_total = Counter(
"worker_jobs_processed_total",
"Total jobs processed by worker",
["worker_name", "result"], # success, error
)
# Prometheus Metrics for System Health
redis_up = Gauge("redis_up", "Redis connectivity (1=up, 0=down)")
s3_up = Gauge("s3_up", "S3 connectivity (1=up, 0=down)")
# Prometheus Metrics for S3 Operations
s3_operations_total = Counter(
"s3_operations_total",
"Total S3 operations",
["operation", "bucket", "result"] # result: success, error, circuit_open
)
s3_operation_duration_seconds = Histogram(
"s3_operation_duration_seconds",
"S3 operation duration in seconds",
["operation", "bucket"],
buckets=[0.1, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0] # 100ms to 60s
)
s3_circuit_breaker_state = Gauge(
"s3_circuit_breaker_state",
"Circuit breaker state (0=closed, 1=half_open, 2=open)",
["circuit_name"]
)
s3_retry_attempts_total = Counter(
"s3_retry_attempts_total",
"Total S3 retry attempts",
["operation", "attempt"]
)
# Prometheus Metrics for LLM Operations
llm_tokens_total = Counter(
"llm_tokens_total",
"Total tokens consumed by LLM calls",
["agent", "direction"], # agent: planner/worker/paragraph, direction: input/output
)
llm_request_duration_seconds = Histogram(
"llm_request_duration_seconds",
"LLM API request duration in seconds",
["agent"],
buckets=[0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0], # 500ms to 5min
)
llm_cost_cents_total = Counter(
"llm_cost_cents_total",
"Total estimated LLM cost in cents",
["agent"],
)
llm_requests_total = Counter(
"llm_requests_total",
"Total LLM API requests",
["agent", "status"], # status: success/error
)
# Prometheus Metrics for Multi-Round Processing
round_processing_total = Counter(
"round_processing_total",
"Total rounds processed",
["round_number", "convergence_reason"], # round: "1","2","3"..., reason: max_rounds/quality_met/etc
)
round_duration_seconds = Histogram(
"round_duration_seconds",
"Round processing duration in seconds",
["round_number"],
buckets=[5, 15, 30, 60, 120, 300, 600], # 5s to 10min
)
critic_issues_total = Counter(
"critic_issues_total",
"Issues found by CriticAgent",
["severity", "category"], # severity: critical/major/minor/cosmetic
)
document_quality_score = Gauge(
"document_quality_score",
"Current document quality score (0-1)",
["document_id", "round_number"],
)
convergence_events_total = Counter(
"convergence_events_total",
"Total convergence events by reason",
["reason"], # max_rounds_reached, quality_threshold_met, no_improvement, etc.
)
def record_llm_call(
agent: str,
input_tokens: int,
output_tokens: int,
cost_cents: float,
duration_ms: int,
success: bool = True,
) -> None:
"""Record Prometheus metrics for an LLM API call.
Args:
agent: Agent name (planner, worker, paragraph, recovery, verification)
input_tokens: Number of input tokens
output_tokens: Number of output tokens
cost_cents: Estimated cost in cents
duration_ms: Call duration in milliseconds
success: Whether the call succeeded
"""
llm_tokens_total.labels(agent=agent, direction="input").inc(input_tokens)
llm_tokens_total.labels(agent=agent, direction="output").inc(output_tokens)
llm_cost_cents_total.labels(agent=agent).inc(cost_cents)
llm_request_duration_seconds.labels(agent=agent).observe(duration_ms / 1000)
llm_requests_total.labels(
agent=agent, status="success" if success else "error"
).inc()
def record_round_metrics(
round_number: int,
duration_ms: int,
quality_score: float,
document_id: str,
convergence_reason: str | None = None,
issues_by_severity: dict[str, int] | None = None,
issues_by_category: dict[str, int] | None = None,
) -> None:
"""Record Prometheus metrics for a processing round.
Args:
round_number: Round number (1-indexed)
duration_ms: Round duration in milliseconds
quality_score: Quality score after this round (0-1)
document_id: Document identifier
convergence_reason: If this is the final round, the convergence reason
issues_by_severity: Count of issues by severity (critic rounds only)
issues_by_category: Count of issues by category (critic rounds only)
"""
# Record round duration
round_duration_seconds.labels(round_number=str(round_number)).observe(duration_ms / 1000)
# Record quality score
document_quality_score.labels(
document_id=document_id,
round_number=str(round_number),
).set(quality_score)
# Record convergence if this is the final round
if convergence_reason:
round_processing_total.labels(
round_number=str(round_number),
convergence_reason=convergence_reason,
).inc()
convergence_events_total.labels(reason=convergence_reason).inc()
# Record critic issues if provided
if issues_by_severity:
for severity, count in issues_by_severity.items():
for _ in range(count):
# We increment the counter for each issue
# This allows us to track issues over time
pass # Issues are recorded per-issue, not per-round
if issues_by_category:
for category, count in issues_by_category.items():
for _ in range(count):
pass # Issues are recorded per-issue, not per-round
def record_critic_issue(severity: str, category: str) -> None:
"""Record a single critic issue to Prometheus.
Args:
severity: Issue severity (critical, major, minor, cosmetic)
category: Issue category (structure, accessibility, content, formatting)
"""
critic_issues_total.labels(severity=severity, category=category).inc()
class MetricsService:
"""Service for metrics tracking and cleanup."""
# Redis key prefix for daily metrics
METRICS_PREFIX = "eq-pdf:metrics:daily:"
def __init__(self, redis_client: Any) -> None:
"""Initialize metrics service.
Args:
redis_client: Redis async client instance
"""
self.redis = redis_client
def _get_metrics_key(self, date: datetime | None = None) -> str:
"""Get Redis key for metrics on a specific date.
Args:
date: Date for metrics (defaults to today)
Returns:
Redis key for daily metrics
"""
if date is None:
date = datetime.now(UTC)
date_str = date.strftime("%Y%m%d")
return f"{self.METRICS_PREFIX}{date_str}"
async def increment_metric(self, metric_name: str, value: int = 1) -> None:
"""Increment a metric counter for today.
Args:
metric_name: Name of metric to increment
value: Value to increment by (default: 1)
"""
try:
key = self._get_metrics_key()
# Increment the metric field in today's hash
await self.redis.hincrby(key, metric_name, value)
# Set expiration on the key (auto-cleanup after retention period + buffer)
ttl_days = settings.metrics_retention_days + 7 # 7 day buffer
await self.redis.expire(key, ttl_days * 24 * 60 * 60)
logger.debug(f"Incremented metric {metric_name} by {value}")
except Exception as e:
logger.error(
f"Failed to increment metric {metric_name}: {e}",
exc_info=True
)
# Don't raise - metrics failures shouldn't break operations
async def get_metric(
self,
metric_name: str,
date: datetime | None = None
) -> int:
"""Get value of a metric for a specific date.
Args:
metric_name: Name of metric to retrieve
date: Date for metrics (defaults to today)
Returns:
Metric value (0 if not found)
"""
try:
key = self._get_metrics_key(date)
value = await self.redis.hget(key, metric_name)
if value is None:
return 0
return int(value)
except Exception as e:
logger.error(
f"Failed to get metric {metric_name}: {e}",
exc_info=True
)
return 0
async def get_all_metrics(
self,
date: datetime | None = None
) -> dict[str, int]:
"""Get all metrics for a specific date.
Args:
date: Date for metrics (defaults to today)
Returns:
Dictionary of metric names to values
"""
try:
key = self._get_metrics_key(date)
metrics = await self.redis.hgetall(key)
if not metrics:
return {}
# Convert values to integers
return {k: int(v) for k, v in metrics.items()}
except Exception as e:
logger.error(f"Failed to get all metrics: {e}", exc_info=True)
return {}
async def cleanup_old_metrics(self) -> int:
"""Delete metrics older than retention period.
Returns:
Number of metric keys deleted
"""
try:
# Calculate cutoff date
cutoff_date = datetime.now(UTC) - timedelta(
days=settings.metrics_retention_days
)
logger.info(
f"Starting metrics cleanup (retention: {settings.metrics_retention_days} days, "
f"cutoff: {cutoff_date.strftime('%Y-%m-%d')})"
)
# Scan for all metric keys
pattern = f"{self.METRICS_PREFIX}*"
deleted_count = 0
cursor = 0
while True:
cursor, keys = await self.redis.scan(
cursor=cursor,
match=pattern,
count=100
)
for key in keys:
try:
# Extract date from key (format: eq-pdf:metrics:daily:YYYYMMDD)
date_str = key.split(":")[-1]
key_date = datetime.strptime(date_str, "%Y%m%d").replace(
tzinfo=UTC
)
# Delete if older than cutoff
if key_date < cutoff_date:
await self.redis.delete(key)
deleted_count += 1
logger.debug(f"Deleted old metrics key: {key}")
except (ValueError, IndexError) as e:
logger.warning(f"Invalid metrics key format: {key}, error: {e}")
if cursor == 0:
break
logger.info(f"Metrics cleanup complete: {deleted_count} keys deleted")
return deleted_count
except Exception as e:
logger.error(f"Error during metrics cleanup: {e}", exc_info=True)
return 0
async def log_daily_summary(self) -> None:
"""Log summary of today's metrics (for debugging/monitoring).
This method is useful for daily health checks and debugging.
"""
try:
metrics = await self.get_all_metrics()
if not metrics:
logger.info("Daily metrics summary: No metrics recorded today")
return
# Format metrics for logging
summary_lines = ["Daily metrics summary:"]
for metric_name, value in sorted(metrics.items()):
summary_lines.append(f" {metric_name}: {value}")
logger.info("\n".join(summary_lines))
except Exception as e:
logger.error(f"Failed to log daily summary: {e}", exc_info=True)