#!/usr/bin/env python3 """ runner.py — NEXUS DAEMON v17 (autonomous, make-and-forget). APScheduler-free simple loop (robust on HF Space): - boot: warmup if vault empty → 1 instant short - quota reset daily 00:05 UTC - next_run from scheduler brain (1-3 shorts/day, 1-2 longs/week) - heartbeat every 15s → state/live_status.json - kill switch / force burst every 30s - memory + disk watchdogs """ from __future__ import annotations import os import signal import sys import time from pathlib import Path from nexus.config import load_settings from nexus.scheduler import (daily_plan, next_run_plan, override_requests, today_counts) from nexus.utils import (cleanup_temp, disk_guard, get_live_status, get_system_stats, live_status, log, memory_guard, purge_older_than, setup_logging) RUNNING = True def _signal_handler(signum, frame): global RUNNING log.warning("Signal %s received — graceful shutdown after current job", signum) RUNNING = False def warmup_if_empty() -> None: cfg = load_settings() mp4s = list(cfg.paths.vault.glob("*.mp4")) if not mp4s: log.info("Vault empty — warmup render (1 short)") from main import render_one try: render_one("short") except Exception as e: # noqa: BLE001 log.exception("Warmup render failed: %s", e) def daily_maintenance() -> None: cfg = load_settings() purge_older_than(cfg.paths.artifacts, cfg.artifact_purge_hours) disk_guard() cleanup_temp() def boot_maintenance() -> None: """Boot hygiene BEFORE heavy work (fixes 'launch timed out' crashes): 1) free stale render workdirs + temp junk (ephemeral disk protection) 2) trim huge log files 3) wait for the UI to pass the HF health check (max ~5 min) so the container is 'healthy' before whisper/ffmpeg load their RAM.""" import urllib.request cfg = load_settings() log.info("Boot maintenance: disk + log hygiene") try: purge_older_than(cfg.paths.artifacts, cfg.artifact_purge_hours) cleanup_temp() disk_guard() except Exception as e: # noqa: BLE001 log.warning("Boot cleanup partial failure: %s", str(e)[:120]) logf = cfg.paths.logs / "nexus.log" try: if logf.exists() and logf.stat().st_size > 5 * 1024 * 1024: tail = logf.read_text(encoding="utf-8", errors="ignore").splitlines()[-500:] logf.write_text("\n".join(tail), encoding="utf-8") log.info("Boot maintenance: nexus.log trimmed to 500 lines") except OSError: pass port = os.getenv("PORT", "7860") for _ in range(60): try: with urllib.request.urlopen( "http://127.0.0.1:%s/healthz" % port, timeout=3) as r: if r.status == 200: log.info("Boot maintenance: UI healthy — safe to proceed") return except Exception: # noqa: BLE001 time.sleep(5) log.warning("Boot maintenance: UI not healthy after 5 min — proceeding anyway") def main_loop() -> int: cfg = load_settings() setup_logging(log_dir=cfg.paths.logs) signal.signal(signal.SIGTERM, _signal_handler) signal.signal(signal.SIGINT, _signal_handler) log.info("═══ NEXUS DAEMON v17 starting (pid=%d) ═══", os.getpid()) live_status("daemon", "online", {"pid": os.getpid(), "stage": "BOOT"}) boot_maintenance() last_heartbeat = 0.0 last_check = 0.0 last_day = time.strftime("%Y-%m-%d", time.gmtime()) warmed = False while RUNNING: now = time.time() # heartbeats if now - last_heartbeat >= 15: st = get_system_stats() live_status("system", st) live_status("daemon_heartbeat", time.strftime("%H:%M:%S", time.gmtime())) last_heartbeat = now # overrides every 30s if now - last_check >= 30: ov = override_requests() if ov["kill"]: log.warning("KILL_SWITCH — stopping daemon") live_status("daemon", "killed") break last_check = now # memory + disk watchdogs memory_guard() disk_guard() # quota reset (00:05 UTC) today = time.strftime("%Y-%m-%d", time.gmtime()) if today != last_day: last_day = today daily_maintenance() log.info("New UTC day — quotas reset, plan=%s", daily_plan()) # warmup once — but NEVER under memory pressure (defer, retry next # loop): a heavy render at boot was the top suspect for the # "workload was not healthy after 30 min" launch failures. if not warmed: if memory_guard(): log.warning("Warmup deferred: memory pressure — retry next loop") else: warmup_if_empty() warmed = True # plan next action plan = next_run_plan() live_status("next_plan", plan) if plan.get("action") == "render": kind = plan["kind"] log.info("NEXT: render %s (longs_left=%s shorts_left=%s reason=%s)", kind, plan["longs_left"], plan["shorts_left"], plan["reason"]) try: from main import render_one render_one(kind) except Exception as e: # noqa: BLE001 log.exception("Render crashed: %s", e) continue # sleep until next time (bounded to keep loop responsive) nxt = plan.get("next_time", "") sleep_s = 60 if nxt: try: from datetime import datetime t = datetime.fromisoformat(nxt.replace("Z", "+00:00")) sleep_s = max(15, min(3600, (t - datetime.now(tz=t.tzinfo)).total_seconds())) except Exception: # noqa: BLE001 sleep_s = 300 time.sleep(sleep_s) live_status("daemon", "offline") return 0 if __name__ == "__main__": sys.exit(main_loop())