health_check.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #!/usr/bin/env python3
  2. """
  3. health_check.py — One-stop verification that the ComfyUI environment is ready.
  4. Runs through the verification checklist:
  5. 1. comfy-cli on PATH
  6. 2. server reachable (/system_stats)
  7. 3. at least one checkpoint installed
  8. 4. (optional) a specific workflow's deps are met
  9. 5. (optional) actually submit a tiny test workflow and verify round-trip
  10. Usage:
  11. python3 health_check.py
  12. python3 health_check.py --host https://cloud.comfy.org
  13. python3 health_check.py --workflow my.json
  14. python3 health_check.py --smoke-test # actually submit a tiny workflow
  15. """
  16. from __future__ import annotations
  17. import argparse
  18. import json
  19. import shutil
  20. import sys
  21. from pathlib import Path
  22. sys.path.insert(0, str(Path(__file__).resolve().parent))
  23. from _common import (
  24. DEFAULT_LOCAL_HOST, ENV_API_KEY, emit_json, http_get, parse_model_list,
  25. resolve_api_key, resolve_url, unwrap_workflow,
  26. )
  27. def comfy_cli_status() -> dict:
  28. if shutil.which("comfy"):
  29. return {"available": True, "method": "comfy", "path": shutil.which("comfy")}
  30. if shutil.which("uvx"):
  31. return {"available": True, "method": "uvx",
  32. "hint": "Invoke as `uvx --from comfy-cli comfy ...`"}
  33. return {
  34. "available": False,
  35. "hint": "Install with: pipx install comfy-cli (or `pip install comfy-cli`)",
  36. }
  37. def server_status(host: str, headers: dict) -> dict:
  38. url = resolve_url(host, "/system_stats")
  39. try:
  40. r = http_get(url, headers=headers, retries=2, timeout=10)
  41. if r.status == 200:
  42. try:
  43. stats = r.json() or {}
  44. except Exception:
  45. stats = {}
  46. return {"reachable": True, "url": url, "stats": stats}
  47. return {"reachable": False, "url": url, "http_status": r.status, "body": r.text()[:200]}
  48. except Exception as e:
  49. return {"reachable": False, "url": url, "error": str(e)}
  50. def checkpoint_status(host: str, headers: dict) -> dict:
  51. url = resolve_url(host, "/models/checkpoints")
  52. try:
  53. r = http_get(url, headers=headers, retries=2, timeout=15)
  54. except Exception as e:
  55. return {"queryable": False, "error": str(e)}
  56. if r.status != 200:
  57. return {"queryable": False, "http_status": r.status, "url": url, "body": r.text()[:200]}
  58. try:
  59. models = parse_model_list(r.json())
  60. except Exception:
  61. models = set()
  62. return {"queryable": True, "count": len(models),
  63. "first_few": sorted(models)[:5]}
  64. SMOKE_WORKFLOW = {
  65. # Minimal SD1.5 workflow that doesn't depend on rare nodes.
  66. # 256x256 + 1 step is the smallest config that doesn't trigger SDXL/Flux
  67. # validation errors while still executing fast.
  68. "3": {
  69. "class_type": "KSampler",
  70. "inputs": {
  71. "seed": 1, "steps": 1, "cfg": 7.0,
  72. "sampler_name": "euler", "scheduler": "normal", "denoise": 1.0,
  73. "model": ["4", 0], "positive": ["6", 0], "negative": ["7", 0],
  74. "latent_image": ["5", 0],
  75. },
  76. },
  77. "4": {"class_type": "CheckpointLoaderSimple",
  78. "inputs": {"ckpt_name": "REPLACE_ME"}},
  79. "5": {"class_type": "EmptyLatentImage",
  80. "inputs": {"width": 256, "height": 256, "batch_size": 1}},
  81. "6": {"class_type": "CLIPTextEncode",
  82. "inputs": {"text": "test", "clip": ["4", 1]}},
  83. "7": {"class_type": "CLIPTextEncode",
  84. "inputs": {"text": "", "clip": ["4", 1]}},
  85. "9": {"class_type": "SaveImage",
  86. "inputs": {"filename_prefix": "smoke", "images": ["3", 0]}},
  87. }
  88. def smoke_test(host: str, headers: dict, ckpt_name: str | None) -> dict:
  89. """Submit a tiny workflow and verify the server accepts it.
  90. Cancels the job immediately after acceptance so we don't burn GPU
  91. time / cloud minutes on a smoke test.
  92. """
  93. if not ckpt_name:
  94. return {"ran": False, "reason": "no checkpoint available"}
  95. wf = json.loads(json.dumps(SMOKE_WORKFLOW))
  96. wf["4"]["inputs"]["ckpt_name"] = ckpt_name
  97. # Lazy import to avoid circular issues
  98. from run_workflow import ComfyRunner
  99. api_key = headers.get("X-API-Key")
  100. runner = ComfyRunner(host=host, api_key=api_key)
  101. sub = runner.submit(wf)
  102. if "_http_error" in sub:
  103. return {"ran": True, "submitted": False,
  104. "http_status": sub["_http_error"], "body": sub.get("body")}
  105. pid = sub.get("prompt_id")
  106. if not pid:
  107. return {"ran": True, "submitted": False, "response": sub}
  108. # Cancel so we don't actually waste compute on the smoke test.
  109. cancelled = False
  110. try:
  111. cancelled = runner.cancel(pid)
  112. except Exception:
  113. pass
  114. return {
  115. "ran": True, "submitted": True, "prompt_id": pid,
  116. "cancelled_after_submit": cancelled,
  117. "note": "Submission accepted; cancelled to avoid running the full pipeline.",
  118. }
  119. def main(argv: list[str] | None = None) -> int:
  120. p = argparse.ArgumentParser(description="One-stop ComfyUI health check")
  121. p.add_argument("--host", default=DEFAULT_LOCAL_HOST)
  122. p.add_argument("--api-key", help=f"or set ${ENV_API_KEY}")
  123. p.add_argument("--workflow", help="Optional: also run check_deps on this workflow")
  124. p.add_argument("--smoke-test", action="store_true",
  125. help="Submit a tiny test workflow and verify round-trip")
  126. p.add_argument("--strict", action="store_true",
  127. help="Exit non-zero on any non-pass condition (including warnings)")
  128. args = p.parse_args(argv)
  129. api_key = resolve_api_key(args.api_key)
  130. headers = {"X-API-Key": api_key} if api_key else {}
  131. cli = comfy_cli_status()
  132. server = server_status(args.host, headers)
  133. ckpts = checkpoint_status(args.host, headers) if server.get("reachable") else None
  134. # ---- workflow check ----
  135. workflow_check: dict | None = None
  136. if args.workflow:
  137. wf_path = Path(args.workflow).expanduser()
  138. if not wf_path.exists():
  139. workflow_check = {"error": "workflow file not found"}
  140. else:
  141. try:
  142. with wf_path.open(encoding="utf-8-sig") as f:
  143. workflow = unwrap_workflow(json.load(f))
  144. from check_deps import check_deps
  145. workflow_check = check_deps(workflow, host=args.host, api_key=api_key)
  146. except (ValueError, json.JSONDecodeError) as e:
  147. workflow_check = {"error": str(e)}
  148. smoke = None
  149. if args.smoke_test and server.get("reachable"):
  150. first_ckpt = ckpts["first_few"][0] if ckpts and ckpts.get("first_few") else None
  151. smoke = smoke_test(args.host, headers, first_ckpt)
  152. # ---- verdict ----
  153. verdict = "pass"
  154. reasons: list[str] = []
  155. if not server.get("reachable"):
  156. verdict = "fail"
  157. reasons.append("server unreachable")
  158. if ckpts and ckpts.get("queryable") and ckpts.get("count", 0) == 0:
  159. verdict = "warn" if verdict == "pass" else verdict
  160. reasons.append("no checkpoints installed")
  161. if workflow_check and workflow_check.get("error"):
  162. verdict = "fail"
  163. reasons.append(f"workflow check failed: {workflow_check['error']}")
  164. elif workflow_check and not workflow_check.get("is_ready"):
  165. if workflow_check.get("node_check_skipped"):
  166. reasons.append("node check skipped (cloud free tier)")
  167. else:
  168. verdict = "fail"
  169. reasons.append("workflow has missing deps")
  170. if smoke and smoke.get("ran") and not smoke.get("submitted"):
  171. verdict = "fail"
  172. reasons.append("smoke-test submission failed")
  173. if not cli.get("available"):
  174. verdict = "warn" if verdict == "pass" else verdict
  175. reasons.append("comfy-cli not on PATH (lifecycle commands won't work)")
  176. report = {
  177. "verdict": verdict,
  178. "reasons": reasons,
  179. "host": args.host,
  180. "comfy_cli": cli,
  181. "server": server,
  182. "checkpoints": ckpts,
  183. "workflow_check": workflow_check,
  184. "smoke_test": smoke,
  185. }
  186. emit_json(report)
  187. if verdict == "pass":
  188. return 0
  189. if verdict == "warn":
  190. return 1 if args.strict else 0
  191. return 1
  192. if __name__ == "__main__":
  193. sys.exit(main())