From 73cf665c714f28a62b63e05687d11a1579ebf78a Mon Sep 17 00:00:00 2001 From: Laura Kasian Date: Fri, 13 Nov 2026 20:39:38 -0700 Subject: [PATCH 1/4] feat: run the PARAVIEW session in a pvpython process --- .../viewer/app/paraview/session_channel.py | 255 +++++++++++++++ .../visor/viewer/app/paraview/session_main.py | 142 +++++++++ .../viewer/app/paraview/session_process.py | 236 ++++++++++++++ tests/unit/app/test_session_channel.py | 214 +++++++++++++ tests/unit/app/test_session_main.py | 138 ++++++++ tests/unit/app/test_session_process.py | 295 ++++++++++++++++++ 6 files changed, 1280 insertions(+) create mode 100644 src/ansys/visor/viewer/app/paraview/session_channel.py create mode 100644 src/ansys/visor/viewer/app/paraview/session_main.py create mode 100644 src/ansys/visor/viewer/app/paraview/session_process.py create mode 100644 tests/unit/app/test_session_channel.py create mode 100644 tests/unit/app/test_session_main.py create mode 100644 tests/unit/app/test_session_process.py diff --git a/src/ansys/visor/viewer/app/paraview/session_channel.py b/src/ansys/visor/viewer/app/paraview/session_channel.py new file mode 100644 index 00000000..89a5fae6 --- /dev/null +++ b/src/ansys/visor/viewer/app/paraview/session_channel.py @@ -0,0 +1,255 @@ +""" +Session channel +=============== +The messages and both ends of the connection between the API process and the +pvpython session process. + +Every class that crosses the connection is defined here, never in the child's +entry script: that script runs as ``__main__``, and a class pickled from there +would be named ``__main__.X`` and fail to load on the other side. + +Payloads are pickled by the connection. Numpy values in arguments and results +are turned into plain Python values first (:func:`to_plain`), so neither end +unpickles a numpy object written by the other end's numpy version. +""" + +from __future__ import annotations + +import dataclasses +import inspect +import threading +from dataclasses import dataclass, field +from multiprocessing.connection import Connection +from pathlib import Path +from typing import Any, Callable, Coroutine + +import numpy as np +from pydantic import BaseModel + +from ansys.visor.viewer.core import errors +from ansys.visor.viewer.core.pvserver_address import PvserverAddress +from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger + +logger = VisorDefaultLogger(__name__) + +SERVED_METHODS: frozenset[str] = frozenset({ + "start", + "stop", + "update", + "add_dataset", + "remove_dataset", + "list_datasets", + "list_variables", + "save_state", + "load_state", + "_health", +}) +"""The methods the session process serves on its Visor.""" + +_VALUE_STYLE_ERRORS: tuple[type[Exception], ...] = ( + errors.InvalidFileError, + errors.InvalidFileFormatError, + errors.InvalidUrlError, + errors.InvalidPathError, + errors.ServerNotStartedError, + errors.InvalidServerTimeoutError, +) +"""Errors whose ``str`` wraps the constructor value in a prefix, so the value is sent instead.""" + +_KNOWN_ERRORS: dict[str, type[Exception]] = { + cls.__name__: cls + for cls in ( + *_VALUE_STYLE_ERRORS, + errors.VisorAddDatasetError, + errors.PvserverConnectionError, + errors.UnsupportedInModeError, + TypeError, + ValueError, + FileNotFoundError, + RuntimeError, + ) +} + + +def to_plain(value: Any) -> Any: + """Return value with numpy scalars and arrays replaced by Python values, inside lists, tuples, dicts and dataclasses. + + A dataclass keeps its type: it is rebuilt with ``dataclasses.replace``. + Any other object, including a pydantic model, is returned unchanged. + """ + if isinstance(value, np.ndarray): + return value.tolist() + if isinstance(value, np.generic): + return value.item() + if isinstance(value, dict): + return {to_plain(key): to_plain(item) for key, item in value.items()} + if isinstance(value, list): + return [to_plain(item) for item in value] + if isinstance(value, tuple): + return tuple(to_plain(item) for item in value) + if dataclasses.is_dataclass(value) and not isinstance(value, type): + changes = {f.name: to_plain(getattr(value, f.name)) for f in dataclasses.fields(value) if f.init} + return dataclasses.replace(value, **changes) + return value + + +class SessionLaunchRequest(BaseModel): + """Everything the session process needs to build its VisorVTKParaview.""" + + url: str + standalone: bool + dark_mode: bool | None + trame_log_dir: str | None + pvserver: PvserverAddress + + +class SessionReady(BaseModel): + """Sent once by the session process when its Visor is built.""" + + +class SessionError(BaseModel): + """An error crossing the process boundary as its class name and message.""" + + type_name: str + message: str + + @classmethod + def from_exception(cls, exc: BaseException) -> SessionError: + """Describe exc; a value-style Visor error sends its constructor value so it is not wrapped twice.""" + if isinstance(exc, _VALUE_STYLE_ERRORS) and exc.args: + message = str(exc.args[0]) + else: + message = str(exc) + return cls(type_name=type(exc).__name__, message=message) + + def to_exception(self) -> Exception: + """Rebuild a known Visor or builtin error type; anything else becomes RuntimeError with the type named.""" + error_cls = _KNOWN_ERRORS.get(self.type_name) + if error_cls is None: + return RuntimeError(f"{self.type_name}: {self.message}") + return error_cls(self.message) + + +@dataclass(frozen=True) +class SessionRequest: + """One method call on the session's Visor.""" + + method: str + args: tuple = () + kwargs: dict = field(default_factory=dict) + + +@dataclass(frozen=True) +class SessionResult: + """The value a served method returned.""" + + value: Any = None + + +@dataclass(frozen=True) +class SessionShutdown: + """Ends the serve loop; the session process then exits.""" + + +class SessionChannel: + """Parent end of the session connection: one request, one reply, serialized by a lock.""" + + def __init__(self, connection: Connection, log_path: Path) -> None: + """Wrap an authenticated connection; log_path is named when the connection is lost.""" + self._connection = connection + self._log_path = log_path + self._lock = threading.Lock() + + def call(self, method: str, *args: Any, **kwargs: Any) -> Any: + """Send one request and return its result, or raise the error the child reported. + + There is no per-call timeout. A session process that exits or crashes + closes the connection, and the wait ends in ParaviewSessionError. + """ + request = SessionRequest(method=method, args=to_plain(args), kwargs=to_plain(kwargs)) + with self._lock: + try: + self._connection.send(request) + reply = self._connection.recv() + except (EOFError, OSError) as exc: + raise errors.ParaviewSessionError( + f"The PARAVIEW session process was lost during {method!r}; see its log at {self._log_path}" + ) from exc + if isinstance(reply, SessionError): + raise reply.to_exception() + return reply.value + + def shutdown(self) -> bool: + """Ask the session process to exit; return False when a call holds the channel or the connection is gone.""" + if not self._lock.acquire(blocking=False): + return False + try: + self._connection.send(SessionShutdown()) + return True + except OSError: + return False + finally: + self._lock.release() + + def close(self) -> None: + """Close the connection.""" + self._connection.close() + + +class SessionServer: + """Child end: receive requests, dispatch them to a target object, reply.""" + + def __init__( + self, + connection: Connection, + target: object, + allowed: frozenset[str], + run_coroutine: Callable[[Coroutine], Any], + ) -> None: + """Serve only the method names in allowed; run_coroutine runs a coroutine result to completion.""" + self._connection = connection + self._target = target + self._allowed = allowed + self._run_coroutine = run_coroutine + + def serve_forever(self) -> None: + """Serve until shutdown or until the connection closes.""" + while True: + try: + message = self._connection.recv() + except (EOFError, OSError): + logger.info("Session channel closed") + return + if isinstance(message, SessionShutdown): + logger.info("Session shutdown requested") + return + reply = self._dispatch(message) + try: + self._connection.send(reply) + except OSError: + logger.info("Session channel closed while replying") + return + except Exception as exc: + logger.exception("Result of %r could not be sent", getattr(message, "method", message)) + try: + self._connection.send(SessionError.from_exception(exc)) + except OSError: + return + + def _dispatch(self, message: object) -> SessionResult | SessionError: + """Run one request on the target and describe its outcome.""" + if not isinstance(message, SessionRequest): + return SessionError(type_name="RuntimeError", message=f"Unexpected session message {type(message).__name__}") + if message.method not in self._allowed: + return SessionError( + type_name="RuntimeError", + message=f"Method {message.method!r} is not served by the PARAVIEW session", + ) + try: + result = getattr(self._target, message.method)(*message.args, **message.kwargs) + if inspect.iscoroutine(result): + result = self._run_coroutine(result) + return SessionResult(value=to_plain(result)) + except Exception as exc: + logger.exception("Session method %r failed", message.method) + return SessionError.from_exception(exc) diff --git a/src/ansys/visor/viewer/app/paraview/session_main.py b/src/ansys/visor/viewer/app/paraview/session_main.py new file mode 100644 index 00000000..8d0919f5 --- /dev/null +++ b/src/ansys/visor/viewer/app/paraview/session_main.py @@ -0,0 +1,142 @@ +""" +Session main +============ +The program pvpython runs for one PARAVIEW session. + +It reads the channel authkey from the first line of stdin, connects to the +parent on ``--channel-host``/``--channel-port``, receives a +:class:`SessionLaunchRequest`, connects to pvserver, builds a +:class:`VisorVTKParaview` and reports ready or failed. It then serves the +channel until shutdown or until the connection closes, and exits. A parent +that exits or crashes closes the connection, so this process exits with it. +""" + +from __future__ import annotations + +import argparse +import os +import socket +import sys +import traceback +from multiprocessing.connection import Connection, answer_challenge, deliver_challenge +from typing import TextIO + +from ansys.visor.viewer.app.paraview.session_channel import ( + SERVED_METHODS, + SessionError, + SessionLaunchRequest, + SessionReady, + SessionServer, +) +from ansys.visor.viewer.app.paraview.visor_vtk_paraview import VisorVTKParaview +from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger +from ansys.visor.viewer.renderer.paraview_session import PvSimpleSession + +logger = VisorDefaultLogger(__name__) + + +class ParaviewSessionMain: + """The pvpython-side program: parse argv, read the authkey, build the session, serve the channel.""" + + def __init__(self, argv: list[str], stdin: TextIO) -> None: + """Parse --channel-host/--channel-port with parse_known_args, since pvpython adds arguments of its own.""" + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument("--channel-host", required=True) + parser.add_argument("--channel-port", required=True, type=int) + options, _unknown = parser.parse_known_args(argv) + self._host: str = options.channel_host + self._port: int = options.channel_port + self._stdin = stdin + + def run(self) -> int: + """Connect the channel, build VisorVTKParaview, report ready or failed, serve; return the exit code.""" + authkey = bytes.fromhex(self._stdin.readline().strip()) + if not authkey: + logger.error("No channel authkey on stdin") + print("No channel authkey on stdin", file=sys.stderr) + return 1 + connection = self._connect(authkey) + try: + return self._serve(connection) + finally: + connection.close() + + def connect_session(self, request: SessionLaunchRequest) -> PvSimpleSession: + """Connect to the requested pvserver.""" + return PvSimpleSession(request.pvserver) + + def build_visor(self, request: SessionLaunchRequest, session: PvSimpleSession) -> VisorVTKParaview: + """Build the session's Visor over the connected session.""" + return VisorVTKParaview( + url=request.url, + standalone=request.standalone, + dark_mode=request.dark_mode, + trame_log_dir=request.trame_log_dir, + pvserver=request.pvserver, + session=session, + ) + + def _connect(self, authkey: bytes) -> Connection: + """Connect to the parent and authenticate both ways, in the order the parent expects.""" + sock = socket.create_connection((self._host, self._port)) + connection = Connection(sock.detach()) + answer_challenge(connection, authkey) + deliver_challenge(connection, authkey) + return connection + + def _serve(self, connection: Connection) -> int: + """Build the session from the parent's request, report the outcome, and serve until the channel ends.""" + request: SessionLaunchRequest = connection.recv() + try: + session = self.connect_session(request) + except Exception as exc: + logger.exception("Could not connect the ParaView session") + traceback.print_exc() + connection.send(SessionError.from_exception(exc)) + return 1 + try: + try: + visor = self.build_visor(request, session) + except Exception as exc: + logger.exception("Could not build the PARAVIEW Visor") + traceback.print_exc() + connection.send(SessionError.from_exception(exc)) + return 1 + connection.send(SessionReady()) + runner = visor._server_manager.async_runner + server = SessionServer( + connection, + visor, + SERVED_METHODS, + run_coroutine=lambda coroutine: runner.run_coroutine_block(coroutine, False), + ) + server.serve_forever() + if visor.running: + visor.stop() + return 0 + finally: + session.disconnect() + + +def main() -> int: + """Run ParaviewSessionMain over sys.argv and sys.stdin, then end the process. + + A failure is written to stderr, which is the session log, as well as to + the Visor log. ``os._exit`` ends the process even if a non-daemon thread + is still running, so the process never outlives its channel. + """ + code = 1 + try: + code = ParaviewSessionMain(sys.argv[1:], sys.stdin).run() + except BaseException: + logger.exception("PARAVIEW session failed") + traceback.print_exc() + finally: + sys.stdout.flush() + sys.stderr.flush() + os._exit(code) + return code + + +if __name__ == "__main__": + main() diff --git a/src/ansys/visor/viewer/app/paraview/session_process.py b/src/ansys/visor/viewer/app/paraview/session_process.py new file mode 100644 index 00000000..254e2d0a --- /dev/null +++ b/src/ansys/visor/viewer/app/paraview/session_process.py @@ -0,0 +1,236 @@ +""" +Session process +=============== +Spawns and ends the pvpython process that runs one PARAVIEW session, and +returns the channel to it once the session reports ready. + +The parent listens on a loopback port and the child connects. The 32-byte +authkey reaches the child as one hex line on its stdin, never in argv or the +environment. The child's stdout and stderr go to a log file, so no pipe can +fill and block it. The child is not detached: it exits when its connection +closes, so it does not outlive this process. +""" + +from __future__ import annotations + +import importlib.util +import secrets +import socket +import subprocess +import time +from multiprocessing import AuthenticationError +from multiprocessing.connection import Connection, answer_challenge, deliver_challenge +from pathlib import Path + +from ansys.visor.viewer.app.paraview.session_channel import ( + SessionChannel, + SessionError, + SessionLaunchRequest, + SessionReady, +) +from ansys.visor.viewer.config import Settings +from ansys.visor.viewer.core.errors import ParaviewNotConfiguredError, ParaviewSessionError +from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger + +logger = VisorDefaultLogger(__name__) + +SESSION_MAIN_MODULE = "ansys.visor.viewer.app.paraview.session_main" +"""The child entry module; its file path is passed to pvpython.""" + +CHANNEL_HOST = "127.0.0.1" +"""The loopback address the parent listens on.""" + +WAIT_SLICE_S = 0.5 +"""Seconds between checks that the child is still running while waiting for it.""" + +END_GRACE_S = 5.0 +"""Seconds end() waits after each step before escalating.""" + + +class ParaviewSessionProcess: + """Spawns and ends one pvpython session process and owns its channel.""" + + def __init__(self, pvpython: Path, venv: Path, log_path: Path, start_timeout: float) -> None: + """Hold the launch settings; spawns nothing.""" + self._pvpython = Path(pvpython) + self._venv = Path(venv) + self._log_path = Path(log_path) + self._start_timeout = start_timeout + self._process: subprocess.Popen | None = None + self._connection: Connection | None = None + self._channel: SessionChannel | None = None + self._ended = False + + @classmethod + def from_settings(cls, settings: Settings, url_port: int) -> ParaviewSessionProcess: + """Build from settings; raise ParaviewNotConfiguredError naming the missing .visor key.""" + for key in ("paraview_pvpython", "paraview_venv"): + if not getattr(settings, key): + raise ParaviewNotConfiguredError(f"PARAVIEW mode needs '{key}' set in the .visor file") + return cls( + pvpython=Path(settings.paraview_pvpython), + venv=Path(settings.paraview_venv), + log_path=Path(settings.default_log_dir) / f"visor_paraview_session_{url_port}.log", + start_timeout=settings.paraview_session_start_timeout, + ) + + @property + def alive(self) -> bool: + """Whether the child process is still running.""" + return self._process is not None and self._process.poll() is None + + @property + def log_path(self) -> Path: + """The file receiving the child's stdout and stderr.""" + return self._log_path + + def launch(self, request: SessionLaunchRequest) -> SessionChannel: + """Spawn the child, hand it the authkey on stdin, and return the channel once it reports ready. + + An error the child reports is raised as its own type after the child + is ended. A child that exits, never connects or never reports ready + within the start timeout is ended, and ParaviewSessionError names the log. + """ + if self._process is not None: + raise RuntimeError("This session process has already been launched") + authkey = secrets.token_bytes(32) + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + listener.bind((CHANNEL_HOST, 0)) + listener.listen(1) + listener.settimeout(WAIT_SLICE_S) + self._spawn(listener.getsockname()[1], authkey) + deadline = time.monotonic() + self._start_timeout + reply = self._await_ready(listener, authkey, request, deadline) + except ParaviewSessionError: + self.end() + raise + except (EOFError, OSError, AuthenticationError) as exc: + self.end() + raise ParaviewSessionError( + f"The PARAVIEW session process was lost before it reported ready; see its log at {self._log_path}" + ) from exc + finally: + listener.close() + if isinstance(reply, SessionError): + logger.error("PARAVIEW session failed to start: %s: %s", reply.type_name, reply.message) + self.end() + raise reply.to_exception() + self._channel = SessionChannel(self._connection, self._log_path) + logger.info("PARAVIEW session ready; log at %s", self._log_path) + return self._channel + + def end(self) -> None: + """Send shutdown and wait, then terminate and wait, then kill; idempotent. + + A child that reported an error gets the same wait to exit by itself. + With no connection to the child, it is terminated at once. + """ + if self._process is None or self._ended: + return + self._ended = True + process = self._process + if self._channel is not None: + self._channel.shutdown() + if self._connection is not None and process.poll() is None: + if self._wait(process): + self._close_connection() + return + if process.poll() is None: + logger.warning("Terminating PARAVIEW session process %s", process.pid) + process.terminate() + if not self._wait(process): + logger.warning("Killing PARAVIEW session process %s", process.pid) + process.kill() + process.wait() + self._close_connection() + + def _spawn(self, port: int, authkey: bytes) -> None: + """Start pvpython with stdout and stderr appended to the log, then write the authkey line and close stdin.""" + self._log_path.parent.mkdir(parents=True, exist_ok=True) + command = self._command(port) + logger.info("Launching PARAVIEW session: %s", command) + with open(self._log_path, "ab") as log: + try: + self._process = subprocess.Popen( + command, + stdin=subprocess.PIPE, + stdout=log, + stderr=subprocess.STDOUT, + ) + except OSError as exc: + raise ParaviewSessionError(f"Could not start pvpython at {self._pvpython}: {exc}") from exc + try: + self._process.stdin.write(authkey.hex().encode("ascii") + b"\n") + self._process.stdin.flush() + finally: + self._process.stdin.close() + + def _command(self, port: int) -> list[str]: + """The pvpython command line; --venv takes a forward-slash path.""" + script = importlib.util.find_spec(SESSION_MAIN_MODULE).origin + return [ + str(self._pvpython), + "--venv", + self._venv.as_posix(), + script, + "--channel-host", + CHANNEL_HOST, + "--channel-port", + str(port), + ] + + def _await_ready( + self, + listener: socket.socket, + authkey: bytes, + request: SessionLaunchRequest, + deadline: float, + ) -> SessionReady | SessionError: + """Accept the child, authenticate both ways, send the request and return its reply.""" + sock = self._accept(listener, deadline) + sock.setblocking(True) + self._connection = Connection(sock.detach()) + deliver_challenge(self._connection, authkey) + answer_challenge(self._connection, authkey) + self._connection.send(request) + while not self._connection.poll(WAIT_SLICE_S): + self._check_waiting("report ready", deadline) + return self._connection.recv() + + def _accept(self, listener: socket.socket, deadline: float) -> socket.socket: + """Accept the child's connection, checking between waits that it is running and in time.""" + while True: + try: + sock, _address = listener.accept() + return sock + except TimeoutError: + self._check_waiting("connect", deadline) + + def _check_waiting(self, step: str, deadline: float) -> None: + """Raise ParaviewSessionError when the child has exited or the deadline has passed.""" + code = self._process.poll() + if code is not None: + raise ParaviewSessionError( + f"The PARAVIEW session process exited with code {code} before it could {step}; " + f"see its log at {self._log_path}" + ) + if time.monotonic() >= deadline: + raise ParaviewSessionError( + f"The PARAVIEW session process did not {step} within {self._start_timeout} s; " + f"see its log at {self._log_path}" + ) + + @staticmethod + def _wait(process: subprocess.Popen) -> bool: + """Wait up to END_GRACE_S for process to exit; return whether it did.""" + try: + process.wait(END_GRACE_S) + return True + except subprocess.TimeoutExpired: + return False + + def _close_connection(self) -> None: + """Close the parent end of the connection, if any.""" + if self._connection is not None: + self._connection.close() diff --git a/tests/unit/app/test_session_channel.py b/tests/unit/app/test_session_channel.py new file mode 100644 index 00000000..daf000e2 --- /dev/null +++ b/tests/unit/app/test_session_channel.py @@ -0,0 +1,214 @@ +"""Unit tests for the session channel: error transport, dispatch, coroutine results, +lost connections and numpy values in payloads. + +Both ends run in this process over a loopback socket pair, the transport the +session uses. Coroutine results run on a real ``AsyncRunner``. Every +blocking call runs under a thread guard so a hang fails instead of stalling. +""" + +import socket +import struct +import sys +import threading +from multiprocessing.connection import Connection +from pathlib import Path + +import numpy as np +import pytest + +from ansys.visor.viewer.app.paraview.session_channel import ( + SERVED_METHODS, + SessionChannel, + SessionError, + SessionServer, + to_plain, +) +from ansys.visor.viewer.app.trame.async_runner import AsyncRunner +from ansys.visor.viewer.core.errors import InvalidFileError, ParaviewSessionError +from ansys.visor.viewer.vtk.variables.visor_part_variables import VisorPartVariables + +LOG_PATH = Path("logs") / "visor_paraview_session_8081.log" + + +def run_bounded(fn, timeout=10.0): + """Run fn in a thread; fail if it has not returned within timeout, else return or raise its outcome.""" + outcome = {} + + def target(): + try: + outcome["value"] = fn() + except BaseException as exc: + outcome["error"] = exc + + thread = threading.Thread(target=target, daemon=True) + thread.start() + thread.join(timeout) + assert not thread.is_alive(), "the call did not return within the guard" + if "error" in outcome: + raise outcome["error"] + return outcome.get("value") + + +class Target: + """Stands in for the session's Visor.""" + + def __init__(self): + self.calls = [] + self.coroutine_thread = None + + def list_datasets(self): + return {1: "a"} + + def remove_dataset(self, dataset_id): + self.calls.append(("remove_dataset", dataset_id, type(dataset_id))) + + def add_dataset(self, input, metadata=None): + raise ValueError("bad input") + + def list_variables(self, dataset_id): + return [VisorPartVariables(part_id=np.int64(dataset_id), part_name="p", variables=[])] + + def clear(self): + self.calls.append(("clear",)) + + async def save_state(self, state_dir): + self.coroutine_thread = threading.current_thread() + self.calls.append(("save_state", state_dir)) + + +def connection_pair(): + """Two connected Connections over a socket pair.""" + left, right = socket.socketpair() + return Connection(left.detach()), Connection(right.detach()) + + +@pytest.fixture +def served(): + """Yield (channel, target, runner) with a SessionServer serving target in a thread.""" + parent, child = connection_pair() + runner = AsyncRunner() + target = Target() + server = SessionServer( + child, target, SERVED_METHODS, run_coroutine=lambda coroutine: runner.run_coroutine_block(coroutine, False) + ) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + channel = SessionChannel(parent, LOG_PATH) + yield channel, target, runner + channel.shutdown() + thread.join(5) + channel.close() + child.close() + runner.dispose() + + +def test_value_style_error_crosses_with_its_message_once(): + """The constructor value is sent, so the rebuilt error's str has one prefix.""" + rebuilt = SessionError.from_exception(InvalidFileError("x")).to_exception() + + assert type(rebuilt) is InvalidFileError + assert str(rebuilt) == "'Invalid file: x'" + + +def test_unknown_error_type_becomes_runtime_error_naming_it(): + rebuilt = SessionError.from_exception(KeyError("k")).to_exception() + + assert type(rebuilt) is RuntimeError + assert str(rebuilt) == "KeyError: 'k'" + + +def test_int_keyed_dict_round_trips(served): + channel, _target, _runner = served + + result = run_bounded(lambda: channel.call("list_datasets")) + + assert result == {1: "a"} + assert [type(key) for key in result] == [int] + + +def test_target_value_error_reaches_caller_and_server_keeps_serving(served): + channel, _target, _runner = served + + with pytest.raises(ValueError, match="^bad input$"): + run_bounded(lambda: channel.call("add_dataset", "file.vtu")) + + assert run_bounded(lambda: channel.call("list_datasets")) == {1: "a"} + + +def test_method_outside_served_set_is_refused_without_calling_target(served): + channel, target, _runner = served + + with pytest.raises(RuntimeError, match="^Method 'clear' is not served by the PARAVIEW session$"): + run_bounded(lambda: channel.call("clear")) + + assert target.calls == [] + + +def test_coroutine_method_runs_on_the_runner_loop(served): + channel, target, runner = served + + assert run_bounded(lambda: channel.call("save_state", "state_dir")) is None + + assert target.calls == [("save_state", "state_dir")] + assert target.coroutine_thread is runner.thread + + +def test_serve_forever_returns_when_channel_closes(): + parent, child = connection_pair() + server = SessionServer(child, Target(), SERVED_METHODS, run_coroutine=lambda coroutine: None) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + + parent.close() + thread.join(5) + + assert not thread.is_alive() + child.close() + + +@pytest.mark.parametrize("close", ["graceful", "reset"]) +def test_call_on_lost_channel_raises_session_error_naming_log(close): + """A peer that closes, or whose process dies (a reset), ends the wait with ParaviewSessionError.""" + left, right = socket.socketpair() + channel = SessionChannel(Connection(left.detach()), LOG_PATH) + if close == "reset": + linger_on_zero_seconds = struct.pack("HH" if sys.platform == "win32" else "ii", 1, 0) + right.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, linger_on_zero_seconds) + right.close() + + with pytest.raises(ParaviewSessionError) as raised: + run_bounded(lambda: channel.call("list_datasets")) + + assert str(raised.value) == ( + f"The PARAVIEW session process was lost during 'list_datasets'; see its log at {LOG_PATH}" + ) + channel.close() + + +def test_to_plain_replaces_numpy_values_and_keeps_visor_types(): + payload = { + np.int64(1): [np.float32(0.5), np.arange(2)], + "flags": (np.bool_(True), "s"), + "part": VisorPartVariables(part_id=np.int64(3), part_name="p", variables=[]), + } + + plain = to_plain(payload) + + assert plain == {1: [0.5, [0, 1]], "flags": (True, "s"), "part": VisorPartVariables(3, "p", [])} + assert [type(key) for key in plain] == [int, str, str] + assert [type(item) for item in plain[1]] == [float, list] + assert type(plain[1][1][0]) is int + assert type(plain["flags"][0]) is bool + assert type(plain["part"]) is VisorPartVariables + assert type(plain["part"].part_id) is int + + +def test_numpy_arguments_and_results_cross_as_python_values(served): + channel, target, _runner = served + + run_bounded(lambda: channel.call("remove_dataset", np.int64(4))) + variables = run_bounded(lambda: channel.call("list_variables", 2)) + + assert target.calls == [("remove_dataset", 4, int)] + assert variables == [VisorPartVariables(part_id=2, part_name="p", variables=[])] + assert type(variables[0].part_id) is int diff --git a/tests/unit/app/test_session_main.py b/tests/unit/app/test_session_main.py new file mode 100644 index 00000000..7484bc50 --- /dev/null +++ b/tests/unit/app/test_session_main.py @@ -0,0 +1,138 @@ +"""Unit tests for ``ParaviewSessionMain``: reporting a failed build, reporting +ready and serving until shutdown, and ending when the parent closes the channel. + +Mocking boundary: the ``connect_session`` and ``build_visor`` seams, overridden +in a subclass. The test plays the parent over a real loopback connection; +ParaView is not imported and no trame server starts. +""" + +import io +import secrets +import socket +import threading +from multiprocessing.connection import Connection, answer_challenge, deliver_challenge +from unittest.mock import MagicMock + +import pytest + +from ansys.visor.viewer.app.paraview.session_channel import ( + SessionError, + SessionLaunchRequest, + SessionReady, + SessionRequest, + SessionResult, + SessionShutdown, +) +from ansys.visor.viewer.app.paraview.session_main import ParaviewSessionMain +from ansys.visor.viewer.core.errors import InvalidPathError +from ansys.visor.viewer.core.pvserver_address import PvserverAddress + +REQUEST = SessionLaunchRequest( + url="http://localhost:8081", + standalone=True, + dark_mode=False, + trame_log_dir=None, + pvserver=PvserverAddress(host="localhost", port=11111), +) + + +class SeamedMain(ParaviewSessionMain): + """ParaviewSessionMain with the session and the Visor supplied by the test.""" + + def __init__(self, argv, stdin, session, visor=None, build_error=None): + super().__init__(argv, stdin) + self.session = session + self.visor = visor + self.build_error = build_error + self.built_with = None + + def connect_session(self, request): + return self.session + + def build_visor(self, request, session): + self.built_with = (request, session) + if self.build_error is not None: + raise self.build_error + return self.visor + + +@pytest.fixture +def parent(): + """Return a function that starts a SeamedMain against a listening parent and yields (connection, outcome, thread).""" + started = [] + + def start(**seams): + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + listener.settimeout(10) + authkey = secrets.token_bytes(32) + argv = ["--channel-host", "127.0.0.1", "--channel-port", str(listener.getsockname()[1]), "--pvpython-own-arg"] + main = SeamedMain(argv, io.StringIO(authkey.hex() + "\n"), **seams) + outcome = {} + thread = threading.Thread(target=lambda: outcome.update(code=main.run()), daemon=True) + thread.start() + sock, _address = listener.accept() + listener.close() + sock.setblocking(True) + connection = Connection(sock.detach()) + deliver_challenge(connection, authkey) + answer_challenge(connection, authkey) + connection.send(REQUEST) + assert connection.poll(10), "no reply to the launch request" + started.append(connection) + return connection, outcome, thread, main + + yield start + for connection in started: + connection.close() + + +def test_build_failure_is_reported_and_run_returns_1(parent): + session = MagicMock(name="session") + + connection, outcome, thread, main = parent(session=session, build_error=InvalidPathError("p")) + reply = connection.recv() + thread.join(10) + + assert reply == SessionError(type_name="InvalidPathError", message="p") + assert main.built_with == (REQUEST, session) + assert outcome == {"code": 1} + session.disconnect.assert_called_once_with() + + +def test_ready_then_serves_until_shutdown(parent): + session = MagicMock(name="session") + visor = MagicMock(name="visor") + visor.list_datasets.return_value = {1: "a"} + visor.running = True + + connection, outcome, thread, _main = parent(session=session, visor=visor) + ready = connection.recv() + connection.send(SessionRequest(method="list_datasets")) + assert connection.poll(10) + result = connection.recv() + connection.send(SessionShutdown()) + thread.join(10) + + assert ready == SessionReady() + assert result == SessionResult(value={1: "a"}) + assert outcome == {"code": 0} + visor.stop.assert_called_once_with() + session.disconnect.assert_called_once_with() + + +def test_parent_closing_channel_ends_the_session(parent): + session = MagicMock(name="session") + visor = MagicMock(name="visor") + visor.running = False + + connection, outcome, thread, _main = parent(session=session, visor=visor) + assert connection.recv() == SessionReady() + connection.close() + thread.join(10) + + assert not thread.is_alive() + assert outcome == {"code": 0} + visor.stop.assert_not_called() + session.disconnect.assert_called_once_with() diff --git a/tests/unit/app/test_session_process.py b/tests/unit/app/test_session_process.py new file mode 100644 index 00000000..c4e3f40b --- /dev/null +++ b/tests/unit/app/test_session_process.py @@ -0,0 +1,295 @@ +"""Unit tests for ``ParaviewSessionProcess``: the launch command line, the authkey +on stdin, the ready handshake, reported errors, start timeouts and ``end``. + +Mocking boundary: ``subprocess.Popen``. The fake process plays the session +process in a thread once the parent closes its stdin: it connects with a real +``multiprocessing.connection.Client`` using the authkey written to its stdin +and serves a real ``SessionServer``. No pvpython is started. +""" + +import asyncio +import subprocess +import threading +import time +from multiprocessing.connection import Client +from pathlib import Path + +import pytest + +from ansys.visor.viewer.app.paraview import session_process +from ansys.visor.viewer.app.paraview.session_channel import ( + SERVED_METHODS, + SessionError, + SessionLaunchRequest, + SessionReady, + SessionServer, +) +from ansys.visor.viewer.app.paraview.session_process import ParaviewSessionProcess +from ansys.visor.viewer.config import Settings +from ansys.visor.viewer.core.errors import ( + ParaviewNotConfiguredError, + ParaviewSessionError, + PvserverConnectionError, +) +from ansys.visor.viewer.core.pvserver_address import PvserverAddress + +REQUEST = SessionLaunchRequest( + url="http://localhost:8081", + standalone=True, + dark_mode=None, + trame_log_dir=None, + pvserver=PvserverAddress(host="localhost", port=11111), +) + + +def run_bounded(fn, timeout=15.0): + """Run fn in a thread; fail if it has not returned within timeout, else return or raise its outcome.""" + outcome = {} + + def target(): + try: + outcome["value"] = fn() + except BaseException as exc: + outcome["error"] = exc + + thread = threading.Thread(target=target, daemon=True) + thread.start() + thread.join(timeout) + assert not thread.is_alive(), "the call did not return within the guard" + if "error" in outcome: + raise outcome["error"] + return outcome.get("value") + + +class Target: + def list_datasets(self): + return {1: "a"} + + +class FakeStdin: + """Collects what the parent writes and starts the fake child when closed.""" + + def __init__(self, on_close): + self.data = b"" + self._on_close = on_close + + def write(self, data): + self.data += data + + def flush(self): + pass + + def close(self): + self._on_close() + + +class FakePopen: + """A session process whose behaviour is chosen by the test. + + ready connect, report ready, serve until shutdown, exit 0 + error connect, report PvserverConnectionError, exit 1 + silent connect, read the request, never reply + absent never connect + exits exit with code 3 before connecting + stubborn like ready, but survives shutdown and terminate until killed + """ + + def __init__(self, command, stdin, stdout, stderr, behaviour): + self.args = command + self.stdin_arg = stdin + self.stdout_arg = stdout + self.stderr_arg = stderr + self.behaviour = behaviour + self.stdin = FakeStdin(self._start) + self.pid = 4242 + self.returncode = None + self.request = None + self.terminate_calls = 0 + self.kill_calls = 0 + self._exited = threading.Event() + self._released = threading.Event() + + def _start(self): + if self.behaviour == "exits": + self._exit(3) + return + if self.behaviour != "absent": + threading.Thread(target=self._play, daemon=True).start() + + def _play(self): + authkey = bytes.fromhex(self.stdin.data.decode("ascii").strip()) + connection = Client(("127.0.0.1", int(self.args[-1])), authkey=authkey) + self.request = connection.recv() + if self.behaviour == "error": + connection.send(SessionError.from_exception( + PvserverConnectionError("Could not connect to pvserver at localhost:11111") + )) + connection.close() + self._exit(1) + return + if self.behaviour == "silent": + self._released.wait(30) + connection.close() + return + connection.send(SessionReady()) + SessionServer(connection, Target(), SERVED_METHODS, run_coroutine=asyncio.run).serve_forever() + connection.close() + if self.behaviour == "ready": + self._exit(0) + + def _exit(self, code): + self.returncode = code + self._exited.set() + + def poll(self): + return self.returncode + + def wait(self, timeout=None): + if not self._exited.wait(timeout): + raise subprocess.TimeoutExpired(self.args, timeout) + return self.returncode + + def terminate(self): + self.terminate_calls += 1 + if self.behaviour != "stubborn": + self._released.set() + self._exit(1) + + def kill(self): + self.kill_calls += 1 + self._released.set() + self._exit(-9) + + +@pytest.fixture +def spawn(monkeypatch, tmp_path): + """Return a function that builds a ParaviewSessionProcess whose Popen is a FakePopen with the given behaviour.""" + monkeypatch.setattr(session_process, "END_GRACE_S", 0.2) + created = [] + + def build(behaviour, start_timeout=10.0): + def fake_popen(command, stdin, stdout, stderr): + created.append(FakePopen(command, stdin, stdout, stderr, behaviour)) + return created[-1] + + monkeypatch.setattr(session_process.subprocess, "Popen", fake_popen) + process = ParaviewSessionProcess( + pvpython=Path("pv") / "pvpython.exe", + venv=Path("pv") / ".pvenv", + log_path=tmp_path / "logs" / "visor_paraview_session_8081.log", + start_timeout=start_timeout, + ) + return process, created + + return build + + +def test_launch_command_line_and_streams(spawn, tmp_path): + process, created = spawn("ready") + + run_bounded(lambda: process.launch(REQUEST)) + popen = created[0] + authkey_hex = popen.stdin.data.decode("ascii").strip() + run_bounded(process.end) + + assert popen.args[0] == str(Path("pv") / "pvpython.exe") + assert popen.args[1:3] == ["--venv", "pv/.pvenv"] + assert Path(popen.args[3]).name == "session_main.py" + assert popen.args[4:7] == ["--channel-host", "127.0.0.1", "--channel-port"] + assert popen.args[7].isdigit() and popen.args[7] != "0" + assert len(authkey_hex) == 64 + assert authkey_hex not in " ".join(popen.args) + assert popen.stdin_arg is subprocess.PIPE + assert popen.stdout_arg.name == str(tmp_path / "logs" / "visor_paraview_session_8081.log") + assert popen.stdout_arg.mode == "ab" + assert popen.stderr_arg is subprocess.STDOUT + + +def test_launch_delivers_request_and_returns_working_channel(spawn): + process, created = spawn("ready") + + channel = run_bounded(lambda: process.launch(REQUEST)) + result = run_bounded(lambda: channel.call("list_datasets")) + run_bounded(process.end) + + assert created[0].request == REQUEST + assert result == {1: "a"} + assert created[0].returncode == 0 + assert created[0].terminate_calls == 0 + assert process.alive is False + + +def test_reported_pvserver_error_is_raised_and_child_ended(spawn): + process, created = spawn("error") + + with pytest.raises(PvserverConnectionError, match="^Could not connect to pvserver at localhost:11111$"): + run_bounded(lambda: process.launch(REQUEST)) + + assert process.alive is False + assert created[0].returncode == 1 + + +def test_child_that_never_reports_ready_is_terminated_and_log_named(spawn, tmp_path): + process, created = spawn("silent", start_timeout=1.0) + + with pytest.raises(ParaviewSessionError) as raised: + run_bounded(lambda: process.launch(REQUEST)) + + assert str(raised.value) == ( + "The PARAVIEW session process did not report ready within 1.0 s; " + f"see its log at {tmp_path / 'logs' / 'visor_paraview_session_8081.log'}" + ) + assert created[0].terminate_calls == 1 + assert process.alive is False + + +def test_child_that_never_connects_times_out(spawn, tmp_path): + process, created = spawn("absent", start_timeout=1.0) + + with pytest.raises(ParaviewSessionError) as raised: + run_bounded(lambda: process.launch(REQUEST)) + + assert str(raised.value) == ( + "The PARAVIEW session process did not connect within 1.0 s; " + f"see its log at {tmp_path / 'logs' / 'visor_paraview_session_8081.log'}" + ) + assert created[0].terminate_calls == 1 + + +def test_child_that_exits_before_connecting_fails_fast(spawn, tmp_path): + process, _created = spawn("exits", start_timeout=60.0) + started = time.monotonic() + + with pytest.raises(ParaviewSessionError) as raised: + run_bounded(lambda: process.launch(REQUEST)) + + assert time.monotonic() - started < 5.0 + assert str(raised.value) == ( + "The PARAVIEW session process exited with code 3 before it could connect; " + f"see its log at {tmp_path / 'logs' / 'visor_paraview_session_8081.log'}" + ) + + +def test_end_escalates_to_kill_and_is_idempotent(spawn): + process, created = spawn("stubborn") + run_bounded(lambda: process.launch(REQUEST)) + + run_bounded(process.end) + run_bounded(process.end) + + assert created[0].terminate_calls == 1 + assert created[0].kill_calls == 1 + assert created[0].returncode == -9 + + +def test_from_settings_names_missing_key_and_builds_log_path(tmp_path): + with pytest.raises(ParaviewNotConfiguredError, match="^PARAVIEW mode needs 'paraview_pvpython' set in the .visor file$"): + ParaviewSessionProcess.from_settings(Settings(paraview_pvpython=None, paraview_venv="venv"), 8081) + with pytest.raises(ParaviewNotConfiguredError, match="^PARAVIEW mode needs 'paraview_venv' set in the .visor file$"): + ParaviewSessionProcess.from_settings(Settings(paraview_pvpython="pvpython", paraview_venv=None), 8081) + + process = ParaviewSessionProcess.from_settings( + Settings(paraview_pvpython="pvpython", paraview_venv="venv", default_log_dir=str(tmp_path)), 8081 + ) + + assert process.log_path == tmp_path / "visor_paraview_session_8081.log" From 0d5b9f5a5cff13b98d1caef45c3e30f82ffab22c Mon Sep 17 00:00:00 2001 From: Laura Kasian Date: Fri, 13 Nov 2026 20:52:28 -0700 Subject: [PATCH 2/4] chore: get visor api list from class public methods --- .../viewer/app/paraview/session_channel.py | 25 +++++++++---------- tests/unit/app/test_session_channel.py | 8 ++++++ 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/ansys/visor/viewer/app/paraview/session_channel.py b/src/ansys/visor/viewer/app/paraview/session_channel.py index 89a5fae6..71052e22 100644 --- a/src/ansys/visor/viewer/app/paraview/session_channel.py +++ b/src/ansys/visor/viewer/app/paraview/session_channel.py @@ -26,25 +26,24 @@ import numpy as np from pydantic import BaseModel +from ansys.visor.viewer.app.visor import Visor from ansys.visor.viewer.core import errors from ansys.visor.viewer.core.pvserver_address import PvserverAddress from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger logger = VisorDefaultLogger(__name__) -SERVED_METHODS: frozenset[str] = frozenset({ - "start", - "stop", - "update", - "add_dataset", - "remove_dataset", - "list_datasets", - "list_variables", - "save_state", - "load_state", - "_health", -}) -"""The methods the session process serves on its Visor.""" +def served_methods(visor_class: type) -> frozenset[str]: + """The public methods declared on visor_class, plus ``_health``.""" + declared = { + name for name, member in vars(visor_class).items() + if inspect.isfunction(member) and not name.startswith("_") + } + return frozenset(declared | {"_health"}) + + +SERVED_METHODS: frozenset[str] = served_methods(Visor) +"""The methods the session process serves on its Visor: Visor's public interface and ``_health``.""" _VALUE_STYLE_ERRORS: tuple[type[Exception], ...] = ( errors.InvalidFileError, diff --git a/tests/unit/app/test_session_channel.py b/tests/unit/app/test_session_channel.py index daf000e2..71b4148e 100644 --- a/tests/unit/app/test_session_channel.py +++ b/tests/unit/app/test_session_channel.py @@ -6,6 +6,7 @@ blocking call runs under a thread guard so a hang fails instead of stalling. """ +import inspect import socket import struct import sys @@ -24,6 +25,7 @@ to_plain, ) from ansys.visor.viewer.app.trame.async_runner import AsyncRunner +from ansys.visor.viewer.app.visor import Visor from ansys.visor.viewer.core.errors import InvalidFileError, ParaviewSessionError from ansys.visor.viewer.vtk.variables.visor_part_variables import VisorPartVariables @@ -144,6 +146,12 @@ def test_method_outside_served_set_is_refused_without_calling_target(served): assert target.calls == [] +def test_served_set_is_visors_public_interface_and_health(): + public = {name for name, _ in inspect.getmembers(Visor, inspect.isfunction) if not name.startswith("_")} + + assert SERVED_METHODS == public | {"_health"} + + def test_coroutine_method_runs_on_the_runner_loop(served): channel, target, runner = served From 9a7288880e47974932f7a9956dc36d12ec444b60 Mon Sep 17 00:00:00 2001 From: Laura Kasian Date: Sat, 14 Nov 2026 13:46:49 -0700 Subject: [PATCH 3/4] feat: start PARAVIEW sessions from the API --- src/ansys/visor/viewer/api/server.py | 13 +- src/ansys/visor/viewer/api/visor_cache.py | 28 +- .../viewer/app/paraview/paraview_handle.py | 209 ++++++++++ .../viewer/app/paraview/session_process.py | 23 ++ .../viewer/app/paraview/visor_vtk_paraview.py | 32 +- src/ansys/visor/viewer/app/visor.py | 17 + src/ansys/visor/viewer/app/visor_vtk.py | 5 + tests/unit/api/test_server.py | 75 +++- tests/unit/api/test_visor_cache.py | 86 +++- tests/unit/app/test_paraview_handle.py | 382 ++++++++++++++++++ tests/unit/app/test_session_process.py | 34 +- tests/unit/app/test_thiea.py | 15 + tests/unit/app/test_visor_vtk_paraview.py | 74 +++- 13 files changed, 975 insertions(+), 18 deletions(-) create mode 100644 src/ansys/visor/viewer/app/paraview/paraview_handle.py create mode 100644 tests/unit/app/test_paraview_handle.py diff --git a/src/ansys/visor/viewer/api/server.py b/src/ansys/visor/viewer/api/server.py index b2603604..e3695f16 100644 --- a/src/ansys/visor/viewer/api/server.py +++ b/src/ansys/visor/viewer/api/server.py @@ -27,6 +27,7 @@ from ansys.visor.viewer.api.visor_cache import VisorCache from ansys.visor.viewer.config import settings from ansys.visor.viewer.core.net import find_unused_port +from ansys.visor.viewer.core.pvserver_address import PvserverAddress from ansys.visor.viewer.core.visor_enums import RenderingMode from ansys.visor.viewer.core.visor_logging import VisorLogger @@ -139,6 +140,7 @@ def __init__(self): self.settings.default_port, self.settings.default_standalone, self.settings.default_dark_mode, + None, )[0] # Configure FastAPI application @@ -209,12 +211,15 @@ async def connect_or_initialize_server(self, init_props: InitProps = Body( else settings.default_dark_mode rendering_mode = init_props.rendering_mode if init_props.rendering_mode is not None\ else RenderingMode.CLIENT + pvserver = init_props.pvserver_address(self.settings.default_pvserver_address())\ + if rendering_mode == RenderingMode.PARAVIEW else None # initialize an instance of Visor self.visualizer, warnings = self._connect_or_initialize_visualizer( host, port, standalone, dark_mode, + pvserver, rendering_mode ) url = self._get_url(host, port) @@ -440,17 +445,21 @@ def _connect_or_initialize_visualizer( port: int, standalone: bool, dark_mode: bool, + pvserver: PvserverAddress | None, rendering_mode: RenderingMode = RenderingMode.CLIENT, ) -> Tuple[Visor, str]: """Connect to a visualizer instance with the given host and port if one - exists; otherwise, create a new visualizer instance on that host and port.""" + exists; otherwise, create a new visualizer instance on that host and port. + pvserver is the PARAVIEW session's address, None for other modes.""" url = self._get_url(host, port) msg = ( f'Connecting to Visor server on {url} (standalone={standalone}, dark_mode={dark_mode})' ) logger.info(msg) # Initialize the server with the given port, host and client distribution path - instance, warnings = VisorCache.get_instance(url, rendering_mode, standalone, dark_mode, self.trame_log_dir) + instance, warnings = VisorCache.get_instance( + url, rendering_mode, standalone, dark_mode, pvserver, self.trame_log_dir + ) return instance, warnings diff --git a/src/ansys/visor/viewer/api/visor_cache.py b/src/ansys/visor/viewer/api/visor_cache.py index e559db5e..cc0dc136 100644 --- a/src/ansys/visor/viewer/api/visor_cache.py +++ b/src/ansys/visor/viewer/api/visor_cache.py @@ -3,7 +3,9 @@ from typing import Dict, Tuple from ansys.visor.viewer import Visor +from ansys.visor.viewer.app.paraview.paraview_handle import VisorParaviewHandle from ansys.visor.viewer.app.visor_vtk import VisorVTK +from ansys.visor.viewer.core.pvserver_address import PvserverAddress from ansys.visor.viewer.core.visor_enums import RenderingMode from ansys.visor.viewer.core.visor_logging import VisorLogger @@ -20,10 +22,13 @@ def get_instance(cls, rendering_mode: RenderingMode, standalone: bool, dark_mode: bool, + pvserver: PvserverAddress | None, trame_log_dir: str | None = None, ) -> Tuple["Visor", str | None]: """Get an instance of Visor from the cache or create a new one. + pvserver is the PARAVIEW session's address, None for other modes. + Returns ------- tuple[Visor, list[str], bool] @@ -36,16 +41,16 @@ def get_instance(cls, f"Visor instance not found on url {url}. " f"Creating a new one with rendering_mode={rendering_mode}," f"standalone={standalone}," - f"dark_mode={dark_mode}, trame_log_dir={trame_log_dir}." + f"dark_mode={dark_mode}, pvserver={pvserver}, trame_log_dir={trame_log_dir}." ) logger.warning(msg) - cls.create_instance(url, rendering_mode, standalone, dark_mode, trame_log_dir) + cls.create_instance(url, rendering_mode, standalone, dark_mode, pvserver, trame_log_dir) instance = cls._instances[url] if instance is None: raise Exception(f"Failed to create Visor instance for url {url}.") return instance, None - warnings = cls.validate_args(url, rendering_mode, standalone, dark_mode, trame_log_dir) + warnings = cls.validate_args(url, rendering_mode, standalone, dark_mode, pvserver, trame_log_dir) return cls._instances.get(url), warnings @classmethod @@ -55,13 +60,14 @@ def validate_args( rendering_mode: RenderingMode, standalone: bool, dark_mode: bool, + pvserver: PvserverAddress | None, trame_log_dir: str ) -> str: """Validate the arguments for this instance.""" warnings = None existing = cls._instances[url] ignored = [] - if rendering_mode is not None and not isinstance(existing, VisorVTK): + if rendering_mode is not None and not isinstance(existing, (VisorVTK, VisorParaviewHandle)): # TODO: update to check the VisorVtkLocal class type once VisorVTK has # been renamed VisorVtk with VisorVtkLocal as a concrete implementation/subclass. ignored.append( @@ -75,6 +81,12 @@ def validate_args( ignored.append( f"dark_mode={dark_mode} (existing value: {existing.dark_mode})" ) + if pvserver is not None: + existing_pvserver = existing.pvserver if isinstance(existing, VisorParaviewHandle) else None + if existing_pvserver != pvserver: + ignored.append( + f"pvserver={pvserver} (existing value: {existing_pvserver})" + ) if ignored: warnings = ( f"Connected to existing Visor instance at {url}. " @@ -92,6 +104,7 @@ def create_instance( rendering_mode: RenderingMode, standalone: bool, dark_mode: bool, + pvserver: PvserverAddress | None, trame_log_dir: str | None = None ) -> None: """Create a new instance of Visor and store it in the cache.""" @@ -101,21 +114,22 @@ def create_instance( standalone=standalone, dark_mode=dark_mode, trame_log_dir=trame_log_dir, + pvserver=pvserver, ) msg = ( f"Created new Visor instance for URL: {url} " f"(rendering_mode={rendering_mode}, standalone={standalone}, " - f"dark_mode={dark_mode}, trame_log_dir={trame_log_dir})" + f"dark_mode={dark_mode}, pvserver={pvserver}, trame_log_dir={trame_log_dir})" ) logger.info(msg) print(msg) @classmethod def delete_instance(cls, url: str) -> None: - """Delete an instance of Visor from the cache.""" + """Delete an instance of Visor from the cache and close it.""" if url not in cls._instances: return - cls._instances.pop(url) + cls._instances.pop(url).close() return @classmethod diff --git a/src/ansys/visor/viewer/app/paraview/paraview_handle.py b/src/ansys/visor/viewer/app/paraview/paraview_handle.py new file mode 100644 index 00000000..94a34711 --- /dev/null +++ b/src/ansys/visor/viewer/app/paraview/paraview_handle.py @@ -0,0 +1,209 @@ +""" +PARAVIEW handle +=============== +The Visor that ``Visor(rendering_mode="PARAVIEW", ...)`` returns. The session +runs in its own pvpython process; this object launches it, forwards each +Visor method over the session channel, and ends it. + +The session process is ended by :meth:`VisorParaviewHandle.close`, or at +interpreter exit if close was never called. +""" + +from __future__ import annotations + +import asyncio +import threading +import weakref +from typing import Any + +from ansys.visor.viewer.app.paraview.session_channel import SessionLaunchRequest +from ansys.visor.viewer.app.paraview.session_process import ParaviewSessionProcess +from ansys.visor.viewer.app.visor import Visor +from ansys.visor.viewer.config import settings +from ansys.visor.viewer.core.errors import ParaviewSessionError, UnsupportedInModeError +from ansys.visor.viewer.core.metadata import Metadata +from ansys.visor.viewer.core.pvserver_address import PvserverAddress +from ansys.visor.viewer.core.visor_enums import RenderingMode +from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger +from ansys.visor.viewer.core.visor_types import VisorDatasetType +from ansys.visor.viewer.vtk.variables.visor_part_variables import VisorPartVariables + +logger = VisorDefaultLogger(__name__) + +BLOCKING_WAIT_SLICE_S = 0.5 +"""Seconds between checks that the session process is running while a blocking start waits.""" + + +class VisorParaviewHandle(Visor): + """Visor for PARAVIEW mode: the session runs in its own pvpython process, reached over its channel.""" + + def __init__( + self, + url: str | None = None, + rendering_mode: RenderingMode = RenderingMode.PARAVIEW, + standalone: bool = True, + dark_mode: bool | None = None, + trame_log_dir: str | None = None, + pvserver: PvserverAddress | None = None, + ) -> None: + """Launch the session for url against pvserver, the settings default when None. + + Raises ValueError for a rendering mode other than PARAVIEW, and + whatever the session process raises when it cannot start. + """ + rendering_mode = RenderingMode.from_string(rendering_mode) + if rendering_mode is not RenderingMode.PARAVIEW: + raise ValueError(f"VisorParaviewHandle runs PARAVIEW sessions only, not {rendering_mode.name}") + super().__init__(url, standalone, dark_mode) + self._pvserver = pvserver if pvserver is not None else settings.default_pvserver_address() + self._wait_released = threading.Event() + process = self._create_session_process() + self._channel = process.launch( + SessionLaunchRequest( + url=self.url, + standalone=standalone, + dark_mode=self.dark_mode, + trame_log_dir=trame_log_dir, + pvserver=self._pvserver, + ) + ) + self._process = process + self._finalizer = weakref.finalize(self, process.end) + logger.info("PARAVIEW session ready on %s (pvserver %s, pid %s)", self.url, self._pvserver, process.pid) + + def _create_session_process(self) -> ParaviewSessionProcess: + """The session process for this handle's port, configured from settings.""" + return ParaviewSessionProcess.from_settings(settings, self.port) + + """ Properties """ + @property + def pvserver(self) -> PvserverAddress: + """The pvserver this session renders on.""" + return self._pvserver + + @property + def running(self) -> bool: + """Whether the session process is running.""" + return self._process.alive + + """ Public Methods """ + def start(self, + input: str | VisorDatasetType | None = None, + metadata: Metadata | str | None = None, + timeout: int = 0, + blocking: bool = False, + ) -> int | None: + """Start the session's server; with blocking, wait until the session ends. + + The wait ends when :meth:`stop` or :meth:`close` is called. A session + process that exits by itself during the wait raises + ParaviewSessionError. KeyboardInterrupt during the wait ends the + session through :meth:`close` and is raised again. + """ + self._reject_in_memory_input(input) + self._wait_released.clear() + dataset_id = self._channel.call("start", input, metadata, timeout) + if blocking: + self._wait_until_released() + return dataset_id + + def stop(self) -> None: + """Stop the session's server; a blocking start waiting on this handle returns.""" + self._channel.call("stop") + self._wait_released.set() + + def update(self, + input: str | VisorDatasetType, + metadata: Metadata | str | None = None, + ) -> int: + """Replace the session's datasets with the file at input.""" + self._reject_in_memory_input(input) + return self._channel.call("update", input, metadata) + + def add_dataset(self, + input: str | VisorDatasetType, + metadata: Metadata | str | None = None, + ) -> int: + """Add the file at input to the session's scene and return its dataset ID.""" + self._reject_in_memory_input(input) + return self._channel.call("add_dataset", input, metadata) + + def remove_dataset(self, dataset_id: int) -> None: + """Remove a dataset from the session's scene.""" + return self._channel.call("remove_dataset", dataset_id) + + def list_datasets(self) -> dict: + """List the datasets in the session's scene.""" + return self._channel.call("list_datasets") + + def list_variables(self, dataset_id: int) -> list[VisorPartVariables]: + """List the variables of a dataset in the session's scene, grouped by part.""" + return self._channel.call("list_variables", dataset_id) + + def update_variables(self, dataset_id: int, variables: list[dict[str, Any]]) -> None: + """Raise UnsupportedInModeError: pvserver holds its own copy of the arrays.""" + raise UnsupportedInModeError("update_variables is not supported in PARAVIEW mode") + + async def save_state(self, state_dir: str) -> None: + """Save the session's state to state_dir; the call waits on a worker thread, not the event loop.""" + await asyncio.to_thread(self._channel.call, "save_state", state_dir) + + def load_state(self, state_dir: str) -> None: + """Load the session's state from state_dir.""" + return self._channel.call("load_state", state_dir) + + def close(self) -> None: + """End the session process; idempotent. A blocking start waiting on this handle returns.""" + self._wait_released.set() + self._finalizer() + + def _health(self) -> bool: + """The session server's health; False when the session process is gone.""" + if not self._process.alive: + return False + return self._channel.call("_health") + + """ Protected Async Methods (for use in the FastAPI endpoints) """ + async def _start_async(self, + input: str | VisorDatasetType | None = None, + metadata: Metadata | str | None = None, + timeout: int = 0, + ) -> tuple[int | None, None]: + """Start the session's server on a worker thread; there is no server task in this process.""" + dataset_id = await asyncio.to_thread(self.start, input, metadata, timeout) + return dataset_id, None + + async def _stop_async(self) -> None: + """Stop the session's server on a worker thread.""" + await asyncio.to_thread(self.stop) + + """ Private Methods """ + @staticmethod + def _reject_in_memory_input(input: str | VisorDatasetType | None) -> None: + """Raise UnsupportedInModeError for input other than a file path or None: pvserver opens files only.""" + if input is not None and not isinstance(input, str): + raise UnsupportedInModeError("in-memory dataset input is not supported in PARAVIEW mode") + + def _wait_until_released(self) -> None: + """Wait until stop or close releases the wait. + + close releases the wait before it ends the session process, so a + process found gone with the wait released was ended by close, not by + itself. + """ + try: + while not self._wait_released.wait(BLOCKING_WAIT_SLICE_S): + if self._process.alive: + continue + if self._wait_released.is_set(): + return + code = self._process.exit_code + self.close() + raise ParaviewSessionError( + f"The PARAVIEW session process exited with code {code} while start was blocking; " + f"see its log at {self._process.log_path}" + ) + except KeyboardInterrupt: + logger.info("Interrupted; ending the PARAVIEW session on %s", self.url) + self.close() + raise diff --git a/src/ansys/visor/viewer/app/paraview/session_process.py b/src/ansys/visor/viewer/app/paraview/session_process.py index 254e2d0a..b263c00b 100644 --- a/src/ansys/visor/viewer/app/paraview/session_process.py +++ b/src/ansys/visor/viewer/app/paraview/session_process.py @@ -9,11 +9,16 @@ environment. The child's stdout and stderr go to a log file, so no pipe can fill and block it. The child is not detached: it exits when its connection closes, so it does not outlive this process. + +The child runs in its own process group, so a console Ctrl+C reaches only +this process. The owner of the session then ends the child over the channel, +through the same shutdown as any other end. """ from __future__ import annotations import importlib.util +import os import secrets import socket import subprocess @@ -47,6 +52,13 @@ """Seconds end() waits after each step before escalating.""" +def own_process_group_options() -> dict: + """Popen options that start the child in its own process group, out of reach of a console Ctrl+C.""" + if os.name == "nt": + return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} + return {"start_new_session": True} + + class ParaviewSessionProcess: """Spawns and ends one pvpython session process and owns its channel.""" @@ -84,6 +96,16 @@ def log_path(self) -> Path: """The file receiving the child's stdout and stderr.""" return self._log_path + @property + def pid(self) -> int | None: + """The child's process id; None before launch.""" + return None if self._process is None else self._process.pid + + @property + def exit_code(self) -> int | None: + """The child's exit code; None before launch and while it runs.""" + return None if self._process is None else self._process.poll() + def launch(self, request: SessionLaunchRequest) -> SessionChannel: """Spawn the child, hand it the authkey on stdin, and return the channel once it reports ready. @@ -157,6 +179,7 @@ def _spawn(self, port: int, authkey: bytes) -> None: stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + **own_process_group_options(), ) except OSError as exc: raise ParaviewSessionError(f"Could not start pvpython at {self._pvpython}: {exc}") from exc diff --git a/src/ansys/visor/viewer/app/paraview/visor_vtk_paraview.py b/src/ansys/visor/viewer/app/paraview/visor_vtk_paraview.py index 0bccc313..78bdbe84 100644 --- a/src/ansys/visor/viewer/app/paraview/visor_vtk_paraview.py +++ b/src/ansys/visor/viewer/app/paraview/visor_vtk_paraview.py @@ -18,14 +18,42 @@ from ansys.visor.viewer.app.trame.server_state_publisher import ServerStatePublisher from ansys.visor.viewer.app.visor_vtk import VisorVTK from ansys.visor.viewer.core.errors import UnsupportedInModeError +from ansys.visor.viewer.core.metadata import ExtendedMetadata, Metadata from ansys.visor.viewer.core.visor_enums import RenderingMode -from ansys.visor.viewer.core.visor_logging import get_trame_logger +from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger, get_trame_logger +from ansys.visor.viewer.core.visor_types import VisorDatasetType +from ansys.visor.viewer.vtk.io.visor_file_io import VisorFileIO from ansys.visor.viewer.vtk.scene.paraview_scene import VisorParaviewScene if TYPE_CHECKING: from ansys.visor.viewer.core.pvserver_address import PvserverAddress from ansys.visor.viewer.renderer.paraview_session import ParaviewSession +logger = VisorDefaultLogger(__name__) + + +class ParaviewFileIO(VisorFileIO): + """VisorFileIO whose resolved user metadata never names a dataset snapshot. + + pvserver opens a dataset's snapshot path in preference to its input file, + so a snapshot path in user metadata would make pvserver open that file + instead. Restoring state builds its metadata without :meth:`resolve`, so + a restored dataset keeps its snapshot path. + """ + + def resolve( + self, + input: str | VisorDatasetType | None, + metadata: str | Metadata | None, + ) -> tuple[VisorDatasetType | None, ExtendedMetadata]: + """Resolve as the base does, then clear the snapshot path from the metadata's state; its parts are kept.""" + loaded_input, extended_metadata = super().resolve(input, metadata) + snapshot_path = extended_metadata.state.serialized_dataset_path + if snapshot_path: + logger.warning("Ignoring state.serialized_dataset_path %r in user metadata", snapshot_path) + extended_metadata.state = extended_metadata.state.model_copy(update={"serialized_dataset_path": None}) + return loaded_input, extended_metadata + class VisorVTKParaview(VisorVTK): """VisorVTK for PARAVIEW mode: the scene renders through a pvserver and is streamed through trame-rca.""" @@ -45,6 +73,7 @@ def __init__( """Store the pvserver address and the connected session, then build the base. Both are stored first because the base constructor builds the scene. + User input is resolved by :class:`ParaviewFileIO`. """ self._pvserver = pvserver self._session = session @@ -55,6 +84,7 @@ def __init__( dark_mode=dark_mode, trame_log_dir=trame_log_dir, ) + self._file_io = ParaviewFileIO() def _initialize_rendering(self, standalone: bool, trame_log_dir: str | None) -> None: """Wire the bridge, the state publisher, the ParaView scene and ParaviewApp. diff --git a/src/ansys/visor/viewer/app/visor.py b/src/ansys/visor/viewer/app/visor.py index 70f63958..ded3bbf9 100644 --- a/src/ansys/visor/viewer/app/visor.py +++ b/src/ansys/visor/viewer/app/visor.py @@ -5,6 +5,7 @@ import ansys.visor.viewer.core.errors as errors from ansys.visor.viewer.config import settings from ansys.visor.viewer.core.metadata import Metadata +from ansys.visor.viewer.core.pvserver_address import PvserverAddress from ansys.visor.viewer.core.visor_enums import RenderingEngine, RenderingMode from ansys.visor.viewer.core.visor_helpers import validate_url from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger @@ -34,6 +35,9 @@ class Visor: dark_mode : bool, Default: None Whether to use dark mode for the app. If ``None``, the default dark mode setting from the configuration is used. + pvserver : PvserverAddress, default: None + The pvserver a PARAVIEW session renders on; the settings default when + ``None``. Any other mode rejects an address. """ def __new__(cls, rendering_engine: RenderingEngine = RenderingEngine.VTK, @@ -41,6 +45,7 @@ def __new__(cls, url: str | None = None, standalone: bool = True, dark_mode: bool | None = None, + pvserver: PvserverAddress | None = None, **kwargs, ) -> "Visor": """ @@ -48,12 +53,14 @@ def __new__(cls, This is a factory method to return an instance of a subclass that is determined by the ``rendering_engine`` enum value provided as input. + PARAVIEW mode returns a handle to a session in its own process. """ if cls is not Visor: return super().__new__(cls) rendering_engine = RenderingEngine.from_string(rendering_engine) rendering_mode = RenderingMode.from_string(rendering_mode) + Visor._reject_pvserver_outside_paraview(rendering_mode, pvserver) from ansys.visor.viewer.app.visor_vtk import VisorVTK @@ -68,6 +75,10 @@ def __new__(cls, f"Unsupported rendering engine: {rendering_engine}. " f"Valid values: {list(engine_map.keys())}." )) + if rendering_mode is RenderingMode.PARAVIEW: + from ansys.visor.viewer.app.paraview.paraview_handle import VisorParaviewHandle + + return super().__new__(VisorParaviewHandle) # Delegate to the engine class's __new__, passing rendering_mode through. return engine_class.__new__(engine_class, rendering_mode=rendering_mode, **kwargs) @@ -238,6 +249,12 @@ def update_variables(self, dataset_id: int, variables: List[Dict[str, Any]]) -> raise NotImplementedError """ Protected Methods """ + @staticmethod + def _reject_pvserver_outside_paraview(rendering_mode: RenderingMode, pvserver: PvserverAddress | None) -> None: + """Raise ValueError naming rendering_mode when a pvserver address is given for a mode other than PARAVIEW.""" + if pvserver is not None and rendering_mode is not RenderingMode.PARAVIEW: + raise ValueError(f"pvserver is accepted only in PARAVIEW mode, not {rendering_mode.name}") + def _set_default_url(self, url: str | None) -> None: """Validate and parse the provided URL, set as default if None""" if url is None: diff --git a/src/ansys/visor/viewer/app/visor_vtk.py b/src/ansys/visor/viewer/app/visor_vtk.py index 303f4d38..62005ccd 100644 --- a/src/ansys/visor/viewer/app/visor_vtk.py +++ b/src/ansys/visor/viewer/app/visor_vtk.py @@ -13,6 +13,7 @@ from ansys.visor.viewer.app.trame.trame_server_manager import TrameServerManager from ansys.visor.viewer.app.visor import Metadata from ansys.visor.viewer.core.perf_timer import PerfTimer +from ansys.visor.viewer.core.pvserver_address import PvserverAddress from ansys.visor.viewer.core.visor_enums import RenderingMode from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger from ansys.visor.viewer.core.visor_types import VisorDatasetType @@ -170,6 +171,7 @@ def __init__( standalone: bool = True, dark_mode: bool | None = None, trame_log_dir: str | None = None, + pvserver: PvserverAddress | None = None, ): """ Initializes the Visor class. @@ -181,7 +183,10 @@ def __init__( dark_mode (bool): A flag indicating whether to use the Dark mode trame_log_dir (Optional[str]): The path to the Trame log file. Defaults to None. If set to a value, Trame logging is enabled (is disabled by default). + pvserver (Optional[PvserverAddress]): Accepted so that ``Visor(...)`` has one + signature in every mode; an address raises ValueError naming the mode. """ + self._reject_pvserver_outside_paraview(RenderingMode.from_string(rendering_mode), pvserver) super().__init__(url, standalone, dark_mode) # I/O helper — owns all filesystem interactions (e.g. reading datasets, reading/writing state) diff --git a/tests/unit/api/test_server.py b/tests/unit/api/test_server.py index 9be9f2aa..e3a1ac7a 100644 --- a/tests/unit/api/test_server.py +++ b/tests/unit/api/test_server.py @@ -3,6 +3,10 @@ import pytest import ansys.visor.viewer.api.server as server_mod +from ansys.visor.viewer.api.models import InitProps +from ansys.visor.viewer.core.errors import PvserverConnectionError +from ansys.visor.viewer.core.pvserver_address import PvserverAddress +from ansys.visor.viewer.core.visor_enums import RenderingMode @pytest.fixture @@ -59,12 +63,81 @@ def test_initialize_visualizer(api): with patch.object(server_mod, "VisorCache") as mock_cache: mock_instance = MagicMock() mock_cache.get_instance.return_value = (mock_instance, None) - result, warnings = api._connect_or_initialize_visualizer("host", 1234, True, False) + result, warnings = api._connect_or_initialize_visualizer("host", 1234, True, False, None) assert result is mock_instance assert warnings is None mock_cache.get_instance.assert_called_once() +def paraview_props(**fields): + return InitProps(host="localhost", port=1, standalone=True, dark_mode=False, rendering_mode="PARAVIEW", **fields) + + +@pytest.mark.asyncio +async def test_initialize_paraview_resolves_pvserver_from_props(api, mock_settings): + """Each pvserver field missing from the request is taken from the settings default.""" + mock_settings.default_pvserver_address.return_value = PvserverAddress(host="dflt", port=11111) + + with patch.object(api, "_connect_or_initialize_visualizer", + return_value=(MagicMock(), None)) as mock_conn: + await api.connect_or_initialize_server(paraview_props(pvserver_host="pv.example")) + + assert mock_conn.call_args.args == ( + "localhost", 1, True, False, PvserverAddress(host="pv.example", port=11111), RenderingMode.PARAVIEW + ) + + +@pytest.mark.asyncio +async def test_initialize_paraview_uses_settings_default_pvserver(api, mock_settings): + """A PARAVIEW request without pvserver fields uses the settings default address.""" + mock_settings.default_pvserver_address.return_value = PvserverAddress(host="dflt", port=11111) + + with patch.object(api, "_connect_or_initialize_visualizer", + return_value=(MagicMock(), None)) as mock_conn: + await api.connect_or_initialize_server(paraview_props()) + + assert mock_conn.call_args.args[4] == PvserverAddress(host="dflt", port=11111) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["CLIENT", "SERVER"]) +async def test_initialize_other_modes_pass_no_pvserver(api, mode): + """Modes other than PARAVIEW pass no pvserver address.""" + props = InitProps(host="localhost", port=1, standalone=True, dark_mode=False, rendering_mode=mode) + + with patch.object(api, "_connect_or_initialize_visualizer", + return_value=(MagicMock(), None)) as mock_conn: + await api.connect_or_initialize_server(props) + + assert mock_conn.call_args.args[4] is None + + +def test_connect_or_initialize_visualizer_passes_pvserver_to_cache(api): + """The pvserver address reaches the cache with the URL, mode and trame log dir.""" + address = PvserverAddress(host="pv.example", port=22222) + with patch.object(server_mod, "VisorCache") as mock_cache: + mock_cache.get_instance.return_value = (MagicMock(), None) + api._connect_or_initialize_visualizer("h", 1, True, False, address, RenderingMode.PARAVIEW) + + mock_cache.get_instance.assert_called_once_with( + "http://h:1", RenderingMode.PARAVIEW, True, False, address, "logdir" + ) + + +@pytest.mark.asyncio +async def test_pvserver_connection_error_is_500_naming_address(api, mock_settings): + """A session that cannot reach pvserver gives HTTP 500 naming the address.""" + mock_settings.default_pvserver_address.return_value = PvserverAddress(host="dflt", port=11111) + error = PvserverConnectionError("Could not connect to pvserver at dflt:11111") + + with patch.object(api, "_connect_or_initialize_visualizer", side_effect=error): + with pytest.raises(server_mod.HTTPException) as exc: + await api.connect_or_initialize_server(paraview_props()) + + assert exc.value.status_code == 500 + assert exc.value.detail == "Runtime error: Could not connect to pvserver at dflt:11111" + + @pytest.mark.asyncio async def test_info_with_visualizer(api): """Verify that visualizer information is returned when available.""" diff --git a/tests/unit/api/test_visor_cache.py b/tests/unit/api/test_visor_cache.py index 75a3a1e2..138875ea 100644 --- a/tests/unit/api/test_visor_cache.py +++ b/tests/unit/api/test_visor_cache.py @@ -3,6 +3,8 @@ import pytest from ansys.visor.viewer.api.visor_cache import VisorCache +from ansys.visor.viewer.app.paraview.paraview_handle import VisorParaviewHandle +from ansys.visor.viewer.core.pvserver_address import PvserverAddress from ansys.visor.viewer.core.visor_enums import RenderingMode @@ -22,6 +24,7 @@ def test_get_instance_creates_new(monkeypatch): rendering_mode=RenderingMode.CLIENT, standalone=False, dark_mode=False, + pvserver=None, trame_log_dir="dir" ) assert inst is mock_visor @@ -32,7 +35,8 @@ def test_get_instance_creates_new(monkeypatch): rendering_mode=RenderingMode.CLIENT, standalone=False, dark_mode=False, - trame_log_dir="dir" + trame_log_dir="dir", + pvserver=None, ) @@ -48,12 +52,90 @@ def test_get_instance_returns_existing(monkeypatch): "url2", rendering_mode=RenderingMode.CLIENT, standalone=False, - dark_mode=False + dark_mode=False, + pvserver=None, ) assert inst is mock_visor mock_cls.assert_not_called() +def test_create_instance_passes_pvserver(): + """The pvserver address reaches the Visor factory.""" + address = PvserverAddress(host="pv.example", port=22222) + with patch("ansys.visor.viewer.api.visor_cache.Visor") as mock_cls: + VisorCache.create_instance("url4", RenderingMode.PARAVIEW, True, False, address, "dir") + + mock_cls.assert_called_once_with( + url="url4", + rendering_mode=RenderingMode.PARAVIEW, + standalone=True, + dark_mode=False, + trame_log_dir="dir", + pvserver=address, + ) + + +def test_delete_instance_closes_instance(): + """A deleted instance is closed, so a PARAVIEW session process ends with it.""" + mock_visor = MagicMock() + VisorCache._instances["url5"] = mock_visor + + VisorCache.delete_instance("url5") + + mock_visor.close.assert_called_once_with() + + +def make_handle(pvserver): + handle = MagicMock(spec=VisorParaviewHandle) + handle.standalone = True + handle.dark_mode = False + handle.pvserver = pvserver + return handle + + +def test_existing_handle_accepted_without_warning(): + """A cached PARAVIEW handle asked for with its own arguments gives no warning.""" + address = PvserverAddress(host="pv.example", port=22222) + VisorCache._instances["url6"] = make_handle(address) + + _inst, warnings = VisorCache.get_instance("url6", RenderingMode.PARAVIEW, True, False, address) + + assert warnings is None + + +def test_pvserver_mismatch_warns(): + """A different pvserver for a cached handle is ignored, with a warning naming both addresses.""" + VisorCache._instances["url7"] = make_handle(PvserverAddress(host="pv.example", port=22222)) + + _inst, warnings = VisorCache.get_instance( + "url7", RenderingMode.PARAVIEW, True, False, PvserverAddress(host="other", port=11111) + ) + + assert warnings == ( + "Connected to existing Visor instance at url7. " + "The following parameters were ignored because they cannot be " + "changed on an existing instance: pvserver=other:11111 (existing value: pv.example:22222)" + ) + + +def test_pvserver_for_non_handle_instance_warns(): + """A pvserver for a cached instance that is not a PARAVIEW handle is ignored, with a warning.""" + mock_visor = MagicMock() + mock_visor.standalone = True + mock_visor.dark_mode = False + VisorCache._instances["url8"] = mock_visor + + _inst, warnings = VisorCache.get_instance( + "url8", None, True, False, PvserverAddress(host="other", port=11111) + ) + + assert warnings == ( + "Connected to existing Visor instance at url8. " + "The following parameters were ignored because they cannot be " + "changed on an existing instance: pvserver=other:11111 (existing value: None)" + ) + + def test_delete_instance_removes(monkeypatch): """Verify that an instance is removed from the cache.""" mock_visor = MagicMock() diff --git a/tests/unit/app/test_paraview_handle.py b/tests/unit/app/test_paraview_handle.py new file mode 100644 index 00000000..9af6f567 --- /dev/null +++ b/tests/unit/app/test_paraview_handle.py @@ -0,0 +1,382 @@ +"""Unit tests for ``VisorParaviewHandle``: the launch of its session process, +the forwarding of each Visor method over the session channel, blocking start +and the end of the session process. + +Mocking boundary: ``VisorParaviewHandle._create_session_process`` returns a +fake session process whose channel records each call and the thread it was +made on; ``ParaviewSessionProcess.from_settings`` where the ``Visor`` factory +is exercised. No pvpython is started. +""" + +import asyncio +import gc +import threading +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + +from ansys.visor.viewer.app.paraview import paraview_handle +from ansys.visor.viewer.app.paraview.paraview_handle import VisorParaviewHandle +from ansys.visor.viewer.app.paraview.session_process import ParaviewSessionProcess +from ansys.visor.viewer.app.visor import Visor +from ansys.visor.viewer.config import settings +from ansys.visor.viewer.core.errors import ( + ParaviewNotConfiguredError, + ParaviewSessionError, + PvserverConnectionError, + UnsupportedInModeError, +) +from ansys.visor.viewer.core.pvserver_address import PvserverAddress + +URL = "http://localhost:8095" +ADDRESS = PvserverAddress(host="pv.example", port=22222) + + +def run_bounded(fn, timeout=10.0): + """Run fn in a thread; fail if it has not returned within timeout, else return or raise its outcome.""" + outcome = {} + + def target(): + try: + outcome["value"] = fn() + except BaseException as exc: + outcome["error"] = exc + + thread = threading.Thread(target=target, daemon=True) + thread.start() + thread.join(timeout) + assert not thread.is_alive(), "the call did not return within the guard" + if "error" in outcome: + raise outcome["error"] + return outcome.get("value") + + +class FakeChannel: + """Records each call; a handler set for a method runs in its place.""" + + def __init__(self): + self.calls = [] + self.handlers = {} + self.started = threading.Event() + + def call(self, method, *args): + self.calls.append((method, args, threading.get_ident())) + if method == "start": + self.started.set() + if method in self.handlers: + return self.handlers[method](*args) + return f"{method}-result" + + +class FakeSessionProcess: + def __init__(self, launch_error=None): + self.channel = FakeChannel() + self.launch_error = launch_error + self.requests = [] + self.alive = False + self.exit_code = None + self.end_calls = 0 + self.pid = 4242 + self.log_path = Path("logs") / "visor_paraview_session_8095.log" + + def launch(self, request): + self.requests.append(request) + if self.launch_error is not None: + raise self.launch_error + self.alive = True + return self.channel + + def end(self): + self.end_calls += 1 + self.alive = False + self.exit_code = 0 + + +@pytest.fixture +def fake(monkeypatch): + """The session process every handle built in the test is given.""" + process = FakeSessionProcess() + monkeypatch.setattr(VisorParaviewHandle, "_create_session_process", lambda self: process) + monkeypatch.setattr(paraview_handle, "BLOCKING_WAIT_SLICE_S", 0.01) + return process + + +@pytest.fixture +def handle(fake): + built = VisorParaviewHandle(url=URL, pvserver=ADDRESS) + yield built + built.close() + + +class StubEvent: + """An event whose wait is chosen by the test; set and is_set behave as threading.Event.""" + + def __init__(self, wait): + self._flag = False + self._wait = wait + + def set(self): + self._flag = True + + def clear(self): + self._flag = False + + def is_set(self): + return self._flag + + def wait(self, timeout=None): + return self._wait() + + +def test_init_launches_session_with_request_fields(fake): + handle = VisorParaviewHandle(url=URL, standalone=False, dark_mode=True, trame_log_dir="tl", pvserver=ADDRESS) + + request = fake.requests[0] + assert request.url == "http://localhost:8095" + assert request.standalone is False + assert request.dark_mode is True + assert request.trame_log_dir == "tl" + assert request.pvserver == ADDRESS + assert handle.pvserver == ADDRESS + handle.close() + + +def test_init_uses_settings_default_pvserver_when_omitted(fake, monkeypatch): + monkeypatch.setattr(paraview_handle, "settings", MagicMock()) + paraview_handle.settings.default_pvserver_address.return_value = PvserverAddress(host="dflt", port=11111) + + handle = VisorParaviewHandle(url=URL) + + assert fake.requests[0].pvserver == PvserverAddress(host="dflt", port=11111) + assert handle.pvserver == PvserverAddress(host="dflt", port=11111) + handle.close() + + +def test_init_logs_ready_line_with_url_pvserver_and_pid(fake, monkeypatch): + logger = MagicMock() + monkeypatch.setattr(paraview_handle, "logger", logger) + + handle = VisorParaviewHandle(url=URL, pvserver=ADDRESS) + + logger.info.assert_called_once_with( + "PARAVIEW session ready on %s (pvserver %s, pid %s)", "http://localhost:8095", ADDRESS, 4242 + ) + handle.close() + + +def test_finalizer_ends_session_process(fake): + handle = VisorParaviewHandle(url=URL, pvserver=ADDRESS) + + del handle + gc.collect() + + assert fake.end_calls == 1 + + +def test_launch_error_propagates(monkeypatch): + process = FakeSessionProcess(launch_error=PvserverConnectionError("Could not connect to pvserver at pv.example:22222")) + monkeypatch.setattr(VisorParaviewHandle, "_create_session_process", lambda self: process) + + with pytest.raises(PvserverConnectionError, match="^Could not connect to pvserver at pv.example:22222$"): + VisorParaviewHandle(url=URL, pvserver=ADDRESS) + + +@pytest.mark.parametrize(("method", "args"), [ + ("update", ("a.vtu", None)), + ("add_dataset", ("a.vtu", None)), + ("remove_dataset", (3,)), + ("list_datasets", ()), + ("list_variables", (3,)), + ("load_state", ("state_dir",)), +]) +def test_methods_forward_to_channel(handle, fake, method, args): + result = getattr(handle, method)(*args) + + assert result == f"{method}-result" + assert [(name, called_args) for name, called_args, _ in fake.channel.calls] == [(method, args)] + + +def test_start_forwards_without_blocking(handle, fake): + result = run_bounded(lambda: handle.start("a.vtu", None, 5)) + + assert result == "start-result" + assert [(name, args) for name, args, _ in fake.channel.calls] == [("start", ("a.vtu", None, 5))] + + +@pytest.mark.parametrize("method", ["start", "update", "add_dataset"]) +def test_non_str_input_raises_without_channel_call(handle, fake, method): + with pytest.raises(UnsupportedInModeError, match="^in-memory dataset input is not supported in PARAVIEW mode$"): + getattr(handle, method)(MagicMock(name="dataset")) + + assert fake.channel.calls == [] + + +def test_blocking_start_returns_when_stopped(handle, fake): + def stop_once_started(): + assert fake.channel.started.wait(5) + handle.stop() + + stopper = threading.Thread(target=stop_once_started, daemon=True) + stopper.start() + + result = run_bounded(lambda: handle.start("a.vtu", blocking=True)) + stopper.join(5) + + assert result == "start-result" + assert [name for name, _, _ in fake.channel.calls] == ["start", "stop"] + assert fake.end_calls == 0 + + +def test_blocking_start_returns_when_closed(handle, fake): + def close_once_started(): + assert fake.channel.started.wait(5) + handle.close() + + closer = threading.Thread(target=close_once_started, daemon=True) + closer.start() + + result = run_bounded(lambda: handle.start("a.vtu", blocking=True)) + closer.join(5) + + assert result == "start-result" + assert fake.end_calls == 1 + + +def test_blocking_start_raises_when_session_process_exits_by_itself(handle, fake): + def exit_by_itself(*args): + fake.alive = False + fake.exit_code = 3 + return "start-result" + + fake.channel.handlers["start"] = exit_by_itself + + with pytest.raises(ParaviewSessionError) as raised: + run_bounded(lambda: handle.start("a.vtu", blocking=True)) + + assert str(raised.value) == ( + "The PARAVIEW session process exited with code 3 while start was blocking; " + f"see its log at {Path('logs') / 'visor_paraview_session_8095.log'}" + ) + assert fake.end_calls == 1 + + +def test_blocking_start_interrupt_ends_session_and_reraises(handle, fake): + def interrupt(): + raise KeyboardInterrupt + + handle._wait_released = StubEvent(interrupt) + + with pytest.raises(KeyboardInterrupt): + handle.start("a.vtu", blocking=True) + + assert fake.end_calls == 1 + assert [name for name, _, _ in fake.channel.calls] == ["start"] + + +def test_session_ended_by_close_is_not_reported_as_error(handle, fake): + """A wait that times out just as close ends the session process returns normally.""" + handle._wait_released = StubEvent(lambda: False) + + def close_during_start(*args): + handle.close() + return "start-result" + + fake.channel.handlers["start"] = close_during_start + + result = run_bounded(lambda: handle.start("a.vtu", blocking=True)) + + assert result == "start-result" + assert fake.end_calls == 1 + + +def test_update_variables_raises_unsupported(handle, fake): + with pytest.raises(UnsupportedInModeError, match="^update_variables is not supported in PARAVIEW mode$"): + handle.update_variables(0, []) + + assert fake.channel.calls == [] + + +def test_save_state_forwards_off_event_loop(handle, fake): + loop_thread = threading.get_ident() + + asyncio.run(handle.save_state("state_dir")) + + [(name, args, thread)] = fake.channel.calls + assert (name, args) == ("save_state", ("state_dir",)) + assert thread != loop_thread + + +def test_start_async_returns_dataset_id_and_none(handle, fake): + fake.channel.handlers["start"] = lambda *args: 7 + + result = asyncio.run(handle._start_async("a.vtu", None, 5)) + + assert result == (7, None) + assert [(name, args) for name, args, _ in fake.channel.calls] == [("start", ("a.vtu", None, 5))] + + +def test_stop_async_forwards_stop(handle, fake): + asyncio.run(handle._stop_async()) + + assert [(name, args) for name, args, _ in fake.channel.calls] == [("stop", ())] + + +def test_health_false_when_process_gone(handle, fake): + fake.alive = False + + assert handle._health() is False + assert fake.channel.calls == [] + + +def test_health_forwards_when_alive(handle, fake): + fake.channel.handlers["_health"] = lambda: True + + assert handle._health() is True + + +def test_close_ends_session_process_once(handle, fake): + handle.close() + handle.close() + + assert fake.end_calls == 1 + + +def test_running_reflects_process_alive(handle, fake): + assert handle.running is True + + fake.alive = False + + assert handle.running is False + + +def test_rendering_mode_other_than_paraview_rejected(fake): + with pytest.raises(ValueError, match="^VisorParaviewHandle runs PARAVIEW sessions only, not CLIENT$"): + VisorParaviewHandle(url=URL, rendering_mode="CLIENT") + + assert fake.requests == [] + + +def test_visor_factory_returns_handle_for_paraview(monkeypatch): + process = FakeSessionProcess() + received = [] + + def from_settings(given_settings, port): + received.append((given_settings, port)) + return process + + monkeypatch.setattr(ParaviewSessionProcess, "from_settings", from_settings) + + handle = Visor(rendering_mode="PARAVIEW", url=URL, pvserver=ADDRESS) + + assert type(handle) is VisorParaviewHandle + assert received == [(settings, 8095)] + assert process.requests[0].pvserver == ADDRESS + handle.close() + + +def test_production_seam_names_missing_pvpython(monkeypatch): + monkeypatch.setattr(settings, "paraview_pvpython", None) + + with pytest.raises(ParaviewNotConfiguredError, match="^PARAVIEW mode needs 'paraview_pvpython' set in the .visor file$"): + VisorParaviewHandle(url=URL, pvserver=ADDRESS) diff --git a/tests/unit/app/test_session_process.py b/tests/unit/app/test_session_process.py index c4e3f40b..8d0ef30d 100644 --- a/tests/unit/app/test_session_process.py +++ b/tests/unit/app/test_session_process.py @@ -8,6 +8,7 @@ """ import asyncio +import os import subprocess import threading import time @@ -94,11 +95,12 @@ class FakePopen: stubborn like ready, but survives shutdown and terminate until killed """ - def __init__(self, command, stdin, stdout, stderr, behaviour): + def __init__(self, command, stdin, stdout, stderr, behaviour, options=None): self.args = command self.stdin_arg = stdin self.stdout_arg = stdout self.stderr_arg = stderr + self.options = options or {} self.behaviour = behaviour self.stdin = FakeStdin(self._start) self.pid = 4242 @@ -168,8 +170,8 @@ def spawn(monkeypatch, tmp_path): created = [] def build(behaviour, start_timeout=10.0): - def fake_popen(command, stdin, stdout, stderr): - created.append(FakePopen(command, stdin, stdout, stderr, behaviour)) + def fake_popen(command, stdin, stdout, stderr, **options): + created.append(FakePopen(command, stdin, stdout, stderr, behaviour, options)) return created[-1] monkeypatch.setattr(session_process.subprocess, "Popen", fake_popen) @@ -282,6 +284,32 @@ def test_end_escalates_to_kill_and_is_idempotent(spawn): assert created[0].returncode == -9 +def test_pid_and_exit_code(spawn): + process, _created = spawn("ready") + assert process.pid is None + assert process.exit_code is None + + run_bounded(lambda: process.launch(REQUEST)) + running_code = process.exit_code + run_bounded(process.end) + + assert process.pid == 4242 + assert running_code is None + assert process.exit_code == 0 + + +def test_launch_spawns_child_in_its_own_process_group(spawn): + process, created = spawn("ready") + + run_bounded(lambda: process.launch(REQUEST)) + run_bounded(process.end) + + if os.name == "nt": + assert created[0].options == {"creationflags": 0x00000200} + else: + assert created[0].options == {"start_new_session": True} + + def test_from_settings_names_missing_key_and_builds_log_path(tmp_path): with pytest.raises(ParaviewNotConfiguredError, match="^PARAVIEW mode needs 'paraview_pvpython' set in the .visor file$"): ParaviewSessionProcess.from_settings(Settings(paraview_pvpython=None, paraview_venv="venv"), 8081) diff --git a/tests/unit/app/test_thiea.py b/tests/unit/app/test_thiea.py index 8f47266f..cad81ff8 100644 --- a/tests/unit/app/test_thiea.py +++ b/tests/unit/app/test_thiea.py @@ -1,6 +1,7 @@ import pytest from ansys.visor.viewer.app.visor import Visor +from ansys.visor.viewer.core.pvserver_address import PvserverAddress class ConcreteVisor(Visor): @@ -58,6 +59,20 @@ class DummyEngine: with pytest.raises(ValueError): Visor(rendering_engine=DummyEngine) +@pytest.mark.parametrize("mode", ["CLIENT", "SERVER"]) +def test_pvserver_rejected_outside_paraview(mode): + """A pvserver address outside PARAVIEW mode raises an error naming the mode.""" + address = PvserverAddress(host="localhost", port=11111) + with pytest.raises(ValueError, match=f"^pvserver is accepted only in PARAVIEW mode, not {mode}$"): + Visor(rendering_mode=mode, url="http://localhost:1234", pvserver=address) + +def test_pvserver_rejected_on_direct_vtk_construction(): + """A VTK viewer built directly rejects a pvserver address too.""" + from ansys.visor.viewer.app.visor_vtk import VisorVTK + address = PvserverAddress(host="localhost", port=11111) + with pytest.raises(ValueError, match="^pvserver is accepted only in PARAVIEW mode, not SERVER$"): + VisorVTK(rendering_mode="SERVER", url="http://localhost:1234", pvserver=address) + def test_set_default_url_sets_properties(monkeypatch): """Verify that default settings are used to construct the URL.""" monkeypatch.setattr("ansys.visor.viewer.config.settings.default_host", "localhost") diff --git a/tests/unit/app/test_visor_vtk_paraview.py b/tests/unit/app/test_visor_vtk_paraview.py index c5b48af8..499cc2fe 100644 --- a/tests/unit/app/test_visor_vtk_paraview.py +++ b/tests/unit/app/test_visor_vtk_paraview.py @@ -1,10 +1,12 @@ """Unit tests for ``VisorVTKParaview``'s wiring of the bridge, the ParaView -scene and ``ParaviewApp``, and its refusal of variable updates. +scene and ``ParaviewApp``, its refusal of variable updates, and the snapshot +path it clears from user metadata but keeps on restored state. Mocking boundary: ``visor_vtk.TrameServerManager``, ``visor_vtk_paraview.ParaviewApp``, ``visor_vtk_paraview.VisorParaviewScene``, ``visor_vtk_paraview.ServerLoopBridge`` and -``visor_vtk_paraview.ServerStatePublisher``. Nothing here starts a trame +``visor_vtk_paraview.ServerStatePublisher``; the file readers of the viewer's +file IO where a dataset or state is read. Nothing here starts a trame server or imports ParaView. """ @@ -14,6 +16,8 @@ from ansys.visor.viewer.app.paraview.visor_vtk_paraview import VisorVTKParaview from ansys.visor.viewer.core.errors import UnsupportedInModeError +from ansys.visor.viewer.core.metadata import Metadata +from ansys.visor.viewer.models.persist.dataset.persisted_dataset_state import PersistedDatasetState @pytest.fixture @@ -94,3 +98,69 @@ def test_update_variables_raises_unsupported(wiring): with pytest.raises(UnsupportedInModeError): viewer.update_variables(0, []) + + +def added_metadata(scene_cls): + """The metadata the scene received with the one dataset added to it.""" + scene = scene_cls.return_value + scene.add_dataset.assert_called_once() + return scene.add_dataset.call_args.args[1] + + +def add_with_metadata(scene_cls, viewer, metadata): + scene_cls.return_value.add_dataset.return_value = 1 + with patch.object(viewer._file_io, "read_dataset", return_value=MagicMock(name="dataset")): + viewer.add_dataset("model.vtu", metadata) + + +def test_user_metadata_snapshot_path_is_cleared(wiring): + """pvserver would open a snapshot path in place of the input, so user metadata loses it.""" + _app_cls, scene_cls, *_, viewer = wiring + metadata = Metadata(name="m", unit="mm", state={"serialized_dataset_path": "elsewhere.vtm"}) + + add_with_metadata(scene_cls, viewer, metadata) + + assert added_metadata(scene_cls).state.serialized_dataset_path is None + assert added_metadata(scene_cls).file_path == "model.vtu" + assert metadata.state.serialized_dataset_path == "elsewhere.vtm" + + +def test_user_metadata_parts_are_kept(wiring): + _app_cls, scene_cls, *_, viewer = wiring + metadata = Metadata( + name="m", unit="mm", state={"serialized_dataset_path": "elsewhere.vtm", "parts": {"wing": {}}} + ) + + add_with_metadata(scene_cls, viewer, metadata) + + assert list(added_metadata(scene_cls).state.parts) == ["wing"] + + +def test_json_metadata_snapshot_path_is_cleared(wiring, tmp_path): + _app_cls, scene_cls, *_, viewer = wiring + metadata_file = tmp_path / "meta.json" + metadata_file.write_text( + '{"name": "m", "unit": "mm", "state": {"serialized_dataset_path": "elsewhere.vtm"}}' + ) + + add_with_metadata(scene_cls, viewer, str(metadata_file)) + + assert added_metadata(scene_cls).state.serialized_dataset_path is None + assert added_metadata(scene_cls).metadata_path == str(metadata_file) + + +def test_load_state_keeps_snapshot_path(wiring, tmp_path): + """Restoring state builds metadata without resolving user input, so its snapshot path is kept.""" + _app_cls, scene_cls, *_, viewer = wiring + snapshot = tmp_path / "ds.vtm" + snapshot.write_text("") + state = MagicMock(name="state") + state.scene.unit = "mm" + state.scene.dataset_states = {"ds": PersistedDatasetState(serialized_dataset_path=str(snapshot))} + scene_cls.return_value.dataset_count = 0 + + with patch.object(viewer._file_io, "read_state", return_value=state), \ + patch.object(viewer._file_io, "read_snapshot", return_value=MagicMock(name="dataset")): + viewer.load_state(str(tmp_path)) + + assert added_metadata(scene_cls).state.serialized_dataset_path == str(snapshot) From 98f9c9c490dc44367ba50ee168566976cd179f22 Mon Sep 17 00:00:00 2001 From: pyansys-ci-bot <92810346+pyansys-ci-bot@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:46:37 +0000 Subject: [PATCH 4/4] chore: adding changelog file 226.added.md [dependabot-skip] --- doc/changelog.d/226.added.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 doc/changelog.d/226.added.md diff --git a/doc/changelog.d/226.added.md b/doc/changelog.d/226.added.md new file mode 100644 index 00000000..b94c0e6f --- /dev/null +++ b/doc/changelog.d/226.added.md @@ -0,0 +1 @@ +Remote rendering 5.2c - Wire ParaView mode in VISOR