diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6b11d21..15fb58f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,7 +5,7 @@ Thanks for helping improve the patch-bay for AI audio. This project is **Apache ## Before you open a PR ```bash -./scripts/install.sh # one-time (Python 3.11 venv + Studio deps) +./scripts/install.sh # one-time (Python 3.11/3.12 venv + Studio deps; DFN uses 3.11 sidecar) ``` Then run tests from the repo root: @@ -27,7 +27,15 @@ PR CI never proves cold Real. On a Mac that matches the [README OS contract](REA GROOVY_INFERENCE_STUB=0 uv run pytest tests/test_cold_machine_hero.py -q -m integration ``` -Expect **0 failed and 0 skipped**. Then smoke one featured template in the studio: **Render** → play the **cached** preview (patch-bay audition, not live inference). +Expect **0 failed and 0 skipped** (includes `test_dfn_whisper_cofile_cold_machine_gate` — DFN sidecar + Whisper on the same project). + +Multi-model runtime isolation PRs also keep these CI-safe gates green: + +```bash +uv run pytest tests/test_runtime_isolation_gates.py tests/test_runtime_isolation.py -q +``` + +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/README.md b/README.md index 796bf2a..045e8b2 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,7 @@ Experimental. APIs and UI will change. Expect rough edges on clean machines and ## OS compatibility -Use **Python 3.11**, keep Inference on **Real** for demos, and install models via **Cmd+K** / Model Browser when prompted. Some models need CUDA or other hardware; Mac CPU/MPS may be slow or unsupported depending on the backend. +Use **Python 3.11 or 3.12** for the studio `.venv`. DeepFilterNet installs into a **Python 3.11 sidecar** via Model Browser (do not recreate `.venv` just for denoise). Keep Inference on **Real** for demos, and install models via **Cmd+K** / Model Browser when prompted. Some models need CUDA or other hardware; Mac CPU/MPS may be slow or unsupported depending on the backend. **macOS (Apple Silicon) contract for Real / cold-machine work:** @@ -249,7 +249,7 @@ Also: - **ffmpeg** on `PATH` for Video mux / PreviewVideo - Install template models from Model Browser before the first real **Render** - If the platform below (or CUDA where noted) is missing, use Settings → Inference → **Stub** for UI-only demos -- On failure, check ports `8188` / `5173`, disk space, Python **3.11**, and `HF_TOKEN` in Compliance / Settings for gated weights +- On failure, check ports `8188` / `5173`, disk space, Python **3.11+**, DeepFilterNet runtime install (sidecar), and `HF_TOKEN` in Compliance / Settings for gated weights - Step on Apple Silicon needs `uv` on `PATH`; later runs reuse `.groovy/models/step-audio-editx/` | Template | Model | Platform | First-run expectation | diff --git a/apps/studio/src/App.tsx b/apps/studio/src/App.tsx index ac42553..45b94d9 100644 --- a/apps/studio/src/App.tsx +++ b/apps/studio/src/App.tsx @@ -1134,11 +1134,14 @@ export default function App() { const missing = await findMissingWorkflowModels(workflow); if (missing.length > 0) { const label = missing.map((entry) => entry.name || entry.modelId).join(", "); - const needsRuntime = missing.some((entry) => entry.reason === "inference_not_ready"); + const needsFamilyRuntime = missing.some((entry) => entry.reason === "runtime_missing"); + const needsInferenceSetup = missing.some((entry) => entry.reason === "inference_not_ready"); setStatus( - needsRuntime - ? `Inference setup required: ${label} — reinstall from Model Browser (Cmd+K)` - : `Install required: ${label} — use Model Browser (Cmd+K)`, + needsFamilyRuntime + ? `Install AI runtime for ${label} — Model Browser (Cmd+K)` + : needsInferenceSetup + ? `Inference setup required: ${label} — Model Browser (Cmd+K)` + : `Install required: ${label} — use Model Browser (Cmd+K)`, ); openModelBrowser({ mode: "search", diff --git a/apps/studio/src/api.ts b/apps/studio/src/api.ts index 50d8e4b..42ec2a5 100644 --- a/apps/studio/src/api.ts +++ b/apps/studio/src/api.ts @@ -914,11 +914,16 @@ export async function findMissingWorkflowModels( reason: "not_installed", }); } else if (!card.dev_stub && card.inference_ready === false) { + const runtimeId = + typeof card.runtime_id === "string" ? card.runtime_id : undefined; + // Only provisionable sidecars (DFN today) use Install-runtime CTA. + // ACE/Step stay inference_not_ready until their provision story matches. + const needsFamilyRuntime = runtimeId === "R-py311-dfn"; missing.push({ modelId, status: card.install_status, name: card.name, - reason: "inference_not_ready", + reason: needsFamilyRuntime ? "runtime_missing" : "inference_not_ready", }); } } catch { diff --git a/apps/studio/src/components/ModelBrowser.tsx b/apps/studio/src/components/ModelBrowser.tsx index 6bc9d17..9f7dd06 100644 --- a/apps/studio/src/components/ModelBrowser.tsx +++ b/apps/studio/src/components/ModelBrowser.tsx @@ -177,6 +177,11 @@ function modelNeedsReinstall(model: ModelCard): boolean { return model.install_status === "ready" && !model.dev_stub && model.inference_ready === false; } +/** Sidecars provisioned via Model Browser Install (not studio pip). */ +function modelNeedsRuntimeInstall(model: ModelCard): boolean { + return modelNeedsReinstall(model) && model.runtime_id === "R-py311-dfn"; +} + function hostFromCapabilities(machine: { ram_available_gb: number | null; vram_available_gb: number | null; @@ -678,7 +683,10 @@ export default function ModelBrowser({ }; const runPlanAction = (action: AgentPlanAction) => { - if (action.type === "install_model" && action.model_id) { + if ( + (action.type === "install_model" || action.type === "install_runtime") && + action.model_id + ) { void handleInstall(action.model_id); return; } @@ -698,13 +706,16 @@ export default function ModelBrowser({ agentPlan?.actions.filter( (action) => action.type === "install_model" || + action.type === "install_runtime" || action.type === "drop_node" || action.type === "suggest_public_model", ) ?? [], [agentPlan], ); const planInstallActions = useMemo(() => { - const installs = planModelActions.filter((action) => action.type === "install_model"); + const installs = planModelActions.filter( + (action) => action.type === "install_model" || action.type === "install_runtime", + ); const filtered = installs.filter((action) => matchesComputePreset(action.model?.compute_resolved, computePreset), ); @@ -824,6 +835,9 @@ export default function ModelBrowser({ } if (needsSetup) { + const setupLabel = modelNeedsRuntimeInstall(model) + ? "Install AI runtime" + : "Reinstall / fix setup"; return isInstalling ? ( {removeButton} @@ -1137,7 +1151,9 @@ export default function ModelBrowser({
{recovery.error ? ( {model.similar_rationale ? ( {model.similar_rationale} @@ -1485,7 +1503,11 @@ export default function ModelBrowser({ {model.dev_stub && !isDraftModel(model) ? stub : null} {isDraftModel(model) ? pending review : null} {model.inference_ready === false && model.install_status === "ready" ? ( - runtime missing + + {model.runtime_id === "R-py311-dfn" + ? "AI runtime missing" + : "inference not ready"} + ) : null}
{compatibleNodes.length > 0 ? ( diff --git a/apps/studio/src/components/ProvenanceVisualizer.tsx b/apps/studio/src/components/ProvenanceVisualizer.tsx index a758dbb..0e52900 100644 --- a/apps/studio/src/components/ProvenanceVisualizer.tsx +++ b/apps/studio/src/components/ProvenanceVisualizer.tsx @@ -10,13 +10,18 @@ function modelLabel(model: { registry_id?: string; role?: string; lora_scale?: number; + runtime_id?: string; }): string { const id = model.registry_id ?? "unknown"; if (model.role === "adapter") { const scale = typeof model.lora_scale === "number" ? ` ×${model.lora_scale}` : ""; return `LoRA: ${id}${scale}`; } - return `Model: ${id}`; + const runtime = + typeof model.runtime_id === "string" && model.runtime_id.trim() + ? ` · ${model.runtime_id.trim()}` + : ""; + return `Model: ${id}${runtime}`; } export default function ProvenanceVisualizer({ entry }: Props) { diff --git a/apps/studio/src/types.ts b/apps/studio/src/types.ts index ee78694..2d25473 100644 --- a/apps/studio/src/types.ts +++ b/apps/studio/src/types.ts @@ -236,6 +236,8 @@ export type ModelCard = { install_progress?: number; install_error?: string | null; dev_stub?: boolean; + /** Family worker id (R-…); distinct from compute.runtimes device tags. */ + runtime_id?: string | null; inference_ready?: boolean; install_complete?: boolean; inference_params?: InferenceParamSpec[]; @@ -450,7 +452,12 @@ export type ProvenanceLineageNode = { content_hash?: string; node?: { node_id?: string; node_type?: string }; contribution?: { class?: string; disclosure_label?: string }; - models?: Array<{ registry_id?: string; role?: string; lora_scale?: number }>; + models?: Array<{ + registry_id?: string; + role?: string; + lora_scale?: number; + runtime_id?: string; + }>; record_hash?: string; }; @@ -467,7 +474,12 @@ export type ProvenanceEntry = { cache_id?: string; contribution?: { class?: string; disclosure_label?: string }; node?: { node_id?: string; node_type?: string }; - models?: Array<{ registry_id?: string; role?: string; lora_scale?: number }>; + models?: Array<{ + registry_id?: string; + role?: string; + lora_scale?: number; + runtime_id?: string; + }>; }>; /** Full branching DAG when available (from cache provenance records). */ lineage?: ProvenanceLineage; @@ -490,6 +502,7 @@ export type ModelRecommendation = { export type AgentPlanAction = { type: | "install_model" + | "install_runtime" | "drop_node" | "apply_template" | "propose_workflow" @@ -561,6 +574,8 @@ export type InstallRecovery = { explain?: string; similar_models: Array; suggested_fixes: string[]; + /** HITL vocabulary: install_runtime (sidecar) vs install_model (studio env). */ + action?: "install_runtime" | "install_model" | string; }; export type JobState = { diff --git a/nodes/ai/src/groovy/nodes/ai/backends/deepfilternet_runner.py b/nodes/ai/src/groovy/nodes/ai/backends/deepfilternet_runner.py index b2de700..c600f71 100644 --- a/nodes/ai/src/groovy/nodes/ai/backends/deepfilternet_runner.py +++ b/nodes/ai/src/groovy/nodes/ai/backends/deepfilternet_runner.py @@ -1,26 +1,115 @@ +"""DeepFilterNet denoise — prefers uv Python 3.11 sidecar (never studio .venv pip).""" + from __future__ import annotations +import json +import os +import subprocess +import tempfile from functools import lru_cache +from pathlib import Path import numpy as np -import torch from scipy import signal from groovy.nodes.ai.deepfilter_compat import ensure_deepfilter_importable DF_SAMPLE_RATE = 48_000 +_DFN_WORKER = r""" +import json +import sys +from pathlib import Path -@lru_cache(maxsize=1) -def _load_deepfilter(): - ensure_deepfilter_importable() - from df.enhance import init_df +import numpy as np +import soundfile as sf + +payload = json.loads(Path(sys.argv[1]).read_text()) +# Avoid accidental git probes from cwd/parents during model init. +os_environ_git = __import__("os").environ +os_environ_git.pop("GIT_DIR", None) +os_environ_git.pop("GIT_WORK_TREE", None) + +# Torchaudio shims (inline — sidecar may not have groovy.nodes on path). +import types +import torchaudio as ta +from dataclasses import dataclass + +@dataclass +class _AudioMetaData: + sample_rate: int + num_frames: int = 0 + num_channels: int = 1 + +if not hasattr(ta, "AudioMetaData"): + ta.AudioMetaData = _AudioMetaData +if "torchaudio.backend.common" not in sys.modules: + common = types.ModuleType("torchaudio.backend.common") + common.AudioMetaData = _AudioMetaData + backend = types.ModuleType("torchaudio.backend") + backend.common = common + sys.modules["torchaudio.backend.common"] = common + sys.modules["torchaudio.backend"] = backend + +from df.enhance import enhance, init_df +import torch +from scipy import signal + +DF_SR = 48000 +wav, sr = sf.read(payload["in_wav"], always_2d=True) +# soundfile: (frames, channels) → (channels, frames) +pcm = wav.T.astype(np.float32) +strength = float(payload.get("strength", 1.0)) +strength = max(0.0, min(1.0, strength)) +sample_rate = int(sr) + +def resample(x, from_rate, to_rate): + if from_rate == to_rate: + return x + out = [] + for ch in x: + n = max(1, int(len(ch) * to_rate / from_rate)) + out.append(signal.resample(ch, n).astype(np.float32)) + return np.stack(out, axis=0) +if strength <= 0: + enhanced = pcm +else: loaded = init_df() if len(loaded) < 2: raise RuntimeError(f"Unexpected init_df() return arity: {len(loaded)}") model, df_state = loaded[0], loaded[1] - return model, df_state + working = resample(pcm, sample_rate, DF_SR) + channels = [] + with torch.no_grad(): + for channel in working: + audio = torch.from_numpy(channel.astype(np.float32)[None, :]) + cleaned = enhance(model, df_state, audio).detach().cpu().numpy()[0] + channels.append(cleaned) + enhanced = np.stack(channels, axis=0) + enhanced = resample(enhanced, DF_SR, sample_rate) + if enhanced.shape[1] > pcm.shape[1]: + enhanced = enhanced[:, : pcm.shape[1]] + elif enhanced.shape[1] < pcm.shape[1]: + enhanced = np.pad(enhanced, ((0, 0), (0, pcm.shape[1] - enhanced.shape[1]))) + if strength < 1.0: + enhanced = pcm * (1.0 - strength) + enhanced * strength + +sf.write(payload["out_wav"], enhanced.T, sample_rate) +Path(payload["out_meta"]).write_text(json.dumps({ + "sample_rate": sample_rate, + "channels": int(enhanced.shape[0]), + "frames": int(enhanced.shape[1]), + "runtime_id": "R-py311-dfn", +})) +""" + + +def _project_dir() -> Path: + override = os.environ.get("GROOVY_PROJECT_DIR", "").strip() + if override: + return Path(override).expanduser().resolve() + return Path.cwd().resolve() def _resample_pcm(pcm: np.ndarray, *, from_rate: int, to_rate: int) -> np.ndarray: @@ -35,13 +124,25 @@ def _resample_pcm(pcm: np.ndarray, *, from_rate: int, to_rate: int) -> np.ndarra return np.stack(out_channels, axis=0) -def denoise_pcm( +@lru_cache(maxsize=1) +def _load_deepfilter(): + ensure_deepfilter_importable() + from df.enhance import init_df + + loaded = init_df() + if len(loaded) < 2: + raise RuntimeError(f"Unexpected init_df() return arity: {len(loaded)}") + model, df_state = loaded[0], loaded[1] + return model, df_state + + +def _denoise_pcm_inprocess( pcm: np.ndarray, *, sample_rate: int, strength: float = 1.0, ) -> np.ndarray: - ensure_deepfilter_importable() + import torch from df.enhance import enhance if pcm.ndim == 1: @@ -51,6 +152,7 @@ def denoise_pcm( if strength <= 0: return pcm.copy() + ensure_deepfilter_importable() model, df_state = _load_deepfilter() working = _resample_pcm(pcm, from_rate=sample_rate, to_rate=DF_SAMPLE_RATE) enhanced_channels = [] @@ -71,3 +173,135 @@ def denoise_pcm( if strength >= 1.0: return enhanced return pcm * (1.0 - strength) + enhanced * strength + + +def _denoise_pcm_sidecar( + pcm: np.ndarray, + *, + sample_rate: int, + strength: float = 1.0, +) -> np.ndarray: + from groovy.registry.runtime_provision import dfn_runtime_ready + from groovy.registry.runtimes import RUNTIME_PY311_DFN, sidecar_python + + if pcm.ndim == 1: + pcm = pcm.reshape(1, -1) + + project = _project_dir() + # Fail closed: Model Browser Install owns uv bootstrap (B-QA-005) — never + # silent-provision mid-render. + if not dfn_runtime_ready(project): + raise RuntimeError( + "Install AI runtime for DeepFilterNet from Model Browser " + "(Python 3.11 sidecar). Render does not bootstrap the runtime." + ) + py = sidecar_python(project, RUNTIME_PY311_DFN) + if py is None: + raise RuntimeError( + "Install AI runtime for DeepFilterNet from Model Browser " + "(sidecar interpreter missing)." + ) + + with tempfile.TemporaryDirectory(prefix="groovy-dfn-") as tmp: + tmp_path = Path(tmp) + in_wav = tmp_path / "in.wav" + out_wav = tmp_path / "out.wav" + out_meta = tmp_path / "out.json" + payload_path = tmp_path / "payload.json" + + import soundfile as sf + + # soundfile wants (frames, channels) + sf.write(str(in_wav), pcm.T, int(sample_rate)) + payload = { + "in_wav": str(in_wav), + "out_wav": str(out_wav), + "out_meta": str(out_meta), + "strength": float(strength), + "runtime_id": RUNTIME_PY311_DFN, + } + payload_path.write_text(json.dumps(payload)) + worker_py = tmp_path / "dfn_worker.py" + worker_py.write_text(_DFN_WORKER) + # Allowlist worker env (B-SEC-005) — no HF/cloud tokens, no proxy creds. + allow = { + "PATH", + "HOME", + "USER", + "LOGNAME", + "TMPDIR", + "TMP", + "TEMP", + "LANG", + "LC_ALL", + "LC_CTYPE", + "TERM", + "SYSTEMROOT", + "WINDIR", + "PATHEXT", + "COMSPEC", + "DYLD_LIBRARY_PATH", + "LD_LIBRARY_PATH", + "PYTHONPATH", + "VIRTUAL_ENV", + "UV_CACHE_DIR", + "XDG_CACHE_HOME", + } + child_env = {k: os.environ[k] for k in allow if k in os.environ} + child_env["GROOVY_PROJECT_DIR"] = str(project) + child_env["PYTHONNOUSERSITE"] = "1" + proc = subprocess.run( + [str(py), str(worker_py), str(payload_path)], + capture_output=True, + text=True, + env=child_env, + cwd=str(tmp_path), + ) + if proc.returncode != 0: + err = (proc.stderr or proc.stdout or "DFN sidecar failed").strip() + raise RuntimeError( + "DeepFilterNet sidecar failed. " + f"Install AI runtime for DeepFilterNet from Model Browser. Detail: {err[-700:]}" + ) + if not out_wav.is_file(): + raise RuntimeError("DeepFilterNet sidecar produced no output WAV") + wav, sr = sf.read(str(out_wav), always_2d=True) + out = wav.T.astype(np.float32) + if int(sr) != int(sample_rate): + raise RuntimeError( + f"DeepFilterNet sidecar sample-rate mismatch: got {int(sr)} Hz, " + f"expected {int(sample_rate)} Hz (fail-loud; no silent re-resample)." + ) + if out.shape[0] != pcm.shape[0]: + raise RuntimeError( + f"DeepFilterNet sidecar channel mismatch: got {out.shape[0]}, " + f"expected {pcm.shape[0]}." + ) + if out.shape[1] > pcm.shape[1]: + out = out[:, : pcm.shape[1]] + elif out.shape[1] < pcm.shape[1]: + out = np.pad(out, ((0, 0), (0, pcm.shape[1] - out.shape[1]))) + if out.dtype != np.float32: + out = out.astype(np.float32, copy=False) + return out + + +def denoise_pcm( + pcm: np.ndarray, + *, + sample_rate: int, + strength: float = 1.0, +) -> np.ndarray: + from groovy.registry.runtimes import dfn_sidecar_enabled + + if dfn_sidecar_enabled(): + return _denoise_pcm_sidecar(pcm, sample_rate=sample_rate, strength=strength) + + # Legacy in-process only when flag off and packages already present — never install here. + try: + return _denoise_pcm_inprocess(pcm, sample_rate=sample_rate, strength=strength) + except ImportError as exc: + raise RuntimeError( + "Install AI runtime for DeepFilterNet " + "(enable GROOVY_DFN_SIDECAR=1 — DeepFilterNet is not pip-installed into studio .venv)." + ) from exc diff --git a/nodes/ai/src/groovy/nodes/ai/deepfilter_compat.py b/nodes/ai/src/groovy/nodes/ai/deepfilter_compat.py index 5faef3f..28042d1 100644 --- a/nodes/ai/src/groovy/nodes/ai/deepfilter_compat.py +++ b/nodes/ai/src/groovy/nodes/ai/deepfilter_compat.py @@ -1,10 +1,12 @@ -"""Torchaudio compatibility shims for DeepFilterNet on newer torchaudio releases.""" +"""Torchaudio compatibility shims + DeepFilterNet availability (sidecar-aware).""" from __future__ import annotations +import os import sys import types from dataclasses import dataclass +from pathlib import Path @dataclass @@ -18,7 +20,7 @@ def ensure_deepfilter_importable() -> None: """Patch torchaudio so DeepFilterNet's ``df.io`` can import on modern wheels. Recent torchaudio dropped ``AudioMetaData`` / ``torchaudio.backend``; DeepFilterNet - still imports them. Call this before ``import df.enhance``. + still imports them. Call this before ``import df.enhance`` (in-process or sidecar). """ import torchaudio as ta @@ -43,7 +45,7 @@ def info(path: str, **kwargs: object) -> _AudioMetaData: sys.modules["torchaudio.backend"] = backend -def deepfilternet_available() -> bool: +def deepfilternet_available_inprocess() -> bool: try: ensure_deepfilter_importable() import df.enhance # noqa: F401 @@ -51,3 +53,23 @@ def deepfilternet_available() -> bool: return True except ImportError: return False + + +def _project_dir() -> Path: + override = os.environ.get("GROOVY_PROJECT_DIR", "").strip() + if override: + return Path(override).expanduser().resolve() + return Path.cwd().resolve() + + +def deepfilternet_available() -> bool: + """True when Denoise Real path can run (sidecar preferred).""" + try: + from groovy.registry.runtimes import dfn_sidecar_enabled + from groovy.registry.runtime_provision import dfn_runtime_ready + except ImportError: + return deepfilternet_available_inprocess() + + if dfn_sidecar_enabled(): + return dfn_runtime_ready(_project_dir()) + return deepfilternet_available_inprocess() diff --git a/nodes/ai/src/groovy/nodes/ai/inference_env.py b/nodes/ai/src/groovy/nodes/ai/inference_env.py index 16c661a..041dd03 100644 --- a/nodes/ai/src/groovy/nodes/ai/inference_env.py +++ b/nodes/ai/src/groovy/nodes/ai/inference_env.py @@ -134,6 +134,23 @@ def deepfilternet_available() -> bool: return _available() +def deepfilternet_available_for_project(project_dir: str | None = None) -> bool: + """Project-scoped readiness (install verify / API cards).""" + import os + from pathlib import Path + + from groovy.nodes.ai.deepfilter_compat import deepfilternet_available_inprocess + from groovy.registry.runtime_provision import dfn_runtime_ready + from groovy.registry.runtimes import dfn_sidecar_enabled + + if not dfn_sidecar_enabled(): + return deepfilternet_available_inprocess() + root = Path(project_dir).expanduser().resolve() if project_dir else Path( + os.environ.get("GROOVY_PROJECT_DIR") or Path.cwd() + ).expanduser().resolve() + return dfn_runtime_ready(root) + + def whisper_available() -> bool: try: import faster_whisper # noqa: F401 @@ -308,9 +325,16 @@ def stereo2spatial_available() -> bool: } -def model_inference_ready(model_id: str, *, dev_stub: bool = False) -> bool: +def model_inference_ready( + model_id: str, + *, + dev_stub: bool = False, + project_dir: str | None = None, +) -> bool: if dev_stub or inference_stub_enabled(): return True + if model_id == "deepfilternet-v3": + return deepfilternet_available_for_project(project_dir) checker = _MODEL_RUNTIME_CHECKS.get(model_id) if checker is None: return True diff --git a/packages/executor/src/groovy/executor/engine.py b/packages/executor/src/groovy/executor/engine.py index 0c2bed0..9904228 100644 --- a/packages/executor/src/groovy/executor/engine.py +++ b/packages/executor/src/groovy/executor/engine.py @@ -190,7 +190,23 @@ def overall_fraction(local: float) -> float: fingerprint = media_path_fingerprint(self.cache, path_val) if fingerprint is not None: widgets_for_sig["_source_media"] = fingerprint + # Family runtime_id busts cache when sidecar/env swaps (MLOPS-003). + # Fail closed on resolve errors — never silently key as studio-default. + model_for_runtime = widgets_for_sig.get("model") + if isinstance(model_for_runtime, str) and model_for_runtime.strip(): + from groovy.registry.runtimes import resolve_runtime_id + + declared = None + if self.model_metadata_resolver: + meta = self.model_metadata_resolver(model_for_runtime.strip()) + if isinstance(meta, dict): + declared = meta.get("runtime_id") + widgets_for_sig["_runtime_id"] = resolve_runtime_id( + model_for_runtime.strip(), + manifest_runtime_id=str(declared) if declared else None, + ) signature = compute_node_signature(node.type, widgets_for_sig, kwargs) + cacheable = getattr(node_cls, "CACHEABLE", True) cached_state = ( None @@ -363,6 +379,25 @@ def _write_provenance( if model_id and self.model_metadata_resolver else None ) + if model_id: + try: + from groovy.registry.runtimes import resolve_runtime_id + + declared = None + if isinstance(model_metadata, dict): + declared = model_metadata.get("runtime_id") + runtime_id = resolve_runtime_id( + str(model_id), + manifest_runtime_id=str(declared) if declared else None, + ) + if model_metadata is None: + model_metadata = {} + else: + model_metadata = dict(model_metadata) + model_metadata.setdefault("runtime_id", runtime_id) + except Exception: + pass + workflow_json = json.dumps( workflow.model_dump(mode="json", by_alias=True), sort_keys=True, diff --git a/packages/executor/src/groovy/executor/provenance.py b/packages/executor/src/groovy/executor/provenance.py index a8ae489..5f40eef 100644 --- a/packages/executor/src/groovy/executor/provenance.py +++ b/packages/executor/src/groovy/executor/provenance.py @@ -210,6 +210,13 @@ def build_record( model.update(model_metadata) model["registry_id"] = str(model_id) model["role"] = "base" + if "runtime_id" not in model: + try: + from groovy.registry.runtimes import resolve_runtime_id + + model["runtime_id"] = resolve_runtime_id(str(model_id)) + except Exception: + model["runtime_id"] = "R-studio-default" models.append(model) lora_id = widgets.get("lora") if isinstance(lora_id, str) and lora_id.strip(): diff --git a/packages/model-registry/src/groovy/registry/agent/install_recovery.py b/packages/model-registry/src/groovy/registry/agent/install_recovery.py index 9df4b48..2457ff3 100644 --- a/packages/model-registry/src/groovy/registry/agent/install_recovery.py +++ b/packages/model-registry/src/groovy/registry/agent/install_recovery.py @@ -20,14 +20,31 @@ def install_recovery( manifest = catalog.get(model_id) fixes = _suggested_fixes(base.get("error") or "", manifest) explain = _explain_failure(base.get("summary") or "", base.get("error") or "", manifest) + action = _recovery_action(manifest, base.get("error") or "") return { **base, "explain": explain, "suggested_fixes": fixes, + "action": action, "agent": "install_recovery_v1", } +def _recovery_action(manifest: ModelManifest | None, error: str) -> str: + """HITL vocabulary: install_runtime vs install_model (agents never author profiles).""" + from groovy.registry.runtimes import is_provisionable_sidecar, runtime_id_for_manifest + + if manifest is None: + return "install_model" + rid = runtime_id_for_manifest(manifest) + lowered = error.lower() + if is_provisionable_sidecar(rid) or ( + rid and ("sidecar" in lowered or "install ai runtime" in lowered or "r-py311-dfn" in lowered) + ): + return "install_runtime" + return "install_model" + + def _explain_failure(summary: str, error: str, manifest: ModelManifest | None) -> str: bits = [summary.strip()] if summary.strip() else [] if manifest: @@ -69,8 +86,30 @@ def _suggested_fixes(error: str, manifest: ModelManifest | None) -> list[str]: ) if manifest and manifest.id == "spleeter-2stems": fixes.append("Open template Demucs vs Open-Unmix for a Mac-real stem A/B.") - if "inference runtime not ready" in lowered or "runtime not ready" in lowered or "not importable" in lowered: - fixes.append("Reinstall from Model Browser (Cmd+K) to pull Python inference deps.") + from groovy.registry.runtimes import ( + RUNTIME_PY311_DFN, + install_runtime_cta, + is_provisionable_sidecar, + runtime_id_for_manifest, + ) + + rid = runtime_id_for_manifest(manifest) if manifest else None + if is_provisionable_sidecar(rid) or ( + "install ai runtime" in lowered + or "sidecar" in lowered + or "deepfilter" in lowered + or (rid == RUNTIME_PY311_DFN and ("runtime" in lowered or "not importable" in lowered)) + ): + name = manifest.name if manifest else "DeepFilterNet" + fixes.append( + install_runtime_cta(name, rid or RUNTIME_PY311_DFN) + + " Model Browser Install provisions the sidecar — do not recreate studio .venv." + ) + elif "inference runtime not ready" in lowered or "runtime not ready" in lowered or "not importable" in lowered: + fixes.append( + "Install model from Model Browser (Cmd+K) to pull Python inference packages " + "into the studio environment (not a family sidecar)." + ) if not fixes: fixes.append("Retry install from Model Browser or run: groovy-model install ") if manifest and (manifest.similar_models or manifest.task_types): diff --git a/packages/model-registry/src/groovy/registry/agent/llm_planner.py b/packages/model-registry/src/groovy/registry/agent/llm_planner.py index f3cc7e3..8c81b51 100644 --- a/packages/model-registry/src/groovy/registry/agent/llm_planner.py +++ b/packages/model-registry/src/groovy/registry/agent/llm_planner.py @@ -935,11 +935,20 @@ def plan_models_for_task_llm( "role": role, } ) + from groovy.registry.runtimes import install_action_vocab + + action_type, title = install_action_vocab( + resolved, + name=card.get("name"), + manifest_runtime_id=(card.get("install") or {}).get("runtime_id") + if isinstance(card.get("install"), dict) + else card.get("runtime_id"), + ) actions.append( { - "type": "install_model", + "type": action_type, "id": f"install:{resolved}", - "title": f"Install {card.get('name') or resolved}", + "title": title, "summary": card.get("name") or resolved, "rationale": rationale or f"Claude suggested “{public_name}”; remapped to local `{resolved}`.", @@ -1008,7 +1017,9 @@ def plan_models_for_task_llm( "commercial_ok": commercial_ok, "node_type": node_type, "actions": actions, - "recommend_count": len([a for a in actions if a["type"] == "install_model"]), + "recommend_count": len( + [a for a in actions if a["type"] in ("install_model", "install_runtime")] + ), "public_pick_count": len(public_picks), "notes": " ".join(part for part in note_parts if part), "mode": "plan", diff --git a/packages/model-registry/src/groovy/registry/agent/node_enricher.py b/packages/model-registry/src/groovy/registry/agent/node_enricher.py index 08e195e..44a36f2 100644 --- a/packages/model-registry/src/groovy/registry/agent/node_enricher.py +++ b/packages/model-registry/src/groovy/registry/agent/node_enricher.py @@ -92,9 +92,16 @@ }, }, "Denoise": { - "description": "Remove background noise from speech using a registry denoiser model.", + "description": ( + "Remove background noise from speech using a registry denoiser model. " + "DeepFilterNet uses a Python 3.11 AI runtime sidecar — Install AI runtime " + "from Model Browser (do not recreate studio .venv)." + ), "widgets": { - "model": "Denoise model from the registry (e.g. DeepFilterNet).", + "model": ( + "Denoise model from the registry (e.g. DeepFilterNet). " + "Missing sidecar → Install AI runtime, not reinstall-into-.venv." + ), "strength": "How aggressively to attenuate noise (0–1).", }, }, diff --git a/packages/model-registry/src/groovy/registry/agent/planner.py b/packages/model-registry/src/groovy/registry/agent/planner.py index fc46aeb..a6f9198 100644 --- a/packages/model-registry/src/groovy/registry/agent/planner.py +++ b/packages/model-registry/src/groovy/registry/agent/planner.py @@ -59,13 +59,22 @@ def plan_agent_request( actions: list[dict[str, Any]] = [] tools_used = ["recommend_models"] + from groovy.registry.runtimes import install_action_vocab + for index, item in enumerate(recommend.get("results") or []): model = item["model"] + action_type, title = install_action_vocab( + model.get("id"), + name=model.get("name"), + manifest_runtime_id=(model.get("install") or {}).get("runtime_id") + if isinstance(model.get("install"), dict) + else model.get("runtime_id"), + ) actions.append( { - "type": "install_model", + "type": action_type, "id": f"install:{model['id']}", - "title": f"Install {model['name']}", + "title": title, "summary": model.get("name") or model["id"], "rationale": item.get("rationale") or model.get("description") or model["id"], "model_id": model["id"], diff --git a/packages/model-registry/src/groovy/registry/installer.py b/packages/model-registry/src/groovy/registry/installer.py index 4a479cb..a4b5782 100644 --- a/packages/model-registry/src/groovy/registry/installer.py +++ b/packages/model-registry/src/groovy/registry/installer.py @@ -159,6 +159,29 @@ def _install_python_deps( deps = manifest.install.python_deps if not deps: return + + from groovy.registry.runtimes import RUNTIME_PY311_DFN, runtime_id_for_manifest + + runtime_id = runtime_id_for_manifest(manifest) + # DeepFilterNet family: provision uv 3.11 sidecar — never pip into studio .venv. + if runtime_id == RUNTIME_PY311_DFN: + if cancel_check and cancel_check(): + raise DownloadCancelled("Install cancelled before runtime provision") + store.mark_progress(model_id, "downloading", 0.2) + + def _progress(phase: str, frac: float) -> None: + store.mark_progress(model_id, phase, max(0.2, min(0.85, float(frac)))) + + from groovy.registry.runtime_provision import provision_runtime + + provision_runtime( + RUNTIME_PY311_DFN, + project_dir=project_dir, + deps=list(deps), + progress=_progress, + ) + return + total = len(deps) for index, dep in enumerate(deps): if cancel_check and cancel_check(): @@ -218,6 +241,20 @@ def _verify_runtime(manifest: ModelManifest, *, project_dir: Path | None = None) return if manifest.install.dev_stub: return + + from groovy.registry.runtimes import RUNTIME_PY311_DFN, runtime_id_for_manifest + + if runtime_id_for_manifest(manifest) == RUNTIME_PY311_DFN: + from groovy.registry.runtime_provision import dfn_runtime_ready + + root = project_dir or Path.cwd() + if not dfn_runtime_ready(root): + raise RuntimeError( + "Install AI runtime for DeepFilterNet " + "(Python 3.11 sidecar not ready). Retry from Model Browser (Cmd+K)." + ) + return + try: from groovy.nodes.ai.inference_env import model_inference_ready except ImportError: @@ -266,6 +303,21 @@ def _imports_verified_manifest( def _verify_imports(manifest: ModelManifest, *, project_dir: Path | None = None) -> None: if inference_stub_active(project_dir=project_dir): return + + from groovy.registry.runtimes import RUNTIME_PY311_DFN, runtime_id_for_manifest + + if runtime_id_for_manifest(manifest) == RUNTIME_PY311_DFN: + from groovy.registry.runtime_provision import dfn_runtime_ready + + root = project_dir or Path.cwd() + if not dfn_runtime_ready(root): + raise RuntimeError( + "Install AI runtime for DeepFilterNet " + "(Python 3.11 sidecar not ready). Retry from Model Browser (Cmd+K) — " + "studio .venv is not recreated for DeepFilterNet." + ) + return + missing: list[str] = [] for module in manifest.install.verify_imports: try: @@ -303,9 +355,10 @@ def _run_pip_install( raise RuntimeError( "deepfilterlib (DeepFilterNet / podcast-denoise) has no wheel for " f"Python {py_major}.{py_minor}. " - "Use Python 3.11: rm -rf .venv && ./scripts/install.sh. " - "Source builds need Rust/cargo and are not supported for cold installs." + "Install AI runtime for DeepFilterNet from Model Browser " + "(provisions a Python 3.11 sidecar — do not recreate studio .venv)." ) + # Deezer Spleeter pins TensorFlow==2.12.1 and declares Python <3.12. On 3.12+ # (GroovyUI default on modern Macs) the resolver only sees ancient TF builds. if package_name in {"spleeter", "tensorflow"} and ( @@ -353,10 +406,11 @@ def _run_pip_install( raise RuntimeError( f"Failed to install {requirement}: no usable binary wheel " f"(Python {py_major}.{py_minor}). " - "Podcast denoise needs Python 3.11 for deepfilterlib wheels. " - "Recreate: rm -rf .venv && ./scripts/install.sh. " + "Install AI runtime for DeepFilterNet from Model Browser " + "(Python 3.11 sidecar; studio .venv is not recreated). " f"Detail: {detail[:300]}" ) + raise RuntimeError(f"Failed to install {requirement}: {detail[:500]}") finally: if proc.poll() is None: @@ -401,10 +455,10 @@ def _human_error(error: str) -> str: if "cuda" in lowered or "gpu" in lowered: return "GPU/CUDA requirement not met for this model." if "failed to install" in lowered or "pip install" in lowered: - if "deepfilterlib" in lowered or "python 3.11" in lowered: + if "deepfilterlib" in lowered or "python 3.11" in lowered or "deepfilternet" in lowered: return ( - "DeepFilterNet needs Python 3.11 (deepfilterlib has no 3.12+ wheel). " - "Recreate the venv with: rm -rf .venv && ./scripts/install.sh" + "Install AI runtime for DeepFilterNet " + "(Python 3.11 sidecar — studio .venv is not recreated)." ) if "spleeter" in lowered or "tensorflow" in lowered: return ( diff --git a/packages/model-registry/src/groovy/registry/models.py b/packages/model-registry/src/groovy/registry/models.py index 4d7545a..1f4efdc 100644 --- a/packages/model-registry/src/groovy/registry/models.py +++ b/packages/model-registry/src/groovy/registry/models.py @@ -1,6 +1,6 @@ from __future__ import annotations -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, field_validator class LicenseInfo(BaseModel): @@ -25,6 +25,17 @@ class InstallSpec(BaseModel): verify_imports: list[str] = Field(default_factory=list) install_script: str | None = None dev_stub: bool = False + # Family worker id (R-…); distinct from compute.runtimes device tags. + runtime_id: str | None = None + + @field_validator("runtime_id") + @classmethod + def _allowlisted_runtime_id(cls, value: str | None) -> str | None: + if value: + from groovy.registry.runtimes import assert_allowlisted + + return assert_allowlisted(value) + return value class InferenceParam(BaseModel): diff --git a/packages/model-registry/src/groovy/registry/runtime_provision.py b/packages/model-registry/src/groovy/registry/runtime_provision.py new file mode 100644 index 0000000..549d4f3 --- /dev/null +++ b/packages/model-registry/src/groovy/registry/runtime_provision.py @@ -0,0 +1,270 @@ +"""Provision allowlisted family runtimes (uv sidecars). Never pip into studio .venv for DFN.""" + +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path +from typing import Any + +from groovy.registry.runtimes import ( + RUNTIME_PY311_DFN, + assert_allowlisted, + current_os_arch, + dfn_sidecar_enabled, + runtime_env_dir, + sidecar_python, +) + +# Map studio-seed package names that target 3.12 onto 3.11-friendly wheels. +_DFN_PACKAGE_ALIASES = { + "deepfilternet-py312": "DeepFilterNet", +} + +# Sidecar pip allowlist (B-SEC-005) — refuse free-form Hub packages into the DFN env. +_DFN_ALLOWED_PACKAGES = frozenset( + { + "torch", + "torchaudio", + "soundfile", + "scipy", + "numpy", + "deepfilternet", + "deepfilterlib", + "deepfilternet-py312", + } +) + + +def _which_uv() -> str | None: + return shutil.which("uv") + + +def _venv_python(env_dir: Path) -> Path: + if sys.platform.startswith("win"): + return env_dir / "Scripts" / "python.exe" + return env_dir / "bin" / "python" + + +def _marker_path(env_dir: Path) -> Path: + return env_dir / ".groovy-runtime-ok" + + +def _fingerprint(deps: list[dict[str, Any]], *, python: str) -> str: + payload = {"python": python, "deps": deps, "os_arch": current_os_arch()} + raw = json.dumps(payload, sort_keys=True, separators=(",", ":")) + return hashlib.sha256(raw.encode()).hexdigest()[:16] + + +def _normalize_dfn_requirement(package: str, version: str) -> str: + key = package.strip().lower() + mapped = _DFN_PACKAGE_ALIASES.get(key, package.strip()) + return f"{mapped}{version}" if version else mapped + + +def dfn_deps_from_manifest(manifest: Any) -> list[dict[str, Any]]: + deps = list(getattr(getattr(manifest, "install", None), "python_deps", None) or []) + if deps: + return deps + return [ + {"package": "torch", "version": ">=2.0.0"}, + {"package": "torchaudio", "version": ">=2.0.0"}, + {"package": "DeepFilterNet", "version": ">=0.5.6"}, + {"package": "deepfilterlib", "version": "==0.5.6"}, + ] + + +def provision_runtime( + runtime_id: str, + *, + project_dir: Path, + deps: list[dict[str, Any]] | None = None, + progress: Any | None = None, +) -> Path: + """Create/update an allowlisted sidecar env. Returns path to python.""" + rid = assert_allowlisted(runtime_id) + if rid != RUNTIME_PY311_DFN: + raise RuntimeError( + f"Provisioner for {rid} is not implemented yet " + "(studio-default / ACE use the studio interpreter)." + ) + if not dfn_sidecar_enabled(): + raise RuntimeError( + "DFN sidecar is disabled (GROOVY_DFN_SIDECAR=0). " + "Re-enable the sidecar — DeepFilterNet is not installed into studio .venv." + ) + + uv = _which_uv() + if not uv: + raise RuntimeError( + "Install AI runtime for DeepFilterNet needs `uv` " + "(https://docs.astral.sh/uv/) to bootstrap Python 3.11." + ) + + env_dir = runtime_env_dir(project_dir, rid) + env_dir.parent.mkdir(parents=True, exist_ok=True) + py = _venv_python(env_dir) + marker = _marker_path(env_dir) + req_deps = deps or [ + {"package": "torch", "version": ">=2.0.0"}, + {"package": "torchaudio", "version": ">=2.0.0"}, + {"package": "DeepFilterNet", "version": ">=0.5.6"}, + {"package": "deepfilterlib", "version": "==0.5.6"}, + ] + fp = _fingerprint(req_deps, python="3.11") + + if py.is_file() and marker.is_file(): + try: + prev = json.loads(marker.read_text()) + except (OSError, json.JSONDecodeError): + prev = {} + if prev.get("fingerprint") == fp and _probe_dfn(py): + return py + + if progress: + progress("provisioning", 0.2) + + install_py = subprocess.run( + [uv, "python", "install", "3.11"], + capture_output=True, + text=True, + ) + if install_py.returncode != 0: + detail = (install_py.stderr or install_py.stdout or "").strip() + raise RuntimeError( + "Could not install Python 3.11 via uv for DeepFilterNet runtime. " + f"{detail[:400]}" + ) + + if env_dir.exists() and not py.is_file(): + shutil.rmtree(env_dir, ignore_errors=True) + + if not py.is_file(): + create = subprocess.run( + [uv, "venv", "--python", "3.11", str(env_dir)], + capture_output=True, + text=True, + ) + if create.returncode != 0 or not py.is_file(): + detail = (create.stderr or create.stdout or "").strip() + raise RuntimeError( + f"Could not create DeepFilterNet runtime at {env_dir}: {detail[:400]}" + ) + + if progress: + progress("installing", 0.45) + + for dep in req_deps: + package = str(dep.get("package", "")).strip() + if not package: + continue + if package.lower() not in _DFN_ALLOWED_PACKAGES: + raise RuntimeError( + f"Refusing non-allowlisted package {package!r} for DeepFilterNet runtime. " + f"Allowed: {', '.join(sorted(_DFN_ALLOWED_PACKAGES))}." + ) + version = str(dep.get("version", "")).strip() + requirement = _normalize_dfn_requirement(package, version) + cmd = [uv, "pip", "install", "--python", str(py)] + # deepfilterlib: wheels only — never compile Rust into the sidecar. + if package.lower() == "deepfilterlib": + cmd.append("--only-binary=:all:") + if dep.get("no_deps"): + cmd.append("--no-deps") + cmd.append(requirement) + pip = subprocess.run(cmd, capture_output=True, text=True) + if pip.returncode != 0: + detail = (pip.stderr or pip.stdout or "").strip() + raise RuntimeError( + f"Failed to install {requirement} into DeepFilterNet runtime: {detail[:500]}" + ) + + if progress: + progress("verifying", 0.9) + + if not _probe_dfn(py): + raise RuntimeError( + "DeepFilterNet runtime provisioned but df.enhance is not importable. " + "Retry Install from Model Browser." + ) + + marker.write_text( + json.dumps( + { + "runtime_id": rid, + "fingerprint": fp, + "python": "3.11", + "os_arch": current_os_arch(), + }, + indent=2, + ) + + "\n" + ) + return py + + +def _probe_dfn(py: Path) -> bool: + # DeepFilterNet still imports removed torchaudio.backend / AudioMetaData APIs. + script = r""" +import sys, types +from dataclasses import dataclass +import torchaudio as ta + +@dataclass +class _AudioMetaData: + sample_rate: int + num_frames: int = 0 + num_channels: int = 1 + +if not hasattr(ta, "AudioMetaData"): + ta.AudioMetaData = _AudioMetaData +if "torchaudio.backend.common" not in sys.modules: + common = types.ModuleType("torchaudio.backend.common") + common.AudioMetaData = _AudioMetaData + backend = types.ModuleType("torchaudio.backend") + backend.common = common + sys.modules["torchaudio.backend.common"] = common + sys.modules["torchaudio.backend"] = backend + +import df.enhance # noqa: F401 +import libdf # noqa: F401 +""" + env = { + k: v + for k, v in os.environ.items() + if k not in {"HF_TOKEN", "HUGGING_FACE_HUB_TOKEN", "ANTHROPIC_API_KEY"} + } + probe = subprocess.run( + [str(py), "-c", script], + capture_output=True, + text=True, + env=env, + ) + return probe.returncode == 0 + + +def dfn_runtime_ready(project_dir: Path) -> bool: + if not dfn_sidecar_enabled(): + # Legacy: only if already importable in studio — never trigger studio pip. + try: + from groovy.nodes.ai.deepfilter_compat import deepfilternet_available_inprocess + + return deepfilternet_available_inprocess() + except Exception: + return False + py = sidecar_python(project_dir, RUNTIME_PY311_DFN) + if py is None: + return False + marker = _marker_path(runtime_env_dir(project_dir, RUNTIME_PY311_DFN)) + return marker.is_file() and _probe_dfn(py) + + +def ensure_dfn_python(project_dir: Path, *, deps: list[dict[str, Any]] | None = None) -> Path: + existing = sidecar_python(project_dir, RUNTIME_PY311_DFN) + if existing and dfn_runtime_ready(project_dir): + return existing + return provision_runtime(RUNTIME_PY311_DFN, project_dir=project_dir, deps=deps) diff --git a/packages/model-registry/src/groovy/registry/runtimes.py b/packages/model-registry/src/groovy/registry/runtimes.py new file mode 100644 index 0000000..07ae297 --- /dev/null +++ b/packages/model-registry/src/groovy/registry/runtimes.py @@ -0,0 +1,225 @@ +"""Family runtime profiles for multi-model isolation. + +Canonical ``runtime_id`` values use the ``R-…`` scheme from +``docs/internal/TEMPLATE_MODEL_ENV_CONFLICTS.md``. Distinct from seed +``compute.runtimes`` (cpu/cuda/mps device tags). +""" + +from __future__ import annotations + +import os +import platform +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +# Allowlisted family ids only — provision refuses anything else (B-SEC-005). +RUNTIME_STUDIO_DEFAULT = "R-studio-default" +RUNTIME_PY311_DFN = "R-py311-dfn" +RUNTIME_TORCH_ACE = "R-torch-ace" +RUNTIME_MLX_STEP = "R-mlx-step" + +ALLOWED_RUNTIME_IDS: frozenset[str] = frozenset( + { + RUNTIME_STUDIO_DEFAULT, + RUNTIME_PY311_DFN, + RUNTIME_TORCH_ACE, + RUNTIME_MLX_STEP, + } +) + +# Families that still cannot share one worker process (post-DFN isolation). +# DFN is intentionally absent — it runs in a uv 3.11 sidecar. +HARD_MUTEX_GROUPS: tuple[frozenset[str], ...] = ( + frozenset({"R-tf-spleeter", "R-torch-ace", "R-torch-stems", "R-torch-asr", RUNTIME_STUDIO_DEFAULT}), +) + + +@dataclass(frozen=True) +class RuntimeProfile: + runtime_id: str + python: str + os_arch: tuple[str, ...] + accel: tuple[str, ...] + description: str + + +PROFILES: dict[str, RuntimeProfile] = { + RUNTIME_STUDIO_DEFAULT: RuntimeProfile( + runtime_id=RUNTIME_STUDIO_DEFAULT, + python=f"{sys.version_info.major}.{sys.version_info.minor}", + os_arch=("darwin-arm64", "darwin-x86_64", "linux-x86_64", "win-amd64"), + accel=("cpu", "cuda", "mps"), + description="Studio interpreter (shared Real worker)", + ), + RUNTIME_PY311_DFN: RuntimeProfile( + runtime_id=RUNTIME_PY311_DFN, + python="3.11", + os_arch=("darwin-arm64", "darwin-x86_64", "linux-x86_64", "win-amd64"), + accel=("cpu", "cuda"), + description="DeepFilterNet / deepfilterlib (Python 3.11 sidecar)", + ), + RUNTIME_TORCH_ACE: RuntimeProfile( + runtime_id=RUNTIME_TORCH_ACE, + python="3.12", + os_arch=("darwin-arm64", "linux-x86_64", "win-amd64"), + accel=("cuda", "cpu", "mps"), + description="ACE-Step Diffusers family", + ), + RUNTIME_MLX_STEP: RuntimeProfile( + runtime_id=RUNTIME_MLX_STEP, + python="3.13", + os_arch=("darwin-arm64",), + accel=("mlx", "cuda"), + description="Step-Audio-EditX MLX sidecar", + ), +} + + +def dfn_sidecar_enabled() -> bool: + """Feature flag: DFN uses uv 3.11 sidecar (default on). + + Set ``GROOVY_DFN_SIDECAR=0`` only for legacy in-process probe when DeepFilterNet + is already importable in the studio env. Installer never pip-installs DFN into + studio ``.venv`` either way. + """ + raw = os.environ.get("GROOVY_DFN_SIDECAR", "1").strip().lower() + return raw not in {"0", "false", "no", "off"} + + +def assert_allowlisted(runtime_id: str) -> str: + rid = (runtime_id or "").strip() + if rid not in ALLOWED_RUNTIME_IDS: + raise ValueError( + f"runtime_id {runtime_id!r} is not allowlisted. " + f"Allowed: {', '.join(sorted(ALLOWED_RUNTIME_IDS))}" + ) + return rid + + +def resolve_runtime_id(model_id: str | None, *, manifest_runtime_id: str | None = None) -> str: + """Resolve catalog runtime for a model id.""" + if manifest_runtime_id and str(manifest_runtime_id).strip(): + return assert_allowlisted(str(manifest_runtime_id).strip()) + mid = (model_id or "").strip() + if mid == "deepfilternet-v3": + return RUNTIME_PY311_DFN + if mid.startswith("ace-step"): + return RUNTIME_TORCH_ACE + if mid == "step-audio-editx": + return RUNTIME_MLX_STEP + return RUNTIME_STUDIO_DEFAULT + + +def runtime_id_for_manifest(manifest: Any) -> str: + install = getattr(manifest, "install", None) + declared = getattr(install, "runtime_id", None) if install is not None else None + return resolve_runtime_id(getattr(manifest, "id", None), manifest_runtime_id=declared) + + +def current_os_arch() -> str: + system = platform.system().lower() + machine = platform.machine().lower() + if system == "darwin": + sys_name = "darwin" + elif system == "linux": + sys_name = "linux" + elif system in {"windows", "win32"}: + sys_name = "win" + else: + sys_name = system + if machine in {"arm64", "aarch64"}: + arch = "arm64" + elif machine in {"x86_64", "amd64"}: + arch = "x86_64" if sys_name != "win" else "amd64" + else: + arch = machine + return f"{sys_name}-{arch}" + + +def runtimes_root(project_dir: Path) -> Path: + """Provision roots live under ``.groovy/runtimes/`` (outside signed app tree).""" + root = (project_dir.resolve() / ".groovy" / "runtimes").resolve() + groovy = (project_dir.resolve() / ".groovy").resolve() + if groovy not in root.parents and root != groovy: + # Path jail: must stay under project .groovy + raise RuntimeError(f"Refusing runtime root outside .groovy: {root}") + return root + + +def runtime_env_dir(project_dir: Path, runtime_id: str) -> Path: + rid = assert_allowlisted(runtime_id) + root = runtimes_root(project_dir) + env = (root / rid).resolve() + if root not in env.parents and env != root: + raise RuntimeError(f"Refusing runtime env path outside jail: {env}") + return env + + +def sidecar_python(project_dir: Path, runtime_id: str) -> Path | None: + """Return interpreter path if the sidecar venv exists.""" + env = runtime_env_dir(project_dir, runtime_id) + if platform.system() == "Windows": + py = env / "Scripts" / "python.exe" + else: + py = env / "bin" / "python" + return py if py.is_file() else None + + +def hard_conflicts(runtime_ids: set[str]) -> list[tuple[str, str]]: + """Return pairs that cannot co-render on this machine (post-DFN isolation). + + DFN (``R-py311-dfn``) is isolated via sidecar and does not conflict with studio + / ACE families. Remaining HARD cases are reserved for TF/Spleeter-class stacks. + """ + ids = {r for r in runtime_ids if r and r != RUNTIME_PY311_DFN} + conflicts: list[tuple[str, str]] = [] + if "R-tf-spleeter" in ids: + for other in sorted(ids - {"R-tf-spleeter"}): + if other.startswith("R-torch") or other == RUNTIME_STUDIO_DEFAULT: + conflicts.append(("R-tf-spleeter", other)) + return conflicts + + +# Sidecars that Model Browser / pre-Render provision via Install (not studio pip). +PROVISIONABLE_SIDECAR_IDS: frozenset[str] = frozenset( + { + RUNTIME_PY311_DFN, + # Step EditX bootstraps on first Real edit today; keep off Install-runtime CTA + # until provision is Install-owned (B-UX-006 / Step parity). + } +) + + +def is_provisionable_sidecar(runtime_id: str | None) -> bool: + return bool(runtime_id) and str(runtime_id).strip() in PROVISIONABLE_SIDECAR_IDS + + +def install_runtime_cta(model_name: str, runtime_id: str) -> str: + """Model-named Install-runtime copy (no raw jargon as primary UX).""" + label = model_name or "this model" + if runtime_id == RUNTIME_PY311_DFN: + return ( + f"Install AI runtime for {label} " + "(DeepFilterNet needs a Python 3.11 sidecar — studio .venv is not recreated)." + ) + return f"Install AI runtime for {label}." + + +def install_action_vocab( + model_id: str | None, + *, + name: str | None = None, + manifest_runtime_id: str | None = None, +) -> tuple[str, str]: + """HITL plan action type + title for agents (never author profiles). + + Returns ``(action_type, title)`` where action_type is + ``install_runtime`` or ``install_model``. + """ + rid = resolve_runtime_id(model_id, manifest_runtime_id=manifest_runtime_id) + label = (name or model_id or "model").strip() or "model" + if is_provisionable_sidecar(rid): + return "install_runtime", f"Install AI runtime for {label}" + return "install_model", f"Install {label}" diff --git a/packages/model-registry/src/groovy/registry/seed.json b/packages/model-registry/src/groovy/registry/seed.json index e954e5b..c481135 100644 --- a/packages/model-registry/src/groovy/registry/seed.json +++ b/packages/model-registry/src/groovy/registry/seed.json @@ -29,6 +29,7 @@ "Denoise" ], "install": { + "runtime_id": "R-py311-dfn", "python_deps": [ { "package": "torch", @@ -39,8 +40,16 @@ "version": ">=2.0.0" }, { - "package": "DeepFilterNet-py312", - "version": ">=0.5.7" + "package": "soundfile", + "version": ">=0.12.0" + }, + { + "package": "scipy", + "version": ">=1.10.0" + }, + { + "package": "DeepFilterNet", + "version": ">=0.5.6" }, { "package": "deepfilterlib", @@ -65,7 +74,7 @@ "description": "Denoising blend (0 = dry, 1 = full noise reduction)." } ], - "architecture_notes": "DeepFilterNet: ERB + Deep Filtering stages on STFT features → enhanced waveform.", + "architecture_notes": "DeepFilterNet: ERB + Deep Filtering stages on STFT features → enhanced waveform. Runs in uv Python 3.11 sidecar (R-py311-dfn); studio .venv is not recreated.", "internal_connections": [ { "from": "noisy audio", @@ -742,6 +751,7 @@ "VoiceConvert" ], "install": { + "runtime_id": "R-mlx-step", "dev_stub": false, "python_deps": [ { @@ -2093,6 +2103,7 @@ "GenerateAudio" ], "install": { + "runtime_id": "R-torch-ace", "dev_stub": false, "python_deps": [ { @@ -2208,6 +2219,7 @@ "GenerateAudio" ], "install": { + "runtime_id": "R-torch-ace", "dev_stub": false, "python_deps": [ { @@ -2323,6 +2335,7 @@ "GenerateAudio" ], "install": { + "runtime_id": "R-torch-ace", "dev_stub": false, "python_deps": [ { diff --git a/scripts/dev.sh b/scripts/dev.sh index a5fc8a1..e67e8b2 100755 --- a/scripts/dev.sh +++ b/scripts/dev.sh @@ -60,9 +60,8 @@ if [[ -n "${PY_VER}" ]]; then MAJOR="${PY_VER%%.*}" MINOR="${PY_VER#*.}" if [[ "${MAJOR}" -gt 3 ]] || { [[ "${MAJOR}" -eq 3 ]] && [[ "${MINOR}" -ge 12 ]]; }; then - echo "Warning: .venv is Python ${PY_VER}. Podcast denoise (DeepFilterNet) needs 3.11" >&2 - echo " (deepfilterlib has no 3.12+ wheel). Recreate with:" >&2 - echo " rm -rf .venv && ./scripts/install.sh" >&2 + echo "Note: .venv is Python ${PY_VER}. DeepFilterNet uses a Python 3.11 sidecar" >&2 + echo " (Install AI runtime for DeepFilterNet from Model Browser — do not recreate .venv)." >&2 fi fi if [[ ! -d apps/studio/node_modules ]] && ! command -v pnpm >/dev/null 2>&1; then diff --git a/scripts/install.sh b/scripts/install.sh index ef8bfe5..7c29b8c 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1,5 +1,7 @@ #!/usr/bin/env bash -# One-time install: Python 3.11 venv + workspace sync + Studio UI deps. +# One-time install: Python venv + workspace sync + Studio UI deps. +# DeepFilterNet uses a separate Python 3.11 sidecar (Model Browser Install) — +# studio .venv is not forced onto 3.11 for DFN. # Usage (from repo root): ./scripts/install.sh # Optional: ./scripts/install.sh --inference # also pull AI inference extras set -euo pipefail @@ -43,18 +45,18 @@ fi if [[ -d .venv ]]; then PY_VER="$("$ROOT/.venv/bin/python" -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")' 2>/dev/null || true)" if [[ -n "${PY_VER}" ]]; then - MAJOR="${PY_VER%%.*}" - MINOR="${PY_VER#*.}" - if [[ "${MAJOR}" -gt 3 ]] || { [[ "${MAJOR}" -eq 3 ]] && [[ "${MINOR}" -ge 12 ]]; }; then - echo "Existing .venv is Python ${PY_VER}; recreating with 3.11 (DeepFilterNet wheels)." - rm -rf .venv - fi + echo "Keeping existing .venv (Python ${PY_VER}). DeepFilterNet installs into a 3.11 sidecar." fi fi -echo "==> Python 3.11 venv" +echo "==> Python venv (3.12 preferred; 3.11 OK)" if [[ ! -d .venv ]]; then - uv venv --python 3.11 + if uv venv --python 3.12; then + : + else + echo "Python 3.12 unavailable via uv; falling back to 3.11" + uv venv --python 3.11 + fi fi echo "==> Sync workspace packages" @@ -65,7 +67,7 @@ fi uv "${SYNC_ARGS[@]}" if [[ "${WITH_INFERENCE}" -eq 1 ]]; then - # basic-pitch: --no-deps avoids tensorflow pins on Python 3.12+ (we stay on 3.11). + # basic-pitch: --no-deps avoids tensorflow pins on Python 3.12+. uv pip install "basic-pitch==0.4.0" --no-deps fi diff --git a/server/src/groovy/server/main.py b/server/src/groovy/server/main.py index 9adcb60..edda1d5 100644 --- a/server/src/groovy/server/main.py +++ b/server/src/groovy/server/main.py @@ -151,6 +151,8 @@ def _model_provenance_metadata(model_id: str) -> dict[str, Any] | None: weights_hash_status = "partial" else: weights_hash_status = "unavailable" + from groovy.registry.runtimes import runtime_id_for_manifest + return { "name": manifest.name, "version": install_state.version, @@ -159,6 +161,7 @@ def _model_provenance_metadata(model_id: str) -> dict[str, Any] | None: "license": manifest.license.model_dump(), "weights": weights, "weights_hash_status": weights_hash_status, + "runtime_id": runtime_id_for_manifest(manifest), } @@ -1483,7 +1486,11 @@ def _installed_models_payload() -> dict[str, Any]: "can_remove": not busy, "task_types": list(manifest.task_types) if manifest else [], "inference_ready": ( - model_inference_ready(model_id, dev_stub=manifest.install.dev_stub) + model_inference_ready( + model_id, + dev_stub=manifest.install.dev_stub, + project_dir=str(PROJECT_DIR), + ) if manifest else False ), @@ -1532,15 +1539,22 @@ def _model_card(manifest) -> dict[str, Any]: state = _registry.store.get(manifest.id) from groovy.nodes.ai.inference_env import model_inference_ready from groovy.registry.compute import resolve_compute + from groovy.registry.runtimes import runtime_id_for_manifest + runtime_id = runtime_id_for_manifest(manifest) return { **manifest.model_dump(), "install_status": state.status, "install_progress": state.progress, "install_error": state.error, "dev_stub": manifest.install.dev_stub, - "inference_ready": model_inference_ready(manifest.id, dev_stub=manifest.install.dev_stub), - "install_complete": model_install_complete(manifest, state), + "runtime_id": runtime_id, + "inference_ready": model_inference_ready( + manifest.id, + dev_stub=manifest.install.dev_stub, + project_dir=str(PROJECT_DIR), + ), + "install_complete": model_install_complete(manifest, state, project_dir=PROJECT_DIR), # Resolved affinity for Model Browser hardware presets / card labels. "compute_resolved": resolve_compute(manifest), } diff --git a/tests/test_agent_plan.py b/tests/test_agent_plan.py index 77ff23d..710ab1a 100644 --- a/tests/test_agent_plan.py +++ b/tests/test_agent_plan.py @@ -68,10 +68,20 @@ def test_plan_podcast_returns_actions(tmp_path: Path) -> None: assert "recommend_models" in result["tools_used"] assert "suggest_workflows" not in result["tools_used"] types = {action["type"] for action in result["actions"]} - assert "install_model" in types + # DeepFilterNet uses install_runtime (sidecar); other models use install_model. + assert "install_runtime" in types or "install_model" in types assert "apply_template" not in types assert "propose_workflow" not in types - assert all(action["type"] in {"install_model", "drop_node"} for action in result["actions"]) + assert all( + action["type"] in {"install_model", "install_runtime", "drop_node"} + for action in result["actions"] + ) + dfn = next( + (a for a in result["actions"] if a.get("model_id") == "deepfilternet-v3"), + None, + ) + if dfn is not None: + assert dfn["type"] == "install_runtime" assert "Model Plan" in result["notes"] diff --git a/tests/test_cold_machine_hero.py b/tests/test_cold_machine_hero.py index dd52638..e871cc9 100644 --- a/tests/test_cold_machine_hero.py +++ b/tests/test_cold_machine_hero.py @@ -139,3 +139,34 @@ def test_transcribe_dialogue_cold_machine_gate(project_dir: Path) -> None: assert saved.name.startswith("dialogue-source-") assert saved.exists() assert saved.stat().st_size > 1_000 + + +def test_dfn_whisper_cofile_cold_machine_gate(project_dir: Path) -> None: + """B-QA-004: same project — DFN sidecar + Whisper studio worker both Real-green.""" + registry = ModelRegistry(project_dir) + dfn = registry.installer.install("deepfilternet-v3") + assert dfn.status == "ready", dfn.error + whisper = registry.installer.install("whisper-large-v3-turbo") + assert whisper.status == "ready", whisper.error + assert whisper_available(), "faster_whisper unavailable after Model Browser install" + + from groovy.registry.runtime_provision import dfn_runtime_ready + + assert dfn_runtime_ready(project_dir), "DFN sidecar must be ready in the same project as Whisper" + + podcast = Workflow.model_validate(json.loads(PODCAST.read_text())) + for node in podcast.nodes: + if node.type == "LoadAudio": + node.widgets["path"] = "assets/samples/podcast_denoise_demo.wav" + executor = Executor(project_dir) + denoise = executor.execute(podcast, target_nodes=["n4", "n5"], force_rebuild=True) + assert denoise.status == "completed", denoise.error + + dialogue_wf = Workflow.model_validate(json.loads(DIALOGUE.read_text())) + for node in dialogue_wf.nodes: + if node.type == "LoadAudio": + node.widgets["path"] = "assets/samples/dialogue_48k.wav" + stt = executor.execute(dialogue_wf, target_nodes=["n2", "n5"], force_rebuild=True) + assert stt.status == "completed", stt.error + text = (stt.outputs["n2"].get("text") or "").strip() + assert text, "Whisper returned empty transcript after DFN sidecar install on same project" diff --git a/tests/test_dfn_sidecar_pcm_contract.py b/tests/test_dfn_sidecar_pcm_contract.py new file mode 100644 index 0000000..19404a0 --- /dev/null +++ b/tests/test_dfn_sidecar_pcm_contract.py @@ -0,0 +1,29 @@ +"""DSP contract at the DFN sidecar WAV IPC boundary (B-DSP-007).""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import soundfile as sf + +import groovy.nodes.ai.backends.deepfilternet_runner as dfn_runner + + +def test_sidecar_wav_roundtrip_layout(tmp_path: Path) -> None: + pcm = np.zeros((2, 4800), dtype=np.float32) + out_wav = tmp_path / "out.wav" + sf.write(str(out_wav), pcm.T, 48000) + wav, sr = sf.read(str(out_wav), always_2d=True) + out = wav.T.astype(np.float32) + assert int(sr) == 48000 + assert out.shape == (2, 4800) + assert out.dtype == np.float32 + + +def test_dfn_runner_fail_loud_and_no_mid_render_provision() -> None: + src = Path(dfn_runner.__file__).read_text() + assert "Unexpected init_df() return arity" in src + assert "sample-rate mismatch" in src + assert "does not bootstrap" in src + assert "ensure_dfn_python" not in src diff --git a/tests/test_install_recovery.py b/tests/test_install_recovery.py index b889133..e7bc3cb 100644 --- a/tests/test_install_recovery.py +++ b/tests/test_install_recovery.py @@ -27,5 +27,21 @@ def test_install_recovery_inference_runtime_not_ready(tmp_path) -> None: registry.catalog, registry.store, registry.installer, "demucs-v4" ) assert result["agent"] == "install_recovery_v1" + assert result["action"] == "install_model" joined = " ".join(result["suggested_fixes"]).lower() - assert "reinstall" in joined or "python" in joined or "deps" in joined + assert "install model" in joined or "python" in joined or "deps" in joined + + +def test_install_recovery_dfn_uses_install_runtime(tmp_path) -> None: + registry = ModelRegistry(tmp_path) + registry.store.mark_failed( + "deepfilternet-v3", + "Install AI runtime for DeepFilterNet (Python 3.11 sidecar not ready).", + ) + result = install_recovery( + registry.catalog, registry.store, registry.installer, "deepfilternet-v3" + ) + assert result["action"] == "install_runtime" + joined = " ".join(result["suggested_fixes"]).lower() + assert "install ai runtime" in joined + assert "recreate studio .venv" in joined or "sidecar" in joined diff --git a/tests/test_model_browser_runtime.py b/tests/test_model_browser_runtime.py index ebe21ab..917197e 100644 --- a/tests/test_model_browser_runtime.py +++ b/tests/test_model_browser_runtime.py @@ -72,11 +72,14 @@ def test_model_install_complete_requires_runtime(monkeypatch: pytest.MonkeyPatch assert complete in {True, False} -def test_deepfilternet_seed_uses_numpy2_fork() -> None: +def test_deepfilternet_seed_uses_py311_sidecar() -> None: + """DFN pins upstream DeepFilterNet into R-py311-dfn — not studio DeepFilterNet-py312.""" manifest = ModelCatalog().get("deepfilternet-v3") assert manifest is not None + assert manifest.install.runtime_id == "R-py311-dfn" packages = {dep["package"] for dep in manifest.install.python_deps} - assert "DeepFilterNet-py312" in packages + assert "DeepFilterNet" in packages + assert "DeepFilterNet-py312" not in packages assert "deepfilterlib" in packages assert "torch" in packages assert "torchaudio" in packages diff --git a/tests/test_rescore_video.py b/tests/test_rescore_video.py index c4b7f4a..ac63904 100644 --- a/tests/test_rescore_video.py +++ b/tests/test_rescore_video.py @@ -182,11 +182,11 @@ def test_rescore_video_template_schema_and_stub_render(tmp_path: Path, monkeypat ) by_id = {n["id"]: n for n in data["nodes"]} - assert by_id["n0"]["widgets"]["path"] == "assets/samples/Cyberpunk-station-5s.mp4" + assert by_id["n0"]["widgets"]["path"] == "assets/samples/Cyberpunk-station.mp4" assert by_id["n3"]["widgets"]["model"] == "ace-step-1.5-sft" assert by_id["n3"]["widgets"]["num_inference_steps"] == 72 assert by_id["n3"]["widgets"]["guidance_scale"] == 9.0 - assert by_id["n3"]["widgets"]["seconds_total"] == 5.0 + assert by_id["n3"]["widgets"]["seconds_total"] == 2.0 assert by_id["n3"]["widgets"]["seed"] == 43 assert by_id["n2"]["type"] == "BatchPrompt" prompts_raw = by_id["n2"]["widgets"]["prompts"] @@ -299,11 +299,15 @@ def test_rescore_video_template_schema_and_stub_render(tmp_path: Path, monkeypat samples = tmp_path / "assets" / "samples" samples.mkdir(parents=True) - src = Path(__file__).resolve().parents[1] / "assets" / "samples" / "Cyberpunk-station-5s.mp4" + src = Path(__file__).resolve().parents[1] / "assets" / "samples" / "Cyberpunk-station.mp4" if src.is_file(): - (samples / "Cyberpunk-station-5s.mp4").write_bytes(src.read_bytes()) + (samples / "Cyberpunk-station.mp4").write_bytes(src.read_bytes()) else: - _write_av_mov(samples / "Cyberpunk-station-5s.mp4", seconds=1.0) + alt = Path(__file__).resolve().parents[1] / "assets" / "samples" / "Cyberpunk-station-5s.mp4" + if alt.is_file(): + (samples / "Cyberpunk-station.mp4").write_bytes(alt.read_bytes()) + else: + _write_av_mov(samples / "Cyberpunk-station.mp4", seconds=1.0) registry = ModelRegistry(tmp_path) registry.installer.install("ace-step-1.5-sft") diff --git a/tests/test_runtime_dfn_ace_coexist.py b/tests/test_runtime_dfn_ace_coexist.py new file mode 100644 index 0000000..5ce507a --- /dev/null +++ b/tests/test_runtime_dfn_ace_coexist.py @@ -0,0 +1,24 @@ +"""Stub-mode proof: DFN + ACE families can coexist (no HARD mutex; templates present).""" + +from __future__ import annotations + +from pathlib import Path + +from groovy.registry.runtimes import ( + RUNTIME_PY311_DFN, + RUNTIME_TORCH_ACE, + hard_conflicts, + resolve_runtime_id, +) + + +def test_dfn_ace_families_coexist_without_hard_conflict() -> None: + assert resolve_runtime_id("deepfilternet-v3") == RUNTIME_PY311_DFN + assert resolve_runtime_id("ace-step-1.5-sft") == RUNTIME_TORCH_ACE + assert hard_conflicts({RUNTIME_PY311_DFN, RUNTIME_TORCH_ACE}) == [] + + +def test_podcast_denoise_and_ace_template_ids_present() -> None: + root = Path(__file__).resolve().parents[1] / "templates" + assert (root / "podcast-denoise.groovy.json").is_file() + assert (root / "ace-step-1.5-sft.groovy.json").is_file() diff --git a/tests/test_runtime_isolation.py b/tests/test_runtime_isolation.py new file mode 100644 index 0000000..f401342 --- /dev/null +++ b/tests/test_runtime_isolation.py @@ -0,0 +1,148 @@ +"""Multi-model runtime isolation — schema, router hooks, cache, fail-closed.""" + +from __future__ import annotations + +import os +from pathlib import Path + +import pytest + +from groovy.executor.node_cache import compute_node_signature +from groovy.executor.provenance import build_record +from groovy.registry.models import InstallSpec, LicenseInfo, ModelManifest +from groovy.registry.runtimes import ( + ALLOWED_RUNTIME_IDS, + RUNTIME_PY311_DFN, + RUNTIME_STUDIO_DEFAULT, + RUNTIME_TORCH_ACE, + assert_allowlisted, + dfn_sidecar_enabled, + hard_conflicts, + resolve_runtime_id, + runtime_env_dir, + runtime_id_for_manifest, +) + + +def test_allowlist_rejects_unknown() -> None: + with pytest.raises(ValueError, match="not allowlisted"): + assert_allowlisted("R-evil-shell") + + +def test_canonical_ids_include_dfn_and_ace() -> None: + assert RUNTIME_PY311_DFN in ALLOWED_RUNTIME_IDS + assert RUNTIME_TORCH_ACE in ALLOWED_RUNTIME_IDS + assert resolve_runtime_id("deepfilternet-v3") == RUNTIME_PY311_DFN + assert resolve_runtime_id("ace-step-1.5-sft") == RUNTIME_TORCH_ACE + + +def test_manifest_runtime_id_wins() -> None: + m = ModelManifest( + id="deepfilternet-v3", + name="DFN", + description="x", + task_types=["denoise"], + license=LicenseInfo(spdx="MIT", commercial_ok=True), + install=InstallSpec(runtime_id=RUNTIME_PY311_DFN), + ) + assert runtime_id_for_manifest(m) == RUNTIME_PY311_DFN + + +def test_dfn_ace_not_hard_conflict_after_isolation() -> None: + """Sidecar isolation: DFN + ACE may co-render; no HARD mutex.""" + assert hard_conflicts({RUNTIME_PY311_DFN, RUNTIME_TORCH_ACE}) == [] + assert hard_conflicts({RUNTIME_PY311_DFN, RUNTIME_STUDIO_DEFAULT}) == [] + + +def test_runtime_env_path_jail(tmp_path: Path) -> None: + env = runtime_env_dir(tmp_path, RUNTIME_PY311_DFN) + assert env.is_relative_to(tmp_path / ".groovy" / "runtimes") + + +def test_cache_signature_includes_runtime_id() -> None: + a = compute_node_signature( + "Denoise", + {"model": "deepfilternet-v3", "strength": 1.0, "_runtime_id": RUNTIME_PY311_DFN}, + {}, + ) + b = compute_node_signature( + "Denoise", + {"model": "deepfilternet-v3", "strength": 1.0, "_runtime_id": "legacy-studio"}, + {}, + ) + assert a != b + + +def test_provenance_models_carry_runtime_id() -> None: + record = build_record( + cache_id="c1", + content_hash="sha256:abc", + node_id="n1", + node_type="Denoise", + widgets={"model": "deepfilternet-v3"}, + node_cls=type("N", (), {"PROVENANCE_CLASS": "ai_generated"}), + job_id="j1", + workflow_id="w1", + groovy_version="0.1.0", + executor_version="0.1.0", + parent_records=[], + parent_refs_list=[], + model_metadata={"runtime_id": RUNTIME_PY311_DFN}, + ) + assert record["models"][0]["runtime_id"] == RUNTIME_PY311_DFN + + +def test_dfn_sidecar_flag_matrix(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("GROOVY_DFN_SIDECAR", raising=False) + assert dfn_sidecar_enabled() is True + monkeypatch.setenv("GROOVY_DFN_SIDECAR", "0") + assert dfn_sidecar_enabled() is False + monkeypatch.setenv("GROOVY_DFN_SIDECAR", "1") + assert dfn_sidecar_enabled() is True + + +def test_seed_deepfilternet_declares_runtime_id() -> None: + from groovy.registry.catalog import ModelCatalog + + cat = ModelCatalog() + manifest = cat.get("deepfilternet-v3") + assert manifest is not None + assert runtime_id_for_manifest(manifest) == RUNTIME_PY311_DFN + ace = cat.get("ace-step-1.5-sft") + assert ace is not None + assert runtime_id_for_manifest(ace) == RUNTIME_TORCH_ACE + + +def test_installer_never_targets_studio_for_dfn_message() -> None: + from groovy.registry.installer import _human_error + + msg = _human_error( + "Failed to install deepfilterlib==0.5.6: no usable binary wheel (Python 3.12)." + ) + assert "rm -rf .venv" not in msg + assert "Install AI runtime" in msg + + +def test_dfn_runtime_fail_closed_when_missing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("GROOVY_DFN_SIDECAR", "1") + from groovy.registry.runtime_provision import dfn_runtime_ready + + assert dfn_runtime_ready(tmp_path) is False + + +def test_denoise_does_not_provision_mid_render(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("GROOVY_DFN_SIDECAR", "1") + monkeypatch.setenv("GROOVY_PROJECT_DIR", str(tmp_path)) + import numpy as np + from groovy.nodes.ai.backends.deepfilternet_runner import denoise_pcm + + with pytest.raises(RuntimeError, match="does not bootstrap"): + denoise_pcm(np.zeros((1, 1024), dtype=np.float32), sample_rate=48000, strength=1.0) + + +def test_provisionable_sidecar_ids() -> None: + from groovy.registry.runtimes import is_provisionable_sidecar + + assert is_provisionable_sidecar(RUNTIME_PY311_DFN) is True + assert is_provisionable_sidecar(RUNTIME_TORCH_ACE) is False + assert is_provisionable_sidecar(RUNTIME_STUDIO_DEFAULT) is False diff --git a/tests/test_runtime_isolation_gates.py b/tests/test_runtime_isolation_gates.py new file mode 100644 index 0000000..e16c42e --- /dev/null +++ b/tests/test_runtime_isolation_gates.py @@ -0,0 +1,74 @@ +"""Named gates required on every multi-model runtime isolation PR (B-QA-001 / B-QA-004).""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from groovy.registry.agent.node_enricher import enrich_node_schema +from groovy.registry.agent.planner import plan_agent_request +from groovy.registry.catalog import ModelCatalog +from groovy.registry.runtimes import ( + RUNTIME_PY311_DFN, + RUNTIME_TORCH_ACE, + dfn_sidecar_enabled, + install_action_vocab, +) +from groovy.registry.store import InstallStore + + +def test_isolation_pr_named_rescore_stub_gate(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """B-QA-001: Rescore Video stub path must stay green on isolation PRs.""" + from test_rescore_video import test_rescore_video_template_schema_and_stub_render + + test_rescore_video_template_schema_and_stub_render(tmp_path, monkeypatch) + + +def test_isolation_pr_flag_matrix_documented() -> None: + """Flag on by default; flag off never studio-pips DFN (covered elsewhere).""" + assert dfn_sidecar_enabled() is True + + +def test_install_action_vocab_dfn_vs_ace() -> None: + action, title = install_action_vocab("deepfilternet-v3", name="DeepFilterNet v3") + assert action == "install_runtime" + assert "Install AI runtime" in title + action2, title2 = install_action_vocab("ace-step-1.5-sft", name="ACE-Step 1.5 SFT") + assert action2 == "install_model" + assert title2.startswith("Install ACE") + assert RUNTIME_PY311_DFN and RUNTIME_TORCH_ACE + + +def test_planner_dfn_emits_install_runtime(tmp_path: Path) -> None: + catalog = ModelCatalog() + store = InstallStore(tmp_path) + plan = plan_agent_request( + catalog, + store, + registry=None, + prompt="denoise podcast dialogue", + max_models=8, + ) + dfn_actions = [ + a + for a in plan.get("actions") or [] + if a.get("model_id") == "deepfilternet-v3" and str(a.get("type", "")).startswith("install") + ] + assert dfn_actions, "expected DeepFilterNet in denoise recommend plan" + assert dfn_actions[0]["type"] == "install_runtime" + assert "Install AI runtime" in dfn_actions[0]["title"] + + +def test_denoise_enricher_mentions_install_ai_runtime() -> None: + schema = enrich_node_schema("Denoise", {"inputs": [], "outputs": [], "widgets": {}}) + blob = f"{schema.get('description', '')} {schema.get('widgets', {})}".lower() + assert "install ai runtime" in blob + assert "sidecar" in blob or ".venv" in blob + + +def test_cold_cofile_gate_is_registered() -> None: + """B-QA-004 lives in cold hero suite — fail closed if renamed/removed.""" + root = Path(__file__).resolve().parent + src = (root / "test_cold_machine_hero.py").read_text() + assert "test_dfn_whisper_cofile_cold_machine_gate" in src