diff --git a/docs/source/markdown/get_started/mcp.md b/docs/source/markdown/get_started/mcp.md index 32b31cb..87567e9 100644 --- a/docs/source/markdown/get_started/mcp.md +++ b/docs/source/markdown/get_started/mcp.md @@ -91,7 +91,11 @@ model and output parameters. Set its animation timing inside `options`: - `frame_duration`: milliseconds for each intermediate frame (default `600`); - `final_hold_duration`: milliseconds to hold the completed diagram (default `1500`); and -- `loop`: whether the GIF repeats (default `true`). +- `loop`: whether the GIF repeats forever (default `true`); `false` plays it once. + +GIF stores frame delays in 10 ms steps, so durations are rounded to the nearest 10 ms. Durations +must be between `20` and `655350`: viewers slow shorter delays down to about 100 ms, and GIF cannot +store longer ones. Passing `null` for any of these controls selects its default. ### `visualtorch_capabilities` @@ -114,9 +118,9 @@ filters the links to one style. | `style` | string | no | `graph`, `flow`, or `lenet`; defaults to `graph`. | | `model_expression` | string | no | Expression evaluated after `source`; defaults to `model`. | | `output_path` | string | no | Output filename or path. Relative paths are resolved below `output_dir`. | -| `output_dir` | string | no | Base directory for generated output. | +| `output_dir` | string | no | Base directory for output; defaults to `~/visualtorch_outputs`. | | `options` | object | no | Style-specific VisualTorch options advertised by capabilities. | -| `workdir` | string | no | Existing working directory made available to imports in `source`. | +| `workdir` | string | no | Existing absolute directory made available to imports in `source`. | | `timeout_seconds` | integer | no | Worker timeout in seconds; defaults to `120` and must be between `1` and `600`. | Use a flat array for one model input: @@ -159,10 +163,25 @@ validates. ## Output paths and metadata -If `output_path` is omitted, the server creates a unique filename below `output_dir` (or its -default output directory). The server normalizes static output names to `.png` and animation output -names to `.gif`. It creates missing parent directories, rejects relative paths that escape -`output_dir`, and validates paths before launching the worker. +If `output_path` is omitted, the server creates a unique filename below `output_dir`. Without +`output_dir`, output goes to `visualtorch_outputs` in the user's home directory. Relative paths never +depend on the directory the MCP host started the server in, since hosts choose it themselves and it +is often read-only: + +- a relative `output_path` is resolved below `output_dir`; +- a relative `output_dir` is resolved below `workdir` when one is given, and below + `~/visualtorch_outputs` otherwise; +- `workdir` must be an absolute path (a leading `~` is expanded); and +- Windows drive-relative (`C:images`) and root-relative (`\images`) paths are rejected. + +Model source runs in `workdir` when one is given, and otherwise in the output file's directory. + +Static outputs always end in `.png` and animations in `.gif`. An existing image extension is +replaced (`diagram.jpg` becomes `diagram.png`), while any other dotted name keeps its dots +(`resnet-1.5` becomes `resnet-1.5.png`). The server creates missing parent directories, rejects +relative paths that escape `output_dir`, and validates paths before launching the worker. The new +file replaces an existing one only after the render has succeeded, and it keeps the existing file's +permissions. A successful tool result is structured data containing at least: @@ -234,7 +253,8 @@ Requests are validated before a worker starts. Invalid styles, shapes, path trav directories, options, and timeouts produce actionable MCP tool errors. Model import, evaluation, tracing, and rendering happen in a separate subprocess with a timeout; a failed render therefore does not terminate the long-running MCP server. Each tool call returns only after its output file -has been written and inspected for metadata. +has been written and inspected for metadata. If the MCP server itself exits while a render is +running, the worker notices and stops on its own. ## Security: trusted source only diff --git a/setup.py b/setup.py index bbdf00e..22c4051 100644 --- a/setup.py +++ b/setup.py @@ -41,7 +41,10 @@ def _read_requirements(file: str) -> list: install_requires=_read_requirements("requirements.txt"), extras_require={ "dev": _read_requirements("docs/requirements.txt") + _read_requirements("dev-requirements.txt"), - "mcp": ["mcp>=1.0.0,<2"], + # FastMCP accepts instructions= from 1.3.0, but releases before 1.22.0 import a pydantic + # internal that current pydantic no longer has, without capping pydantic, so a fresh + # install of them cannot start the server. + "mcp": ["mcp>=1.22.0,<2"], }, entry_points={"console_scripts": ["visualtorch-mcp=visualtorch_mcp.server:main"]}, python_requires=">=3.10", diff --git a/tests/test_animation.py b/tests/test_animation.py index ce2eef9..b142322 100644 --- a/tests/test_animation.py +++ b/tests/test_animation.py @@ -12,7 +12,7 @@ import pytest import torch -from PIL import Image, ImageSequence +from PIL import Image, ImageSequence, features from torch import nn from visualtorch import animate from visualtorch.backend import extract_architecture @@ -284,7 +284,29 @@ def test_loop_false_plays_once(style: str, sequential_model: nn.Module, tmp_path out_path = tmp_path / "out.gif" animate(sequential_model, (1, 3, 8, 8), style=style, to_file=str(out_path), loop=False) with Image.open(out_path) as saved: - assert saved.info.get("loop") == 1 + # No NETSCAPE extension at all: a loop count of 1 would make browsers play it twice. + assert "loop" not in saved.info + + +@pytest.mark.parametrize( + ("suffix", "loop", "expected_loop"), + [(".png", False, 1), (".png", True, 0), (".webp", False, 1), (".webp", True, 0)], +) +def test_loop_for_other_animated_formats( + suffix: str, + loop: bool, + expected_loop: int, + sequential_model: nn.Module, + tmp_path: object, +) -> None: + """APNG and WebP store a play count, so `loop=False` must write 1 rather than PIL's 0 default.""" + if suffix == ".webp" and not features.check("webp"): + pytest.skip("Pillow was built without WebP support") + out_path = tmp_path / f"out{suffix}" + animate(sequential_model, (1, 3, 8, 8), style="graph", to_file=str(out_path), loop=loop) + with Image.open(out_path) as saved: + assert getattr(saved, "n_frames", 1) > 1 + assert saved.info.get("loop") == expected_loop @pytest.mark.parametrize("style", _STYLES) diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 5816bb5..e61282b 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -3,23 +3,35 @@ from __future__ import annotations import asyncio +import gc import importlib import json +import os import shutil +import stat import subprocess import sys +import threading +import time from dataclasses import MISSING, fields from pathlib import Path import pytest -from visualtorch_mcp.api_reference import capabilities_manifest, normalize_style_name +from PIL import Image +from visualtorch_mcp._files import publish_artifact, reserve_staging_path +from visualtorch_mcp.api_reference import capabilities_manifest, docs_manifest, normalize_style_name from visualtorch_mcp.runner import ( animate_model, normalize_input_shape, render_model, resolve_output_path, ) -from visualtorch_mcp.worker import _coerce_options, _restore_tuples, _validate_animation_options +from visualtorch_mcp.worker import ( + _coerce_options, + _prepare_animation_options, + _restore_tuples, + _validate_animation_options, +) MODEL_SOURCE = "import torch\nmodel = torch.nn.Sequential(torch.nn.Flatten(), torch.nn.Linear(4, 2))" @@ -208,8 +220,10 @@ def test_worker_rejects_invalid_json_option_encodings( @pytest.mark.parametrize( ("options", "error", "match"), [ - ({"frame_duration": 0}, ValueError, "frame_duration must be a positive integer"), - ({"final_hold_duration": True}, ValueError, "final_hold_duration must be a positive integer"), + ({"frame_duration": 0}, ValueError, "frame_duration must be an integer number of milliseconds"), + ({"frame_duration": 10}, ValueError, "between 20 and 655350"), + ({"final_hold_duration": 655351}, ValueError, "between 20 and 655350"), + ({"final_hold_duration": True}, ValueError, "final_hold_duration must be an integer"), ({"loop": 1}, TypeError, "loop must be a boolean"), ], ) @@ -256,8 +270,8 @@ def test_animate_model_worker_smoke(tmp_path: Path, style: str) -> None: """Animate every canonical style and report verified GIF metadata.""" options: dict[str, object] = { "show_input": False, - "frame_duration": 1, - "final_hold_duration": 1, + "frame_duration": 20, + "final_hold_duration": 20, "loop": False, } if style == "graph": @@ -280,6 +294,7 @@ def test_animate_model_worker_smoke(tmp_path: Path, style: str) -> None: assert result["style"] == style assert result["media_type"] == "image/gif" assert result["frame_count"] >= 1 + assert result["loop"] is False assert result["width"] > 0 assert result["height"] > 0 assert result["bytes"] == output_path.stat().st_size @@ -486,7 +501,7 @@ def test_worker_protocol_keeps_stdout_json( payload_path = tmp_path / "payload.json" options: dict[str, object] = {"show_neurons": False, "show_input": False} if job == "animate": - options.update({"frame_duration": 1, "final_hold_duration": 1, "loop": False}) + options.update({"frame_duration": 20, "final_hold_duration": 20, "loop": False}) payload_path.write_text( json.dumps( { @@ -593,8 +608,8 @@ async def exercise_server() -> tuple[object, object, object, object, object, obj "output_dir": str(tmp_path), "options": { "show_input": False, - "frame_duration": 1, - "final_hold_duration": 1, + "frame_duration": 20, + "final_hold_duration": 20, "loop": False, }, "timeout_seconds": 30, @@ -632,3 +647,573 @@ async def exercise_server() -> tuple[object, object, object, object, object, obj assert not animation_result.isError assert (tmp_path / "stdio-static.png").is_file() assert (tmp_path / "stdio-animation.gif").is_file() + + +def test_default_output_dir_ignores_server_working_directory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Resolve the default and relative output directories per call, never from the host's cwd.""" + home = tmp_path / "home" + host_cwd = tmp_path / "host-cwd" + workdir = tmp_path / "project" + for directory in (home, host_cwd, workdir): + directory.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.chdir(host_cwd) + default_dir = (home / "visualtorch_outputs").resolve() + + assert resolve_output_path("architecture.png", None, "graph").parent == default_dir + assert resolve_output_path(None, None, "graph").parent == default_dir + assert resolve_output_path("a.png", "diagrams", "graph") == default_dir / "diagrams" / "a.png" + in_workdir = resolve_output_path("a.png", "diagrams", "graph", workdir=workdir) + assert in_workdir == (workdir / "diagrams" / "a.png").resolve() + assert not list(host_cwd.iterdir()) + + +def test_runner_rejects_relative_workdir(tmp_path: Path) -> None: + """Refuse a workdir that would depend on the server's working directory.""" + with pytest.raises(ValueError, match="workdir must be an absolute path"): + render_model(source=MODEL_SOURCE, input_shape=[1, 1, 2, 2], output_dir=str(tmp_path), workdir="project") + + +@pytest.mark.parametrize( + ("requested", "job", "expected"), + [ + ("resnet-1.5", "render", "resnet-1.5.png"), + ("model_v1.1", "render", "model_v1.1.png"), + ("model_v1.2", "render", "model_v1.2.png"), + ("Diagram.PNG", "render", "Diagram.PNG"), + ("diagram.jpeg", "render", "diagram.png"), + ("reveal.v2.png", "animate", "reveal.v2.gif"), + ("Reveal.GIF", "animate", "Reveal.GIF"), + ("figure.avif", "render", "figure.png"), + ], +) +def test_output_suffix_keeps_dotted_names(tmp_path: Path, requested: str, job: str, expected: str) -> None: + """Swap only real image extensions so dotted names never collapse onto each other.""" + assert resolve_output_path(requested, str(tmp_path), "graph", job=job) == (tmp_path / expected).resolve() + + +def test_absolute_output_path_ignores_unused_output_dir(tmp_path: Path) -> None: + """Do not validate an output_dir that an absolute output_path never uses.""" + stale_output_dir = tmp_path / "not-a-directory" + stale_output_dir.write_text("content", encoding="utf-8") + target = tmp_path / "out.png" + + assert resolve_output_path(str(target), str(stale_output_dir), "graph") == target.resolve() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") +def test_published_artifacts_get_regular_file_permissions(tmp_path: Path) -> None: + """Create staging files through the umask and keep an existing artifact's mode on replace.""" + previous_umask = os.umask(0o022) + try: + staging = reserve_staging_path(tmp_path, ".png") + finally: + os.umask(previous_umask) + assert stat.S_IMODE(staging.stat().st_mode) == 0o644 + fresh = tmp_path / "fresh.png" + publish_artifact(staging, fresh) + assert stat.S_IMODE(fresh.stat().st_mode) == 0o644 + + existing = tmp_path / "existing.png" + existing.write_bytes(b"old") + existing.chmod(0o640) + staging = reserve_staging_path(tmp_path, ".png") + staging.write_bytes(b"new") + publish_artifact(staging, existing) + assert existing.read_bytes() == b"new" + assert stat.S_IMODE(existing.stat().st_mode) == 0o640 + + +def test_worker_exits_without_waiting_for_lingering_source_threads(tmp_path: Path) -> None: + """Return as soon as the artifact is written, even if model source leaves threads or atexit hooks.""" + source = ( + "import atexit, threading, time\n" + "threading.Thread(target=time.sleep, args=(60,)).start()\n" + "atexit.register(time.sleep, 60)\n" + f"{MODEL_SOURCE}\n" + ) + started = time.monotonic() + result = render_model( + source=source, + input_shape=(1, 1, 2, 2), + output_path="lingering.png", + output_dir=str(tmp_path), + options={"show_neurons": False}, + timeout_seconds=40, + ) + + assert time.monotonic() - started < 30 + assert Path(result["output_path"]).is_file() + assert not list(tmp_path.glob(".visualtorch-mcp-*")) + + +def test_late_failure_leaves_existing_artifact_untouched( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Keep the previous file when the job fails after the worker has finished rendering.""" + runner = importlib.import_module("visualtorch_mcp.runner") + + def reject_result(*_args: object) -> None: + message = "result rejected after the render finished" + raise RuntimeError(message) + + monkeypatch.setattr(runner, "_parse_worker_result", reject_result) + existing = tmp_path / "architecture.png" + existing.write_bytes(b"previous artifact") + + with pytest.raises(RuntimeError, match="result rejected"): + render_model( + source=MODEL_SOURCE, + input_shape=(1, 1, 2, 2), + output_path=str(existing), + options={"show_neurons": False}, + timeout_seconds=30, + ) + + assert existing.read_bytes() == b"previous artifact" + assert not list(tmp_path.glob(".visualtorch-mcp-*")) + + +def test_worker_ignores_modules_in_server_working_directory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Start the worker outside the host's cwd so local files cannot shadow installed packages.""" + host_cwd = tmp_path / "host-cwd" + host_cwd.mkdir() + for module in ("json", "inspect", "visualtorch"): + (host_cwd / f"{module}.py").write_text("raise RuntimeError('shadowed module imported')\n", encoding="utf-8") + monkeypatch.chdir(host_cwd) + + result = render_model( + source=MODEL_SOURCE, + input_shape=(1, 1, 2, 2), + output_path="shadow-free.png", + output_dir=str(tmp_path), + options={"show_neurons": False}, + timeout_seconds=30, + ) + + assert Path(result["output_path"]).is_file() + + +def test_source_cannot_exit_the_worker_silently(tmp_path: Path) -> None: + """Report sys.exit() from model source instead of an empty, invalid protocol response.""" + with pytest.raises(RuntimeError, match=r"(?s)SystemExit\(0\).*sys\.exit\(\)"): + render_model( + source=f"{MODEL_SOURCE}\nimport sys\nsys.exit(0)", + input_shape=(1, 1, 2, 2), + output_dir=str(tmp_path), + timeout_seconds=30, + ) + + +def test_source_sees_clean_argv(tmp_path: Path) -> None: + """Hide the worker's payload argument from module-level argument parsing in model source.""" + result = render_model( + source=f"import argparse\nargparse.ArgumentParser().parse_args()\n{MODEL_SOURCE}", + input_shape=(1, 1, 2, 2), + output_path="argparse.png", + output_dir=str(tmp_path), + options={"show_neurons": False}, + timeout_seconds=30, + ) + + assert Path(result["output_path"]).is_file() + + +def test_animation_controls_use_defaults_for_null_and_round_to_gif_resolution() -> None: + """Drop null animation controls so defaults apply, and round delays to 10 ms steps.""" + prepared = _prepare_animation_options( + {"frame_duration": None, "final_hold_duration": 25, "loop": None, "show_input": False}, + ) + assert prepared == {"final_hold_duration": 30, "show_input": False} + assert _prepare_animation_options({"frame_duration": 333})["frame_duration"] == 330 + assert _prepare_animation_options({"frame_duration": 655345})["frame_duration"] == 655350 + + +def test_animate_model_accepts_null_animation_controls(tmp_path: Path) -> None: + """Render with VisualTorch's defaults when a client sends null animation controls.""" + result = animate_model( + source=MODEL_SOURCE, + input_shape=(1, 1, 2, 2), + output_path="null-controls.gif", + output_dir=str(tmp_path), + options={"show_neurons": False, "frame_duration": None, "final_hold_duration": None, "loop": None}, + timeout_seconds=30, + ) + + assert result["durations_ms"][-1] == 1500 + assert result["loop"] is True + with Image.open(result["output_path"]) as artifact: + assert artifact.info["loop"] == 0 + + +def test_reference_for_one_style_keeps_render_page() -> None: + """Keep the render() API page when filtering documentation links to one style.""" + reference = docs_manifest("layered") + + assert "- Render\n" in reference + assert "- Flow View\n" in reference + assert "- Graph View\n" not in reference + + +def test_stop_worker_gives_up_on_an_unkillable_worker(monkeypatch: pytest.MonkeyPatch) -> None: + """Bound every wait when a worker cannot be reaped, so timeouts and cancellations still return.""" + runner = importlib.import_module("visualtorch_mcp.runner") + monkeypatch.setattr(runner, "_terminate_process_tree", lambda _process: None) + timeouts: list[float | None] = [] + + class Stream: + closed = False + + def close(self) -> None: + self.closed = True + + class StuckProcess: + args = ("worker",) + stdout = Stream() + + def communicate(self, timeout: float | None = None) -> None: + timeouts.append(timeout) + raise subprocess.TimeoutExpired(self.args, timeout or 0) + + def kill(self) -> None: + return + + def wait(self, timeout: float | None = None) -> None: + timeouts.append(timeout) + raise subprocess.TimeoutExpired(self.args, timeout or 0) + + process = StuckProcess() + runner._stop_worker(process) # noqa: SLF001 - exercise the cleanup primitive directly. + + assert timeouts + assert None not in timeouts + assert process.stdout.closed is (os.name != "nt") + + +def test_worker_stops_itself_when_server_process_dies(tmp_path: Path) -> None: + """Stop an orphaned worker and remove its staging file once the supervising process exits.""" + fake_server = subprocess.Popen( + [sys.executable, "-c", "import time; time.sleep(120)"], + stdin=subprocess.DEVNULL, + ) + output_path = tmp_path / "orphan.png" + staging_path = reserve_staging_path(tmp_path, ".png") + payload_path = tmp_path / "payload.json" + payload_path.write_text( + json.dumps( + { + "job": "render", + "source": "import time\ntime.sleep(120)\nmodel = None", + "input_shape": [1, 1, 2, 2], + "style": "graph", + "output_path": str(output_path), + "staging_path": str(staging_path), + "parent_pid": fake_server.pid, + "timeout_seconds": 600, + }, + ), + encoding="utf-8", + ) + worker = subprocess.Popen( # noqa: S603 - fixed interpreter and module invocation under test. + [sys.executable, "-m", "visualtorch_mcp.worker", str(payload_path)], + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + try: + time.sleep(2) + assert worker.poll() is None + fake_server.kill() + fake_server.wait(timeout=10) + _, stderr = worker.communicate(timeout=30) + finally: + for process in (fake_server, worker): + if process.poll() is None: + process.kill() + process.wait(timeout=10) + + assert worker.returncode != 0 + assert "MCP server process exited" in stderr + assert not staging_path.exists() + assert not output_path.exists() + + +def _process_alive(pid: int) -> bool: + """Return whether a process exists and has not exited, without signalling it.""" + if sys.platform == "win32": + import ctypes # noqa: PLC0415 - Windows-only helper. + + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + handle = kernel32.OpenProcess(0x00100000, False, pid) # noqa: FBT003 - Win32 BOOL argument. + if not handle: + return False + try: + return kernel32.WaitForSingleObject(handle, 0) == 0x102 # WAIT_TIMEOUT: still running. + finally: + kernel32.CloseHandle(handle) + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + proc_stat = Path(f"/proc/{pid}/stat") + if proc_stat.exists(): + return proc_stat.read_text().rsplit(")", 1)[-1].split()[0] != "Z" + return True + + +def _wait_until_gone(pid: int, timeout: float = 15) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if not _process_alive(pid): + return True + time.sleep(0.1) + return False + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") +def test_staging_file_is_no_more_readable_than_the_file_it_replaces(tmp_path: Path) -> None: + """Start a replacement's staging file with the existing artifact's private mode.""" + existing = tmp_path / "private.png" + existing.write_bytes(b"old") + existing.chmod(0o600) + previous_umask = os.umask(0o022) + try: + staging = reserve_staging_path(tmp_path, ".png", replaces=existing) + finally: + os.umask(previous_umask) + + assert stat.S_IMODE(staging.stat().st_mode) == 0o600 + + +def test_cancelled_call_has_no_side_effects_after_it_returns( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Finish cancellation only once the job thread is done, so a late publish cannot follow it.""" + pytest.importorskip("mcp") + server = importlib.import_module("visualtorch_mcp.server") + runner = importlib.import_module("visualtorch_mcp.runner") + real_publish = runner.publish_artifact + publishing = threading.Event() + release = threading.Event() + + def slow_publish(staging_path: Path, output_path: Path) -> None: + publishing.set() + release.wait(30) + real_publish(staging_path, output_path) + + monkeypatch.setattr(runner, "publish_artifact", slow_publish) + output_path = tmp_path / "raced.png" + output_path.write_bytes(b"previous artifact") + + async def cancel_while_publishing() -> None: + task = asyncio.create_task( + server.visualize_model( + source=MODEL_SOURCE, + input_shape=[1, 1, 2, 2], + output_path=str(output_path), + options={"show_neurons": False}, + timeout_seconds=30, + ), + ) + for _ in range(600): + if publishing.is_set(): + break + await asyncio.sleep(0.05) + else: + release.set() + pytest.fail("job never reached publication") + + task.cancel() + await asyncio.sleep(0.3) + assert not task.done(), "cancellation completed while the job thread was still publishing" + release.set() + with pytest.raises(asyncio.CancelledError): + await task + + asyncio.run(cancel_while_publishing()) + settled = output_path.read_bytes() + time.sleep(0.5) + assert output_path.read_bytes() == settled + assert not list(tmp_path.glob(".visualtorch-mcp-*")) + + +def test_successful_job_stops_daemonic_multiprocessing_children(tmp_path: Path) -> None: + """Terminate daemonic children as normal interpreter shutdown would, despite os._exit().""" + pid_file = tmp_path / "child.pid" + source = ( + "import multiprocessing, time\n" + "from pathlib import Path\n" + "child = multiprocessing.Process(target=time.sleep, args=(300,), daemon=True)\n" + "child.start()\n" + f"Path({str(pid_file)!r}).write_text(str(child.pid))\n" + f"{MODEL_SOURCE}\n" + ) + render_model( + source=source, + input_shape=(1, 1, 2, 2), + output_path="daemon-child.png", + output_dir=str(tmp_path), + options={"show_neurons": False}, + timeout_seconds=60, + ) + + assert _wait_until_gone(int(pid_file.read_text())) + + +def test_model_source_runs_beside_its_artifact_without_workdir(tmp_path: Path) -> None: + """Run model source in the output directory, not in the worker's deleted scratch directory.""" + source = f"from pathlib import Path\nPath('side-file.txt').write_text(str(Path.cwd()))\n{MODEL_SOURCE}" + render_model( + source=source, + input_shape=(1, 1, 2, 2), + output_path="cwd-check.png", + output_dir=str(tmp_path), + options={"show_neurons": False}, + timeout_seconds=30, + ) + + side_file = tmp_path / "side-file.txt" + assert side_file.is_file() + assert Path(side_file.read_text()).resolve() == tmp_path.resolve() + + +def test_relative_pythonpath_resolves_against_server_directory( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Keep relative PYTHONPATH entries pointing where they did for the server process.""" + project = tmp_path / "project" + (project / "lib").mkdir(parents=True) + (project / "lib" / "helper_model.py").write_text(MODEL_SOURCE + "\n", encoding="utf-8") + monkeypatch.chdir(project) + monkeypatch.setenv("PYTHONPATH", "lib") + + result = render_model( + source="from helper_model import model", + input_shape=(1, 1, 2, 2), + output_path="pythonpath.png", + output_dir=str(tmp_path), + workdir=str(project), + options={"show_neurons": False}, + timeout_seconds=30, + ) + + assert Path(result["output_path"]).is_file() + + +@pytest.mark.skipif(os.name != "nt", reason="Windows drive- and root-relative paths") +@pytest.mark.parametrize("output_dir", ["C:images", "\\images"]) +def test_partly_anchored_windows_output_dir_is_rejected(tmp_path: Path, output_dir: str) -> None: + """Reject Windows paths that would silently resolve against the server's current directory.""" + with pytest.raises(ValueError, match="plain relative path"): + resolve_output_path("a.png", output_dir, "graph", workdir=tmp_path) + + +def test_absolute_output_path_ignores_blank_output_dir(tmp_path: Path) -> None: + """Treat a blank output_dir like any other unused output_dir.""" + target = tmp_path / "out.png" + + assert resolve_output_path(str(target), " ", "graph") == target.resolve() + + +def test_watchdog_only_deletes_reserved_staging_files(tmp_path: Path) -> None: + """Never let an orphaned worker delete an output path or another arbitrary file.""" + worker = importlib.import_module("visualtorch_mcp.worker") + output_path = tmp_path / "out.png" + staging_path = tmp_path / ".visualtorch-mcp-0123456789abcdef.png" + + cleanup = worker._orphan_cleanup_path # noqa: SLF001 - exercise the guard directly. + assert cleanup({"staging_path": str(staging_path), "output_path": str(output_path)}) == staging_path + assert cleanup({"staging_path": str(output_path), "output_path": str(output_path)}) is None + assert cleanup({"staging_path": str(tmp_path / "notes.txt"), "output_path": str(output_path)}) is None + assert cleanup({"output_path": str(output_path)}) is None + + +def test_parent_monitor_reports_an_already_exited_parent() -> None: + """Treat a server that exited before the worker started as gone, on every platform.""" + worker = importlib.import_module("visualtorch_mcp.worker") + exited = subprocess.Popen([sys.executable, "-c", "pass"], stdin=subprocess.DEVNULL) + exited.wait(timeout=30) + pid = exited.pid + # Drop Popen's process handle too, so on Windows no handle keeps the exited process around. + del exited + gc.collect() + + assert worker._parent_monitor(pid)() is False # noqa: SLF001 - exercise the monitor directly. + + +def test_direct_worker_with_staging_path_still_publishes(tmp_path: Path) -> None: + """Publish the artifact itself when a direct caller did not ask the server to publish it.""" + output_path = tmp_path / "direct.png" + staging_path = reserve_staging_path(tmp_path, ".png") + payload_path = tmp_path / "payload.json" + payload_path.write_text( + json.dumps( + { + "job": "render", + "source": MODEL_SOURCE, + "input_shape": [1, 1, 2, 2], + "style": "graph", + "output_path": str(output_path), + "staging_path": str(staging_path), + "options": {"show_neurons": False}, + }, + ), + encoding="utf-8", + ) + completed = subprocess.run( # noqa: S603 - fixed interpreter and module invocation under test. + [sys.executable, "-m", "visualtorch_mcp.worker", str(payload_path)], + check=False, + capture_output=True, + text=True, + timeout=60, + ) + + assert completed.returncode == 0, completed.stderr + assert output_path.is_file() + assert not staging_path.exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX sessions and process groups") +def test_server_crash_stops_worker_and_its_descendants(tmp_path: Path) -> None: + """SIGKILL a real server mid-render; its worker and the worker's children must go too.""" + pid_file = tmp_path / "pids" + model_source = ( + "import os, subprocess, time\n" + "from pathlib import Path\n" + "child = subprocess.Popen(['sleep', '300'])\n" + f"Path({str(pid_file)!r}).write_text(f'{{os.getpid()}} {{child.pid}}')\n" + "time.sleep(300)\n" + "model = None\n" + ) + server_code = ( + "from visualtorch_mcp.runner import render_model\n" + f"render_model(source={model_source!r}, input_shape=[1, 4], output_path='crash.png', " + f"output_dir={str(tmp_path)!r}, timeout_seconds=600)\n" + ) + server = subprocess.Popen( # noqa: S603 - fixed interpreter running test-built code. + [sys.executable, "-c", server_code], + stdin=subprocess.DEVNULL, + ) + try: + for _ in range(600): + if pid_file.exists() and pid_file.read_text().strip(): + break + time.sleep(0.1) + else: + pytest.fail("worker never started model source") + worker_pid, grandchild_pid = map(int, pid_file.read_text().split()) + assert list(tmp_path.glob(".visualtorch-mcp-*")) + finally: + server.kill() + server.wait(timeout=10) + + assert _wait_until_gone(worker_pid) + assert _wait_until_gone(grandchild_pid) + assert not list(tmp_path.glob(".visualtorch-mcp-*")) diff --git a/visualtorch/_animation.py b/visualtorch/_animation.py index 8af24b7..63c5dba 100644 --- a/visualtorch/_animation.py +++ b/visualtorch/_animation.py @@ -11,6 +11,7 @@ # SPDX-License-Identifier: MIT from collections.abc import Callable +from pathlib import Path from PIL import Image @@ -32,13 +33,16 @@ def animate_frames( resulting frame count. to_file: Path to write the animated GIF to. If None, no file is written and the list of frames is returned instead. Format is inferred from the filename, same as every other - `*_view()`'s `to_file` - a non-`.gif` extension won't raise, it'll silently save only - the first frame, since `save_all` is GIF-specific. + `*_view()`'s `to_file`; PIL writes every frame for animated formats such as GIF, + APNG (`.png`) and WebP. frame_duration: Per-frame display duration in milliseconds, for every frame except the last. final_hold_duration: Display duration in milliseconds for the last (fully revealed) frame, so the completed diagram holds on screen before the GIF loops. - loop: Whether the GIF should loop forever (`loop=0` to PIL) or play once (`loop=1`). + loop: Whether the animation should loop forever (`loop=0` to PIL) or play once. A GIF + plays once when it has no NETSCAPE looping extension, so `loop` is left out for + `.gif`; other animated formats (APNG, WebP) default to looping forever in PIL and + get `loop=1`, which they read as a single play. Returns: list[Image.Image] | None: The rendered frames if `to_file` is None, else None. @@ -47,12 +51,25 @@ def animate_frames( durations = [frame_duration] * (n_columns - 1) + [final_hold_duration] if to_file is not None: + loop_kwargs = {"loop": 0} if loop else _play_once_kwargs(to_file) frames[0].save( to_file, save_all=True, append_images=frames[1:], duration=durations, - loop=0 if loop else 1, + **loop_kwargs, ) return None return frames + + +def _play_once_kwargs(to_file: str) -> dict[str, int]: + """Return the PIL save arguments that make an animation play exactly once. + + A GIF NETSCAPE loop count of N repeats the animation N more times, so PIL's `loop=1` would + play a GIF twice; a GIF without the extension plays once. APNG and WebP instead store the + total number of plays and default to 0 (forever) when `loop` is omitted. + """ + if Path(to_file).suffix.lower() == ".gif": + return {} + return {"loop": 1} diff --git a/visualtorch_mcp/_files.py b/visualtorch_mcp/_files.py new file mode 100644 index 0000000..814666f --- /dev/null +++ b/visualtorch_mcp/_files.py @@ -0,0 +1,59 @@ +"""Artifact file helpers shared by the MCP server process and its render worker.""" + +from __future__ import annotations + +import os +import secrets +import stat +from contextlib import suppress +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from pathlib import Path + +STAGING_PREFIX = ".visualtorch-mcp-" +_STAGING_ATTEMPTS = 100 +_DEFAULT_FILE_MODE = 0o666 + + +def reserve_staging_path(directory: Path, suffix: str, *, replaces: Path | None = None) -> Path: + """Create an empty, uniquely named staging file in the artifact's directory. + + ``tempfile.mkstemp`` always creates mode 0600 files, and Pillow keeps that mode when it + rewrites the file. A new artifact's staging file is created with 0666 instead, so the process + umask decides its permissions as it would for a file the renderer wrote directly. When the + staging file will replace an existing file, it starts with that file's (possibly stricter) + mode, so the new content is never more readable while it is staged than after publication. + """ + mode = _DEFAULT_FILE_MODE + if replaces is not None and os.name != "nt": + with suppress(OSError): + mode = stat.S_IMODE(replaces.stat().st_mode) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0) + for _ in range(_STAGING_ATTEMPTS): + candidate = directory / f"{STAGING_PREFIX}{secrets.token_hex(8)}{suffix}" + try: + descriptor = os.open(candidate, flags, mode) + except FileExistsError: + continue + os.close(descriptor) + return candidate + message = f"Could not reserve a unique staging file in {directory}." + raise FileExistsError(message) + + +def is_staging_path(path: Path) -> bool: + """Return whether ``path`` is named like a file created by :func:`reserve_staging_path`.""" + return path.name.startswith(STAGING_PREFIX) + + +def publish_artifact(staging_path: Path, output_path: Path) -> None: + """Atomically move a finished staging file to its final path. + + When the destination already exists its permission bits are kept, as they would be if the + file had been rewritten in place, instead of being replaced by the staging file's mode. + """ + if os.name != "nt": + with suppress(FileNotFoundError): + staging_path.chmod(stat.S_IMODE(output_path.stat().st_mode)) + staging_path.replace(output_path) diff --git a/visualtorch_mcp/api_reference.py b/visualtorch_mcp/api_reference.py index 0d6e773..3c37583 100644 --- a/visualtorch_mcp/api_reference.py +++ b/visualtorch_mcp/api_reference.py @@ -200,25 +200,35 @@ class DocsPage: "offset_z": "Depth-axis offset between LeNet-style feature-map planes.", } +_GIF_DELAY_NOTE = ( + "GIF stores delays in 10 ms steps up to 655350 ms, so values are rounded to the nearest 10 ms; " + "viewers slow delays under 20 ms down to about 100 ms, so 20 is the minimum. null selects the " + "default." +) + ANIMATION_OPTIONS: dict[str, dict[str, object]] = { "frame_duration": { - "type": "integer", + "type": "integer | null", "default": 600, - "minimum": 1, + "minimum": 20, + "maximum": 655350, + "resolution": 10, "unit": "milliseconds", - "description": "Display duration for each intermediate reveal frame.", + "description": f"Display duration for each intermediate reveal frame. {_GIF_DELAY_NOTE}", }, "final_hold_duration": { - "type": "integer", + "type": "integer | null", "default": 1500, - "minimum": 1, + "minimum": 20, + "maximum": 655350, + "resolution": 10, "unit": "milliseconds", - "description": "Display duration for the final complete architecture frame.", + "description": f"Display duration for the final complete architecture frame. {_GIF_DELAY_NOTE}", }, "loop": { - "type": "boolean", + "type": "boolean | null", "default": True, - "description": "Loop forever when true; play once when false.", + "description": "Loop forever when true; play once when false. null selects the default.", }, } @@ -272,7 +282,8 @@ def docs_manifest(style: str | None = None) -> str: """Return upstream VisualTorch docs links without duplicating API documentation.""" keys = ["index", "installation", "render", "flow", "graph", "lenet", "examples"] if style is not None: - keys = [normalize_style_name(style)] + # Keep the render() page, which the MCP tools call, next to the style's own page. + keys = ["index", "render", normalize_style_name(style), "examples"] lines = [ "Upstream VisualTorch documentation:", diff --git a/visualtorch_mcp/runner.py b/visualtorch_mcp/runner.py index 5d9b231..8c4e23e 100644 --- a/visualtorch_mcp/runner.py +++ b/visualtorch_mcp/runner.py @@ -4,6 +4,7 @@ import json import os +import shutil import signal import subprocess import sys @@ -13,18 +14,45 @@ from contextlib import suppress from datetime import datetime, timezone from pathlib import Path -from typing import TYPE_CHECKING, Any, Literal, NoReturn +from typing import TYPE_CHECKING, Any, Literal if TYPE_CHECKING: from threading import Event +from ._files import publish_artifact, reserve_staging_path from .api_reference import normalize_style_name -DEFAULT_OUTPUT_DIR = Path.cwd() / "visualtorch_outputs" +DEFAULT_OUTPUT_DIR_NAME = "visualtorch_outputs" MIN_TIMEOUT_SECONDS = 1 MAX_TIMEOUT_SECONDS = 600 _ERROR_OUTPUT_LIMIT = 16_000 _WORKER_POLL_INTERVAL_SECONDS = 0.1 +_WORKER_STOP_GRACE_SECONDS = 5 + +# Extensions that name an image format. Only these are swapped for the job's own extension; +# any other dotted tail (``resnet-1.5``, ``model_v1.2``) is part of the file name. +_IMAGE_SUFFIXES = frozenset( + { + ".apng", + ".avif", + ".bmp", + ".eps", + ".gif", + ".heic", + ".heif", + ".ico", + ".jp2", + ".jpeg", + ".jpg", + ".jxl", + ".pdf", + ".png", + ".svg", + ".tif", + ".tiff", + ".webp", + }, +) JobKind = Literal["render", "animate"] @@ -57,42 +85,54 @@ def normalize_input_shape(value: object) -> tuple[int, ...] | tuple[tuple[int, . return _normalize_single_shape(value) +def default_output_dir() -> Path: + """Return the directory that receives artifacts when a call gives no ``output_dir``. + + It is worked out for each call from the user's home directory, never from the server's + working directory: MCP hosts choose that directory themselves, and it is often read-only + (``/`` for GUI hosts on macOS) or an application install folder. + """ + try: + home = Path.home() + except RuntimeError: + home = Path(tempfile.gettempdir()) + return home / DEFAULT_OUTPUT_DIR_NAME + + def resolve_output_path( output_path: str | None, output_dir: str | None, style: str, *, job: JobKind = "render", + workdir: Path | None = None, ) -> Path: - """Resolve an output path and normalize its suffix for the requested job.""" - suffix = ".png" if job == "render" else ".gif" - if output_dir is not None and (not isinstance(output_dir, str) or not output_dir.strip()): - message = "output_dir must be a non-empty path string when provided." - raise ValueError(message) - base_dir = Path(output_dir).expanduser() if output_dir else DEFAULT_OUTPUT_DIR - base_dir = base_dir.resolve() + """Resolve where a job's artifact is written and give it the job's image extension. - if base_dir.exists() and not base_dir.is_dir(): - message = f"output_dir is not a directory: {base_dir}" + Relative paths never depend on the server's working directory. A relative ``output_path`` + goes below ``output_dir``. A relative ``output_dir`` goes below ``workdir`` when one is + given, and below :func:`default_output_dir` otherwise. + """ + suffix = ".png" if job == "render" else ".gif" + if output_path is not None and (not isinstance(output_path, str) or not output_path.strip()): + message = "output_path must be a non-empty path string when provided." raise ValueError(message) - relative_output = False - if output_path is not None: - if not isinstance(output_path, str) or not output_path.strip(): - message = "output_path must be a non-empty path string when provided." - raise ValueError(message) - path = Path(output_path).expanduser() - if not path.is_absolute(): - relative_output = True - path = base_dir / path + requested = _user_path(output_path, "output_path") if output_path is not None else None + base_dir: Path | None = None + if requested is not None and requested.is_absolute(): + # output_dir plays no part in an absolute output_path, so it is not validated either. + path = requested else: - stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") - path = base_dir / f"visualtorch_{style}_{stamp}_{uuid.uuid4().hex[:8]}{suffix}" - - # VisualTorch/Pillow infer the file format from the suffix. Always force the format - # promised by the tool, rather than silently writing a single frame for a non-GIF path. - path = path.with_suffix(suffix).resolve() - if relative_output and not path.is_relative_to(base_dir): + base_dir = _resolve_output_dir(output_dir, workdir) + if requested is None: + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + path = base_dir / f"visualtorch_{style}_{stamp}_{uuid.uuid4().hex[:8]}{suffix}" + else: + path = base_dir / requested + + path = _with_artifact_suffix(path, suffix).resolve() + if requested is not None and base_dir is not None and not path.is_relative_to(base_dir): message = f"relative output_path must stay within output_dir: {base_dir}" raise ValueError(message) if path.exists() and path.is_dir(): @@ -102,6 +142,58 @@ def resolve_output_path( return path +def _resolve_output_dir(output_dir: str | None, workdir: Path | None) -> Path: + """Resolve the base directory for generated or relative output paths.""" + if output_dir is None: + base_dir = default_output_dir() + else: + if not isinstance(output_dir, str) or not output_dir.strip(): + message = "output_dir must be a non-empty path string when provided." + raise ValueError(message) + base_dir = _user_path(output_dir, "output_dir") + if not base_dir.is_absolute(): + base_dir = (workdir or default_output_dir()) / base_dir + base_dir = base_dir.resolve() + if base_dir.exists() and not base_dir.is_dir(): + message = f"output_dir is not a directory: {base_dir}" + raise ValueError(message) + return base_dir + + +def _user_path(value: str, name: str) -> Path: + r"""Expand ``~`` in a client path and reject paths that are only partly anchored. + + On Windows, ``C:images`` (drive-relative) and ``\images`` (root-relative) are neither absolute + nor relative to a base directory: joining them to one switches drive or root, which would make + them depend on the server's current directory again. + """ + path = Path(value).expanduser() + if not path.is_absolute() and (path.drive or path.root): + message = f"{name} must be an absolute path or a plain relative path, got {value!r}." + raise ValueError(message) + return path + + +def _with_artifact_suffix(path: Path, suffix: str) -> Path: + """Give ``path`` the job's image extension without cutting dotted names short. + + VisualTorch and Pillow infer the file format from the extension, so the tool always uses the + format it promises instead of, for example, silently writing one frame for a non-GIF path. + A recognised image extension is swapped (``diagram.jpg`` becomes ``diagram.png``) and a + matching one keeps its case (``Diagram.PNG``). Any other dotted tail is kept as part of the + name (``resnet-1.5`` becomes ``resnet-1.5.png``). + """ + if not path.name or path.name == "..": + message = f"output_path must name a file, not a directory: {path}" + raise ValueError(message) + current = path.suffix.lower() + if current == suffix: + return path + if current in _IMAGE_SUFFIXES: + return path.with_suffix(suffix) + return path.with_name(path.name + suffix) + + def render_model( *, source: str, @@ -189,9 +281,19 @@ def _run_job( canonical_style = normalize_style_name(style) normalized_shape = normalize_input_shape(input_shape) - resolved_output_path = resolve_output_path(output_path, output_dir, canonical_style, job=job) + resolved_output_path = resolve_output_path( + output_path, + output_dir, + canonical_style, + job=job, + workdir=resolved_workdir, + ) _raise_if_cancelled(cancel_event) - staging_path = _reserve_staging_path(resolved_output_path) + staging_path = reserve_staging_path( + resolved_output_path.parent, + resolved_output_path.suffix, + replaces=resolved_output_path, + ) try: payload = { "job": job, @@ -201,8 +303,16 @@ def _run_job( "model_expression": model_expression, "output_path": str(resolved_output_path), "staging_path": str(staging_path), + # This process moves the staging file into place once the worker has succeeded. + "parent_publishes": True, "options": options or {}, "workdir": str(resolved_workdir) if resolved_workdir else None, + # Without a workdir, model source runs beside its artifact rather than in the worker's + # temporary starting directory, which is deleted when the job ends. + "cwd": str(resolved_output_path.parent), + # Let the worker stop itself if this process dies or stops supervising it. + "parent_pid": os.getpid(), + "timeout_seconds": timeout_seconds, } try: @@ -212,10 +322,32 @@ def _run_job( raise TypeError(message) from exc completed = _run_serialized_payload(serialized_payload, timeout_seconds, cancel_event) + result = _parse_worker_result(job, completed) + + # The worker leaves the verified artifact in staging. Moving it into place only after a + # successful, parsed result means a worker that fails late, hangs on exit, or is + # cancelled can never replace an existing file while the call reports failure. + _raise_if_cancelled(cancel_event) + artifact_size = staging_path.stat().st_size if staging_path.is_file() else 0 + if artifact_size == 0: + message = f"VisualTorch {job} reported success without leaving a non-empty artifact." + raise RuntimeError(message) + publish_artifact(staging_path, resolved_output_path) finally: # The parent owns cleanup so a force-killed or crashed worker cannot leak a partial file. - staging_path.unlink(missing_ok=True) + # A descendant that survived the worker may still hold the file open on Windows; leaving + # it behind is better than replacing the job's real error with a PermissionError. + with suppress(OSError): + staging_path.unlink(missing_ok=True) + + # Report what this job wrote, even if another writer replaces the path right afterwards. + result["output_path"] = str(resolved_output_path) + result["bytes"] = artifact_size + return result + +def _parse_worker_result(job: JobKind, completed: subprocess.CompletedProcess[str]) -> dict[str, Any]: + """Turn a finished worker's exit status and protocol output into its result object.""" if completed.returncode != 0: detail = completed.stderr.strip() or completed.stdout.strip() or "worker failed without output" detail = detail[-_ERROR_OUTPUT_LIMIT:] @@ -240,26 +372,27 @@ def _run_serialized_payload( timeout_seconds: int, cancel_event: Event | None, ) -> subprocess.CompletedProcess[str]: - """Write a temporary payload and remove it after the worker stops.""" - with tempfile.NamedTemporaryFile( - "w", - suffix=".json", - encoding="utf-8", - delete=False, - ) as payload_file: - payload_file.write(serialized_payload) - payload_file_path = Path(payload_file.name) + """Write the payload to a private scratch directory and remove both after the worker stops. + The empty directory is also the worker's starting directory. ``python -m`` puts that + directory first on ``sys.path``, so starting the worker in the host's working directory + would let any ``json.py`` or ``visualtorch.py`` there shadow the installed packages. + """ + scratch_dir = Path(tempfile.mkdtemp(prefix="visualtorch-mcp-")) try: - return _run_worker(payload_file_path, timeout_seconds, cancel_event) + payload_file_path = scratch_dir / "payload.json" + payload_file_path.write_text(serialized_payload, encoding="utf-8") + return _run_worker(payload_file_path, timeout_seconds, cancel_event, cwd=scratch_dir) finally: - payload_file_path.unlink(missing_ok=True) + shutil.rmtree(scratch_dir, ignore_errors=True) def _run_worker( payload_file_path: Path, timeout_seconds: int, cancel_event: Event | None, + *, + cwd: Path, ) -> subprocess.CompletedProcess[str]: """Run a worker in its own process group so timeout cleanup reaches descendants.""" _raise_if_cancelled(cancel_event) @@ -271,6 +404,16 @@ def _run_worker( environment = os.environ.copy() environment["PYTHONIOENCODING"] = "utf-8" + python_path = environment.get("PYTHONPATH") + if python_path: + # Python makes relative PYTHONPATH entries absolute against its starting directory. The + # worker starts in a private scratch directory, so resolve them against this process's + # directory, as they were for the server, to keep both processes importing the same code. + environment["PYTHONPATH"] = os.pathsep.join( + os.path.abspath(entry) # noqa: PTH100 - keeps the exact string form of each entry. + for entry in python_path.split(os.pathsep) + if entry + ) # A file keeps arbitrary user diagnostics from consuming the MCP host's memory, and unlike # a pipe it cannot be held open in a way that blocks us by a user-spawned grandchild. with tempfile.TemporaryFile("w+b") as stderr_file: @@ -286,61 +429,65 @@ def _run_worker( stderr=stderr_file, text=True, env=environment, + cwd=cwd, **popen_kwargs, ) deadline = time.monotonic() + timeout_seconds try: - while True: - if cancel_event is not None and cancel_event.is_set(): - _raise_cancelled_worker(process) - - remaining = deadline - time.monotonic() - if remaining <= 0: - _raise_timed_out_worker(process, stderr_file, timeout_seconds) - - try: - stdout, _ = process.communicate( - timeout=min(_WORKER_POLL_INTERVAL_SECONDS, remaining), - ) - break - except subprocess.TimeoutExpired: - continue + stdout = _wait_for_protocol_output(process, deadline, cancel_event) except BaseException: - if process.poll() is None: - _stop_worker(process) + # Cancellation, or an interrupt in this thread: stop the tree before propagating. + _stop_worker(process) raise + if stdout is None: + _stop_worker(process) + message = f"VisualTorch job timed out after {timeout_seconds} seconds." + worker_output = _read_output_tail(stderr_file).strip() + if worker_output: + message = f"{message} Worker output: {worker_output}" + raise TimeoutError(message) stderr = _read_output_tail(stderr_file) return subprocess.CompletedProcess(process.args, process.returncode, stdout, stderr) +def _wait_for_protocol_output( + process: subprocess.Popen[str], + deadline: float, + cancel_event: Event | None, +) -> str | None: + """Return the worker's protocol output, or ``None`` once the deadline has passed.""" + while True: + _raise_if_cancelled(cancel_event) + remaining = deadline - time.monotonic() + if remaining <= 0: + return None + try: + stdout, _ = process.communicate(timeout=min(_WORKER_POLL_INTERVAL_SECONDS, remaining)) + except subprocess.TimeoutExpired: + continue + return stdout + + def _stop_worker(process: subprocess.Popen[str]) -> None: - """Terminate a worker tree and reap the protocol process.""" + """Terminate a worker tree and reap the protocol process, waiting a bounded time. + + A worker stuck in an uninterruptible kernel wait (a CUDA driver hang, an NFS stall) cannot + die even from SIGKILL, and a descendant that left the process group can hold the protocol + pipe open. Neither may keep the caller from reporting its timeout or cancellation. + """ _terminate_process_tree(process) try: - process.communicate(timeout=5) + process.communicate(timeout=_WORKER_STOP_GRACE_SECONDS) except subprocess.TimeoutExpired: process.kill() - process.communicate() - - -def _raise_cancelled_worker(process: subprocess.Popen[str]) -> NoReturn: - _stop_worker(process) - message = "VisualTorch job was cancelled." - raise JobCancelledError(message) - - -def _raise_timed_out_worker( - process: subprocess.Popen[str], - stderr_file: Any, # noqa: ANN401 - binary temporary file protocol. - timeout_seconds: int, -) -> NoReturn: - _stop_worker(process) - stderr = _read_output_tail(stderr_file) - message = f"VisualTorch job timed out after {timeout_seconds} seconds." - if stderr.strip(): - message = f"{message} Worker output: {stderr.strip()}" - raise TimeoutError(message) + with suppress(subprocess.TimeoutExpired): + process.wait(timeout=_WORKER_STOP_GRACE_SECONDS) + # On Windows a communicate() reader thread may still be blocked reading the pipe, and + # closing the stream would wait for it; that daemon thread closes the pipe at EOF. + if os.name != "nt" and process.stdout is not None: + with suppress(OSError): + process.stdout.close() def _terminate_process_tree(process: subprocess.Popen[str]) -> None: @@ -409,17 +556,6 @@ def _read_output_tail(stream: Any) -> str: # noqa: ANN401 - binary temporary fi return stream.read().decode("utf-8", errors="replace")[-_ERROR_OUTPUT_LIMIT:] -def _reserve_staging_path(output_path: Path) -> Path: - """Reserve a same-directory artifact path owned and cleaned by the parent process.""" - descriptor, name = tempfile.mkstemp( - prefix=".visualtorch-mcp-", - suffix=output_path.suffix, - dir=output_path.parent, - ) - os.close(descriptor) - return Path(name) - - def _raise_if_cancelled(cancel_event: Event | None) -> None: if cancel_event is not None and cancel_event.is_set(): message = "VisualTorch job was cancelled." @@ -449,7 +585,13 @@ def _resolve_workdir(value: str | None) -> Path | None: if not isinstance(value, str) or not value.strip(): message = "workdir must be a non-empty path string when provided." raise ValueError(message) - path = Path(value).expanduser().resolve() + path = Path(value).expanduser() + if not path.is_absolute(): + # A relative workdir would resolve against the server's working directory, which the + # MCP host picks and the client cannot see. + message = f"workdir must be an absolute path (or start with ~), got {value!r}." + raise ValueError(message) + path = path.resolve() if not path.exists(): message = f"workdir does not exist: {path}" raise ValueError(message) diff --git a/visualtorch_mcp/server.py b/visualtorch_mcp/server.py index 7898a94..461b057 100644 --- a/visualtorch_mcp/server.py +++ b/visualtorch_mcp/server.py @@ -5,7 +5,7 @@ import argparse import json from functools import partial -from threading import Event +from threading import Event, Lock from typing import TYPE_CHECKING, Annotated import anyio @@ -14,8 +14,8 @@ from . import MCP_API_VERSION, __version__ from .api_reference import capabilities_manifest, docs_manifest +from .runner import JobCancelledError, render_model from .runner import animate_model as run_animation -from .runner import render_model if TYPE_CHECKING: from collections.abc import Callable @@ -129,13 +129,41 @@ async def _run_cancellable_job( function: Callable[..., dict[str, object]], **kwargs: object, ) -> dict[str, object]: - """Run a blocking job while propagating MCP cancellation to its worker process.""" + """Run a blocking job while propagating MCP cancellation to its worker process. + + On cancellation the job thread is told to stop, and the cancellation only completes once that + thread has finished. Otherwise a job that had already passed its last cancellation check + could still replace its output file after the caller was told the call was cancelled, and + even overwrite the result of a later call to the same path. + """ cancel_event = Event() + finished = Event() + state_lock = Lock() + started = False call = partial(function, _cancel_event=cancel_event, **kwargs) + + def run() -> dict[str, object]: + nonlocal started + with state_lock: + if cancel_event.is_set(): + message = "VisualTorch job was cancelled." + raise JobCancelledError(message) + started = True + try: + return call() + finally: + finished.set() + try: - return await anyio.to_thread.run_sync(call, abandon_on_cancel=True) + return await anyio.to_thread.run_sync(run, abandon_on_cancel=True) except anyio.get_cancelled_exc_class(): - cancel_event.set() + with state_lock: + cancel_event.set() + job_started = started + # A job thread that has not started yet will see the event and return without working. + if job_started: + with anyio.CancelScope(shield=True): + await anyio.to_thread.run_sync(finished.wait) raise diff --git a/visualtorch_mcp/worker.py b/visualtorch_mcp/worker.py index bbc50b3..2db3bc2 100644 --- a/visualtorch_mcp/worker.py +++ b/visualtorch_mcp/worker.py @@ -6,8 +6,11 @@ import inspect import json import os +import signal +import subprocess import sys -import tempfile +import threading +import time import traceback from contextlib import suppress from pathlib import Path @@ -15,14 +18,30 @@ from PIL import Image, ImageFont +from visualtorch_mcp._files import is_staging_path, publish_artifact, reserve_staging_path + if TYPE_CHECKING: from collections.abc import Callable JobKind = Literal["render", "animate"] - -def main() -> None: - """Execute the JSON job payload passed on the command line.""" +_SOURCE_FILENAME = "" +_ANIMATION_CONTROLS = ("frame_duration", "final_hold_duration", "loop") +_DURATION_CONTROLS = ("frame_duration", "final_hold_duration") +# GIF stores frame delays as a 16-bit count of hundredths of a second, and browsers slow delays +# of 10 ms or less down to about 100 ms, so 20 ms is the shortest delay that plays as requested. +MIN_FRAME_DURATION_MS = 20 +MAX_FRAME_DURATION_MS = 655_350 +GIF_DELAY_RESOLUTION_MS = 10 +# The server normally stops a late worker itself and reports the timeout. The worker's own +# deadline only takes over when the server has died or stopped supervising it. +_WATCHDOG_GRACE_SECONDS = 10 +_WATCHDOG_INTERVAL_SECONDS = 0.5 +_WATCHDOG_EXIT_CODE = 3 + + +def main() -> int: + """Execute the JSON job payload passed on the command line and return an exit status.""" protocol_fd = os.dup(sys.stdout.fileno()) try: # Redirect the OS-level stdout descriptor, not just Python's sys.stdout. This also @@ -30,15 +49,176 @@ def main() -> None: sys.stdout.flush() os.dup2(sys.stderr.fileno(), sys.stdout.fileno()) payload = _load_payload(sys.argv) + # Model source must not see the worker's own arguments (a module-level argparse call + # would reject the payload path). + sys.argv = [_SOURCE_FILENAME] + _start_watchdog(payload) result = _run_from_payload(payload) - except Exception as exc: - print(f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}", file=sys.stderr) + except BaseException as exc: # noqa: BLE001 - also report SystemExit/KeyboardInterrupt raised by model source. + print(_describe_failure(exc), file=sys.stderr) os.close(protocol_fd) - raise SystemExit(1) from exc + return 1 with os.fdopen(protocol_fd, "w", encoding="utf-8") as protocol_stdout: json.dump(result, protocol_stdout) protocol_stdout.write("\n") + return 0 + + +def _describe_failure(exc: BaseException) -> str: + """Format a job failure, explaining exits that model source triggered itself.""" + detail = f"{type(exc).__name__}: {exc}" + if isinstance(exc, SystemExit): + detail = ( + f"The job raised SystemExit({exc.code!r}) and stopped before the render finished; model " + "source must not call sys.exit() or exit()." + ) + return f"{detail}\n{traceback.format_exc()}" + + +def _exit_now(status: int) -> None: + """Flush diagnostics and exit without running interpreter shutdown. + + Non-daemon threads or atexit hooks left behind by model source would otherwise keep the + worker alive after its result was written, until the server reported a timeout. + """ + _stop_daemonic_children() + for stream in (sys.stdout, sys.stderr): + with suppress(Exception): + stream.flush() + os._exit(status) + + +def _stop_daemonic_children() -> None: + """Terminate daemonic multiprocessing children, as interpreter shutdown would have. + + ``os._exit`` skips the multiprocessing exit handler, so without this every successful job + whose model source started a daemonic ``multiprocessing.Process`` would leave it running. + """ + multiprocessing = sys.modules.get("multiprocessing") + if multiprocessing is None: + return + with suppress(Exception): + children = [child for child in multiprocessing.active_children() if child.daemon] + for child in children: + child.terminate() + for child in children: + child.join(timeout=1) + + +def _start_watchdog(payload: dict[str, Any]) -> None: + """Stop this worker if the server process dies or the job outlives its deadline. + + The worker runs in its own session or process group so the server can stop its whole tree. + That also means a host that kills the server's process group does not reach the worker, so + without this a worker whose server crashed would keep rendering with no timeout. + """ + parent_pid = payload.get("parent_pid") + timeout_seconds = payload.get("timeout_seconds") + parent_alive: Callable[[], bool] | None = None + if isinstance(parent_pid, int) and not isinstance(parent_pid, bool): + parent_alive = _parent_monitor(parent_pid) + deadline: float | None = None + if isinstance(timeout_seconds, int | float) and not isinstance(timeout_seconds, bool): + deadline = time.monotonic() + timeout_seconds + _WATCHDOG_GRACE_SECONDS + if parent_alive is None and deadline is None: + return # A direct invocation without a supervising server. + staging_path = _orphan_cleanup_path(payload) + + def watch() -> None: + while True: + time.sleep(_WATCHDOG_INTERVAL_SECONDS) + if parent_alive is not None and not parent_alive(): + _abort_orphaned_worker("the MCP server process exited", staging_path) + if deadline is not None and time.monotonic() >= deadline: + _abort_orphaned_worker(f"the job exceeded its {timeout_seconds}-second timeout", staging_path) + + threading.Thread(target=watch, name="visualtorch-mcp-watchdog", daemon=True).start() + + +def _orphan_cleanup_path(payload: dict[str, Any]) -> Path | None: + """Return the staging file an orphaned worker may delete, if the payload names a safe one. + + The watchdog starts before the payload's paths are validated, so it only ever deletes a + file named like a reserved staging file that is not the job's output path. + """ + staging_path = payload.get("staging_path") + output_path = payload.get("output_path") + if not isinstance(staging_path, str) or not staging_path.strip(): + return None + candidate = Path(staging_path).expanduser() + if not is_staging_path(candidate): + return None + if isinstance(output_path, str): + try: + if candidate.resolve() == Path(output_path).expanduser().resolve(): + return None + except (OSError, RuntimeError): + return None + return candidate + + +def _parent_monitor(parent_pid: int) -> Callable[[], bool]: + """Return a cheap check that the process which started this worker is still running.""" + if sys.platform == "win32": + import ctypes # noqa: PLC0415 - Windows-only dependency. + from ctypes import wintypes # noqa: PLC0415 - Windows-only dependency. + + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.OpenProcess.restype = wintypes.HANDLE + kernel32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) + kernel32.WaitForSingleObject.restype = wintypes.DWORD + kernel32.WaitForSingleObject.argtypes = (wintypes.HANDLE, wintypes.DWORD) + synchronize = 0x00100000 + wait_object_0 = 0 + # Holding the handle pins this exact process, so a reused process ID cannot fool the check. + handle = kernel32.OpenProcess(synchronize, False, parent_pid) # noqa: FBT003 - Win32 BOOL argument. + if not handle: + error_invalid_parameter = 87 + if ctypes.get_last_error() == error_invalid_parameter: + return lambda: False # No such process: the server exited before we started. + return lambda: True # Cannot observe the parent; the deadline still applies. + return lambda: kernel32.WaitForSingleObject(handle, 0) != wait_object_0 + + if os.getppid() == parent_pid: + # A POSIX child is re-parented (to init or a subreaper) as soon as its parent exits. + return lambda: os.getppid() == parent_pid + + def parent_exists() -> bool: + try: + os.kill(parent_pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True + + return parent_exists + + +def _abort_orphaned_worker(reason: str, staging_path: Path | None) -> None: + """Remove the parent-owned staging file and stop this worker and its descendants.""" + with suppress(Exception): + print(f"VisualTorch worker stopped itself: {reason}.", file=sys.stderr, flush=True) + if staging_path is not None: + with suppress(OSError): + staging_path.unlink(missing_ok=True) + if sys.platform == "win32": + # Take processes started by model source down too; this also ends the worker itself. + with suppress(OSError, subprocess.SubprocessError): + subprocess.run( # noqa: S603 - fixed Windows process-tree cleanup command. + ["taskkill", "/T", "/F", "/PID", str(os.getpid())], # noqa: S607 - platform executable. + check=False, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=5, + ) + elif os.getpgrp() == os.getpid(): + # The server starts the worker as a session leader; take model-spawned processes too. + with suppress(OSError): + os.killpg(os.getpid(), signal.SIGKILL) + _exit_now(_WATCHDOG_EXIT_CODE) def _load_payload(arguments: list[str]) -> dict[str, Any]: @@ -61,13 +241,11 @@ def _run_from_payload(payload: dict[str, Any]) -> dict[str, Any]: workdir = payload.get("workdir") if workdir: - resolved_workdir = Path(workdir).expanduser().resolve() - if not resolved_workdir.is_dir(): - message = f"workdir is not an existing directory: {resolved_workdir}" - raise ValueError(message) - os.chdir(resolved_workdir) - if str(resolved_workdir) not in sys.path: - sys.path.insert(0, str(resolved_workdir)) + _enter_workdir(workdir) + elif payload.get("cwd"): + # The server starts the worker in a private scratch directory that it deletes afterwards; + # model source and the processes it starts run in the directory the server chose instead. + os.chdir(Path(payload["cwd"]).expanduser()) source = payload.get("source") if not isinstance(source, str) or not source.strip(): @@ -99,7 +277,10 @@ def _run_from_payload(payload: dict[str, Any]) -> dict[str, Any]: raise TypeError(message) options = _coerce_options(namespace, raw_options) if job == "animate": - _validate_animation_options(options) + options = _prepare_animation_options(options) + # The server publishes its staging file itself, and only once this worker has reported + # success. A direct invocation has nobody else to move the artifact into place. + server_publishes = payload.get("parent_publishes") is True staging_path = _resolve_staging_path(payload.get("staging_path"), output_path, expected_suffix) try: # Render to a fresh, same-directory staging file. This prevents a pre-existing final @@ -121,12 +302,24 @@ def _run_from_payload(payload: dict[str, Any]) -> dict[str, Any]: raise RuntimeError(message) metadata = _artifact_metadata(staging_path, job, payload["style"]) - staging_path.replace(output_path) + if not server_publishes: + publish_artifact(staging_path, output_path) metadata["output_path"] = str(output_path) - metadata["bytes"] = output_path.stat().st_size return metadata finally: - staging_path.unlink(missing_ok=True) + if not server_publishes: + staging_path.unlink(missing_ok=True) + + +def _enter_workdir(workdir: str) -> None: + """Make ``workdir`` the current directory and the first import location for model source.""" + resolved_workdir = Path(workdir).expanduser().resolve() + if not resolved_workdir.is_dir(): + message = f"workdir is not an existing directory: {resolved_workdir}" + raise ValueError(message) + os.chdir(resolved_workdir) + if str(resolved_workdir) not in sys.path: + sys.path.insert(0, str(resolved_workdir)) # Backward-compatible internal name used by existing unit tests and integrations. @@ -137,7 +330,7 @@ def _render_from_payload(payload: dict[str, Any]) -> dict[str, Any]: def _execute_source(source: str) -> dict[str, Any]: namespace: dict[str, Any] = {"__name__": "__visualtorch_user_model__"} - exec(compile(source, "", "exec"), namespace) # noqa: S102 - intentional model execution. + exec(compile(source, _SOURCE_FILENAME, "exec"), namespace) # noqa: S102 - intentional model execution. return namespace @@ -192,12 +385,13 @@ def _artifact_metadata(output_path: Path, job: JobKind, style: str) -> dict[str, for frame_index in range(frame_count): artifact.seek(frame_index) durations.append(artifact.info.get("duration")) - raw_loop = artifact.info.get("loop") metadata.update( { "frame_count": frame_count, "durations_ms": durations, - "loop": None if raw_loop is None else raw_loop == 0, + # A NETSCAPE loop count of 0 repeats forever. Without that extension + # the GIF plays once; any other count repeats a fixed number of times. + "loop": artifact.info.get("loop") == 0, }, ) return metadata @@ -225,13 +419,7 @@ def _resolve_staging_path(value: object, output_path: Path, suffix: str) -> Path raise ValueError(message) return staging_path - descriptor, name = tempfile.mkstemp( - prefix=".visualtorch-mcp-", - suffix=suffix, - dir=output_path.parent, - ) - os.close(descriptor) - return Path(name) + return reserve_staging_path(output_path.parent, suffix) def _legacy_render_function(style: str) -> Callable[..., object]: @@ -359,14 +547,39 @@ def _coerce_font(value: object) -> object: raise ValueError(message) from exc +def _prepare_animation_options(options: dict[str, Any]) -> dict[str, Any]: + """Return options with null animation controls dropped, validated, and GIF-quantized. + + A null control selects VisualTorch's default instead of reaching Pillow as ``None``. Frame + delays are rounded to the nearest 10 ms because GIF cannot store anything finer. + """ + prepared = {name: value for name, value in options.items() if not (name in _ANIMATION_CONTROLS and value is None)} + _validate_animation_options(prepared) + for name in _DURATION_CONTROLS: + if name in prepared: + prepared[name] = ( + (prepared[name] + GIF_DELAY_RESOLUTION_MS // 2) // GIF_DELAY_RESOLUTION_MS * GIF_DELAY_RESOLUTION_MS + ) + return prepared + + def _validate_animation_options(options: dict[str, Any]) -> None: """Validate the shared JSON animation controls before calling VisualTorch.""" - for name in ("frame_duration", "final_hold_duration"): + for name in _DURATION_CONTROLS: value = options.get(name) - if value is not None and (not isinstance(value, int) or isinstance(value, bool) or value < 1): - message = f"{name} must be a positive integer number of milliseconds." + if value is not None and ( + not isinstance(value, int) + or isinstance(value, bool) + or not MIN_FRAME_DURATION_MS <= value <= MAX_FRAME_DURATION_MS + ): + message = ( + f"{name} must be an integer number of milliseconds between {MIN_FRAME_DURATION_MS} and " + f"{MAX_FRAME_DURATION_MS}: GIF viewers slow shorter frame delays down to about 100 ms, " + "and GIF cannot store longer ones." + ) raise ValueError(message) - if "loop" in options and not isinstance(options["loop"], bool): + loop = options.get("loop") + if loop is not None and not isinstance(loop, bool): message = "loop must be a boolean." raise TypeError(message) @@ -433,4 +646,4 @@ def _restore_tuples(value: object) -> object: if __name__ == "__main__": - main() + _exit_now(main())