failure_analysis.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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.print_log import PrintLogEntry
  6. from backend.app.models.printer import Printer
  7. class FailureAnalysisService:
  8. """Service for analyzing print failure patterns.
  9. Reads from print_log_entries (per-event data) rather than print_archives
  10. so reprints contribute each run and orphan events (archive deleted, log
  11. row survived via ON DELETE SET NULL) still count consistently with
  12. Quick Stats. The archive-based predecessor diverged from Quick Stats
  13. after #1378 moved the rest of the page to per-event aggregation.
  14. """
  15. def __init__(self, db: AsyncSession):
  16. self.db = db
  17. async def analyze_failures(
  18. self,
  19. days: int | None = None,
  20. date_from: date | None = None,
  21. date_to: date | None = None,
  22. printer_id: int | None = None,
  23. project_id: int | None = None,
  24. created_by_id: int | None = None,
  25. ) -> dict:
  26. """Analyze failure patterns across logged print events."""
  27. # Build base query — separate date vs non-date filters for trend reuse
  28. base_filter = []
  29. non_date_filter = []
  30. if date_from or date_to:
  31. if date_from:
  32. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  33. base_filter.append(PrintLogEntry.created_at >= dt_from)
  34. if date_to:
  35. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  36. base_filter.append(PrintLogEntry.created_at <= dt_to)
  37. range_start = dt_from if date_from else datetime.now(timezone.utc) - timedelta(days=365)
  38. range_end = dt_to if date_to else datetime.now(timezone.utc)
  39. effective_days = max((range_end - range_start).days, 1)
  40. else:
  41. effective_days = days if days is not None else 30
  42. cutoff_date = datetime.now(timezone.utc) - timedelta(days=effective_days)
  43. base_filter.append(PrintLogEntry.created_at >= cutoff_date)
  44. if printer_id:
  45. non_date_filter.append(PrintLogEntry.printer_id == printer_id)
  46. # project_id is an archive-level concept; PrintLogEntry has no project
  47. # link, so we resolve it by archive_id where present.
  48. if project_id:
  49. from backend.app.models.archive import PrintArchive
  50. # Soft-deleted archives (#1343) keep their project_id, so without
  51. # this the failure rate for a project still counts prints the user
  52. # deleted from it — and disagrees with the project's own numbers,
  53. # which now exclude them (#2731).
  54. project_archive_ids = await self.db.execute(
  55. select(PrintArchive.id).where(
  56. PrintArchive.project_id == project_id,
  57. PrintArchive.deleted_at.is_(None),
  58. )
  59. )
  60. archive_ids = [row[0] for row in project_archive_ids.fetchall()]
  61. if archive_ids:
  62. non_date_filter.append(PrintLogEntry.archive_id.in_(archive_ids))
  63. else:
  64. # No archives in this project → nothing to count
  65. non_date_filter.append(PrintLogEntry.id.is_(None))
  66. if created_by_id is not None:
  67. if created_by_id == -1:
  68. non_date_filter.append(PrintLogEntry.created_by_id.is_(None))
  69. else:
  70. non_date_filter.append(PrintLogEntry.created_by_id == created_by_id)
  71. base_filter.extend(non_date_filter)
  72. # Total counts
  73. total_result = await self.db.execute(select(func.count(PrintLogEntry.id)).where(and_(*base_filter)))
  74. total_prints = total_result.scalar() or 0
  75. successful_result = await self.db.execute(
  76. select(func.count(PrintLogEntry.id)).where(and_(*base_filter, PrintLogEntry.status == "completed"))
  77. )
  78. successful_prints = successful_result.scalar() or 0
  79. failed_result = await self.db.execute(
  80. select(func.count(PrintLogEntry.id)).where(
  81. and_(*base_filter, PrintLogEntry.status.in_(["failed", "aborted"]))
  82. )
  83. )
  84. failed_prints = failed_result.scalar() or 0
  85. # Failure rate divides by quality-outcome prints only — a cancelled or
  86. # skipped print is neither a success nor a failure of the printer, so
  87. # including it in the denominator silently lowered the displayed rate
  88. # whenever the user stopped jobs (#1390). Total Prints (the absolute
  89. # count incl. cancelled) is still returned separately for the "X / Y
  90. # prints failed" caption.
  91. outcome_prints = successful_prints + failed_prints
  92. failure_rate = (failed_prints / outcome_prints * 100) if outcome_prints > 0 else 0
  93. # Quality dimension (#1898): a completed print the user marked as
  94. # reject is machine-success but scrap. Kept OUT of failure_rate — that
  95. # number stays the machine's — and reported separately, with a yield
  96. # rate that treats rejects as non-good output.
  97. rejected_result = await self.db.execute(
  98. select(func.count(PrintLogEntry.id)).where(
  99. and_(*base_filter, PrintLogEntry.status == "completed", PrintLogEntry.user_verdict == "reject")
  100. )
  101. )
  102. rejected_prints = rejected_result.scalar() or 0
  103. yield_rate = ((successful_prints - rejected_prints) / outcome_prints * 100) if outcome_prints > 0 else 0
  104. rejects_reason_result = await self.db.execute(
  105. select(
  106. PrintLogEntry.failure_reason,
  107. func.count(PrintLogEntry.id).label("count"),
  108. )
  109. .where(and_(*base_filter, PrintLogEntry.status == "completed", PrintLogEntry.user_verdict == "reject"))
  110. .group_by(PrintLogEntry.failure_reason)
  111. .order_by(func.count(PrintLogEntry.id).desc())
  112. )
  113. rejects_by_reason = {(row[0] or "Unknown"): row[1] for row in rejects_reason_result.fetchall()}
  114. # Failures by reason
  115. reason_result = await self.db.execute(
  116. select(
  117. PrintLogEntry.failure_reason,
  118. func.count(PrintLogEntry.id).label("count"),
  119. )
  120. .where(and_(*base_filter, PrintLogEntry.status.in_(["failed", "aborted"])))
  121. .group_by(PrintLogEntry.failure_reason)
  122. .order_by(func.count(PrintLogEntry.id).desc())
  123. )
  124. failures_by_reason = {(row[0] or "Unknown"): row[1] for row in reason_result.fetchall()}
  125. # Failures by filament type
  126. filament_result = await self.db.execute(
  127. select(
  128. PrintLogEntry.filament_type,
  129. func.count(PrintLogEntry.id).label("count"),
  130. )
  131. .where(and_(*base_filter, PrintLogEntry.status.in_(["failed", "aborted"])))
  132. .group_by(PrintLogEntry.filament_type)
  133. .order_by(func.count(PrintLogEntry.id).desc())
  134. )
  135. failures_by_filament = {(row[0] or "Unknown"): row[1] for row in filament_result.fetchall()}
  136. # Failures by printer
  137. printer_result = await self.db.execute(
  138. select(
  139. PrintLogEntry.printer_id,
  140. func.count(PrintLogEntry.id).label("count"),
  141. )
  142. .where(
  143. and_(
  144. *base_filter,
  145. PrintLogEntry.status.in_(["failed", "aborted"]),
  146. PrintLogEntry.printer_id.isnot(None),
  147. )
  148. )
  149. .group_by(PrintLogEntry.printer_id)
  150. .order_by(func.count(PrintLogEntry.id).desc())
  151. )
  152. failures_by_printer_id = {row[0]: row[1] for row in printer_result.fetchall()}
  153. # Get printer names
  154. if failures_by_printer_id:
  155. printers_result = await self.db.execute(
  156. select(Printer.id, Printer.name).where(Printer.id.in_(failures_by_printer_id.keys()))
  157. )
  158. printer_names = {row[0]: row[1] for row in printers_result.fetchall()}
  159. # A printer deleted with its history kept has no row left to read a
  160. # name from, and "Printer 3" tells nobody which machine kept failing
  161. # (#2873). Each run recorded the name it printed on, so fall back to
  162. # the last one that id was known by.
  163. missing = [pid for pid in failures_by_printer_id if pid not in printer_names]
  164. if missing:
  165. last_named_run = (
  166. select(func.max(PrintLogEntry.id).label("entry_id"))
  167. .where(PrintLogEntry.printer_id.in_(missing), PrintLogEntry.printer_name.isnot(None))
  168. .group_by(PrintLogEntry.printer_id)
  169. .subquery()
  170. )
  171. historic_result = await self.db.execute(
  172. select(PrintLogEntry.printer_id, PrintLogEntry.printer_name).join(
  173. last_named_run, PrintLogEntry.id == last_named_run.c.entry_id
  174. )
  175. )
  176. for pid, name in historic_result.fetchall():
  177. printer_names[pid] = name
  178. failures_by_printer = {
  179. printer_names.get(pid, f"Printer {pid}"): count for pid, count in failures_by_printer_id.items()
  180. }
  181. else:
  182. failures_by_printer = {}
  183. # Failures by hour of day
  184. failed_events_result = await self.db.execute(
  185. select(PrintLogEntry.started_at).where(
  186. and_(
  187. *base_filter,
  188. PrintLogEntry.status.in_(["failed", "aborted"]),
  189. PrintLogEntry.started_at.isnot(None),
  190. )
  191. )
  192. )
  193. failures_by_hour = defaultdict(int)
  194. for (started_at,) in failed_events_result.fetchall():
  195. if started_at:
  196. hour = started_at.hour
  197. failures_by_hour[hour] += 1
  198. failures_by_hour_complete = {h: failures_by_hour.get(h, 0) for h in range(24)}
  199. # Recent failures
  200. recent_result = await self.db.execute(
  201. select(PrintLogEntry)
  202. .where(and_(*base_filter, PrintLogEntry.status.in_(["failed", "aborted"])))
  203. .order_by(PrintLogEntry.created_at.desc())
  204. .limit(10)
  205. )
  206. recent_failures = [
  207. {
  208. "id": e.archive_id,
  209. "print_name": e.print_name,
  210. "failure_reason": e.failure_reason,
  211. "filament_type": e.filament_type,
  212. "printer_id": e.printer_id,
  213. "created_at": e.created_at.isoformat() if e.created_at else None,
  214. }
  215. for e in recent_result.scalars().all()
  216. ]
  217. # Failure rate trend (by week)
  218. trend_data = []
  219. num_weeks = max(effective_days // 7, 1)
  220. for i in range(num_weeks):
  221. week_end = datetime.now(timezone.utc) - timedelta(weeks=i)
  222. week_start = week_end - timedelta(weeks=1)
  223. week_filter = [
  224. PrintLogEntry.created_at >= week_start,
  225. PrintLogEntry.created_at < week_end,
  226. *non_date_filter,
  227. ]
  228. week_total = await self.db.execute(select(func.count(PrintLogEntry.id)).where(and_(*week_filter)))
  229. week_successful = await self.db.execute(
  230. select(func.count(PrintLogEntry.id)).where(and_(*week_filter, PrintLogEntry.status == "completed"))
  231. )
  232. week_failed = await self.db.execute(
  233. select(func.count(PrintLogEntry.id)).where(
  234. and_(*week_filter, PrintLogEntry.status.in_(["failed", "aborted"]))
  235. )
  236. )
  237. total = week_total.scalar() or 0
  238. successful = week_successful.scalar() or 0
  239. failed = week_failed.scalar() or 0
  240. week_outcome = successful + failed
  241. rate = (failed / week_outcome * 100) if week_outcome > 0 else 0
  242. trend_data.append(
  243. {
  244. "week_start": week_start.date().isoformat(),
  245. "total_prints": total,
  246. "failed_prints": failed,
  247. "failure_rate": round(rate, 1),
  248. }
  249. )
  250. trend_data.reverse() # Oldest first
  251. return {
  252. "period_days": effective_days,
  253. "total_prints": total_prints,
  254. "failed_prints": failed_prints,
  255. "failure_rate": round(failure_rate, 1),
  256. "rejected_prints": rejected_prints,
  257. "yield_rate": round(yield_rate, 1),
  258. "rejects_by_reason": rejects_by_reason,
  259. "failures_by_reason": failures_by_reason,
  260. "failures_by_filament": failures_by_filament,
  261. "failures_by_printer": failures_by_printer,
  262. "failures_by_hour": failures_by_hour_complete,
  263. "recent_failures": recent_failures,
  264. "trend": trend_data,
  265. }