failure_analysis.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. from collections import defaultdict
  2. from datetime import date, datetime, time, timedelta, timezone
  3. from sqlalchemy import and_, func, select
  4. from sqlalchemy.ext.asyncio import AsyncSession
  5. from backend.app.models.archive import PrintArchive
  6. from backend.app.models.printer import Printer
  7. class FailureAnalysisService:
  8. """Service for analyzing print failure patterns."""
  9. def __init__(self, db: AsyncSession):
  10. self.db = db
  11. async def analyze_failures(
  12. self,
  13. days: int | None = None,
  14. date_from: date | None = None,
  15. date_to: date | None = None,
  16. printer_id: int | None = None,
  17. project_id: int | None = None,
  18. ) -> dict:
  19. """Analyze failure patterns across archives.
  20. Args:
  21. days: Number of days to analyze (fallback when no date range)
  22. date_from: Start date filter (inclusive)
  23. date_to: End date filter (inclusive)
  24. printer_id: Optional filter by printer
  25. project_id: Optional filter by project
  26. Returns:
  27. Dictionary with failure analysis results
  28. """
  29. # Build base query
  30. base_filter = []
  31. if date_from or date_to:
  32. if date_from:
  33. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  34. base_filter.append(PrintArchive.created_at >= dt_from)
  35. if date_to:
  36. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  37. base_filter.append(PrintArchive.created_at <= dt_to)
  38. else:
  39. effective_days = days if days is not None else 30
  40. cutoff_date = datetime.now(timezone.utc) - timedelta(days=effective_days)
  41. base_filter.append(PrintArchive.created_at >= cutoff_date)
  42. if printer_id:
  43. base_filter.append(PrintArchive.printer_id == printer_id)
  44. if project_id:
  45. base_filter.append(PrintArchive.project_id == project_id)
  46. # Total counts
  47. total_result = await self.db.execute(select(func.count(PrintArchive.id)).where(and_(*base_filter)))
  48. total_prints = total_result.scalar() or 0
  49. failed_result = await self.db.execute(
  50. select(func.count(PrintArchive.id)).where(
  51. and_(*base_filter, PrintArchive.status.in_(["failed", "aborted"]))
  52. )
  53. )
  54. failed_prints = failed_result.scalar() or 0
  55. failure_rate = (failed_prints / total_prints * 100) if total_prints > 0 else 0
  56. # Failures by reason
  57. reason_result = await self.db.execute(
  58. select(
  59. PrintArchive.failure_reason,
  60. func.count(PrintArchive.id).label("count"),
  61. )
  62. .where(and_(*base_filter, PrintArchive.status.in_(["failed", "aborted"])))
  63. .group_by(PrintArchive.failure_reason)
  64. .order_by(func.count(PrintArchive.id).desc())
  65. )
  66. failures_by_reason = {(row[0] or "Unknown"): row[1] for row in reason_result.fetchall()}
  67. # Failures by filament type
  68. filament_result = await self.db.execute(
  69. select(
  70. PrintArchive.filament_type,
  71. func.count(PrintArchive.id).label("count"),
  72. )
  73. .where(and_(*base_filter, PrintArchive.status.in_(["failed", "aborted"])))
  74. .group_by(PrintArchive.filament_type)
  75. .order_by(func.count(PrintArchive.id).desc())
  76. )
  77. failures_by_filament = {(row[0] or "Unknown"): row[1] for row in filament_result.fetchall()}
  78. # Failures by printer
  79. printer_result = await self.db.execute(
  80. select(
  81. PrintArchive.printer_id,
  82. func.count(PrintArchive.id).label("count"),
  83. )
  84. .where(
  85. and_(*base_filter, PrintArchive.status.in_(["failed", "aborted"]), PrintArchive.printer_id.isnot(None))
  86. )
  87. .group_by(PrintArchive.printer_id)
  88. .order_by(func.count(PrintArchive.id).desc())
  89. )
  90. failures_by_printer_id = {row[0]: row[1] for row in printer_result.fetchall()}
  91. # Get printer names
  92. if failures_by_printer_id:
  93. printers_result = await self.db.execute(
  94. select(Printer.id, Printer.name).where(Printer.id.in_(failures_by_printer_id.keys()))
  95. )
  96. printer_names = {row[0]: row[1] for row in printers_result.fetchall()}
  97. failures_by_printer = {
  98. printer_names.get(pid, f"Printer {pid}"): count for pid, count in failures_by_printer_id.items()
  99. }
  100. else:
  101. failures_by_printer = {}
  102. # Failures by hour of day
  103. failed_archives_result = await self.db.execute(
  104. select(PrintArchive.started_at).where(
  105. and_(
  106. *base_filter,
  107. PrintArchive.status.in_(["failed", "aborted"]),
  108. PrintArchive.started_at.isnot(None),
  109. )
  110. )
  111. )
  112. failures_by_hour = defaultdict(int)
  113. for (started_at,) in failed_archives_result.fetchall():
  114. if started_at:
  115. hour = started_at.hour
  116. failures_by_hour[hour] += 1
  117. # Convert to dict with all 24 hours
  118. failures_by_hour_complete = {h: failures_by_hour.get(h, 0) for h in range(24)}
  119. # Recent failures
  120. recent_result = await self.db.execute(
  121. select(PrintArchive)
  122. .where(and_(*base_filter, PrintArchive.status.in_(["failed", "aborted"])))
  123. .order_by(PrintArchive.created_at.desc())
  124. .limit(10)
  125. )
  126. recent_failures = [
  127. {
  128. "id": a.id,
  129. "print_name": a.print_name or a.filename,
  130. "failure_reason": a.failure_reason,
  131. "filament_type": a.filament_type,
  132. "printer_id": a.printer_id,
  133. "created_at": a.created_at.isoformat() if a.created_at else None,
  134. }
  135. for a in recent_result.scalars().all()
  136. ]
  137. # Failure rate trend (by week)
  138. trend_data = []
  139. for i in range(min(days // 7, 12)): # Up to 12 weeks
  140. week_end = datetime.now(timezone.utc) - timedelta(weeks=i)
  141. week_start = week_end - timedelta(weeks=1)
  142. week_filter = base_filter.copy()
  143. week_filter[0] = and_(
  144. PrintArchive.created_at >= week_start,
  145. PrintArchive.created_at < week_end,
  146. )
  147. week_total = await self.db.execute(select(func.count(PrintArchive.id)).where(and_(*week_filter)))
  148. week_failed = await self.db.execute(
  149. select(func.count(PrintArchive.id)).where(
  150. and_(*week_filter, PrintArchive.status.in_(["failed", "aborted"]))
  151. )
  152. )
  153. total = week_total.scalar() or 0
  154. failed = week_failed.scalar() or 0
  155. rate = (failed / total * 100) if total > 0 else 0
  156. trend_data.append(
  157. {
  158. "week_start": week_start.date().isoformat(),
  159. "total_prints": total,
  160. "failed_prints": failed,
  161. "failure_rate": round(rate, 1),
  162. }
  163. )
  164. trend_data.reverse() # Oldest first
  165. return {
  166. "period_days": days,
  167. "total_prints": total_prints,
  168. "failed_prints": failed_prints,
  169. "failure_rate": round(failure_rate, 1),
  170. "failures_by_reason": failures_by_reason,
  171. "failures_by_filament": failures_by_filament,
  172. "failures_by_printer": failures_by_printer,
  173. "failures_by_hour": failures_by_hour_complete,
  174. "recent_failures": recent_failures,
  175. "trend": trend_data,
  176. }