diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 15fb58f..d1e1e86 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -35,6 +35,8 @@ Multi-model runtime isolation PRs also keep these CI-safe gates green: uv run pytest tests/test_runtime_isolation_gates.py tests/test_runtime_isolation.py -q ``` +Warm ACE across BatchPrompt (Rescore) is on by default for Real `ace-step-*` GenerateAudio. Disable with `GROOVY_WARM_ACE=0`. Stub CI leaves warm off (`GROOVY_INFERENCE_STUB=1`). + Then smoke one featured template in the studio: **Render** → play the **cached** preview (patch-bay audition, not live inference). Optional for maintainer weekly notes: Settings → **Copy clean-machine report** (privacy-safe snapshot) and paste into your lab log. diff --git a/apps/studio/src/workflow.test.ts b/apps/studio/src/workflow.test.ts index 7afd42e..66cfcfd 100644 --- a/apps/studio/src/workflow.test.ts +++ b/apps/studio/src/workflow.test.ts @@ -279,6 +279,52 @@ describe("BatchPrompt helpers", () => { }), ).toBe("exports/a.mp4"); }); + + it("stamps SaveVideo and SaveGenerateLog with matching -pNN take ids", async () => { + const { batchTakeFilename, patchBatchPromptPass } = await import("./workflow"); + expect(batchTakeFilename("rescore-cyberpunk.mp4", 3, ".mp4")).toBe("rescore-cyberpunk-p03.mp4"); + expect(batchTakeFilename("rescore-cyberpunk-log-p01.json", 2, ".json")).toBe( + "rescore-cyberpunk-log-p02.json", + ); + const workflow = { + schema_version: "1.0.0", + groovy_version: "0.1.0", + id: "w", + metadata: { title: "t" }, + groups: [], + nodes: [ + { + id: "bp", + type: "BatchPrompt", + pos: { x: 0, y: 0 }, + widgets: { prompts: "a\n---\nb", index: 0, led: "ready" }, + }, + { + id: "sv", + type: "SaveVideo", + pos: { x: 200, y: 0 }, + widgets: { path: "exports", filename: "rescore-cyberpunk.mp4" }, + }, + { + id: "lg", + type: "SaveGenerateLog", + pos: { x: 200, y: 100 }, + widgets: { path: "exports", filename: "rescore-cyberpunk-log.json" }, + }, + ], + links: [], + }; + const patched = patchBatchPromptPass(workflow as never, "bp", { + index: 0, + led: "processing", + saveNodeId: "sv", + }); + const byId = Object.fromEntries(patched.nodes.map((n) => [n.id, n])); + expect(byId.sv.widgets.filename).toBe("rescore-cyberpunk-p00.mp4"); + expect(byId.lg.widgets.filename).toBe("rescore-cyberpunk-log-p00.json"); + expect(byId.bp.widgets.index).toBe(0); + expect(byId.bp.widgets.led).toBe("processing"); + }); }); describe("previewTextSnippet", () => { diff --git a/apps/studio/src/workflow.ts b/apps/studio/src/workflow.ts index 8bf79ed..03ff655 100644 --- a/apps/studio/src/workflow.ts +++ b/apps/studio/src/workflow.ts @@ -839,6 +839,16 @@ export function findPromptBatchDriver(workflow: Workflow): string | null { return null; } +/** Stamp SaveVideo / SaveGenerateLog base names with `-pNN` for BatchPrompt passes. */ +export function batchTakeFilename(base: string, index: number, fallbackExt: string): string { + const raw = base.trim() || `output${fallbackExt}`; + const dot = raw.lastIndexOf("."); + const stemRaw = dot >= 0 ? raw.slice(0, dot) : raw; + const suffix = dot >= 0 ? raw.slice(dot) : fallbackExt; + const stem = stemRaw.includes("-p") ? stemRaw.split("-p")[0]! : stemRaw; + return `${stem}-p${String(index).padStart(2, "0")}${suffix}`; +} + export function patchBatchPromptPass( workflow: Workflow, batchNodeId: string, @@ -859,16 +869,29 @@ export function patchBatchPromptPass( }; } if (saveNodeId && node.id === saveNodeId && node.type === "SaveVideo") { - const base = String(node.widgets.filename ?? "output.mp4"); - const dot = base.lastIndexOf("."); - const stemRaw = dot >= 0 ? base.slice(0, dot) : base; - const suffix = dot >= 0 ? base.slice(dot) : ".mp4"; - const stem = stemRaw.includes("-p") ? stemRaw.split("-p")[0]! : stemRaw; return { ...node, widgets: { ...node.widgets, - filename: `${stem}-p${String(index).padStart(2, "0")}${suffix}`, + filename: batchTakeFilename( + String(node.widgets.filename ?? "output.mp4"), + index, + ".mp4", + ), + }, + }; + } + // Same -pNN stamp as SaveVideo so exports/-p00-*.mp4 ↔ *-p00-*.json. + if (node.type === "SaveGenerateLog") { + return { + ...node, + widgets: { + ...node.widgets, + filename: batchTakeFilename( + String(node.widgets.filename ?? "generate-log.json"), + index, + ".json", + ), }, }; } diff --git a/nodes/ai/src/groovy/nodes/ai/inference.py b/nodes/ai/src/groovy/nodes/ai/inference.py index 0cb0ffd..76c3ea9 100644 --- a/nodes/ai/src/groovy/nodes/ai/inference.py +++ b/nodes/ai/src/groovy/nodes/ai/inference.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import os import tempfile from pathlib import Path @@ -1175,6 +1176,20 @@ def run_generate_audio(cache: CacheStore, kwargs: dict) -> list[dict]: out_buffer = AudioBuffer.from_planar(pcm, sample_rate, source_node_type="GenerateAudio") cache.write_audio(out_buffer, pcm) frames = int(pcm.shape[-1]) if getattr(pcm, "ndim", 0) >= 1 else 0 + timing_extra: dict = {} + if str(model_id).startswith("ace-step"): + try: + from groovy.nodes.ai.backends.ace_step_runner import _load_pipeline + + info = _load_pipeline.cache_info() + timing_extra = { + "ace_pipeline_cache_hits": int(info.hits), + "ace_pipeline_cache_misses": int(info.misses), + "warm_ace_worker": os.environ.get("GROOVY_AI_WORKER_MODE", "").strip().lower() + == "warm", + } + except Exception: + timing_extra = {} report = GenerateLogReport.create( { "node_type": "GenerateAudio", @@ -1183,6 +1198,7 @@ def run_generate_audio(cache: CacheStore, kwargs: dict) -> list[dict]: "timing": { "generate_ms": elapsed_ms, "generate_s": round(elapsed_ms / 1000.0, 3), + **timing_extra, }, "output": { "media_type": "audio/pcm", diff --git a/nodes/ai/src/groovy/nodes/ai/worker.py b/nodes/ai/src/groovy/nodes/ai/worker.py index 4e51007..995c774 100644 --- a/nodes/ai/src/groovy/nodes/ai/worker.py +++ b/nodes/ai/src/groovy/nodes/ai/worker.py @@ -1,8 +1,11 @@ from __future__ import annotations import json +import os import sys +import traceback from pathlib import Path +from typing import Any from groovy.executor.cache import CacheStore from groovy.nodes.ai.inference import ( @@ -64,10 +67,7 @@ } -def main() -> None: - import os - - payload = json.loads(sys.stdin.read()) +def _handle_one(payload: dict[str, Any]) -> list[dict[str, Any]]: node_type = payload["node_type"] project_dir = Path(payload["project_dir"]) os.environ.setdefault("GROOVY_PROJECT_DIR", str(project_dir.resolve())) @@ -82,7 +82,49 @@ def main() -> None: if model_id: require_model(project_dir, str(model_id)) - outputs = handler(cache, kwargs) + return handler(cache, kwargs) + + +def _warm_loop() -> None: + """NDJSON request/response loop — keeps ACE pipeline cache warm across takes.""" + for raw in sys.stdin: + line = raw.strip() + if not line: + continue + request_id = None + try: + payload = json.loads(line) + if not isinstance(payload, dict): + raise RuntimeError("Warm worker payload must be a JSON object") + request_id = payload.get("request_id") + if payload.get("cmd") == "shutdown": + reply = {"ok": True, "shutdown": True, "request_id": request_id} + sys.stdout.write(json.dumps(reply) + "\n") + sys.stdout.flush() + return + outputs = _handle_one(payload) + reply = {"ok": True, "outputs": outputs, "request_id": request_id} + sys.stdout.write(json.dumps(reply) + "\n") + sys.stdout.flush() + except Exception as exc: # noqa: BLE001 — per-request isolation in warm loop + traceback.print_exc(file=sys.stderr) + reply = { + "ok": False, + "error": str(exc) or type(exc).__name__, + "request_id": request_id, + } + sys.stdout.write(json.dumps(reply) + "\n") + sys.stdout.flush() + + +def main() -> None: + mode = os.environ.get("GROOVY_AI_WORKER_MODE", "").strip().lower() + if mode == "warm": + _warm_loop() + return + + payload = json.loads(sys.stdin.read()) + outputs = _handle_one(payload) sys.stdout.write(json.dumps({"outputs": outputs})) diff --git a/nodes/core/src/groovy/nodes/core/nodes.py b/nodes/core/src/groovy/nodes/core/nodes.py index cc3ce4b..ae738a9 100644 --- a/nodes/core/src/groovy/nodes/core/nodes.py +++ b/nodes/core/src/groovy/nodes/core/nodes.py @@ -2,10 +2,12 @@ import hashlib import json +import re import shutil import uuid from datetime import UTC, datetime from pathlib import Path +from typing import Any import numpy as np import soundfile as sf @@ -1314,14 +1316,26 @@ def run(self, **kwargs) -> tuple[str]: relative = self._resolve_output_relative(folder, name) if not Path(relative).suffix: relative = f"{relative}.json" + # Capture BatchPrompt take id from widget name before UTC stamp + # (e.g. rescore-cyberpunk-log-p03.json → p03). + batch_match = re.search(r"-p(\d+)\b", Path(name).stem, flags=re.IGNORECASE) relative = self._timestamped_relative(relative).replace("\\", "/") out_path = self._ctx.cache.resolve_project_path(relative) out_path.parent.mkdir(parents=True, exist_ok=True) + export_meta: dict[str, Any] = { + "path": relative, + "node_type": "SaveGenerateLog", + "filename_widget": name, + } + if batch_match: + take = f"p{int(batch_match.group(1)):02d}" + export_meta["batch_prompt_index"] = int(batch_match.group(1)) + export_meta["batch_take_id"] = take payload = { **log_in.record, "exported_at": datetime.now(UTC).isoformat(), "generate_log_id": log_in.id, - "export": {"path": relative, "node_type": "SaveGenerateLog"}, + "export": export_meta, } out_path.write_text(json.dumps(payload, indent=2) + "\n") return (relative,) diff --git a/packages/executor/src/groovy/executor/warm_worker.py b/packages/executor/src/groovy/executor/warm_worker.py new file mode 100644 index 0000000..ea19086 --- /dev/null +++ b/packages/executor/src/groovy/executor/warm_worker.py @@ -0,0 +1,320 @@ +"""Warm AI worker sessions — keep ACE weights loaded across BatchPrompt executes. + +B-MLOPS-002 / feat/runtime-warm-ace-batch: studio BatchPrompt runs one ``/api/execute`` +per prompt. One-shot workers reload ACE every take. A warm session keeps a single +``groovy-ai-worker`` process alive and reuses ``ace_step_runner``'s in-process +pipeline cache. + +Not a live/DAW engine — offline takes only. Cancel terminates the session. +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +import threading +import time +import uuid +from collections.abc import Callable +from pathlib import Path +from typing import Any + +from groovy.executor.cancel import JobCancelled + +# Idle eviction so a finished Rescore batch does not pin RAM forever. +_DEFAULT_IDLE_TTL_S = 15 * 60 + + +def warm_ace_enabled() -> bool: + raw = os.environ.get("GROOVY_WARM_ACE", "1").strip().lower() + return raw not in {"0", "false", "no", "off"} + + +def inference_stub_enabled() -> bool: + raw = os.environ.get("GROOVY_INFERENCE_STUB", "").strip().lower() + return raw in {"1", "true", "yes", "on"} + + +def is_ace_generate_audio(node_type: str, kwargs: dict[str, Any]) -> bool: + if node_type != "GenerateAudio": + return False + model = str(kwargs.get("model") or "").strip().lower() + return model.startswith("ace-step") + + +def should_use_warm_ace(node_type: str, kwargs: dict[str, Any]) -> bool: + if not warm_ace_enabled(): + return False + if inference_stub_enabled(): + # Stub path is already seconds-fast; avoid holding a warm process in CI. + return False + return is_ace_generate_audio(node_type, kwargs) + + +class WarmAiWorkerSession: + """One long-lived AI worker process (NDJSON request/response on stdio).""" + + def __init__(self, project_dir: Path, *, idle_ttl_s: float = _DEFAULT_IDLE_TTL_S) -> None: + self.project_dir = project_dir.resolve() + self.idle_ttl_s = idle_ttl_s + self._lock = threading.RLock() + self._proc: subprocess.Popen[str] | None = None + self._stderr_thread: threading.Thread | None = None + self._stderr_chunks: list[str] = [] + self._last_used = time.monotonic() + self._request_count = 0 + + @property + def request_count(self) -> int: + return self._request_count + + def is_alive(self) -> bool: + return self._proc is not None and self._proc.poll() is None + + def shutdown(self) -> None: + with self._lock: + proc = self._proc + self._proc = None + if proc is None: + return + if proc.poll() is None: + try: + if proc.stdin and not proc.stdin.closed: + proc.stdin.write(json.dumps({"cmd": "shutdown"}) + "\n") + proc.stdin.flush() + except Exception: + pass + _terminate_worker(proc) + self._last_used = time.monotonic() + + def run( + self, + node_type: str, + kwargs: dict[str, Any], + *, + serialize_kwargs: Callable[[dict[str, Any]], dict[str, Any]], + cancel_check: Callable[[], bool] | None = None, + timeout: int | None = None, + parse_stdout_line: Callable[[str], dict[str, Any]], + clean_error: Callable[[str], str], + resolve_timeout: Callable[[int | None], int | None], + worker_cmd: list[str], + ) -> list[dict[str, Any]]: + with self._lock: + self._evict_if_idle_unlocked() + self._ensure_started_unlocked(worker_cmd) + assert self._proc is not None and self._proc.stdin is not None + assert self._proc.stdout is not None + + request_id = uuid.uuid4().hex + payload = { + "mode": "warm", + "request_id": request_id, + "node_type": node_type, + "kwargs": serialize_kwargs(kwargs), + "project_dir": str(self.project_dir), + } + try: + self._proc.stdin.write(json.dumps(payload) + "\n") + self._proc.stdin.flush() + except Exception as exc: + self.shutdown() + raise RuntimeError(f"Warm AI worker stdin failed: {exc}") from exc + + limit = resolve_timeout(timeout) + started = time.monotonic() + while True: + if cancel_check and cancel_check(): + self.shutdown() + raise JobCancelled() + if limit is not None and time.monotonic() - started > limit: + self.shutdown() + raise RuntimeError(f"Warm AI worker timed out after {limit}s") + if self._proc.poll() is not None: + err = "".join(self._stderr_chunks).strip() or "Warm AI worker exited" + self.shutdown() + raise RuntimeError(clean_error(err)) + + line = self._readline_with_cancel(cancel_check=cancel_check, limit=limit, started=started) + if line is None: + continue + data = parse_stdout_line(line) + if data.get("request_id") and data.get("request_id") != request_id: + # Stale / unrelated line — ignore. + continue + if not data.get("ok", True) and "error" in data: + raise RuntimeError(clean_error(str(data.get("error") or "Warm AI worker failed"))) + if "outputs" not in data and "error" in data: + raise RuntimeError(clean_error(str(data.get("error") or "Warm AI worker failed"))) + self._request_count += 1 + self._last_used = time.monotonic() + return list(data.get("outputs") or []) + + def _readline_with_cancel( + self, + *, + cancel_check: Callable[[], bool] | None, + limit: int | None, + started: float, + ) -> str | None: + """Non-blocking-ish readline via short timeouts on a helper thread.""" + assert self._proc is not None and self._proc.stdout is not None + holder: list[str | None] = [None] + error: list[BaseException] = [] + + def _read() -> None: + try: + holder[0] = self._proc.stdout.readline() # type: ignore[union-attr] + except BaseException as exc: # noqa: BLE001 — surface to waiter + error.append(exc) + + reader = threading.Thread(target=_read, name="warm-ai-stdout", daemon=True) + reader.start() + while reader.is_alive(): + if cancel_check and cancel_check(): + self.shutdown() + raise JobCancelled() + if limit is not None and time.monotonic() - started > limit: + self.shutdown() + raise RuntimeError(f"Warm AI worker timed out after {limit}s") + reader.join(timeout=0.25) + if error: + self.shutdown() + raise RuntimeError(f"Warm AI worker stdout failed: {error[0]}") from error[0] + line = holder[0] + if line is None or line == "": + # EOF + err = "".join(self._stderr_chunks).strip() or "Warm AI worker closed stdout" + self.shutdown() + raise RuntimeError(err) + return line.strip() + + def _evict_if_idle_unlocked(self) -> None: + if not self.is_alive(): + return + if time.monotonic() - self._last_used > self.idle_ttl_s: + self.shutdown() + + def _ensure_started_unlocked(self, worker_cmd: list[str]) -> None: + if self.is_alive(): + return + env = os.environ.copy() + env["GROOVY_PROJECT_DIR"] = str(self.project_dir) + env["GROOVY_AI_WORKER_MODE"] = "warm" + self._stderr_chunks = [] + self._proc = subprocess.Popen( + worker_cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=env, + bufsize=1, + ) + self._stderr_thread = threading.Thread( + target=self._drain_stderr, + name="warm-ai-stderr", + daemon=True, + ) + self._stderr_thread.start() + self._last_used = time.monotonic() + + def _drain_stderr(self) -> None: + proc = self._proc + if proc is None or proc.stderr is None: + return + try: + for line in proc.stderr: + self._stderr_chunks.append(line) + if len(self._stderr_chunks) > 400: + self._stderr_chunks = self._stderr_chunks[-200:] + except Exception: + pass + + +_SESSIONS: dict[str, WarmAiWorkerSession] = {} +_SESSIONS_LOCK = threading.Lock() + + +def get_warm_ace_session(project_dir: Path) -> WarmAiWorkerSession: + key = str(project_dir.resolve()) + with _SESSIONS_LOCK: + session = _SESSIONS.get(key) + if session is None: + session = WarmAiWorkerSession(project_dir) + _SESSIONS[key] = session + return session + + +def shutdown_warm_ace_sessions() -> None: + with _SESSIONS_LOCK: + sessions = list(_SESSIONS.values()) + _SESSIONS.clear() + for session in sessions: + session.shutdown() + + +def warm_ace_session_stats(project_dir: Path | None = None) -> dict[str, Any]: + with _SESSIONS_LOCK: + if project_dir is None: + return { + "sessions": len(_SESSIONS), + "alive": sum(1 for s in _SESSIONS.values() if s.is_alive()), + "requests": sum(s.request_count for s in _SESSIONS.values()), + } + session = _SESSIONS.get(str(project_dir.resolve())) + if session is None: + return {"sessions": 0, "alive": 0, "requests": 0} + return { + "sessions": 1, + "alive": int(session.is_alive()), + "requests": session.request_count, + } + + +def _worker_command() -> list[str]: + worker_cmd = shutil.which("groovy-ai-worker") + if worker_cmd: + return [worker_cmd] + return [sys.executable, "-m", "groovy.nodes.ai.worker"] + + +def run_warm_ace_worker( + node_type: str, + kwargs: dict[str, Any], + project_dir: Path, + *, + serialize_kwargs: Callable[[dict[str, Any]], dict[str, Any]], + cancel_check: Callable[[], bool] | None = None, + timeout: int | None = None, + parse_stdout_line: Callable[[str], dict[str, Any]], + clean_error: Callable[[str], str], + resolve_timeout: Callable[[int | None], int | None], +) -> list[dict[str, Any]]: + session = get_warm_ace_session(project_dir) + return session.run( + node_type, + kwargs, + serialize_kwargs=serialize_kwargs, + cancel_check=cancel_check, + timeout=timeout, + parse_stdout_line=parse_stdout_line, + clean_error=clean_error, + resolve_timeout=resolve_timeout, + worker_cmd=_worker_command(), + ) + + +def _terminate_worker(proc: subprocess.Popen[str]) -> None: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + pass diff --git a/packages/executor/src/groovy/executor/worker.py b/packages/executor/src/groovy/executor/worker.py index 7f3366c..1ee5672 100644 --- a/packages/executor/src/groovy/executor/worker.py +++ b/packages/executor/src/groovy/executor/worker.py @@ -49,6 +49,22 @@ def run_ai_worker( except Exception: pass + # B-MLOPS-002: reuse ACE worker across BatchPrompt /api/execute passes. + from groovy.executor.warm_worker import run_warm_ace_worker, should_use_warm_ace + + if should_use_warm_ace(node_type, kwargs): + return run_warm_ace_worker( + node_type, + kwargs, + project_dir, + serialize_kwargs=_serialize_kwargs, + cancel_check=cancel_check, + timeout=timeout, + parse_stdout_line=_parse_worker_stdout_line, + clean_error=_clean_worker_error, + resolve_timeout=_resolve_worker_timeout, + ) + worker_cmd = shutil.which("groovy-ai-worker") if worker_cmd: cmd = [worker_cmd] @@ -123,6 +139,20 @@ def _parse_worker_stdout(stdout: str) -> dict[str, Any]: raise RuntimeError("AI worker returned invalid JSON") +def _parse_worker_stdout_line(line: str) -> dict[str, Any]: + """Parse one NDJSON response line from a warm AI worker.""" + text = (line or "").strip() + if not text: + raise RuntimeError("Warm AI worker returned empty line") + try: + data = json.loads(text) + except json.JSONDecodeError as exc: + raise RuntimeError(f"Warm AI worker returned invalid JSON: {text[:200]}") from exc + if not isinstance(data, dict): + raise RuntimeError("Warm AI worker JSON must be an object") + return data + + def _serialize_kwargs(kwargs: dict[str, Any]) -> dict[str, Any]: out: dict[str, Any] = {} for key, value in kwargs.items(): diff --git a/server/src/groovy/server/main.py b/server/src/groovy/server/main.py index edda1d5..b0fa7e1 100644 --- a/server/src/groovy/server/main.py +++ b/server/src/groovy/server/main.py @@ -1968,6 +1968,13 @@ async def cancel_job(job_id: str) -> dict[str, Any]: flag = _job_cancel_flags.get(job_id) if flag: flag.set() + # B-MLOPS-002: drop warm ACE session so cancel does not leave a hot worker. + try: + from groovy.executor.warm_worker import shutdown_warm_ace_sessions + + shutdown_warm_ace_sessions() + except Exception: + pass job["message"] = "Cancelling…" return {"ok": True, "status": "running"} diff --git a/tests/test_rescore_video.py b/tests/test_rescore_video.py index ac63904..fdae641 100644 --- a/tests/test_rescore_video.py +++ b/tests/test_rescore_video.py @@ -212,6 +212,8 @@ def test_rescore_video_template_schema_and_stub_render(tmp_path: Path, monkeypat assert by_id["n10"]["type"] == "ChannelSplit" assert by_id["n11"]["type"] == "PreviewAudio" assert by_id["n-log"]["type"] == "SaveGenerateLog" + assert by_id["n-log"]["widgets"]["filename"] == "rescore-cyberpunk-log.json" + assert by_id["n7"]["widgets"]["filename"] == "rescore-cyberpunk.mp4" assert by_id["note-monitors"]["type"] == "Note" # Production layout: A/B compare on top, main chain mid, batch under GenerateAudio. assert by_id["n2"]["pos"]["x"] == by_id["n3"]["pos"]["x"] diff --git a/tests/test_warm_ace_worker.py b/tests/test_warm_ace_worker.py new file mode 100644 index 0000000..0b6508b --- /dev/null +++ b/tests/test_warm_ace_worker.py @@ -0,0 +1,195 @@ +"""B-MLOPS-002 — warm ACE worker reuses one process across GenerateAudio calls.""" + +from __future__ import annotations + +import json +import os +import textwrap +from pathlib import Path + +import pytest + +from groovy.executor.cancel import JobCancelled +from groovy.executor.warm_worker import ( + WarmAiWorkerSession, + shutdown_warm_ace_sessions, + should_use_warm_ace, + warm_ace_session_stats, +) +from groovy.executor.worker import ( + _clean_worker_error, + _parse_worker_stdout_line, + _resolve_worker_timeout, + _serialize_kwargs, + run_ai_worker, +) + + +@pytest.fixture(autouse=True) +def _clean_sessions() -> None: + shutdown_warm_ace_sessions() + yield + shutdown_warm_ace_sessions() + + +def test_should_use_warm_ace_gates(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("GROOVY_INFERENCE_STUB", raising=False) + monkeypatch.setenv("GROOVY_WARM_ACE", "1") + assert should_use_warm_ace("GenerateAudio", {"model": "ace-step-1.5-sft"}) + assert should_use_warm_ace("GenerateAudio", {"model": "ace-step-1.5"}) + assert not should_use_warm_ace("GenerateAudio", {"model": "musicgen-small"}) + assert not should_use_warm_ace("Denoise", {"model": "deepfilternet-v3"}) + monkeypatch.setenv("GROOVY_WARM_ACE", "0") + assert not should_use_warm_ace("GenerateAudio", {"model": "ace-step-1.5-sft"}) + monkeypatch.setenv("GROOVY_WARM_ACE", "1") + monkeypatch.setenv("GROOVY_INFERENCE_STUB", "1") + assert not should_use_warm_ace("GenerateAudio", {"model": "ace-step-1.5-sft"}) + + +def _fake_warm_worker_script(tmp_path: Path) -> Path: + """Minimal NDJSON warm worker that counts process boots + requests.""" + script = tmp_path / "fake_warm_ace_worker.py" + state = tmp_path / "fake_warm_state.json" + state.write_text(json.dumps({"boots": 0, "requests": 0})) + script.write_text( + textwrap.dedent( + f"""\ + import json, os, sys + from pathlib import Path + state_path = Path({str(state)!r}) + data = json.loads(state_path.read_text()) + data["boots"] = int(data.get("boots", 0)) + 1 + state_path.write_text(json.dumps(data)) + mode = os.environ.get("GROOVY_AI_WORKER_MODE", "") + assert mode == "warm", mode + for raw in sys.stdin: + line = raw.strip() + if not line: + continue + payload = json.loads(line) + if payload.get("cmd") == "shutdown": + sys.stdout.write(json.dumps({{"ok": True, "shutdown": True}}) + "\\n") + sys.stdout.flush() + break + data = json.loads(state_path.read_text()) + data["requests"] = int(data.get("requests", 0)) + 1 + state_path.write_text(json.dumps(data)) + rid = payload.get("request_id") + out = {{ + "ok": True, + "request_id": rid, + "outputs": [{{"type": "AUDIO", "cache_id": f"fake-{{data['requests']}}"}}], + }} + sys.stdout.write(json.dumps(out) + "\\n") + sys.stdout.flush() + """ + ) + ) + return script + + +def test_warm_session_reuses_one_process(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("GROOVY_INFERENCE_STUB", raising=False) + monkeypatch.setenv("GROOVY_WARM_ACE", "1") + script = _fake_warm_worker_script(tmp_path) + state = tmp_path / "fake_warm_state.json" + + session = WarmAiWorkerSession(tmp_path, idle_ttl_s=600) + cmd = [os.environ.get("UV_PYTHON") or "python3", str(script)] + # Prefer the same interpreter as the test process. + import sys + + cmd = [sys.executable, str(script)] + + def _run_once() -> list[dict]: + return session.run( + "GenerateAudio", + {"model": "ace-step-1.5-sft", "prompt": "x"}, + serialize_kwargs=_serialize_kwargs, + parse_stdout_line=_parse_worker_stdout_line, + clean_error=_clean_worker_error, + resolve_timeout=_resolve_worker_timeout, + worker_cmd=cmd, + ) + + out1 = _run_once() + out2 = _run_once() + out3 = _run_once() + assert out1[0]["cache_id"] == "fake-1" + assert out2[0]["cache_id"] == "fake-2" + assert out3[0]["cache_id"] == "fake-3" + data = json.loads(state.read_text()) + assert data["boots"] == 1 + assert data["requests"] == 3 + assert session.request_count == 3 + session.shutdown() + + +def test_warm_session_cancel_terminates(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("GROOVY_INFERENCE_STUB", raising=False) + import sys + import time + + script = tmp_path / "slow_warm_worker.py" + script.write_text( + textwrap.dedent( + """\ + import json, os, sys, time + assert os.environ.get("GROOVY_AI_WORKER_MODE") == "warm" + for raw in sys.stdin: + payload = json.loads(raw) + if payload.get("cmd") == "shutdown": + break + time.sleep(30) + sys.stdout.write(json.dumps({"ok": True, "outputs": []}) + "\\n") + sys.stdout.flush() + """ + ) + ) + session = WarmAiWorkerSession(tmp_path) + cancelled = {"n": 0} + + def cancel_check() -> bool: + cancelled["n"] += 1 + return cancelled["n"] > 2 + + t0 = time.monotonic() + with pytest.raises(JobCancelled): + session.run( + "GenerateAudio", + {"model": "ace-step-1.5-sft"}, + serialize_kwargs=_serialize_kwargs, + cancel_check=cancel_check, + parse_stdout_line=_parse_worker_stdout_line, + clean_error=_clean_worker_error, + resolve_timeout=_resolve_worker_timeout, + worker_cmd=[sys.executable, str(script)], + ) + assert time.monotonic() - t0 < 10 + assert not session.is_alive() + + +def test_run_ai_worker_routes_ace_to_warm(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("GROOVY_INFERENCE_STUB", raising=False) + monkeypatch.setenv("GROOVY_WARM_ACE", "1") + script = _fake_warm_worker_script(tmp_path) + state = tmp_path / "fake_warm_state.json" + import sys + + monkeypatch.setattr( + "groovy.executor.warm_worker._worker_command", + lambda: [sys.executable, str(script)], + ) + + for _ in range(2): + outs = run_ai_worker( + "GenerateAudio", + {"model": "ace-step-1.5-sft", "prompt": "batch"}, + tmp_path, + ) + assert outs and outs[0]["type"] == "AUDIO" + + data = json.loads(state.read_text()) + assert data["boots"] == 1 + assert data["requests"] == 2 + assert warm_ace_session_stats(tmp_path)["requests"] == 2