# Copyright (c) 2026. Jose Manuel Requena Plens """The ssh command line a remote run starts, and the placement its node runs.""" from __future__ import annotations import dataclasses import io import json import logging import os import shlex import shutil import subprocess import sys from pathlib import Path from types import MappingProxyType from typing import TYPE_CHECKING import pytest import windows_lookup from phonometry.simulation import Compute, ComputeRemoteError from phonometry.simulation._remote import bootstrap, client, command, node from phonometry.simulation._remote.hosts import HostEntry if TYPE_CHECKING: from collections.abc import Mapping from phonometry.simulation.compute import Device, Dtype _DOCKER = HostEntry( name="nas", ssh="root@192.168.0.40", runner="docker", target="phonometry-node:gpu", label="the NAS", timeout_s=None, ) _PYTHON = HostEntry( name="lab", ssh="lab", runner="python", target="/opt/my node's env/bin/python", label="the lab", timeout_s=None, ) #: The longest the loader may take to run a script of one line [s]. _LOADER_TIMEOUT_S = 60 #: A stand-in for a node's program: it writes each word it is given, ended by a NUL. _WORDS_OUT = '#!/bin/sh\nfor word in "$@"; do printf \'%s\\0\' "$word"; done\n' _posix_only = pytest.mark.skipif( sys.platform == "win32", reason="a node's login shell is a POSIX shell" ) def _options(argv: list[str]) -> list[str]: """The options of an ssh command line: between the program and ``--``.""" return argv[1 : argv.index("--")] def _stand_in(path: Path) -> Path: """An executable at *path* that writes the words it is given.""" path.parent.mkdir(parents=True) path.write_text(_WORDS_OUT, encoding="utf-8") path.chmod(0o755) return path def _through_a_shell( remote: str, home: Path, path: str, environment: Mapping[str, str] = MappingProxyType({}), ) -> list[str]: """The words the node's program is given when a POSIX shell runs *remote*, as sshd does.""" done = subprocess.run( ["sh", "-c", remote], capture_output=True, check=True, cwd=home, env={"HOME": str(home), "PATH": path, **environment}, timeout=60, ) return done.stdout.decode().split("\0")[:-1] def test_ssh_takes_these_options_and_no_others() -> None: # Every one of them overrides what ~/.ssh/config says for the host, and # every client from OpenSSH 7.6 on knows it; one more that weakens them, # or that an older client refuses, cannot slip in beside the checks of each. assert command.SSH_OPTIONS == ( "-T", "-a", "-x", "-o", "RequestTTY=no", "-o", "RemoteCommand=none", "-o", "ClearAllForwardings=yes", "-o", "PermitLocalCommand=no", "-o", "GSSAPIDelegateCredentials=no", "-o", "ControlPath=none", "-o", "BatchMode=yes", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4", "-o", "ConnectTimeout=30", ) def test_ssh_never_prompts_and_ends_its_options_before_the_destination( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr(command, "_SSH_PROGRAM", ("ssh",)) argv = command.ssh_argv(_DOCKER, Compute(device="cupy", host="nas")) assert argv[0] == "ssh" assert argv[argv.index("--") + 1] == "root@192.168.0.40" assert len(argv) == argv.index("--") + 3 # the destination, then the remote command options = _options(argv) for setting in ( "BatchMode=yes", "ServerAliveInterval=15", "ServerAliveCountMax=4", "ConnectTimeout=30", ): assert options[options.index(setting) - 1] == "-o" def test_ssh_asks_for_no_terminal_and_forwards_nothing_of_the_client( monkeypatch: pytest.MonkeyPatch, ) -> None: # A "RequestTTY force", a "ForwardAgent yes", a "GSSAPIDelegateCredentials # yes" or a "ControlMaster auto" that ~/.ssh/config gives the host must # not reach a run: a pty rewrites the frames, a node runs the code it is # sent, with neither the client's agent nor its Kerberos credentials, and # a run neither leaves a master behind here nor rides another's, whose # keep-alives and timeout are not the run's. Options on the command line # win over the file. monkeypatch.setattr(command, "_SSH_PROGRAM", ("ssh",)) options = _options(command.ssh_argv(_DOCKER, Compute(host="nas"))) assert {"-T", "-a", "-x"} <= set(options) for setting in ( "RequestTTY=no", "ClearAllForwardings=yes", "GSSAPIDelegateCredentials=no", "ControlPath=none", ): assert options[options.index(setting) - 1] == "-o" @pytest.mark.skipif( shutil.which("ssh") is None, reason="needs an ssh client on PATH; every runner of the CI tests job has one", ) def test_the_ssh_client_here_lets_no_setting_of_a_config_through( tmp_path: Path, ) -> None: # The client on this machine reads a config that asks for everything a run # must not have, and says (-G) what it would do: the options win. A client # built without GSSAPI lists no delegation, and delegates nothing. config = tmp_path / "config" config.write_text( "Host node\n" " ForwardAgent yes\n" " ForwardX11 yes\n" " RequestTTY force\n" " GSSAPIDelegateCredentials yes\n" " RemoteCommand echo config\n" " PermitLocalCommand yes\n" " LocalForward 9999 localhost:22\n" " ControlMaster auto\n" f" ControlPath {tmp_path / 'master-%r@%h:%p'}\n" " ControlPersist yes\n" " BatchMode no\n", encoding="utf-8", ) done = subprocess.run( ["ssh", "-F", str(config), "-G", *command.SSH_OPTIONS, "--", "node"], capture_output=True, check=True, text=True, timeout=60, ) settings: dict[str, list[str]] = {} for line in done.stdout.splitlines(): key, _, value = line.partition(" ") settings.setdefault(key, []).append(value) assert settings["forwardagent"] == ["no"] assert settings["forwardx11"] == ["no"] assert settings["requesttty"] in (["no"], ["false"]) assert settings["permitlocalcommand"] == ["no"] assert settings["batchmode"] == ["yes"] assert settings.get("gssapidelegatecredentials", ["no"]) == ["no"] # No control path, no shared connection, whatever ControlMaster says. assert settings.get("controlpath", ["none"]) == ["none"] for forwarding in ( "remotecommand", "localforward", "remoteforward", "dynamicforward", ): assert forwarding not in settings def test_a_docker_node_runs_the_image_s_bootstrap_cut_off_from_the_network() -> None: sh, flag, script = shlex.split( command.remote_command( _DOCKER, Compute(device="cupy", device_index=1, host="nas") ) ) assert (sh, flag) == ("sh", "-c") words = shlex.split(script) docker = words[words.index("exec") + 1 :] # No log: Docker would copy the result stream, the container's standard # output, into a log on the node's disk. assert docker[:10] == [ "docker", "run", "--rm", "-i", "--init", "--pull=never", "--network", "none", "--log-driver", "none", ] assert docker[docker.index("--gpus") + 1] == "device=1" assert docker[docker.index("--user") + 1] == "$(id -u):$(id -g)" assert docker[docker.index("-v") + 1] == "$cache:/cache" assert docker[-3:] == ["phonometry-node:gpu", "-I", bootstrap.IMAGE_PATH] assert 'mkdir -p "$cache"' in script def test_a_docker_node_s_bootstrap_reads_its_cache_from_the_volume() -> None: _, _, script = shlex.split(command.remote_command(_DOCKER, Compute(host="nas"))) words = shlex.split(script) pairs = set(zip(words, words[1:], strict=False)) assert ("-e", f"{bootstrap.CACHE_VAR}=/cache") in pairs assert ("-v", "$cache:/cache") in pairs @_posix_only @pytest.mark.parametrize("xdg", [None, "", "relative/cache", "absolute"]) def test_a_docker_node_s_cache_is_where_its_bootstrap_would_look( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, xdg: str | None ) -> None: # XDG ignores a relative XDG_CACHE_HOME, and so do the bootstrap and the # shell that mounts the cache: a node's cache is read one way. bin_dir = tmp_path / "bin" _stand_in(bin_dir / "docker") value = str(tmp_path / "xdg") if xdg == "absolute" else xdg environment = {} if value is None else {"XDG_CACHE_HOME": value} words = _through_a_shell( command.remote_command(_DOCKER, Compute(host="nas")), tmp_path, f"{bin_dir}{os.pathsep}{os.environ['PATH']}", environment, ) monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.delenv(bootstrap.CACHE_VAR, raising=False) monkeypatch.delenv("XDG_CACHE_HOME", raising=False) for name, setting in environment.items(): monkeypatch.setenv(name, setting) expected = bootstrap.cache_dir() assert words[words.index("-v") + 1] == f"{expected}:/cache" assert expected.is_dir() assert not (tmp_path / "relative").exists() @pytest.mark.parametrize("device", ["cpu", "cupy"]) def test_a_docker_node_runs_the_bootstrap_as_its_entrypoint(device: Device) -> None: # An image's own ENTRYPOINT (the CUDA images' prints a banner on standard # output) never runs: the bootstrap is the entrypoint, the image's name # the last word before its arguments. request = Compute(device=device, host="nas") _, _, script = shlex.split(command.remote_command(_DOCKER, request)) words = shlex.split(script) image = words.index("phonometry-node:gpu") assert words[words.index("--entrypoint") + 1] == "python" assert words.index("--entrypoint") < image assert words[image + 1 :] == ["-I", bootstrap.IMAGE_PATH] def test_a_numpy_run_on_a_docker_node_asks_for_no_gpu() -> None: assert "--gpus" not in command.remote_command(_DOCKER, Compute(host="nas")) def test_an_image_name_stays_one_word_whatever_it_holds() -> None: odd = dataclasses.replace(_DOCKER, target="reg.example:5000/team/node:gpu;rm -rf") _, _, script = shlex.split(command.remote_command(odd, Compute(host="nas"))) assert "reg.example:5000/team/node:gpu;rm -rf" in shlex.split(script) def test_a_python_node_runs_its_interpreter_isolated_on_the_loader() -> None: words = shlex.split(command.remote_command(_PYTHON, Compute(host="lab"))) assert words == ["/opt/my node's env/bin/python", "-I", "-c", command.LOADER] @_posix_only def test_a_docker_node_s_shell_runs_no_word_of_the_hosts_file(tmp_path: Path) -> None: bin_dir = tmp_path / "bin" _stand_in(bin_dir / "docker") odd = dataclasses.replace( _DOCKER, target="node:gpu;touch injected $(touch injected) `touch injected`" ) remote = command.remote_command( odd, Compute(device="cupy", device_index=1, host="nas") ) words = _through_a_shell( remote, tmp_path, f"{bin_dir}{os.pathsep}{os.environ['PATH']}" ) cache = tmp_path / ".cache" / "phonometry" / "remote" assert words[-3:] == [odd.target, "-I", bootstrap.IMAGE_PATH] assert words[words.index("--entrypoint") + 1] == "python" assert words[words.index("--user") + 1] == f"{os.getuid()}:{os.getgid()}" assert words[words.index("-v") + 1] == f"{cache}:/cache" assert cache.is_dir() assert not (tmp_path / "injected").exists() @_posix_only def test_a_python_node_s_shell_runs_no_word_of_the_hosts_file(tmp_path: Path) -> None: interpreter = _stand_in( tmp_path / "my node's env $(touch injected)" / "bin" / "python" ) entry = dataclasses.replace(_PYTHON, target=str(interpreter)) words = _through_a_shell( command.remote_command(entry, Compute(host="lab")), tmp_path, os.environ["PATH"] ) assert words == ["-I", "-c", command.LOADER] assert not (tmp_path / "injected").exists() def test_the_loader_runs_what_it_is_sent_and_leaves_the_rest_of_the_input() -> None: source = b"import sys; sys.stderr.write(sys.stdin.buffer.read().decode())" done = subprocess.run( [sys.executable, "-I", "-c", command.LOADER], input=b"%d\n" % len(source) + source + b"the frames", capture_output=True, check=False, timeout=_LOADER_TIMEOUT_S, ) assert (done.returncode, done.stderr) == (0, b"the frames") def test_the_loader_runs_the_bootstrap_as_the_image_runs_its_copy( tmp_path: Path, ) -> None: # The bootstrap answers only when it runs as __main__: a hello of another # protocol is refused by name, from the node's standard output. source = Path(bootstrap.__file__).read_bytes() hello = io.BytesIO() bootstrap.write_frame(hello, {"type": "hello", "protocol": bootstrap.PROTOCOL + 1}) done = subprocess.run( [sys.executable, "-I", "-c", command.LOADER], input=b"%d\n" % len(source) + source + hello.getvalue(), capture_output=True, env={**os.environ, bootstrap.CACHE_VAR: str(tmp_path)}, check=False, timeout=120, ) answer = bootstrap.read_header(io.BytesIO(done.stdout)) assert done.returncode == 2, done.stderr assert (answer["type"], answer["stage"]) == ("error", "protocol") def test_a_docker_node_sees_the_one_gpu_it_is_given_as_index_0() -> None: request = Compute(device="cupy", device_index=1, host="nas") assert command.node_placement(_DOCKER, request) == { "device": "cupy", "device_index": 0, "dtype": "float64", } assert ( command.node_placement(_PYTHON, dataclasses.replace(request, host="lab"))[ "device_index" ] == 1 ) @pytest.mark.parametrize("entry", [_DOCKER, _PYTHON], ids=lambda entry: entry.runner) @pytest.mark.parametrize( ("device", "index", "dtype"), [ ("cpu", 0, "float64"), ("torch:cpu", 0, "float32"), ("torch:mps", 0, "float32"), ("cupy", 1, "float64"), ("torch:cuda", 2, "float32"), ], ) def test_a_node_takes_the_placement_it_is_sent( entry: HostEntry, device: Device, index: int, dtype: Dtype ) -> None: # What the node rebuilds from the job, after the JSON of the frame. request = Compute(device=device, device_index=index, dtype=dtype, host=entry.name) placement = json.loads(json.dumps(command.node_placement(entry, request))) taken = node._placement({"compute": placement}) on_one_gpu = entry.runner == "docker" and device in ("cupy", "torch:cuda") assert taken == Compute( device=device, device_index=0 if on_one_gpu else index, dtype=dtype ) def test_no_ssh_on_the_path_is_a_missing_file( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: monkeypatch.setattr(command, "_SSH_PROGRAM", None) monkeypatch.setenv("PATH", str(tmp_path)) with pytest.raises( FileNotFoundError, match=r"^no ssh client on PATH; install OpenSSH to run on a node$", ): command.ssh_program() @pytest.fixture def windows(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: """A Windows lookup of ``ssh`` from *tmp_path*, which holds a planted ``ssh.exe``.""" (tmp_path / "ssh.exe").write_bytes(b"") monkeypatch.chdir(tmp_path) monkeypatch.setenv("PATH", str(tmp_path / "elsewhere")) monkeypatch.setattr(command, "_SSH_PROGRAM", None) monkeypatch.setattr(shutil, "which", windows_lookup.which) monkeypatch.setattr(sys, "platform", "win32") return tmp_path def _install_ssh(directory: Path) -> Path: installed = directory / "ssh.exe" installed.parent.mkdir(exist_ok=True) installed.write_bytes(b"") return installed def test_windows_does_not_run_an_ssh_found_only_in_the_working_directory( windows: Path, ) -> None: with pytest.raises( FileNotFoundError, match=r"^ssh was found only in the working directory \(\.[/\\]ssh\.exe\), " r"which Windows searches before PATH; phonometry does not run a program " r"from there\. Put an OpenSSH client on PATH to run on a node$", ): command.ssh_program() def test_an_ssh_found_only_in_the_working_directory_is_a_remote_error_before_ssh_starts( windows: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """The remote route reports it as it reports no ssh at all: a ComputeRemoteError naming the node.""" def popen(argv: list[str]) -> None: msg = f"ssh started: {argv}" raise AssertionError(msg) monkeypatch.setattr(client, "_popen", popen) with ( pytest.raises( ComputeRemoteError, match=r"^node 'nas': ssh was found only in the working directory ", ) as raised, client.open_session(_DOCKER, Compute(host="nas")), ): pass assert raised.value.host == "nas" def test_windows_runs_the_ssh_on_path_past_one_in_the_working_directory( windows: Path, caplog: pytest.LogCaptureFixture ) -> None: installed = _install_ssh(windows / "elsewhere") with caplog.at_level(logging.INFO, logger="phonometry.simulation"): assert command.ssh_program() == (str(installed),) assert caplog.record_tuples == [ ( "phonometry.simulation", logging.INFO, f"running {installed} from PATH, not {os.curdir}{os.sep}ssh.exe from the " "working directory, which Windows searches first", ) ] def test_windows_takes_the_first_ssh_of_path_in_its_order( windows: Path, monkeypatch: pytest.MonkeyPatch ) -> None: first, second = windows / "first", windows / "second" monkeypatch.setenv("PATH", os.pathsep.join([str(first), str(second)])) _install_ssh(second) assert command.ssh_program() == (str(second / "ssh.exe"),) _install_ssh(first) assert command.ssh_program() == (str(first / "ssh.exe"),) def test_windows_runs_an_ssh_from_a_working_directory_path_lists( windows: Path, monkeypatch: pytest.MonkeyPatch ) -> None: _install_ssh(windows / "elsewhere") monkeypatch.setenv( "PATH", os.pathsep.join([str(windows / "elsewhere"), str(windows)]) ) assert command.ssh_program() == (f"{os.curdir}{os.sep}ssh.exe",) def test_only_windows_passes_over_what_the_lookup_found_in_the_working_directory( windows: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """Elsewhere a bare name is never looked up in the working directory first, so what was found runs.""" monkeypatch.setattr(sys, "platform", "linux") assert command.ssh_program() == (f"{os.curdir}{os.sep}ssh.exe",)