Skip to content

About

ORAGEN TEAM

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ComfyUI-Watchdog

Production-ready automatic monitoring and restart solution for ComfyUI instances.

ComfyUI-Watchdog provides robust, event-driven monitoring that eliminates continuous polling loops while maintaining reliable health checking and automatic recovery capabilities. Battle-tested and ready for production deployment.

Features

  • Event-Driven Architecture: No continuous polling loops - uses timer-based callbacks for efficient resource usage
  • HTTP Health Checking: Async batch health checks with configurable endpoints and retry logic
  • Advanced Health Strategies: Hybrid health checking (majority consensus) and adaptive strategies that switch based on failure rates
  • Process Monitoring: Three-phase process detection (port-based, pattern matching, PID file)
  • Intelligent Restart: Graceful shutdown with exponential backoff and startup verification
  • Advanced Restart Strategies: Exponential backoff and circuit breaker patterns for resilient recovery
  • Multi-Instance Support: Monitor and manage multiple ComfyUI instances simultaneously
  • CLI Management Tool: Comprehensive command-line interface for status, health checks, restarts, and service management
  • Performance Optimization: Connection pooling, rate limiting, caching, and metrics collection
  • Flexible Configuration: YAML/JSON configuration with environment variable overrides
  • Structured Logging: JSON or text format with rotation support
  • Cross-Platform: Windows and Linux support (macOS coming soon)

Architecture

┌─────────────────────────────────────────────────────────────┐
│                  ComfyUI-Watchdog System                     │
├─────────────────────────────────────────────────────────────┤
│  Configuration Manager → Watchdog Orchestrator              │
│                           ↓                                  │
│  ┌─────────────┐  ┌──────────────┐  ┌──────────────┐      │
│  │   Health    │  │   Process    │  │   Restart    │      │
│  │   Checker   │  │   Monitor    │  │   Manager    │      │
│  └─────────────┘  └──────────────┘  └──────────────┘      │
└─────────────────────────────────────────────────────────────┘

Installation

Prerequisites

  • Python 3.8 or higher
  • ComfyUI installation
  • pip package manager

Quick Install

# Clone the repository
git clone https://github.com/MushroomFleet/ComfyUI-Watchdog.git
cd comfy-crash-protections

# Install dependencies
pip install -r requirements.txt

# Or install in development mode
pip install -e .

With Development Tools

pip install -e ".[dev]"

Configuration

Create a config.yaml file based on the example:

cp config/config.example.yaml config.yaml

Edit config.yaml to match your setup:

watchdog:
  mode: "http"  # http, process, or hybrid
  check_interval: 30  # seconds between checks

instances:
  - name: "comfyui-main"
    host: "localhost"
    port: 8188
    comfyui_path: "C:\\MACHINES00\\ComfyUI_windows_portable_nvidia\\ComfyUI_windows_portable\\ComfyUI"
    working_directory: "C:\\MACHINES00\\ComfyUI_windows_portable_nvidia\\ComfyUI_windows_portable"
    python_path: "python_embeded\\python.exe"
    startup_args: "--listen 0.0.0.0 --port 8188"

health_check:
  timeout: 5
  retries: 3

restart:
  max_attempts: 5
  cooldown: 10
  exponential_backoff: true
  grace_period: 5

logging:
  level: "INFO"
  format: "json"
  rotation: "daily"
  max_files: 7

Environment Variables

Override configuration via environment variables:

export COMFYUI_WATCHDOG_CONFIG=/path/to/config.yaml
export COMFYUI_WATCHDOG_MODE=http
export COMFYUI_WATCHDOG_INTERVAL=30
export COMFYUI_WATCHDOG_LOG_LEVEL=DEBUG

Usage

CLI Management Tool

The watchdog includes a comprehensive CLI tool for managing instances:

# Show status of all instances
python -m src.cli --config config.yaml status

# Show status of specific instance
python -m src.cli --config config.yaml status comfyui-main

# Check health of specific instance
python -m src.cli --config config.yaml check comfyui-main

# Restart an instance
python -m src.cli --config config.yaml restart comfyui-main

# Restart without confirmation
python -m src.cli --config config.yaml restart comfyui-main --force

# List all configured instances
python -m src.cli --config config.yaml list

# Show current configuration
python -m src.cli --config config.yaml config

Continuous Monitoring

Run the watchdog in continuous monitoring mode:

python -m src.orchestrator --config config.yaml

One-Shot Execution

For cron/scheduled tasks:

python -m src.orchestrator --config config.yaml --once

Command-Line Options

Options:
  --config PATH    Path to configuration file
  --once          Run once and exit (for scheduled execution)
  --version       Show version and exit
  -h, --help      Show help message

Deployment

ComfyUI-Watchdog supports multiple deployment methods on both Windows and Linux. Use the automated installation scripts for the easiest setup.

Windows Deployment

Automated Installation

Run the PowerShell installation script with administrator privileges:

# Run PowerShell as Administrator
.\scripts\install_windows.ps1

The script will:

  • Check for Python and install dependencies
  • Optionally install NSSM (for Windows Service)
  • Create configuration file
  • Let you choose installation mode:
    1. Windows Service (NSSM) - Recommended for production
    2. Task Scheduler - Lighter weight option
    3. Manual - No automatic startup

Windows Service (NSSM)

Manage the service with NSSM commands:

# Start service
nssm start ComfyUIWatchdog

# Stop service
nssm stop ComfyUIWatchdog

# Check status
nssm status ComfyUIWatchdog

# Remove service
nssm remove ComfyUIWatchdog confirm

Task Scheduler

Manage scheduled task:

# View task
schtasks /query /tn ComfyUIWatchdog

# Run task manually
schtasks /run /tn ComfyUIWatchdog

# Delete task
schtasks /delete /tn ComfyUIWatchdog /f

Linux Deployment

Automated Installation

Run the bash installation script:

# Make script executable (if needed on Windows git checkout)
chmod +x scripts/install_linux.sh

# Run installation script
./scripts/install_linux.sh

The script will:

  • Check for Python 3 and install pip if needed
  • Install dependencies
  • Create configuration file
  • Let you choose installation mode:
    1. systemd service - Recommended for production
    2. cron job - Lighter weight option
    3. Manual - No automatic startup

Systemd Service

Manage the systemd service:

# Start service
sudo systemctl start comfyui-watchdog

# Stop service
sudo systemctl stop comfyui-watchdog

# Enable auto-start on boot
sudo systemctl enable comfyui-watchdog

# Check status
sudo systemctl status comfyui-watchdog

# View logs
sudo journalctl -u comfyui-watchdog -f

# Disable and remove
sudo systemctl disable comfyui-watchdog
sudo rm /etc/systemd/system/comfyui-watchdog.service
sudo systemctl daemon-reload

Cron Job

Manage cron jobs:

# View crontab
crontab -l

# Edit crontab
crontab -e

# View logs
tail -f logs/cron.log

# Remove watchdog cron job
crontab -l | grep -v 'ComfyUI-Watchdog' | crontab -

Docker Deployment

Docker support coming in Phase 4. See docs/05-implementation-phase4-docker-support.md for planned Docker integration.

Monitoring Strategies

HTTP Mode (Recommended)

  • Makes HTTP requests to ComfyUI endpoints
  • Fast and reliable for web-accessible instances
  • Configurable timeout and retry logic

Process Mode

  • Scans for ComfyUI processes by pattern/port
  • Useful when HTTP is not available
  • Slightly higher overhead

Hybrid Mode

  • Combines HTTP, process, and port checks
  • Uses majority consensus (2 out of 3) for reliability
  • More resilient to transient failures
  • Example configuration:
    watchdog:
      mode: "hybrid"

Adaptive Mode

  • Starts with fast HTTP checks
  • Automatically switches to hybrid mode after repeated failures
  • Resets to HTTP mode after successful checks
  • Optimizes for both speed and reliability
  • Configurable failure threshold:
    from src.health_strategies import AdaptiveHealthChecker
    
    checker = AdaptiveHealthChecker(timeout=5)
    # Switches to hybrid after 3 failures (default)

Health Check Flow

1. HTTP Request → ComfyUI endpoint
2. Check Response Status (200 = healthy)
3. Record Response Time
4. Retry on Failure (configurable)
5. Mark as Unhealthy if all retries fail
6. Trigger Restart Process

Restart Strategies

Standard Restart

  • Fixed cooldown period between attempts
  • Configurable maximum attempts
  • Graceful shutdown with force kill fallback

Exponential Backoff

  • Increases delay between restart attempts exponentially
  • Formula: delay = cooldown * 2^(attempt_count)
  • Prevents rapid restart loops
  • Maximum delay capped at 5 minutes
  • Enable in configuration:
    restart:
      exponential_backoff: true
      cooldown: 10  # Base delay in seconds

Circuit Breaker

  • Opens circuit after threshold failures
  • Prevents restart attempts when circuit is open
  • Automatically resets after timeout period
  • Three states: closed (normal), open (blocking), half-open (testing)
  • Example usage:
    from src.restart_strategies import CircuitBreakerRestarter
    
    restarter = CircuitBreakerRestarter(
        circuit_threshold=3,  # Open after 3 failures
        reset_timeout=300     # Reset after 5 minutes
    )

Restart Flow

1. Detect Failure
2. Check Restart Eligibility
3. Check Circuit Breaker State (if enabled)
4. Apply Exponential Backoff Delay (if enabled)
5. Kill Existing Process (graceful → force)
6. Wait Cooldown Period
7. Execute Startup Command
8. Verify Startup (health check)
9. Update Circuit Breaker State
10. Record Success/Failure

Logging

Logs are written to:

  • Console (stdout)
  • File: logs/watchdog.log

JSON Format Example

{
  "timestamp": "2025-01-10T23:45:00Z",
  "level": "INFO",
  "logger": "comfyui_watchdog",
  "message": "Health check passed for main",
  "module": "health_check",
  "function": "check_http",
  "line": 52,
  "instance": "main",
  "response_time": 0.123
}

Text Format Example

2025-01-10 23:45:00 - comfyui_watchdog - INFO - Health check passed for main

Performance Optimization

Connection Pooling

  • Reuses HTTP sessions for health checks
  • Reduces connection overhead
  • Configurable pool size:
    from src.performance import ConnectionPool
    
    pool = ConnectionPool(max_size=10)
    session = await pool.acquire()
    # Use session...
    await pool.release(session)

Rate Limiting

  • Prevents API rate limit violations
  • Time-window based limiting
  • Example usage:
    from src.performance import RateLimiter
    
    limiter = RateLimiter(max_calls=10, time_window=60)
    await limiter.acquire()  # Blocks if rate exceeded

Caching

  • Async cache decorator with TTL
  • Reduces redundant operations
  • Example:
    from src.performance import async_cache
    
    @async_cache(ttl=60)
    async def expensive_operation(arg):
        # Result cached for 60 seconds
        return result

Metrics Collection

  • Counters, gauges, and histograms
  • Performance monitoring and statistics
  • Percentile calculations (P50, P95, P99)
  • Example:
    from src.performance import MetricsCollector
    
    metrics = MetricsCollector()
    metrics.increment('health_checks')
    metrics.set_gauge('active_instances', 5)
    metrics.record_histogram('response_time', 0.123)
    
    stats = metrics.get_histogram_stats('response_time')
    # {'count': 100, 'min': 0.05, 'max': 0.5, 'p50': 0.12, 'p95': 0.45}

Resource Usage Targets

  • CPU: < 1% average, < 5% peak
  • Memory: < 50MB resident
  • Disk I/O: Minimal (logging only)
  • Network: Health check requests only (with connection pooling)

Testing

Run the test suite:

# Run all tests
pytest

# Run with coverage
pytest --cov=src --cov-report=html

# Run specific test file
pytest tests/test_models.py

# Run specific test category
pytest tests/test_health_strategies.py
pytest tests/test_restart_strategies.py
pytest tests/test_performance.py
pytest tests/test_cli.py

# Run with verbose output
pytest -v

# Run async tests
pytest -v -k "asyncio"

Test Coverage

The test suite includes:

  • Core Components: Models, configuration, health checking, process monitoring, restart management
  • Platform Integration: Windows and Linux platform adapters
  • Advanced Features:
    • Health strategies (hybrid, adaptive)
    • Restart strategies (exponential backoff, circuit breaker)
    • Performance utilities (connection pool, rate limiter, metrics)
    • CLI tool (all commands and service management)

Project Structure

comfy-crash-protections/
├── src/
│   ├── __init__.py
│   ├── models.py              # Data models
│   ├── exceptions.py          # Custom exceptions
│   ├── config.py              # Configuration management
│   ├── logger.py              # Logging setup
│   ├── health_check.py        # Health checking
│   ├── health_strategies.py   # Advanced health strategies
│   ├── process_monitor.py     # Process monitoring
│   ├── restart_manager.py     # Restart management
│   ├── restart_strategies.py  # Advanced restart strategies
│   ├── performance.py         # Performance optimization
│   ├── cli.py                 # CLI management tool
│   ├── orchestrator.py        # Main orchestrator
│   └── platform/
│       ├── __init__.py
│       ├── base.py
│       ├── windows.py
│       └── linux.py
├── tests/
│   ├── __init__.py
│   ├── test_models.py
│   ├── test_platform.py
│   ├── test_health_strategies.py
│   ├── test_restart_strategies.py
│   ├── test_performance.py
│   └── test_cli.py
├── config/
│   └── config.example.yaml
├── docs/
│   ├── 00-project-overview.md
│   ├── 01-architecture-design.md
│   ├── 02-implementation-phase1-core.md
│   ├── 03-implementation-phase2-platform-integration.md
│   ├── 04-implementation-phase3-advanced-features.md
│   └── ...
├── scripts/
│   ├── install_windows.ps1
│   └── install_linux.sh
├── logs/
├── requirements.txt
├── setup.py
└── README.md

Troubleshooting

Watchdog Not Starting

  1. Check configuration file exists and is valid:

    python -c "from config import ConfigManager; ConfigManager('config.yaml').load_config()"
  2. Verify Python path and ComfyUI path are correct

  3. Check logs in logs/watchdog.log

Health Checks Failing

  1. Verify ComfyUI is accessible:

    curl http://localhost:8188/
  2. Check firewall/network settings

  3. Increase timeout in configuration

  4. Enable DEBUG logging for more details

Restart Not Working

  1. Verify Python path is correct
  2. Check ComfyUI startup args
  3. Review process permissions
  4. Check logs for startup errors

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

[Add your license here]

Acknowledgments

Built for the ComfyUI community to provide reliable, automatic crash recovery.

Support

Roadmap

  • macOS support
  • Docker integration
  • Web dashboard
  • Metrics/telemetry
  • Slack/Discord notifications
  • Advanced retry strategies
  • Custom health check scripts
  • Multi-node orchestration

Version: 1.0.0
Status: Production Ready - All Core Features Complete
Last Updated: 2025-01-11

For detailed setup and operation instructions, see:

📚 Citation

Academic Citation

If you use this codebase in your research or project, please cite:

@software{comfyui_watchdog,
  title = {ComfyUI Watchdog: Automatic Crash Recovery for ComfyUI},
  author = {[Drift Johnson]},
  year = {2025},
  url = {https://github.com/MushroomFleet/ComfyUI-Watchdog},
  version = {1.0.0}
}

Donate:

Ko-Fi

About

ORAGEN TEAM

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages