failure_analysis.py 13 KB

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