Files
Spellcast3d/code/tests/test_linux.py

610 lines
35 KiB
Python

"""What the installer and the hub do differently off Windows (Linux): the file locks, a tool's process tree, a venv's
layout, the checks before installing, PyTorch's build by card, the prebuilt wheels as pinned downloads, the start
scripts. The rules run on any system; what needs a POSIX system itself is skipped on Windows.
On a Linux machine: code/venvs/hub/bin/python -m pytest code/tests/test_linux.py (with pytest in that venv)
"""
from __future__ import annotations
import os
import shutil
import signal
import subprocess
import sys
import time
from pathlib import Path
import pytest
from spellcast import exports, locks, paths, procman
from spellcast.install import components, models, preflight, sdcpp, venvs, wheels
posix_only = pytest.mark.skipif(os.name == "nt", reason="needs a POSIX system")
ROOT = paths.ROOT
SCRIPTS = ("run-browser/run-spellcast3d.sh", "tools/environment.sh", "tools/spellcast-internal.sh", "tools/update.sh")
# ---- file locks ----------------------------------------------------------------------------------------------------
def test_a_lock_is_held_by_one_open_file_and_free_again_once_released(tmp_path: Path) -> None:
lock = tmp_path / ".hub.lock"
assert not locks.held(lock) and not locks.held(tmp_path / "no" / "folder")
with open(lock, "a+b") as first:
assert locks.take(first)
assert locks.held(lock), "another handle of the same process does not get it either"
with open(lock, "a+b") as second:
assert not locks.take(second)
assert locks.held(lock), "a closed handle that never had the lock takes it from nobody"
locks.release(first)
assert not locks.held(lock)
def test_a_lock_goes_when_its_process_dies(tmp_path: Path) -> None:
lock = tmp_path / "x.lock"
code = ("import sys, time; sys.path.insert(0, sys.argv[1]); from spellcast import locks\n"
"f = open(sys.argv[2], 'a+b'); print(locks.take(f), flush=True); time.sleep(60)")
# (the base Python: a Windows venv's python.exe is a launcher, whose death leaves the real one running)
python = getattr(sys, "_base_executable", sys.executable)
holder = subprocess.Popen([python, "-c", code, str(paths.CODE), str(lock)], stdout=subprocess.PIPE, text=True)
try:
assert holder.stdout is not None and holder.stdout.readline().strip() == "True"
assert locks.held(lock)
finally:
holder.kill()
holder.wait(10)
assert not locks.held(lock)
# ---- a tool's processes --------------------------------------------------------------------------------------------
def test_creation_flags_are_windows_alone() -> None:
if os.name == "nt":
assert procman.spawn_flags(True) == subprocess.CREATE_NEW_PROCESS_GROUP
assert procman.spawn_flags(False) == subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW
else:
assert procman.spawn_flags(True) == procman.spawn_flags(False) == 0
@posix_only
def test_a_tool_leads_a_session_of_its_own_and_its_whole_tree_is_killed(tmp_path: Path) -> None:
"""spawn_in_job: a new session (so a Ctrl+C in the hub's terminal never reaches the tool, and its group can be
killed); kill_tree: the tool, its children, and a grandchild that left the group for a session of its own."""
pids = tmp_path / "pids"
grandchild = "import os, time; os.setsid(); open(r'{0}', 'a').write(str(os.getpid()) + '\\n'); time.sleep(120)"
child = ("import subprocess, sys, time, os\n"
f"subprocess.Popen([sys.executable, '-c', {grandchild.format(pids)!r}])\n"
f"open(r'{pids}', 'a').write(str(os.getpid()) + '\\n'); time.sleep(120)")
tool = ("import subprocess, sys, time\n"
f"subprocess.Popen([sys.executable, '-c', {child!r}]); print('up', flush=True); time.sleep(120)")
proc = procman.spawn_in_job([sys.executable, "-c", tool], tmp_path, dict(os.environ), procman.spawn_flags(True))
try:
assert proc.stdout is not None and proc.stdout.readline().strip() == b"up"
assert os.getsid(proc.pid) == proc.pid != os.getsid(0)
deadline = time.monotonic() + 20
while time.monotonic() < deadline and (not pids.exists() or len(pids.read_text().split()) < 2):
time.sleep(0.1)
others = [int(pid) for pid in pids.read_text().split()]
assert len(others) == 2 and set(others) <= set(procman.descendants(proc.pid))
procman.kill_tree(proc.pid)
proc.wait(10)
deadline = time.monotonic() + 10
while time.monotonic() < deadline and any(_alive(pid) for pid in others):
time.sleep(0.1)
assert not any(_alive(pid) for pid in others)
finally:
proc.kill()
def _alive(pid: int) -> bool:
try:
with open(f"/proc/{pid}/stat", encoding="ascii", errors="replace") as f:
return f.read().rsplit(")", 1)[1].split()[0] != "Z" # (a zombie nobody reaped yet is dead)
except OSError:
return False
@posix_only
def test_a_tool_is_asked_to_stop_with_sigterm() -> None:
proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], stdout=subprocess.PIPE)
assert procman.ask_to_stop(proc, console=False) and proc.wait(10) == -signal.SIGTERM
# ---- a venv's layout -----------------------------------------------------------------------------------------------
def test_a_venvs_packages_and_python_are_where_this_system_puts_them(tmp_path: Path) -> None:
packages = venvs.site_packages(tmp_path)
if os.name == "nt":
assert packages == tmp_path / "Lib" / "site-packages" and venvs.BASE_PYTHON_NAME == "python.exe"
assert paths.venv_python("x") == paths.VENVS / "x" / "Scripts" / "python.exe"
assert paths.PORTABLE_PYTHON == paths.TOOLS / "python" / "python.exe"
else:
minor = f"python{sys.version_info[0]}.{sys.version_info[1]}"
assert packages == tmp_path / "lib" / minor / "site-packages" and venvs.BASE_PYTHON_NAME == "python3"
assert paths.venv_python("x") == paths.VENVS / "x" / "bin" / "python"
assert paths.PORTABLE_PYTHON == paths.TOOLS / "python" / "bin" / "python3"
assert {"nvidia", "cusparselt"} <= set(venvs.SHARED_PACKAGES), "a Linux torch's CUDA libraries are shared too"
@posix_only
def test_a_moved_venv_points_at_the_python_of_its_new_place(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Off Windows a venv's python is a link to the base Python's absolute path: after the folder moved, the link
and pyvenv.cfg are both pointed at the Python there, and the venv is usable again without a reinstall."""
monkeypatch.setattr(paths, "VENVS", tmp_path / "venvs")
base = Path(sys.executable).resolve()
venv = paths.venv_dir("tool")
(venv / "bin").mkdir(parents=True)
(venv / "bin" / "python").symlink_to(tmp_path / "old" / "tools" / "python" / "bin" / "python3")
(venv / "bin" / "python3").symlink_to("python")
version = ".".join(map(str, sys.version_info[:3]))
(venv / "pyvenv.cfg").write_text(f"home = {tmp_path / 'old' / 'tools' / 'python' / 'bin'}\n"
f"include-system-site-packages = false\nversion = {version}\n"
f"executable = {tmp_path / 'old' / 'tools' / 'python' / 'bin' / 'python3.11'}\n")
assert not venvs.usable("tool")
here = tmp_path / "new" / "bin"
here.mkdir(parents=True)
(here / "python3").symlink_to(base)
assert venvs.repair_if_moved("tool", here / "python3") and venvs.usable("tool")
assert os.readlink(venv / "bin" / "python") == str(here / "python3")
assert os.readlink(venv / "bin" / "python3") == "python", "a link inside the venv stays as it is"
assert not venvs.repair_if_moved("tool", here / "python3")
# ---- messages ------------------------------------------------------------------------------------------------------
def test_a_path_is_shown_from_the_spellcast_folder_in_this_systems_notation() -> None:
inside = paths.shown(paths.venv_dir("hub"))
assert inside == os.path.join("code", "venvs", "hub")
assert paths.shown("code\\logs\\install.log") == ("code\\logs\\install.log" if os.name == "nt"
else "code/logs/install.log")
assert paths.LAUNCHER.endswith(".bat" if os.name == "nt" else ".sh") and paths.LAUNCHER in paths.START_AGAIN
assert components.LOG_HINT == f"Details are in {os.path.join('code', 'logs', 'install.log')}."
# ---- the checks before installing ----------------------------------------------------------------------------------
class _Tool:
def __init__(self, tool_id: str) -> None:
self.id = tool_id
def _system(monkeypatch: pytest.MonkeyPatch, machine: str, libc: tuple[str, str], libraries: set[str] | None,
compiler_problem: str | None = None) -> None:
monkeypatch.setattr(preflight.platform, "machine", lambda: machine)
monkeypatch.setattr(preflight.platform, "libc_ver", lambda: libc)
known = None if libraries is None else {name: f"/usr/lib/x86_64-linux-gnu/{name}" for name in libraries}
monkeypatch.setattr(preflight, "system_libraries", lambda: known)
monkeypatch.setattr(preflight, "c_compiler_problem", lambda driver_library=None: compiler_problem)
SAMPLE_LIBRARIES = (("libGL.so.1", "libgl1", (paths.PIXAL3D, paths.TRIFLOW)),
("libGLU.so.1", "libglu1-mesa", (paths.TRIFLOW,)))
def test_linux_needs_an_x86_64_processor_and_a_c_library_as_new_as_the_builds(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(preflight, "SYSTEM_LIBRARIES", SAMPLE_LIBRARIES)
everything = {library for library, _package, _tools in preflight.SYSTEM_LIBRARIES}
todo = [_Tool(tool) for tool in paths.ALL_VENV_IDS]
_system(monkeypatch, "x86_64", ("glibc", "2.35"), everything)
report = preflight.Report()
preflight._check_system(report, todo) # type: ignore[arg-type]
assert not report.fatal and not report.blocked and "glibc 2.35" in report.info[-1]
for machine, libc, said in (("aarch64", ("glibc", "2.39"), "x86_64"), ("x86_64", ("glibc", "2.31"), "glibc 2.35"),
("x86_64", ("musl", "1.2"), "glibc 2.35"), ("x86_64", ("", ""), "glibc 2.35")):
_system(monkeypatch, machine, libc, everything)
report = preflight.Report()
preflight._check_system(report, todo) # type: ignore[arg-type]
assert len(report.fatal) == 1 and said in report.fatal[0], (machine, libc)
def test_a_missing_system_library_blocks_only_the_tools_that_load_it(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(preflight, "SYSTEM_LIBRARIES", SAMPLE_LIBRARIES)
everything = {library for library, _package, _tools in preflight.SYSTEM_LIBRARIES}
todo = [_Tool(tool) for tool in paths.ALL_VENV_IDS]
_system(monkeypatch, "x86_64", ("glibc", "2.39"), everything - {"libGLU.so.1"})
report = preflight.Report()
preflight._check_system(report, todo) # type: ignore[arg-type]
assert not report.fatal and set(report.blocked) == {paths.TRIFLOW}
assert "sudo apt install libglu1-mesa" in report.blocked[paths.TRIFLOW]
_system(monkeypatch, "x86_64", ("glibc", "2.39"), set()) # a tool is told all it lacks at once
report = preflight.Report()
preflight._check_system(report, todo) # type: ignore[arg-type]
assert set(report.blocked) == {paths.PIXAL3D, paths.TRIFLOW}
assert "libGL.so.1 libGLU.so.1" in report.blocked[paths.TRIFLOW]
assert "sudo apt install libgl1 libglu1-mesa). Then start" in report.blocked[paths.TRIFLOW]
_system(monkeypatch, "x86_64", ("glibc", "2.39"), None) # the loader cannot be asked: nothing is said
report = preflight.Report()
preflight._check_system(report, todo) # type: ignore[arg-type]
assert not report.fatal and not report.blocked
def test_without_a_c_compiler_only_the_tools_that_run_tritons_kernels_are_blocked(
monkeypatch: pytest.MonkeyPatch) -> None:
todo = [_Tool(tool) for tool in paths.ALL_VENV_IDS]
problem = "no C compiler (gcc or clang) was found. Install one (Ubuntu / Debian: sudo apt install build-essential)"
_system(monkeypatch, "x86_64", ("glibc", "2.39"), None, compiler_problem=problem)
report = preflight.Report()
preflight._check_system(report, todo) # type: ignore[arg-type]
assert not report.fatal and set(report.blocked) == {paths.PIXAL3D, paths.TRIFLOW}, "LATO.2 never calls Triton"
assert "no C compiler" in report.blocked[paths.PIXAL3D] and "sudo apt install build-essential" in report.blocked[
paths.PIXAL3D] and report.blocked[paths.PIXAL3D].endswith("Then start Spellcast3D again.")
# a tool that lacks a compiler AND libraries is told both at once
monkeypatch.setattr(preflight, "SYSTEM_LIBRARIES", SAMPLE_LIBRARIES)
_system(monkeypatch, "x86_64", ("glibc", "2.39"), set(), compiler_problem=problem)
report = preflight.Report()
preflight._check_system(report, todo) # type: ignore[arg-type]
assert "no C compiler" in report.blocked[paths.TRIFLOW] and "libGL.so.1 libGLU.so.1" in report.blocked[paths.TRIFLOW]
asked: list[int] = []
monkeypatch.setattr(preflight, "c_compiler_problem", lambda driver_library=None: asked.append(1))
preflight._check_system(preflight.Report(), [_Tool(paths.HUB), _Tool(paths.QWEN), _Tool(paths.IMESH),
_Tool(paths.LATO2)]) # type: ignore[list-item]
assert not asked, "nothing is compiled for the tools that need no compiler"
def test_the_compiler_probe_is_given_the_drivers_library_the_loader_knows(monkeypatch: pytest.MonkeyPatch) -> None:
_system(monkeypatch, "x86_64", ("glibc", "2.39"), {preflight.DRIVER_LIBRARY})
given: list[object] = []
monkeypatch.setattr(preflight, "c_compiler_problem", lambda driver_library=None: given.append(driver_library))
preflight._check_system(preflight.Report(), [_Tool(paths.PIXAL3D)]) # type: ignore[list-item]
assert given == ["/usr/lib/x86_64-linux-gnu/libcuda.so.1"]
@posix_only
def test_the_c_compiler_is_tried_on_what_triton_builds(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
here = preflight.c_compiler_problem()
assert here is None or "C compiler" in here
if here is None and "libcuda.so" not in (preflight.system_libraries() or {"libcuda.so": ""}):
# the driver's library by its plain name: Triton links -lcuda, which a folder with libcuda.so.1 alone fails
# (tried where the system itself has no libcuda.so for the linker to fall back on)
alone = tmp_path / "libcuda.so.1"
subprocess.run([shutil.which("gcc") or "clang", "-shared", "-fPIC", "-x", "c", "/dev/null", "-o", str(alone)],
check=True)
said = preflight.c_compiler_problem(str(alone)) or ""
assert "plain name" in said and f"sudo ln -s libcuda.so.1 {tmp_path / 'libcuda.so'}" in said
(tmp_path / "libcuda.so").symlink_to("libcuda.so.1")
assert preflight.c_compiler_problem(str(alone)) is None
monkeypatch.setenv("CC", "/no/such/compiler")
assert "could not be run" in (preflight.c_compiler_problem() or "")
monkeypatch.delenv("CC")
monkeypatch.setattr(preflight.shutil, "which", lambda name: None)
assert (preflight.c_compiler_problem() or "").startswith("no C compiler (gcc or clang) was found. Install one")
def test_the_real_table_of_system_libraries_never_blocks_the_hub() -> None:
for library, package, tools in preflight.SYSTEM_LIBRARIES:
assert ".so" in library and package and tools and paths.HUB not in tools, library
@posix_only
def test_the_systems_loader_is_asked_for_its_libraries() -> None:
known = preflight.system_libraries()
assert known is None or "libc.so.6" in known
# ---- PyTorch's build, the requirement files ------------------------------------------------------------------------
def test_linux_gives_a_gtx_10xx_the_cu126_pytorch_with_cuda_128s_runtime_over_it() -> None:
"""Linux' cu128 PyTorch has no kernels below the RTX 20 series: those cards get cu126 of the same version, and
as the venv's last pip step the CUDA 12.8 runtime and cuBLAS the prebuilt wheels are compiled against."""
for cap in (6.1, 6.0):
build = components.linux_torch_build(cap)
assert build is components.CU126 and build.index.endswith("/cu126") and build.over == sdcpp.CUDA_PACKAGES
assert build.torch == ("torch==2.8.0+cu126", "torchvision==0.23.0+cu126")
assert build.dist == "torch-2.8.0+cu126.dist-info"
for cap in (7.0, 7.5, 8.6, 8.9, 12.0, None):
assert components.linux_torch_build(cap) is components.CU128
assert components.CU128.over == () and components.CU128.dist == components.TORCH_DIST
assert components.CU128.torch[0].split("+")[0] == components.CU126.torch[0].split("+")[0], "one PyTorch version"
if os.name == "nt":
assert components.torch_build() is components.CU128, "Windows' cu128 build has every card's kernels"
def test_a_requirements_file_elsewhere_leaves_out_what_is_windows_alone() -> None:
lines = ["# triton-windows is named in a comment", "torch==2.8.0", "triton-windows==3.4.0.post21",
"pyreadline3==3.5.6", "triton==3.4.0", "uvicorn[standard]==0.53.0", "pyreadline3-not-it==1"]
kept = components.requirements_elsewhere(lines)
assert kept == ["# triton-windows is named in a comment", "torch==2.8.0", "triton==3.4.0",
"uvicorn[standard]==0.53.0", "pyreadline3-not-it==1", "uvloop==0.23.0"]
assert components.requirements_elsewhere(["uvicorn==0.53.0"]) == ["uvicorn==0.53.0"], "plain uvicorn: no uvloop"
# kornia_rs' Linux builds 0.1.11 .. 0.1.14 need AVX2 (an illegal instruction at import on older processors)
assert components.requirements_elsewhere(["kornia==0.8.2", "kornia_rs==0.1.14", "kornia-rs==0.1.13"]) == [
"kornia==0.8.2", "kornia_rs==0.1.15", "kornia_rs==0.1.15"]
tested = components.PIXAL3D_CONSTRAINTS.read_text(encoding="utf-8").splitlines()
assert "kornia_rs==0.1.14" in tested and "kornia_rs==0.1.15" in components.requirements_elsewhere(tested)
for file in (components.HUB_REQUIREMENTS, components.IMESH_REQUIREMENTS,
*components.INSTALL_DIR.glob("requirements-*.txt")):
text = file.read_text(encoding="utf-8").splitlines()
left = [line for line in components.requirements_elsewhere(text) if not line.lstrip().startswith("#")]
assert not any("windows" in line.lower() or line.startswith("pyreadline") for line in left), file.name
# ---- the prebuilt wheels -------------------------------------------------------------------------------------------
def test_every_linux_wheel_a_tool_installs_is_pinned() -> None:
"""linux-wheels.json names a file, its size and its SHA-256 for each project the components fetch."""
wanted = {*wheels.PIXAL3D_LINUX, *components.Imesh.linux_wheels, *components.Lato2.wheel_projects,
*components.Triflow.wheel_projects}
assert wanted <= set(wheels.LINUX), sorted(wanted - set(wheels.LINUX))
for project, (name, size, sha256) in wheels.LINUX.items():
assert name.startswith(project + "-") and name.endswith(".whl") and "win" not in name, name
assert name.endswith(("linux_x86_64.whl", "x86_64.whl")) and size > 10_000, name
assert len(sha256) == 64 and set(sha256) <= set("0123456789abcdef"), name
assert wheels.pin(project) == f"{name}={sha256}"
assert set(wheels.WINDOWS_FILES) == {"flash_attn", "o_voxel", "torchsparse", "pyfqmr_triflow", "xatlas"}
def test_a_linux_wheel_is_downloaded_once_and_checked(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import hashlib
data = b"wheel bytes"
pins = {"cumesh": ("cumesh-1-cp311-cp311-linux_x86_64.whl", len(data), hashlib.sha256(data).hexdigest())}
monkeypatch.setattr(wheels, "WINDOWS", False)
monkeypatch.setattr(wheels, "LINUX", pins)
monkeypatch.setattr(wheels, "LINUX_DIR", tmp_path / "wheels")
asked: list[str] = []
def download(url: str, dst: Path, size: int, sha256: str, log: object) -> None:
asked.append(url)
dst.write_bytes(data)
monkeypatch.setattr(models, "download_file", download)
said: list[str] = []
assert wheels.missing(["cumesh"]) == ["cumesh"] and wheels.file("cumesh") == tmp_path / "wheels" / pins["cumesh"][0]
wheels.fetch(["cumesh"], said.append)
assert asked == [wheels.LINUX_RELEASE.url + pins["cumesh"][0]] and wheels.missing(["cumesh"]) == []
wheels.fetch(["cumesh"], said.append)
assert len(asked) == 1, "there at its size and SHA-256: not downloaded again"
wheels.file("cumesh").write_bytes(b"wheel BYTES") # the same size, other bytes, written later
os.utime(wheels.file("cumesh"), (time.time() + 60, time.time() + 60))
wheels.fetch(["cumesh"], said.append)
assert len(asked) == 2 and "is not the expected file" in " ".join(said)
with pytest.raises(OSError, match="names no Linux build of natten"):
wheels.fetch(["natten"], said.append)
monkeypatch.setattr(wheels, "WINDOWS", True)
wheels.fetch(["natten"], said.append)
assert wheels.missing(["natten"]) == [], "Windows' wheels are files of the checkout: nothing to fetch"
def test_a_wheels_url_escapes_its_plus_sign(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(wheels, "LINUX", {"x": ("x-1+cu128torch2.8-cp311-cp311-linux_x86_64.whl", 1, "0" * 64)})
assert wheels.url("x").endswith("/x-1%2Bcu128torch2.8-cp311-cp311-linux_x86_64.whl")
assert wheels.url("x").startswith("https://github.com/IgorAherne/Pixal3D/releases/download/wheels/")
# ---- the image engine ----------------------------------------------------------------------------------------------
def test_the_engine_is_pinned_for_both_systems_and_linux_takes_cuda_from_pip() -> None:
assert sdcpp.SDCPP_WINDOWS.name.endswith("-bin-win-cuda12-x64.zip")
assert sdcpp.SDCPP_LINUX.name == sdcpp.SDCPP_WINDOWS.name.replace("-win-", "-linux-")
assert sdcpp.SDCPP_LINUX.release == sdcpp.SDCPP_WINDOWS.release == sdcpp.ENGINE
assert len(sdcpp.SDCPP_LINUX.sha256) == 64 and sdcpp.SDCPP_LINUX.size > 100_000_000
assert {"libstable-diffusion.so", "libggml.so", "libggml-base.so", "libggml-cuda.so", "sd-cli",
"SPELLCAST-BUILD.txt"} <= set(sdcpp.SDCPP_LINUX.files)
assert not any(name.endswith((".dll", ".exe")) for name in sdcpp.SDCPP_LINUX.files)
assert [package.split("==")[0] for package in sdcpp.CUDA_PACKAGES] == ["nvidia-cuda-runtime-cu12",
"nvidia-cublas-cu12"]
assert set(sdcpp._NVIDIA_FOLDER.values()) == {"cuda_runtime", "cublas"}
if os.name == "nt":
assert sdcpp.SDCPP is sdcpp.SDCPP_WINDOWS and sdcpp.CUDART is sdcpp.CUDART_WINDOWS
assert sdcpp.OTHER_SYSTEMS == (sdcpp.SDCPP_LINUX,) and sdcpp.LIBRARY == "stable-diffusion.dll"
else:
assert sdcpp.SDCPP is sdcpp.SDCPP_LINUX and sdcpp.CUDART is None and sdcpp.LIBRARY in sdcpp.SDCPP.files
assert set(sdcpp.CUDA_DLLS) == set(sdcpp._NVIDIA_FOLDER) and " ".join(sdcpp.CUDA_PACKAGES) == sdcpp.CUDA_PIN
@posix_only
def test_the_cuda_libraries_are_linked_beside_the_engine_from_a_venvs_nvidia_packages(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(paths, "VENVS", tmp_path / "venvs")
small = {name: (5, __import__("hashlib").sha256(name.encode()[:5]).hexdigest()) for name in sdcpp.CUDA_DLLS}
monkeypatch.setattr(sdcpp, "CUDA_DLLS", small)
for name, folder in sdcpp._NVIDIA_FOLDER.items():
lib = venvs.site_packages(paths.venv_dir(paths.QWEN)) / "nvidia" / folder / "lib" / name
lib.parent.mkdir(parents=True, exist_ok=True)
lib.write_bytes(name.encode()[:5])
engine = tmp_path / "venvs" / "qwen" / "sdcpp"
said: list[str] = []
assert sdcpp.cuda_missing(engine) == list(small) and sdcpp.link_cuda_dlls(engine, said.append) == []
assert all(os.stat(engine / name).st_nlink == 2 for name in small) and "code" not in said[-1].split("in ")[0]
assert sdcpp._venv_of(sdcpp.torch_libs("libcudart.so.12")[0]) == paths.venv_dir(paths.QWEN)
# ---- Pixal3D's models folder, the desktop --------------------------------------------------------------------------
@posix_only
def test_pixal3ds_two_spellings_of_its_models_folder_are_one_folder(tmp_path: Path,
monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(paths, "PIXAL3D_MODELS_LINK", tmp_path / "pixal3d" / "MODELS")
monkeypatch.setattr(paths, "MODELS_PIXAL3D", tmp_path / "models" / "pixal3d")
monkeypatch.setattr(paths, "PIXAL3D_DIR", tmp_path / "pixal3d")
monkeypatch.setattr(paths, "MODELS", tmp_path / "models")
monkeypatch.setattr(paths, "ROOT", tmp_path)
(tmp_path / "pixal3d").mkdir()
models.pixal3d_one_models_folder()
assert not (tmp_path / "pixal3d" / "models").exists(), "nothing to join before MODELS is there"
assert models.link_pixal3d_models(lambda line: None) and (tmp_path / "pixal3d" / "MODELS").is_symlink()
assert os.readlink(tmp_path / "pixal3d" / "MODELS") == os.path.join("..", "models", "pixal3d")
models.pixal3d_one_models_folder()
(tmp_path / "pixal3d" / "models" / "hub").mkdir()
assert (tmp_path / "models" / "pixal3d" / "hub").is_dir() and models.pixal3d_link_work() is None
def test_the_file_manager_is_asked_only_where_there_is_a_desktop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
file = tmp_path / "prop.glb"
monkeypatch.setattr(exports.os, "environ", {})
if os.name == "nt":
assert exports.desktop_here()
return
assert not exports.desktop_here() and exports._file_manager(file, True) is None
monkeypatch.setattr(exports.os, "environ", {"DISPLAY": ":0"})
monkeypatch.setattr(exports.shutil, "which", lambda name: f"/usr/bin/{name}")
selected = exports._file_manager(file, True)
assert selected is not None and selected[0] == "/usr/bin/dbus-send" and file.resolve().as_uri() in selected[-2]
assert exports._file_manager(tmp_path, False) == ["/usr/bin/xdg-open", str(tmp_path)]
monkeypatch.setattr(exports.shutil, "which", lambda name: None if name == "dbus-send" else f"/usr/bin/{name}")
assert exports._file_manager(file, True) == ["/usr/bin/xdg-open", str(tmp_path)], "the folder, without the selection"
# ---- the start scripts ---------------------------------------------------------------------------------------------
def test_the_linux_scripts_are_unix_text_and_git_marks_those_to_run_as_programs() -> None:
for name in SCRIPTS:
text = (ROOT / name).read_bytes()
assert b"\r" not in text and text.endswith(b"\n"), name
assert "*.sh text eol=lf" in (ROOT / ".gitattributes").read_text(encoding="utf-8")
git = shutil.which("git")
if git is None or not (ROOT / ".git").exists():
pytest.skip("not a git checkout")
listed = subprocess.run([git, "-C", str(ROOT), "ls-files", "-s", "--", *SCRIPTS], capture_output=True, text=True)
modes = {line.split("\t")[1]: line.split()[0] for line in listed.stdout.splitlines()}
if not modes:
pytest.skip("the scripts are not in this checkout's index")
assert modes == {name: "100644" if name == "tools/environment.sh" else "100755" for name in SCRIPTS}
def test_a_release_folder_shows_its_own_systems_scripts_alone() -> None:
from spellcast.install import layout
linux = [name for name in SCRIPTS if name.startswith(("run-browser/", "tools/"))]
windows = [name[:-3] + ".bat" for name in linux]
assert sorted(layout.SCRIPTS["linux"]) == sorted(linux) and sorted(layout.SCRIPTS["windows"]) == sorted(windows)
for name in linux:
assert layout.left_out(name, "windows") and not layout.left_out(name, "linux")
for name in windows:
assert layout.left_out(name, "linux") and not layout.left_out(name, "windows")
assert (ROOT / name).is_file(), f"{name}: each of Linux' scripts is the twin of one of Windows'"
for system in layout.SYSTEMS:
assert layout.left_out("code/tests/test_core.py", system) and layout.left_out("README.md", system)
assert layout.sparse_patterns_for(system)[0] == "/*"
# this system's, which tidy() keeps a release copy at
assert layout.LEAVES_OUT == layout.leaves_out(layout.HERE) and layout.HERE == ("windows" if os.name == "nt" else "linux")
# Windows' patterns exactly as every installed copy has them: a change would re-set each copy's sparse checkout
assert layout.sparse_patterns_for("windows") == (
"/*", "!/code/tests/", "!/.gitattributes", "!/.gitignore", "!/.gitmodules", "!/DEVELOPERS.md", "!/LICENSE",
"!/README.md", "!/prepare_release.py", "!/spellcast_yt_video_demo_banner.jpg",
"!/spellcast3d-stage-by-stage.gif", "!/run-browser/run-spellcast3d.sh", "!/tools/environment.sh",
"!/tools/spellcast-internal.sh", "!/tools/update.sh")
def test_the_environment_script_pins_the_python_it_downloads_and_puts_it_where_the_hub_looks() -> None:
text = (ROOT / "tools" / "environment.sh").read_text(encoding="utf-8")
assert 'PYTHON_FILE="cpython-3.11.' in text and "x86_64-unknown-linux-gnu-install_only" in text
sha = text.split('PYTHON_SHA256="')[1].split('"')[0]
assert len(sha) == 64 and "sha256sum --check" in text
assert 'PY="$ROOT/tools/python/bin/python3"' in text # paths.PORTABLE_PYTHON off Windows
assert "https://github.com/astral-sh/python-build-standalone/releases/download/" in text
launcher = (ROOT / "tools" / "spellcast-internal.sh").read_text(encoding="utf-8")
assert '"$ROOT/code/venvs/hub/bin/python"' in launcher and "--only hub --if-needed" in launcher
def test_the_scripts_are_valid_bash() -> None:
bash = shutil.which("bash")
if bash is None:
pytest.skip("no bash here")
for name in SCRIPTS:
done = subprocess.run([bash, "-n", str(ROOT / name)], capture_output=True, text=True)
assert done.returncode == 0, f"{name}: {done.stderr}"
def test_a_tools_messages_name_the_start_script_as_the_hub_does() -> None:
"""The hub hands its words down in the tool's environment; a tool started by hand says Windows' words."""
assert paths.clean_env()["SPELLCAST_START_AGAIN"] == paths.START_AGAIN
for launcher in ("lato2_server.py", "pixal3d_server.py", "qwen_sdcpp.py", "triflow_server.py"):
source = (paths.LAUNCHERS / launcher).read_text(encoding="utf-8")
assert 'START_AGAIN = os.environ.get("SPELLCAST_START_AGAIN", "double-click run-spellcast3d.bat")' in source
assert source.count("run-spellcast3d.bat") == 1, f"{launcher} names the Windows script in a message"
# ---- what the review of the port found --------------------------------------------------------------------------
def test_without_a_card_the_tools_keep_the_pytorch_build_they_have(monkeypatch: pytest.MonkeyPatch) -> None:
"""No answer from nvidia-smi (a driver update before its reboot) must not change the fingerprints of a GTX 10xx's
tools, which would install them anew."""
if os.name == "nt":
pytest.skip("Windows has one PyTorch build")
monkeypatch.setattr(components, "_card", lambda: None)
for installed, build in (({components.CU126.dist, None}, components.CU126), ({components.CU128.dist}, components.CU128),
({None}, components.CU128)):
dists = iter(list(installed) * len(paths.ALL_VENV_IDS))
monkeypatch.setattr(venvs, "torch_dist", lambda venv, dists=dists: next(dists))
components.torch_build.cache_clear()
assert components.torch_build() is build
components.torch_build.cache_clear()
def test_a_requirement_file_that_pins_the_linux_extra_itself_is_not_given_it_twice() -> None:
assert components.requirements_elsewhere([" uvicorn[standard]==0.53.0"])[-1] == "uvloop==0.23.0"
assert components.requirements_elsewhere(["uvicorn[standard]==0.53.0", "uvloop==0.22.1"]) == [
"uvicorn[standard]==0.53.0", "uvloop==0.22.1"]
def test_the_linux_pins_are_part_of_every_fingerprint_there() -> None:
"""A moved Linux pin (as kornia_rs' was) must reach the venvs that are already installed."""
source = (Path(components.__file__)).read_text(encoding="utf-8")
assert '{"elsewhere": [sorted(WINDOWS_ONLY), ELSEWHERE_ALSO, ELSEWHERE_PINS]}' in source
if os.name != "nt":
before = components.Hub().fingerprint()
components.ELSEWHERE_PINS["kornia-rs"], kept = "kornia_rs==9.9.9", components.ELSEWHERE_PINS["kornia-rs"]
try:
assert components.Hub().fingerprint() != before
finally:
components.ELSEWHERE_PINS["kornia-rs"] = kept
def test_a_tool_ended_by_a_signal_says_which() -> None:
assert procman._exit_code_text(3) == "3"
if os.name != "nt":
assert procman._exit_code_text(-9) == "-9: ended by SIGKILL" and procman._exit_code_text(-11).endswith("SIGSEGV")
def test_a_child_is_tied_to_its_parent_only_from_the_main_thread() -> None:
import threading
from spellcast import lifeline
here = lifeline.tie()
assert (here is None) == (not sys.platform.startswith("linux"))
seen: list[object] = []
worker = threading.Thread(target=lambda: seen.append(lifeline.tie()))
worker.start()
worker.join()
assert seen == [None]
def test_the_folder_dialog_says_why_it_cannot_open(monkeypatch: pytest.MonkeyPatch) -> None:
from spellcast import dialogs
monkeypatch.setattr(exports, "explorer_allowed", lambda: True)
if os.name == "nt":
assert dialogs.unavailable() is None
return
monkeypatch.setattr(exports, "desktop_here", lambda: False)
assert "desktop" in (dialogs.unavailable() or "")
monkeypatch.setattr(exports, "desktop_here", lambda: True)
monkeypatch.setattr(dialogs.shutil, "which", lambda name: None)
assert "sudo apt install zenity" in (dialogs.unavailable() or "")
monkeypatch.setattr(dialogs.shutil, "which", lambda name: "/usr/bin/" + name)
assert dialogs.unavailable() is None
@posix_only
def test_a_tied_child_ends_when_its_parent_is_killed() -> None:
"""What keeps pip or git from working on in a venv after the installer was killed (install/runner.py)."""
code = ("import subprocess, sys, time\nfrom spellcast import lifeline\n"
"child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)'], "
"preexec_fn=lifeline.tie())\nprint(child.pid, flush=True)\ntime.sleep(120)\n")
parent = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, text=True, cwd=paths.CODE)
assert parent.stdout is not None
child = int(parent.stdout.readline())
parent.kill()
parent.wait()
def gone() -> bool:
try:
return Path(f"/proc/{child}/stat").read_text().rsplit(")", 1)[1].split()[0] == "Z"
except OSError:
return True
deadline = time.time() + 10
while not gone() and time.time() < deadline:
time.sleep(0.1)
assert gone(), "the child outlived its killed parent"