The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Cache completed documentation films by validated render inputs
Sina Atalay5baae1b661f9
diff --git a/docs/examples.py b/docs/examples.pyindex ffa1ba3b..6e80c569 100644--- a/docs/examples.py+++ b/docs/examples.py@@ -1,10 +1,12 @@"""The docs' examples, rendered: a Python block that defines a scene is shown with its film.-`python -m docs.examples [PATH...]` gathers the Python blocks of the pages (`content/`), of-the README and of the docstrings (`src/manimgx/`) and renders each scene+`python -m docs.examples [PATH...]` gathers the example films (`examples/`) and the Python+blocks of the pages (`content/`), the README and the docstrings (`src/manimgx/`), and renders each sceneamong them — those written under the given paths, if any — into `content/films/`: a still ofits last frame with anything on it, and a video too if anything moves. A film is named after its scene and-a digest of its code, so an example renders once per version. GitHub and PyPI play no video,+a digest of its inputs. Completed outputs and their checksums are kept in `.cache/films/`;+`--cache-key` prints the key and compatible prefix for carrying these files between builds.+GitHub and PyPI play no video,so a README scene is also `readme-<scene>.svg`, a name the README can show: the scene as anSVG that plays itself (`docs.svg`).@@ -12,39 +14,68 @@ While the site builds, `fence` (SuperFences' formatter for Python blocks, set in`docs/zensical.toml`) puts each block's film above its code."""+import argparseimport astimport hashlibimport html+import importlib+import json+import os+import platformimport reimport shutil+import subprocessimport sysimport textwrap-import types+import tomllib+import tracebackfrom concurrent.futures import ProcessPoolExecutor, as_completedfrom dataclasses import dataclass-from functools import cached_property+from functools import cache, cached_propertyfrom pathlib import Path+from tempfile import TemporaryDirectoryfrom typing import TYPE_CHECKING, cast+from docs.render import FORMAT+from docs.render import draw as _draw+from docs.render import load as load+if TYPE_CHECKING:from markdown import Markdownfrom pymdownx.superfences import SuperFencesBlockPreprocessor- from manimgx import Scene-DOCS = Path(__file__).parent+ROOT = DOCS.parentPAGES = DOCS / "content"README = DOCS.parent / "README.md"SOURCE = DOCS.parent / "src" / "manimgx"FILMS = PAGES / "films"-VOICE = DOCS / "voice"+RECORDS = DOCS / ".cache" / "films"URL = "/films"-# how a film is made: at the films' own rate (60 frames a second, the default), encoded for the-# web, where slow and CRF 28 make a tenth of the default's file (ultrafast, 18), alike to the eye,-# in the same time. A film's name digests this with its code, so a change here makes them again.-SIZE, FPS = (1280, 720), 60-PRESET, CRF = "slow", 28-FORMAT = f"{SIZE[0]}x{SIZE[1]} at {FPS} fps, {PRESET}, CRF {CRF}"+OUTPUTS = (".webp", ".mp4", ".svg", "-light.svg")+# Shared inputs are deliberately conservative: even a Python docstring is observable at+# runtime. Scene-specific code is hashed separately, so Markdown prose changes no film and+# editing one standalone example changes only its film. Keep assets read by examples in+# docs/assets/ or docs/voice/; generated pages and outputs are never inputs.+INPUTS = (+ "src/manimgx/**/*.py",+ "rust/Cargo.*",+ "rust/*/Cargo.toml",+ "rust/*/build.rs",+ "rust/*/src/**/*",+ "rust/mitex-spec-gen/lib.typ",+ "rust/mitex-spec-gen/spec.rkyv",+ "rust/.cargo/**/*",+ "rust/rust-toolchain*",+ "rust-toolchain*",+ "fonts/*/pyproject.toml",+ "fonts/*/src/**/*",+ "docs/assets/**/*",+ "docs/voice/**/*",+ "docs/render.py",+ "docs/svg.py",+ "pyproject.toml",+)FENCE = re.compile(r"^(?P<indent>[ \t]*)```(?:python|py)\b[^\n]*\n(?P<code>.*?)^(?P=indent)```",@@ -52,6 +83,65 @@ FENCE = re.compile()+@cache+def render_context() -> str:+ """The shared renderer and its environment, independent of paths and Git history.++ CI names its actual driver/toolchain versions in MANIMGX_DOCS_RENDER_PROFILE. Local+ caches stay on their own machine and OS version; they do not assume two GPUs agree.+ """+ profile = os.environ.get("MANIMGX_DOCS_RENDER_PROFILE") or (+ f"{platform.node()}:{platform.release()}"+ )+ environment = (+ sys.implementation.name,+ platform.python_version(),+ sys.platform,+ platform.machine(),+ profile,+ )+ digest = hashlib.sha256(json.dumps(environment).encode())+ # Let uv select the locked runtime closure, including transitive dependencies and+ # artifact hashes. Test and site tools do not make pixels; workspace sources follow.+ digest.update(+ subprocess.check_output(+ [+ "uv",+ "export",+ "--frozen",+ "--offline",+ "--no-default-groups",+ "--no-emit-workspace",+ "--no-header",+ "--no-annotate",+ ],+ cwd=ROOT,+ )+ )+ paths = sorted({path for pattern in INPUTS for path in ROOT.glob(pattern)})+ for path in paths:+ if path.is_file() and "__pycache__" not in path.parts:+ digest.update(path.relative_to(ROOT).as_posix().encode() + b"\0")+ if path.name == "pyproject.toml":+ project = tomllib.loads(path.read_text(encoding="utf-8"))+ # Packaging and native build settings matter; linter, test and site+ # configuration does not. Runtime versions come from uv above.+ data = [+ project.get("project"),+ project.get("build-system"),+ project.get("tool", {}).get("maturin"),+ ]+ digest.update(json.dumps(data, sort_keys=True).encode())+ else:+ digest.update(bytes.fromhex(_digest(path)))+ return digest.hexdigest()+++def _digest(path: Path) -> str:+ with path.open("rb") as stream:+ return hashlib.file_digest(stream, "sha256").hexdigest()++@dataclass(frozen=True)class Example:"""A Python block of the docs, and where it is written (`path:line`)."""@@ -77,10 +167,11 @@ class Example:@cached_propertydef stem(self) -> str:- """Its film's name: the scene's, and a digest of the code and of how films are- made (`FORMAT`)."""+ """Its film's name: the scene's, and a digest of its code and shared render inputs."""code = textwrap.dedent(self.code).strip() + "\n"- digest = hashlib.sha256(f"{FORMAT}\n{code}".encode()).hexdigest()[:10]+ digest = hashlib.sha256(+ f"{render_context()}\n{FORMAT}\n{code}".encode()+ ).hexdigest()[:20]return f"{self.scene}-{digest}"@@ -104,12 +195,17 @@ def blocks(text: str, path: Path, line: int = 1) -> list[Example]:def examples() -> list[Example]:- """Every scene the docs show: the pages', the README's, then the docstrings'."""+ """Every scene's source; the generated Gallery is a view of examples/, not an input."""found = [blockfor page in [*sorted(PAGES.rglob("*.md")), README]+ if not page.is_relative_to(PAGES / "gallery")for block in blocks(page.read_text(encoding="utf-8"), page)]+ found += [+ Example(path.read_text(encoding="utf-8"), path.relative_to(ROOT).as_posix())+ for path in sorted((ROOT / "examples").glob("*.py"))+ ]for module in sorted(SOURCE.rglob("*.py")):for node in ast.walk(ast.parse(module.read_text(encoding="utf-8"))):if isinstance(@@ -119,63 +215,48 @@ def examples() -> list[Example]:return [example for example in found if example.scene is not None]-def load(example: Example) -> "type[Scene]":- """An example's scene, its code run as a module whose file is in docs/: a narrated- example keeps what it says in docs/voice/ (committed, so the build speaks only a line- that is new)."""- import manimgx as m+def render(example: Example, readme: bool = False) -> None:+ """Publish an example only after all its outputs have finished successfully.- module = types.ModuleType("__example__")- module.__file__ = str(VOICE.parent / "examples.py")- sys.modules[module.__name__] = module- exec(compile(example.code, example.where, "exec"), module.__dict__)- scene = module.__dict__[str(example.scene)]- if not (isinstance(scene, type) and issubclass(scene, m.Scene)):- raise TypeError(f"{example.scene} is not a scene")- return scene+ The completion record is replaced last. A crash during publication leaves a missing+ or mismatched checksum, which the next build repairs. Staging files live outside the+ site and are never cached.+ """+ FILMS.mkdir(parents=True, exist_ok=True)+ RECORDS.mkdir(parents=True, exist_ok=True)+ with TemporaryDirectory(dir=RECORDS.parent, prefix="render-") as temporary:+ folder = Path(temporary)+ _draw(example, folder, readme)+ files = {+ suffix: _digest(path)+ for suffix in OUTPUTS+ if (path := folder / f"{example.stem}{suffix}").is_file()+ }+ record = folder / f"{example.stem}.json"+ record.write_text(json.dumps(files, sort_keys=True) + "\n", encoding="utf-8")+ for suffix in OUTPUTS:+ target = FILMS / f"{example.stem}{suffix}"+ if suffix in files:+ (folder / target.name).replace(target)+ else:+ target.unlink(missing_ok=True)+ record.replace(RECORDS / record.name)-def render(example: Example, readme: bool = False) -> None:- """Render an example's scene into its film — in a process of its own, since an example- may change the configuration — and, for the README's, into its SVGs too: one for a dark- page, one for a light page (`<stem>-light.svg`)."""- from docs import svg- from PIL import Image+def _render(example: Example, readme: bool) -> None:+ """A worker's failures cross the process boundary as text, including native panics."""+ try:+ render(example, readme)+ except (KeyboardInterrupt, SystemExit):+ raise+ except BaseException as error:+ # PyO3's PanicException and exceptions defined by an example cannot necessarily+ # be imported by the coordinator. Pickling them loses the rendering failure.+ raise RuntimeError(traceback.format_exc()) from error- import manimgx as m- from manimgx.rendering.film import Frame-- m.config.pixel_width, m.config.pixel_height = SIZE- m.config.frame_rate = FPS- scene = load(example)- drawn, poster = 0, b""-- def keep(frame: Frame) -> None:- """Count the frames (each is sent once, however long it holds), and keep the last one- with anything on it: a scene that ends empty is shown as it was before."""- nonlocal drawn, poster- drawn += 1- pixels = frame.pixels()- if not poster or pixels.count(pixels[:4]) * 4 != len(pixels):- poster = pixels-- video = FILMS / f"{example.stem}.mp4"- size = m.config.pixel_width, m.config.pixel_height- scene().render(video, frames=keep, preset=PRESET, crf=CRF)- still = Image.frombytes("RGBA", size, poster).convert("RGB")- still.save(FILMS / f"{example.stem}.webp", quality=90, method=6)- if drawn == 1: # nothing moves: the still is the film- video.unlink()- if readme:- recording = svg.record(scene)- svg.write(recording, FILMS / f"{example.stem}.svg")- svg.write(recording, FILMS / f"{example.stem}-light.svg", light=True)---def main(only: list[str]) -> None:- """Render every example whose film is missing — only those written under the paths in- `only`, if any — and, rendering them all, delete the films of none."""- FILMS.mkdir(parents=True, exist_ok=True)++def scenes() -> dict[str, Example]:+ """The unique scenes, rejecting conflicting definitions before any work is done."""scenes: dict[str, Example] = {}for example in examples():seen = scenes.setdefault(str(example.scene), example)@@ -184,14 +265,47 @@ def main(only: list[str]) -> None:f"{example.where}: {example.scene} is also defined at {seen.where}"" (a scene's name is its film's: it must be unique)")+ return scenes+++def cache_key() -> dict[str, str]:+ """Snapshot prefixes for this inventory, then for any compatible renderer."""+ readme = _readme()+ inventory = sorted((name, e.stem, name in readme) for name, e in scenes().items())+ digest = hashlib.sha256(json.dumps(inventory).encode()).hexdigest()+ prefix = f"docs-films-v1-{render_context()}-"+ return {"key": prefix + digest, "prefix": prefix}+++def cache_state() -> str:+ """Fingerprint the transported files, including names and damage, without staging."""+ files = [+ (path.relative_to(ROOT).as_posix(), _digest(path))+ for folder in (FILMS, RECORDS)+ for path in sorted(folder.glob("*"))+ if path.is_file()+ ]+ return hashlib.sha256(json.dumps(files).encode()).hexdigest()+++def main(only: list[str], jobs: int | None = None) -> None:+ """Render missing or damaged films, and discard outputs no current example owns."""+ importlib.import_module("manimgx") # fail once if the shared runtime cannot load+ FILMS.mkdir(parents=True, exist_ok=True)+ scenes_to_render = scenes()readme = _readme()if only:- scenes = {- name: e for name, e in scenes.items() if e.where.startswith(tuple(only))+ scenes_to_render = {+ name: e+ for name, e in scenes_to_render.items()+ if e.where.startswith(tuple(only))}else:- stems = {example.stem for example in scenes.values()}- shown = {e.stem for e in scenes.values() if e.scene in readme}+ stems = {example.stem for example in scenes_to_render.values()}+ for record in RECORDS.glob("*.json"):+ if record.stem not in stems:+ record.unlink()+ shown = {e.stem for e in scenes_to_render.values() if e.scene in readme}shown |= {f"readme-{name}" for name in readme}stems |= shown | {f"{stem}-light" for stem in shown}for (@@ -199,22 +313,29 @@ def main(only: list[str]) -> None:) in FILMS.iterdir(): # a film's files: <stem>.webp, .mp4, .svg, -light.svgif film.name.split(".")[0] not in stems:film.unlink()- todo = [e for e in scenes.values() if not _rendered(e, e.scene in readme)]+ todo = [e for e in scenes_to_render.values() if not _rendered(e, e.scene in readme)]+ print(+ f"{len(scenes_to_render)} scenes: {len(scenes_to_render) - len(todo)} cached, "+ f"{len(todo)} to render (renderer {render_context()[:12]})",+ flush=True,+ )if todo: # a long render shows nothing until it ends: say what is being madenames = ", ".join(str(e.scene) for e in todo[:6])print(f"rendering {len(todo)}: {names}{', ...' * (len(todo) > 6)}", flush=True)failed = 0- with ProcessPoolExecutor(max_tasks_per_child=1) as pool:- futures = {pool.submit(render, e, e.scene in readme): e for e in todo}+ with ProcessPoolExecutor(max_workers=jobs, max_tasks_per_child=1) as pool:+ futures = {pool.submit(_render, e, e.scene in readme): e for e in todo}for done, future in enumerate(as_completed(futures), 1):example = futures[future]if (error := future.exception()) is not None:failed += 1- print(f"{example.where}: {example.scene} failed: {error!r}")+ print(f"{example.where}: {example.scene} failed: {error!r}", flush=True)else:- print(f"[{done}/{len(todo)}] {example.scene}")- print(f"{len(scenes)} scenes: {len(todo) - failed} rendered, {failed} failed")- for example in scenes.values():+ print(f"[{done}/{len(todo)}] {example.scene}", flush=True)+ print(+ f"{len(scenes_to_render)} scenes: {len(todo) - failed} rendered, {failed} failed"+ )+ for example in scenes_to_render.values():for variant in ("", "-light") if example.scene in readme else ():if (film := FILMS / f"{example.stem}{variant}.svg").exists():shutil.copyfile(film, FILMS / f"readme-{example.scene}{variant}.svg")@@ -229,13 +350,21 @@ def _readme() -> set[str]:def _rendered(example: Example, readme: bool) -> bool:- """Whether an example's film is made: its still, and, for the README's, its SVGs (a- scene rendered before the README showed it has none yet)."""- film = FILMS / example.stem- return film.with_suffix(".webp").exists() and (- not readme- or all((FILMS / f"{example.stem}{v}.svg").exists() for v in ("", "-light"))- )+ """A completed render has exactly the files recorded, with the same contents."""+ required = {".webp", ".svg", "-light.svg"} if readme else {".webp"}+ try:+ files = json.loads(+ (RECORDS / f"{example.stem}.json").read_text(encoding="utf-8")+ )+ if not isinstance(files, dict) or not required <= files.keys() <= set(OUTPUTS):+ return False+ return all(+ _digest(path) == files[suffix] if suffix in files else not path.exists()+ for suffix in OUTPUTS+ for path in [FILMS / f"{example.stem}{suffix}"]+ )+ except (OSError, ValueError):+ return Falsedef validate(@@ -314,4 +443,30 @@ def _film(example: Example) -> str | None:if __name__ == "__main__":- main(sys.argv[1:])+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "paths", nargs="*", help="render only examples under these source paths"+ )+ parser.add_argument(+ "--jobs", type=int, help="number of simultaneous render processes"+ )+ metadata = parser.add_mutually_exclusive_group()+ metadata.add_argument(+ "--cache-key",+ action="store_true",+ help="print the cache key and restore prefix as JSON",+ )+ metadata.add_argument(+ "--cache-state",+ action="store_true",+ help="fingerprint the current cached files",+ )+ args = parser.parse_args()+ if args.jobs is not None and args.jobs < 1:+ parser.error("--jobs must be positive")+ if args.cache_key:+ print(json.dumps(cache_key()))+ elif args.cache_state:+ print(cache_state())+ else:+ main(args.paths, args.jobs)diff --git a/docs/links.py b/docs/links.pyindex edd73f39..61d393bb 100644--- a/docs/links.py+++ b/docs/links.py@@ -5,7 +5,9 @@ absolute URLs (`https://manimgx.academa.ai/...`); included as the Welcome page,the deployed site for them, even in a preview. Once a page is rendered, every URL an elementholds (`src`, `srcset`, `href`, `poster`) whose host is the site's keeps only its path, so apage shows the images and links of the site it is on, as it was built, whatever wrote the-URL. Text is left as it is: a code block's `<` is escaped, so no tag is ever in it.+URL. The showcase images use the repository's raw GitHub URLs, avoiding the image proxy's+size limit and updating independently of docs deployments; those become local showcase paths+too. Text is left as it is: a code block's `<` is escaped, so no tag is ever in it."""import re@@ -20,14 +22,19 @@ CONFIG = tomllib.loads((Path(__file__).parent / "zensical.toml").read_text(encoding="utf-8"))HOST = urlsplit(CONFIG["project"]["site_url"]).netloc+RAW_HOST = "raw.githubusercontent.com"+RAW_SHOWCASE = "/academa-labs/manimgx/main/docs/content/showcase/"# an element's start tag (a quoted value may hold ">"), and one of its URLs, quotedTAG = re.compile(r"""<[a-zA-Z](?:"[^"]*"|'[^']*'|[^'">])*>""")URL = re.compile(r"""(\s(src|srcset|href|poster)\s*=\s*)(["'])(.*?)\3""", re.DOTALL)def local(url: str) -> str:- """A URL whose host is the site's, as its path on the site; any other, as it is."""+ """A site URL or the repository's raw showcase asset, as its path on the site."""parts = urlsplit(url)+ if parts.netloc == RAW_HOST and parts.path.startswith(RAW_SHOWCASE):+ path = "/showcase/" + parts.path.removeprefix(RAW_SHOWCASE)+ return urlunsplit(("", "", path, parts.query, parts.fragment))if parts.netloc != HOST:return urlreturn urlunsplit(("", "", parts.path or "/", parts.query, parts.fragment))@@ -35,7 +42,7 @@ def local(url: str) -> str:def _attribute(match: re.Match[str]) -> str:start, name, quote, value = match.groups()- if HOST not in value: # not the site's: as written, to the byte+ if HOST not in value and RAW_HOST not in value:return match.group()if name == "srcset": # candidates: a URL each, and a size or a densityvalue = ", ".join(diff --git a/docs/render.py b/docs/render.pynew file mode 100644index 00000000..796a5eff--- /dev/null+++ b/docs/render.py@@ -0,0 +1,65 @@+"""How documentation scenes become media, independent of discovery, caching and HTML."""++import sys+import types+from pathlib import Path+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from docs.examples import Example++ from manimgx import Scene++# At the films' own rate, slow and CRF 28 make a tenth of the default's file (ultrafast,+# 18), alike to the eye, in the same time. This module is a shared rendering input.+SIZE, FPS = (1280, 720), 60+PRESET, CRF = "slow", 28+FORMAT = f"{SIZE[0]}x{SIZE[1]} at {FPS} fps, {PRESET}, CRF {CRF}"+++def load(example: "Example") -> "type[Scene]":+ """Run an example as a module in docs/, so its narration reads docs/voice/."""+ import manimgx as m++ module = types.ModuleType("__example__")+ module.__file__ = __file__+ sys.modules[module.__name__] = module+ exec(compile(example.code, example.where, "exec"), module.__dict__)+ scene = module.__dict__[str(example.scene)]+ if not (isinstance(scene, type) and issubclass(scene, m.Scene)):+ raise TypeError(f"{example.scene} is not a scene")+ return scene+++def draw(example: "Example", folder: Path, readme: bool) -> None:+ """Render a scene in its own process, with SVGs too for the README's examples."""+ from docs import svg+ from PIL import Image++ import manimgx as m+ from manimgx.rendering.film import Frame++ m.config.pixel_width, m.config.pixel_height = SIZE+ m.config.frame_rate = FPS+ scene = load(example)+ drawn, poster = 0, b""++ def keep(frame: Frame) -> None:+ """Keep the last nonempty frame: a scene that ends empty is shown as it was."""+ nonlocal drawn, poster+ drawn += 1+ pixels = frame.pixels()+ if not poster or pixels.count(pixels[:4]) * 4 != len(pixels):+ poster = pixels++ video = folder / f"{example.stem}.mp4"+ size = m.config.pixel_width, m.config.pixel_height+ scene().render(video, frames=keep, preset=PRESET, crf=CRF)+ still = Image.frombytes("RGBA", size, poster).convert("RGB")+ still.save(folder / f"{example.stem}.webp", quality=90, method=6)+ if drawn == 1: # nothing moves: the still is the film+ video.unlink()+ if readme:+ recording = svg.record(scene)+ svg.write(recording, folder / f"{example.stem}.svg")+ svg.write(recording, folder / f"{example.stem}-light.svg", light=True)diff --git a/tests/docs/test_examples.py b/tests/docs/test_examples.pyindex 10ebabe1..d1531496 100644--- a/tests/docs/test_examples.py+++ b/tests/docs/test_examples.py@@ -1,8 +1,52 @@"""The docs' examples, as the site's build renders them (`docs/examples.py`): the build hasno voice's key (its workflow has none), so a narrated example says what `docs/voice/` keeps."""+import sys+from concurrent.futures import ProcessPoolExecutor+from multiprocessing import get_context+from pathlib import Path+from unittest.mock import Mock++import numpy as npimport pytestfrom docs import examples+from examples.cherenkov_cone import CherenkovCone++from manimgx.rendering.film import Cut+++def test_a_broken_runtime_stops_before_workers_start_or_films_change(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ film = tmp_path / "previous.webp"+ film.write_bytes(b"previous film")+ pool = Mock(side_effect=AssertionError("a broken runtime must not start workers"))+ monkeypatch.setattr(examples, "FILMS", tmp_path)+ monkeypatch.setattr(examples, "ProcessPoolExecutor", pool)+ monkeypatch.setitem(sys.modules, "manimgx", None)++ with pytest.raises(ModuleNotFoundError, match="manimgx"):+ examples.main([])++ pool.assert_not_called()+ assert film.read_bytes() == b"previous film"+++def test_an_unimportable_native_failure_keeps_its_cause_across_processes() -> None:+ example = examples.Example(+ "class NativeFailure(BaseException):\n"+ " pass\n"+ "raise NativeFailure('buffer exceeds the device limit')\n",+ "native-failure.py:1",+ )+ with ProcessPoolExecutor(max_workers=1, mp_context=get_context("spawn")) as pool:+ result = pool.submit(examples._render, example, False)+ with pytest.raises(+ RuntimeError, match="buffer exceeds the device limit"+ ) as caught:+ result.result(timeout=60)+ assert "NativeFailure" in str(caught.value)+ assert "native-failure.py:1" in str(caught.value)def test_a_narrated_example_says_what_docs_voice_keeps(@@ -13,3 +57,11 @@ def test_a_narrated_example_says_what_docs_voice_keeps(assert narratedfor example in narrated:examples.load(example)().render() # its frames counted, not drawn+++def test_unborn_cherenkov_photons_have_no_invalid_numerical_state() -> None:+ # Below the emission threshold every photon slot is empty. Its -inf timestamp+ # must be excluded before periodic arithmetic, not masked after cos(-inf).+ with np.errstate(invalid="raise"):+ film = CherenkovCone().render(plays=Mock(side_effect=Cut))+ assert film.frame_count > 0diff --git a/tests/docs/test_links.py b/tests/docs/test_links.pyindex 2b54497e..7d4cd076 100644--- a/tests/docs/test_links.py+++ b/tests/docs/test_links.py@@ -1,11 +1,13 @@"""The README, included as the Welcome page, reaches the site's own images and pages on thesite it is on (`docs/links.py`), so `just serve-docs` shows the images it built."""+import refrom pathlib import Pathimport pytestREADME = Path(__file__).parents[2] / "README.md"+WELCOME = README.parent / "docs" / "content" / "index.md"def test_the_readme_reaches_the_site_it_is_on() -> None:@@ -23,14 +25,89 @@ def test_the_readme_reaches_the_site_it_is_on() -> None:assert 'srcset="/showcase/logo-dark.svg"' in htmlassert 'src="/showcase/logo-light.svg"' in html# the wall's films, and the scene's film on each ground- assert 'srcset="/showcase/hopf_fibration.avif"' in html # on a low-density screen- assert 'src="/showcase/[email protected]"' in html- assert 'srcset="/films/readme-Hopf.svg"' in html- assert 'src="/films/readme-Hopf-light.svg#readme"' in html+ assert 'src="/showcase/quadratic_formula.gif"' in html+ assert 'srcset="/films/readme-Hello3D.svg"' in html+ assert 'src="/films/readme-Hello3D-light.svg#readme"' in html# a URL written as text, which an agent is told to follow, stays as it isassert f"Follow {site}/llms.txt" in html+def test_the_welcome_page_uses_the_readme_s_same_showcase_images() -> None:+ markdown = pytest.importorskip("markdown")+ from docs import links++ readme = README.read_text(encoding="utf-8")+ raw = f"https://{links.RAW_HOST}{links.RAW_SHOWCASE}"+ images = re.findall(rf'src="{re.escape(raw)}([^"/]+\.gif)"', readme)+ assert len(images) == 9+ html = markdown.markdown(+ WELCOME.read_text(encoding="utf-8"),+ extensions=["pymdownx.snippets", links.makeExtension()],+ extension_configs={+ "pymdownx.snippets": {+ "base_path": [str(README.parent)],+ "check_paths": True,+ }+ },+ )+ assert re.findall(r'src="/showcase/([^"/]+\.gif)"', html) == images+ assert raw not in html+++def test_the_banner_keeps_both_github_themes_and_a_light_fallback() -> None:+ pytest.importorskip("markdown")+ from docs import links++ readme = README.read_text(encoding="utf-8")+ banner = re.search(r"<picture>.*?</picture>", readme, re.DOTALL)+ assert banner is not None+ raw = f"https://{links.RAW_HOST}{links.RAW_SHOWCASE}"+ # GitHub's themed-picture component honors its selected theme, including overrides+ # of the OS preference. Raw repo URLs keep both variants independent of docs deploys.+ sources = re.findall(+ r'<source media="\(prefers-color-scheme: (dark|light)\)" srcset="([^"]+)">',+ banner.group(),+ )+ assert sources == [(theme, f"{raw}logo-{theme}.svg") for theme in ("dark", "light")]+ assert f'src="{raw}logo-light.svg"' in banner.group()+ local = links.paths(banner.group())+ for theme in ("dark", "light"):+ assert f'srcset="/showcase/logo-{theme}.svg"' in local+ assert 'src="/showcase/logo-light.svg"' in local+++def test_raw_showcase_urls_become_local_without_losing_url_parts() -> None:+ pytest.importorskip("markdown")+ from docs import links++ raw = f"https://{links.RAW_HOST}{links.RAW_SHOWCASE}"+ assert links.paths(+ f'<img src="{raw}hopf_fibration.gif?v=2#preview" '+ f'srcset="{raw}one.gif 1x, {raw}two.gif 2x">'+ ) == (+ '<img src="/showcase/hopf_fibration.gif?v=2#preview" '+ 'srcset="/showcase/one.gif 1x, /showcase/two.gif 2x">'+ )+++ "url",+ [+ "https://raw.githubusercontent.com/other/manimgx/main/docs/content/showcase/a.gif",+ "https://raw.githubusercontent.com/academa-labs/manimgx/main/examples/a.gif",+ "https://raw.githubusercontent.com/academa-labs/manimgx/main/docs/content/showcase-other/a.gif",+ "https://raw.githubusercontent.com/academa-labs/manimgx/other/docs/content/showcase/a.gif",+ "https://raw.githubusercontent.com.example.org/academa-labs/manimgx/main/docs/content/showcase/a.gif",+ ],+)+def test_other_raw_urls_are_preserved(url: str) -> None:+ pytest.importorskip("markdown")+ from docs import links++ tag = f'<img src="{url}">'+ assert links.paths(tag) == tag++def test_only_the_site_s_own_urls_become_paths() -> None:pytest.importorskip("markdown")from docs import linksdiff --git a/tests/docs/test_media_cache.py b/tests/docs/test_media_cache.pynew file mode 100644index 00000000..3a1fd2cb--- /dev/null+++ b/tests/docs/test_media_cache.py@@ -0,0 +1,427 @@+"""Rendered media is reused by its inputs, and only complete outputs can be reused."""++import json+import os+import shutil+from collections.abc import Iterator+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import pytest+from docs import examples++SCENE = "class Alpha(Scene):\n pass\n"+++def write(path: Path, text: str) -> Path:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ return path+++def source_tree(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:+ docs = tmp_path / "docs"+ for name, path in {+ "ROOT": tmp_path,+ "DOCS": docs,+ "PAGES": docs / "content",+ "README": tmp_path / "README.md",+ "SOURCE": tmp_path / "src" / "manimgx",+ "FILMS": docs / "content" / "films",+ "RECORDS": docs / ".cache" / "films",+ }.items():+ monkeypatch.setattr(examples, name, path)+ write(tmp_path / "README.md", "# Welcome\n")+ write(tmp_path / "examples" / "alpha.py", SCENE)+ write(+ tmp_path / "pyproject.toml",+ '[project]\nname = "sample"\nversion = "0.1.0"\nrequires-python = ">=3.13"\n'+ 'dependencies = ["painter"]\n'+ '[dependency-groups]\ndev = ["linter"]\ndocs = ["site"]\n'+ '[tool.uv]\ndefault-groups = ["dev", "docs"]\n',+ )+ write(+ tmp_path / "uv.lock",+ 'version = 1\nrevision = 3\nrequires-python = ">=3.13"\n'+ '[[package]]\nname = "sample"\nversion = "0.1.0"\nsource = { virtual = "." }\n'+ 'dependencies = [{ name = "painter" }]\n'+ '[package.dev-dependencies]\ndev = [{ name = "linter" }]\ndocs = [{ name = "site" }]\n'+ '[[package]]\nname = "painter"\nversion = "1.0"\n'+ 'source = { registry = "https://pypi.org/simple" }\n'+ 'dependencies = [{ name = "pigment" }]\n'+ '[[package]]\nname = "pigment"\nversion = "2.0"\n'+ 'source = { registry = "https://pypi.org/simple" }\n'+ f'sdist = {{ url = "https://example.org/pigment.tar.gz", hash = "sha256:{"0" * 64}" }}\n'+ '[[package]]\nname = "linter"\nversion = "3.0"\n'+ 'source = { registry = "https://pypi.org/simple" }\n'+ '[[package]]\nname = "site"\nversion = "4.0"\n'+ 'source = { registry = "https://pypi.org/simple" }\n',+ )+ examples.render_context.cache_clear()+ yield tmp_path+ examples.render_context.cache_clear()+++ "name",+ [+ "src/manimgx/scene.py",+ "rust/engine/src/render.rs",+ "rust/engine/src/stroke.wgsl",+ "rust/engine/Cargo.toml",+ "rust/ffmpeg/build.rs",+ "rust/Cargo.lock",+ "rust/mitex-spec-gen/lib.typ",+ "rust/mitex-spec-gen/spec.rkyv",+ "fonts/manimgx-fonts/src/manimgx_fonts/font.ttf",+ "docs/assets/input.svg",+ "docs/voice/line.mp3",+ "docs/render.py",+ "docs/svg.py",+ ],+)+def test_shared_input_changes_invalidate_films(source_tree: Path, name: str) -> None:+ original = examples.render_context()+ path = write(source_tree / name, "first")+ examples.render_context.cache_clear()+ added = examples.render_context()+ assert added != original+ path.write_text("second", encoding="utf-8")+ examples.render_context.cache_clear()+ assert examples.render_context() not in {original, added}+ path.unlink()+ examples.render_context.cache_clear()+ assert examples.render_context() == original+++def test_tooling_and_orchestration_do_not_invalidate_media(source_tree: Path) -> None:+ before = examples.cache_key()+ project = source_tree / "pyproject.toml"+ project.write_text(+ project.read_text(encoding="utf-8") + "\n[tool.ruff]\nline-length = 99\n",+ encoding="utf-8",+ )+ lock = source_tree / "uv.lock"+ updated = (+ lock.read_text(encoding="utf-8")+ .replace('version = "3.0"', 'version = "3.1"')+ .replace('version = "4.0"', 'version = "4.1"')+ )+ lock.write_text(updated, encoding="utf-8")+ write(source_tree / "docs" / "examples.py", "# New scheduling or HTML logic.\n")+ examples.render_context.cache_clear()+ assert examples.cache_key() == before+ assert lock.read_text(encoding="utf-8") == updated+++ ("old", "new"),+ [+ ('version = "1.0"', 'version = "1.1"'),+ ('version = "2.0"', 'version = "2.1"'),+ ("0" * 64, "1" * 64),+ ('dependencies = [{ name = "pigment" }]', "dependencies = []"),+ ],+)+def test_locked_runtime_changes_invalidate_media(+ source_tree: Path, old: str, new: str+) -> None:+ before = examples.cache_key()+ lock = source_tree / "uv.lock"+ lock.write_text(+ lock.read_text(encoding="utf-8").replace(old, new), encoding="utf-8"+ )+ examples.render_context.cache_clear()+ assert examples.cache_key() != before+++ "settings",+ [+ '[build-system]\nrequires = ["maturin"]\nbuild-backend = "maturin"\n',+ '[tool.maturin]\nfeatures = ["render"]\n',+ ],+)+def test_build_settings_are_render_inputs(source_tree: Path, settings: str) -> None:+ before = examples.render_context()+ project = source_tree / "pyproject.toml"+ project.write_text(project.read_text(encoding="utf-8") + settings, encoding="utf-8")+ examples.render_context.cache_clear()+ assert examples.render_context() != before+++def test_prose_styles_and_generated_files_do_not_change_the_key(+ source_tree: Path,+) -> None:+ before = examples.cache_key()+ for name in (+ "README.md",+ "docs/content/guide.md",+ "docs/content/stylesheets/theme.css",+ "docs/content/javascripts/newsletter.js",+ "docs/content/gallery/old.md",+ "docs/content/films/old.webp",+ "docs/.cache/films/old.json",+ "fonts/manimgx-fonts/src/manimgx_fonts/__pycache__/fonts.pyc",+ ):+ write(source_tree / name, "changed prose")+ examples.render_context.cache_clear()+ assert examples.cache_key() == before+++def test_only_the_edited_example_changes_identity(source_tree: Path) -> None:+ write(source_tree / "examples" / "beta.py", SCENE.replace("Alpha", "Beta"))+ before = {name: e.stem for name, e in examples.scenes().items()}+ key = examples.cache_key()+ write(source_tree / "examples" / "alpha.py", SCENE.replace("pass", "value = 1"))+ after = {name: e.stem for name, e in examples.scenes().items()}+ assert after["Alpha"] != before["Alpha"]+ assert after["Beta"] == before["Beta"]+ assert examples.cache_key()["prefix"] == key["prefix"]+ assert examples.cache_key()["key"] != key["key"]+++def test_gallery_is_discovered_without_generated_pages(source_tree: Path) -> None:+ assert list(examples.scenes()) == ["Alpha"]+ write(+ source_tree / "docs" / "content" / "gallery" / "stale.md",+ "```python\nclass Stale(Scene):\n pass\n```\n",+ )+ assert list(examples.scenes()) == ["Alpha"]+++def test_readme_svg_requirement_changes_the_snapshot_key(source_tree: Path) -> None:+ before = examples.cache_key()+ stem = examples.scenes()["Alpha"].stem+ write(source_tree / "README.md", f"```python\n{SCENE}```\n")+ assert examples.scenes()["Alpha"].stem == stem+ assert examples.cache_key()["key"] != before["key"]+++def test_paths_and_timestamps_are_not_render_inputs(+ source_tree: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ path = write(source_tree / "src" / "manimgx" / "scene.py", '"""Runtime docs."""\n')+ before = examples.render_context()+ os.utime(path, (1, 1))+ examples.render_context.cache_clear()+ assert examples.render_context() == before+ copied = source_tree.parent / f"{source_tree.name}-copy"+ shutil.copytree(source_tree, copied)+ monkeypatch.setattr(examples, "ROOT", copied)+ examples.render_context.cache_clear()+ assert examples.render_context() == before+++def test_driver_profile_and_format_are_render_inputs(+ source_tree: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ before = examples.Example(SCENE).stem+ monkeypatch.setenv("MANIMGX_DOCS_RENDER_PROFILE", "another-driver")+ examples.render_context.cache_clear()+ changed_driver = examples.Example(SCENE).stem+ assert changed_driver != before+ monkeypatch.setattr(examples, "FORMAT", "another format")+ assert examples.Example(SCENE).stem not in {before, changed_driver}++[email protected]("animated", [False, True])+def test_real_renders_record_static_and_animated_outputs(+ source_tree: Path, animated: bool+) -> None:+ code = (+ "from manimgx import Scene, Square\n"+ "class Tiny(Scene):\n"+ " def construct(self):\n"+ " square = Square()\n"+ " self.add(square)\n"+ )+ if animated:+ code += " self.play(square.animate.set_opacity(0.5), run_time=0.05)\n"+ example = examples.Example(code)+ assert not examples._rendered(example, False)+ examples.render(example, readme=True)+ assert examples._rendered(example, True)+ assert (examples.FILMS / f"{example.stem}.mp4").exists() == animated+ assert not list(examples.FILMS.glob("*.json"))+ assert not list(examples.RECORDS.parent.glob("render-*"))+++def draw(monkeypatch: pytest.MonkeyPatch) -> list[str]:+ rendered: list[str] = []++ def make(example: examples.Example, folder: Path, readme: bool) -> None:+ rendered.append(str(example.scene))+ for suffix in examples.OUTPUTS if readme else (".webp", ".mp4"):+ (folder / f"{example.stem}{suffix}").write_bytes(b"complete output")++ monkeypatch.setattr(examples, "_draw", make)+ return rendered++[email protected]("damage", ["delete", "truncate", "modify"])+def test_missing_or_damaged_video_is_rendered_again(+ source_tree: Path, draw: list[str], damage: str+) -> None:+ example = examples.Example(SCENE)+ examples.render(example)+ video = examples.FILMS / f"{example.stem}.mp4"+ if damage == "delete":+ video.unlink()+ elif damage == "truncate":+ video.write_bytes(b"complete")+ else:+ video.write_bytes(b"Complete output")+ assert not examples._rendered(example, False)+ examples.render(example)+ assert examples._rendered(example, False)+ assert draw == ["Alpha", "Alpha"]+++def test_failed_render_preserves_previous_complete_output(+ source_tree: Path, draw: list[str], monkeypatch: pytest.MonkeyPatch+) -> None:+ example = examples.Example(SCENE)+ examples.render(example)++ def fail(example: examples.Example, folder: Path, readme: bool) -> None:+ (folder / f"{example.stem}.webp").write_bytes(b"unfinished")+ raise RuntimeError("render interrupted")++ monkeypatch.setattr(examples, "_draw", fail)+ with pytest.raises(RuntimeError, match="render interrupted"):+ examples.render(example)+ assert examples._rendered(example, False)+ assert not list(examples.RECORDS.parent.glob("render-*"))+++def test_interrupted_publication_is_not_a_completed_render(+ source_tree: Path, draw: list[str], monkeypatch: pytest.MonkeyPatch+) -> None:+ example = examples.Example(SCENE)+ replace = Path.replace++ def fail_record(path: Path, target: Path) -> Path:+ if path.suffix == ".json":+ raise OSError("publication interrupted")+ return replace(path, target)++ with monkeypatch.context() as patch:+ patch.setattr(Path, "replace", fail_record)+ with pytest.raises(OSError, match="publication interrupted"):+ examples.render(example)+ assert (examples.FILMS / f"{example.stem}.webp").exists()+ assert not examples._rendered(example, False)+ examples.render(example)+ assert examples._rendered(example, False)++[email protected]("record", ["{", "null", "[]", "{}", '{"../../outside": "x"}'])+def test_invalid_completion_record_is_a_miss(+ source_tree: Path, draw: list[str], record: str+) -> None:+ example = examples.Example(SCENE)+ examples.render(example)+ write(examples.RECORDS / f"{example.stem}.json", record)+ assert not examples._rendered(example, False)+++def test_snapshot_tracks_names_and_damage_but_not_timestamps_or_staging(+ source_tree: Path, draw: list[str]+) -> None:+ before = examples.cache_state()+ example = examples.Example(SCENE)+ examples.render(example)+ complete = examples.cache_state()+ assert complete != before+ video = examples.FILMS / f"{example.stem}.mp4"+ os.utime(video, (1, 1))+ write(examples.RECORDS.parent / "render-interrupted" / "unfinished.mp4", "partial")+ assert examples.cache_state() == complete+ renamed = video.rename(video.with_stem("same-pixels-new-name"))+ assert examples.cache_state() != complete+ renamed.rename(video)+ assert examples.cache_state() == complete+ video.write_bytes(b"damaged")+ assert examples.cache_state() != complete+ examples.render(example)+ assert examples.cache_state() == complete+++def test_build_reuses_unchanged_scenes_and_prunes_removed_ones(+ source_tree: Path, draw: list[str], monkeypatch: pytest.MonkeyPatch+) -> None:+ # Use the actual scheduler and filesystem with cheap fake renders in this process.+ monkeypatch.setattr(+ examples, "ProcessPoolExecutor", lambda **_: ThreadPoolExecutor(max_workers=1)+ )+ beta = write(source_tree / "examples" / "beta.py", SCENE.replace("Alpha", "Beta"))+ examples.main([])+ assert draw == ["Alpha", "Beta"]+ before = {name: e.stem for name, e in examples.scenes().items()}+ draw.clear()+ examples.main([])+ assert draw == []+ write(source_tree / "examples" / "alpha.py", SCENE.replace("pass", "value = 1"))+ examples.main([])+ assert draw == ["Alpha"]+ assert not (examples.FILMS / f"{before['Alpha']}.mp4").exists()+ assert not (examples.RECORDS / f"{before['Alpha']}.json").exists()+ draw.clear()+ beta.unlink()+ examples.main([])+ assert draw == []+ assert not (examples.FILMS / f"{before['Beta']}.mp4").exists()+ assert len(list(examples.RECORDS.glob("*.json"))) == 1+ assert set(+ json.loads(next(examples.RECORDS.glob("*.json")).read_text(encoding="utf-8"))+ ) == {+ ".webp",+ ".mp4",+ }+++def test_restored_partial_build_resumes_and_repairs_only_missing_or_damaged_films(+ source_tree: Path, draw: list[str], monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(+ examples, "ProcessPoolExecutor", lambda **_: ThreadPoolExecutor(max_workers=1)+ )+ write(source_tree / "examples" / "beta.py", SCENE.replace("Alpha", "Beta"))+ make = examples._draw++ def fail_beta(example: examples.Example, folder: Path, readme: bool) -> None:+ if example.scene == "Beta":+ (folder / f"{example.stem}.mp4").write_bytes(b"unfinished")+ raise RuntimeError("interrupted")+ make(example, folder, readme)++ with monkeypatch.context() as patch:+ patch.setattr(examples, "_draw", fail_beta)+ with pytest.raises(SystemExit):+ examples.main([])+ alpha, beta = examples.scenes().values()+ assert examples._rendered(alpha, False)+ assert not examples._rendered(beta, False)++ # An archive transported to a fresh runner contains completed work, even though+ # the overall build failed. Progress is not part of any film's identity.+ archive = shutil.make_archive(str(source_tree / "snapshot"), "tar", examples.DOCS)+ shutil.rmtree(examples.DOCS)+ shutil.unpack_archive(archive, examples.DOCS, filter="data")+ draw.clear()+ examples.main([])+ assert draw == ["Beta"]+ assert examples._rendered(alpha, False)+ assert examples._rendered(beta, False)++ (examples.FILMS / f"{alpha.stem}.mp4").write_bytes(b"damaged")+ draw.clear()+ examples.main([])+ assert draw == ["Alpha"]+ assert examples._rendered(alpha, False)+ draw.clear()+ examples.main([])+ assert draw == []