The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Retain and authenticate executable and wheel release inputs
Sina Atalay0be2a27f77d3
diff --git a/LICENSE-THIRD-PARTY b/LICENSE-THIRD-PARTYindex 89393f5d..822a0706 100644--- a/LICENSE-THIRD-PARTY+++ b/LICENSE-THIRD-PARTY@@ -4,12 +4,13 @@ Pyodide's, and the player for a page, which the extension carries), with the southe workspace's crates fetch; with the licenses and notices they come with, eachtext once, after what it covers. FFmpeg is under the LGPL-2.1-or-later, and x264, inevery wheel but Pyodide's, under the GPL-2.0-or-later, which makes such a wheel, as-a whole, GPL-3.0-or-later. Its complete source, which builds it offline, is on the-GitHub release of its version,-https://github.com/academa-labs/manimgx/releases/tag/vX.Y.Z for manimgx X.Y.Z:-manimgx-X.Y.Z-source.tar.xz, manimgx's source distribution with every crate-rust/Cargo.lock names and each archive a workspace's crate fetches. The Linux-wheels' lavapipe is in LICENSE-LAVAPIPE. Written by scripts/release/licenses.py.+a whole, GPL-3.0-or-later. Its complete source and build recipes are on the GitHub+release of its version, https://github.com/academa-labs/manimgx/releases/tag/vX.Y.Z+for manimgx X.Y.Z: manimgx-X.Y.Z-source.tar.xz, manimgx's committed repository with+every crate rust/Cargo.lock names and each archive a workspace's crate fetches, with+the Linux builds' Mesa/glslang archives and exact distribution source RPMs. System+build tools remain prerequisites. The Linux wheels' lavapipe is in LICENSE-LAVAPIPE.+Written by scripts/release/licenses.py. The Windows wheels' DXC is in LICENSE-DXC.===============================================================================ab_glyph 0.2.32 (Apache-2.0): LICENSE@@ -4483,7 +4484,6 @@ typst-svg 0.15.1 (Apache-2.0): no license filetypst-syntax 0.15.1 (Apache-2.0): no license filetypst-timing 0.15.1 (Apache-2.0): no license filetypst-utils 0.15.1 (Apache-2.0): no license file-wasmparser 0.239.0 (Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT): no license file-------------------------------------------------------------------------------Apache LicenseVersion 2.0, January 2004@@ -14166,6 +14166,99 @@ EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES ORIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THEUSE OR OTHER DEALINGS IN THE SOFTWARE.+===============================================================================+wasmparser 0.239.0 (Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT): no license file+-------------------------------------------------------------------------------+Apache License+Version 2.0, January 2004+http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.++"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.++"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.++"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.++"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.++"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.++"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).++"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.++"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."++"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.++2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.++3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.++4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:++ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.++ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.++5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.++6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.++7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.++8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.++END OF TERMS AND CONDITIONS++APPENDIX: How to apply the Apache License to your work.++To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.++Copyright [yyyy] [name of copyright owner]++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.++---- LLVM Exceptions to the Apache 2.0 License ----++ As an exception, if, as a result of your compiling your source code, portions+ of this Software are embedded into an Object form of such source code, you+ may redistribute such embedded portions in such Object form without complying+ with the conditions of Sections 4(a), 4(b) and 4(d) of the License.++ In addition, if you combine or link compiled forms of this Software with+ software that is licensed under the GPLv2 ("Combined Software") and if a+ court of competent jurisdiction determines that the patent provision (Section+ 3), the indemnity provision (Section 9) or other Section of the License+ conflicts with the conditions of the GPLv2, you may retroactively and+ prospectively choose to deem waived or otherwise exclude such Section(s) of+ the License, but only in their entirety and only with respect to the Combined+ Software.+===============================================================================wayland-backend 0.3.17 (MIT): LICENSE.txtwayland-client 0.31.15 (MIT): LICENSE.txtdiff --git a/docker/Dockerfile b/docker/Dockerfileindex 21b9920e..294bc6eb 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -6,9 +6,9 @@# Build a release with `just build-docker-image VERSION` (VERSION unset: the latest): this folder# is its context, as it installs manimgx from PyPI.-# uv as a stage: Dependabot bumps FROM lines only+# Mount this pinned installer only while adding Python packages.FROM ghcr.io/astral-sh/uv:0.12.19 AS uv-FROM python:3.14-slim-trixie+FROM python:3.14-slim-trixie AS runtime# Vulkan's loader and Mesa's drivers (lavapipe on the CPU; RADV, ANV, NVK on /dev/dri); NVIDIA's# driver, which the NVIDIA Container Toolkit mounts in, needs libEGL and libXext to start@@ -19,11 +19,6 @@ RUN apt-get update \# the python image ships its standard library without bytecode, and every run starts freshRUN python -m compileall -q /usr/local/lib-# VERSION unset: the latest release. uv is mounted for this step only-ARG VERSION-RUN --mount=from=uv,source=/uv,target=/bin/uv \- uv pip install --system --no-cache --compile-bytecode "manimgx${VERSION:+==$VERSION}"-# NVIDIA's Vulkan driver comes with `graphics`, its shader compiler with `compute`; no# __pycache__ in the mounted project; caches (Mesa's) where any --user can writeENV NVIDIA_DRIVER_CAPABILITIES=all \@@ -32,3 +27,18 @@ ENV NVIDIA_DRIVER_CAPABILITIES=all \WORKDIR /workENTRYPOINT ["manimgx"]CMD ["--help"]++# The release builds from its tested wheels before publishing anything. Runtime dependencies+# follow the same frozen lock; the read-only mount leaves no wheel copies in the final image.+FROM runtime AS release+RUN --mount=from=uv,source=/uv,target=/bin/uv \+ --mount=type=bind,source=wheels,target=/wheels \+ uv pip install --system --no-cache --compile-bytecode --no-deps \+ --require-hashes --requirements /wheels/requirements.txt \+ && uv pip install --system --no-cache --compile-bytecode --no-deps /wheels/*.whl++# The ordinary local command installs an existing PyPI release (unset: the latest).+FROM runtime AS published+ARG VERSION+RUN --mount=from=uv,source=/uv,target=/bin/uv \+ uv pip install --system --no-cache --compile-bytecode "manimgx${VERSION:+==$VERSION}"diff --git a/scripts/release/create_executable.py b/scripts/release/create_executable.pyindex cedc6494..79393720 100644--- a/scripts/release/create_executable.py+++ b/scripts/release/create_executable.py@@ -1,5 +1,5 @@# /// script-# requires-python = ">=3.13"+# requires-python = ">=3.14"# ///"""Create manimgx's executable for this machine, from its wheel in dist/: one file holding aPython with manimgx and its locked dependencies installed.@@ -13,17 +13,88 @@ Run it with `just create-executable`; it writes dist/manimgx-<os>-<arch>.tar.gzWindows), after running what it made once."""+import hashlib+import jsonimport osimport platform+import shutilimport subprocessimport sysimport tarfileimport tempfileimport zipfile-from pathlib import Path+from collections.abc import Mapping+from pathlib import Path, PurePosixPathPYAPP = "0.29.0"-PYTHON = "3.14"+PYAPP_SHA256 = "0ad1267db069a83e16dad2a42b0d01c727f5a9da7614330f44b66876da2d15f6"+PYTHON = "3.14.8"+PBS_RELEASE = "20261003"+PBS_COMMIT = "5e46737f6480fc315ebfea83866910cbfcc772f0"+PBS_SOURCE_SHA256 = "2c4bc5e43a0276046f080f40f0bd9586b10f2a6aa1714c592557f57ef0821e0c"+# The full archives retain PYTHON.json and notices that install-only archives omit.+PYTHONS = {+ "linux-x86_64": (+ "x86_64-unknown-linux-gnu",+ "pgo+lto",+ "43b8c1b02e3daefbbbf4b5714b656ea00a5cae24f55c4589fb87468bcac682ed",+ ),+ "linux-arm64": (+ "aarch64-unknown-linux-gnu",+ "pgo+lto",+ "72cee1a99dfde64850dd5ffde8d96f84b0d352fd694cc1e92dad78abae6b8f29",+ ),+ "macos-arm64": (+ "aarch64-apple-darwin",+ "pgo+lto",+ "6bb6e246d6c2bdfef5b33e833541c232d99afb37b67a08872f233649f4b64ca7",+ ),+ "windows-x86_64": (+ "x86_64-pc-windows-msvc",+ "pgo",+ "c2d2aee5613fbdc2e178b0c90f5f7b16fb5f0d452f1f09c63ff09043c9a1cde3",+ ),+}++# Selected by PBS targets.yml/Makefile and cpython-windows/build.py, not by+# license_paths (which intentionally lists alternatives across Python versions).+PYTHON_COMMON_SOURCES = (+ "cpython-3.14",+ "pip",+ "bzip2",+ "mpdecimal",+ "openssl-3.5",+ "sqlite",+ "xz",+ "zstd",+)+PYTHON_UNIX_SOURCES = ("expat", "libffi", "tcl", "tk", "uuid")+PYTHON_LINUX_SOURCES = (+ "bdb",+ "libedit",+ "libX11",+ "libXau",+ "libxcb",+ "ncurses",+ "zlib",+ "xorgproto",+)+# PBS builds Windows libffi from this commit; CPython3.14.8 get_externals.bat+# selects these Tcl/Tk source tags alongside its tcltk-9.0.4.0 binary bundle.+PYTHON_WINDOWS_SOURCES = {+ "libffi": (+ "16fad4855b3d8c03b5910e405ff3a04395b39a98",+ "f21ae7b0cce58cf9428e01d4d22aac9c3b70722a4e9b2c92b3a97d490a1b401c",+ ),+ "tcl": (+ "53c758cbf2cc178b359abc03fdd912c5e66ed74f",+ "2ec3a0db72d1eb15096940ce67e226bc16a0719e12e554c7feb920eb40bd6f36",+ ),+ "tk": (+ "a6a5bee1ef4b526b0d11200c84bc02e85d8ecc83",+ "b913ff99cc8e0a930d1f3d6064b751fbd4180fa850fa287e6e25e26c379ab73e",+ ),+}ROOT = Path(__file__).resolve().parents[2]DIST = ROOT / "dist"@@ -35,9 +106,13 @@ MACHINE = {"x86_64": "x86_64", "amd64": "x86_64", "arm64": "arm64", "aarch64": "]-def run(*command: str | Path, env: dict[str, str] | None = None) -> None:+def run(+ *command: str | Path,+ env: dict[str, str] | None = None,+ cwd: Path = ROOT,+) -> None:print("$", *command, flush=True)- subprocess.run([str(part) for part in command], check=True, env=env)+ subprocess.run([str(part) for part in command], check=True, env=env, cwd=cwd)def the_wheel() -> Path:@@ -48,16 +123,210 @@ def the_wheel() -> Path:return wheels[0]-def install_python(directory: Path) -> Path:- """A standalone CPython (python-build-standalone, through uv), in its own directory."""- run("uv", "python", "install", PYTHON, "--install-dir", directory, "--no-bin")- # the installation itself, not the links uv adds beside it (cpython-3.14-… to cpython-3.14.N-…)- (python,) = [- path- for path in directory.glob("cpython-*")- if path.is_dir() and not path.is_symlink() and not path.is_junction()- ]- return python+def fetch(url: str, digest: str, directory: Path, *, source: bool = True) -> Path:+ """Use the release's verified acquisition, without retaining binary inputs as source."""+ env = os.environ | {"OUT_DIR": str(directory)}+ if not source:+ env.pop("MANIMGX_SOURCES", None)+ run(+ "cargo", "run", "--locked", "--manifest-path", ROOT / "rust/Cargo.toml",+ "-p", "fetch", "--bin", "fetch-file", "--", url, digest, env=env,+ ) # fmt: skip+ path = directory / digest+ if sha256(path) != digest:+ raise ValueError(f"download changed: {url}")+ return path+++def license_paths(value: object) -> set[str]:+ """Every declared notice, including extension variants, in upstream metadata."""+ if isinstance(value, dict):+ result = set()+ for key, item in value.items():+ if key == "license_path" and isinstance(item, str):+ result.add(item)+ elif key == "license_paths" and isinstance(item, list):+ result.update(path for path in item if isinstance(path, str))+ else:+ result.update(license_paths(item))+ return result+ if isinstance(value, list):+ return set().union(*(license_paths(item) for item in value))+ return set()+++def python_sources(+ recipe: Mapping[str, Mapping[str, object]],+) -> dict[str, dict[str, str]]:+ """The actual runtime source graph, with build scripts retained in PBS/CPython."""+ names = list(PYTHON_COMMON_SOURCES)+ names += ["zlib-ng"] if SYSTEM == "windows" else list(PYTHON_UNIX_SOURCES)+ if SYSTEM == "linux":+ names += PYTHON_LINUX_SOURCES+ inputs = {}+ for name in names:+ url, digest = recipe[name]["url"], recipe[name]["sha256"]+ if not isinstance(url, str) or not isinstance(digest, str):+ raise ValueError(f"invalid source recipe: {name}")+ inputs[name] = {"url": url, "sha256": digest, "purpose": "runtime"}+ if SYSTEM == "windows":+ for name, (commit, digest) in PYTHON_WINDOWS_SOURCES.items():+ inputs[name] = {+ "url": f"https://codeload.github.com/python/cpython-source-deps/tar.gz/{commit}",+ "sha256": digest,+ "purpose": "runtime",+ }+ return inputs+++def source_notice(archive: Path, member: str, destination: Path) -> None:+ """Recover the actual upstream notice without extracting any source executable."""+ with tarfile.open(archive) as packed:+ text = packed.extractfile(member)+ if text is None:+ raise ValueError(f"missing source notice: {member}")+ destination.parent.mkdir(parents=True, exist_ok=True)+ destination.write_bytes(text.read())+++def install_python(work: Path, retained: Path) -> tuple[Path, dict[str, object]]:+ """Extract the pinned runtime and preserve its original metadata and declared notices.++ Open-source runtime inputs share one verified pool across platform artifacts.+ Microsoft's Windows runtime DLLs remain separately identified binary inputs.+ """+ target, options, digest = PYTHONS[f"{SYSTEM}-{MACHINE}"]+ name = f"cpython-{PYTHON}+{PBS_RELEASE}-{target}-{options}-full.tar.zst"+ url = f"https://github.com/astral-sh/python-build-standalone/releases/download/{PBS_RELEASE}/{name}"+ packed = fetch(url, digest, work / "downloads", source=False)+ directory = work / "standalone"+ with tarfile.open(packed) as archive:+ archive.extractall(+ directory,+ members=(+ member+ for member in archive+ if member.name == "python/PYTHON.json"+ or member.name.startswith(("python/install/", "python/licenses/"))+ ),+ filter="data",+ )+ standalone = directory / "python"+ metadata = standalone / "PYTHON.json"+ info = json.loads(metadata.read_text(encoding="utf-8"))+ if (info["python_version"], info["target_triple"], info["build_options"]) != (+ PYTHON,+ target,+ options,+ ):+ raise ValueError("the pinned Python distribution has unexpected metadata")+ provenance = work / "python-inputs"+ provenance.mkdir()+ source_url = f"https://codeload.github.com/astral-sh/python-build-standalone/tar.gz/{PBS_COMMIT}"+ source = fetch(source_url, PBS_SOURCE_SHA256, work / "downloads")+ shutil.copyfile(source, provenance / "python-build-standalone.tar.gz")+ with tarfile.open(source) as archive:+ recipe_file = archive.extractfile(+ f"python-build-standalone-{PBS_COMMIT}/pythonbuild/downloads.json"+ )+ if recipe_file is None:+ raise ValueError("the Python build recipe is missing")+ recipe_bytes = recipe_file.read()+ (provenance / "downloads.json").write_bytes(recipe_bytes)+ recipe = json.loads(recipe_bytes)+ inputs = python_sources(recipe)+ # A common digest path merges identical platform contributions without copying+ # the interpreter binary or four copies of the common dependency sources.+ pool = retained.parent / "python"+ sources = {+ name: fetch(entry["url"], entry["sha256"], pool)+ for name, entry in inputs.items()+ }+ repairs = []+ notices = license_paths(info)+ if SYSTEM == "windows":+ # The prebuilt Tcl/Tk bundle's dependencies are absent from PYTHON.json.+ # Their DLLs are byte-identical to the ones in the pinned Tcl source tree.+ commit = PYTHON_WINDOWS_SOURCES["tcl"][0]+ for component, path in (+ ("zlib", "compat/zlib/LICENSE"),+ ("libtommath", "libtommath/LICENSE"),+ ):+ notice = f"licenses/LICENSE.{component}.txt"+ source_notice(+ sources["tcl"],+ f"cpython-source-deps-{commit}/{path}",+ standalone / notice,+ )+ notices.add(notice)+ repairs.append({"notice": notice, **inputs["tcl"]})+ for notice in sorted(notices):+ path = PurePosixPath(notice)+ if path.is_absolute() or ".." in path.parts or path.parts[0] != "licenses":+ raise ValueError(f"unsafe Python notice path: {notice}")+ original = standalone / notice+ if not original.is_file():+ # These two declared notices are absent in the pinned full archives.+ # Recover their actual text from the source inputs of that same build.+ component = {+ "LICENSE.zstd.txt": "zstd",+ "LICENSE.zlib-ng.txt": "zlib-ng",+ }.get(path.name)+ if component is None:+ raise ValueError(f"Python distribution omits declared notice: {notice}")+ entry = recipe[component]+ # Unix metadata declares zlib-ng even though the Unix build uses zlib.+ # Keep its notice source as provenance, separately from the runtime graph.+ dependency = sources.get(component)+ if dependency is None:+ dependency = fetch(entry["url"], entry["sha256"], pool)+ inputs[component] = {+ "url": entry["url"],+ "sha256": entry["sha256"],+ "purpose": "declared notice",+ }+ filename = "LICENSE.md" if component == "zlib-ng" else "LICENSE"+ source_notice(+ dependency,+ f"cpython-source-deps-{component}-{entry['version']}/{filename}",+ original,+ )+ repairs.append(+ {"notice": notice, "url": entry["url"], "sha256": entry["sha256"]}+ )+ destination = provenance / notice+ destination.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(original, destination)+ shutil.copyfile(metadata, provenance / "PYTHON.json")+ shutil.copyfile(metadata, work / "PYTHON.json")+ notice_file = work / "LICENSE-PYTHON"+ with notice_file.open("wb") as output:+ for notice in sorted(notices):+ output.write(f"{notice}\n{'=' * len(notice)}\n".encode())+ output.write((provenance / notice).read_bytes())+ output.write(b"\n\n")+ # Notices also remain available when only the executable itself is copied.+ runtime = standalone / "install"+ included = runtime / "share/manimgx-python"+ included.mkdir(parents=True, exist_ok=True)+ for path in (metadata, notice_file):+ shutil.copyfile(path, included / path.name)+ retained.mkdir(parents=True, exist_ok=True)+ with tarfile.open(retained / "python-inputs.tar.xz", "w:xz") as archive:+ archive.add(provenance, arcname="python-inputs")+ return runtime, {+ "version": PYTHON,+ "release": PBS_RELEASE,+ "target": target,+ "url": url,+ "sha256": digest,+ "metadata_sha256": sha256(metadata),+ "build_recipe": {"url": source_url, "sha256": PBS_SOURCE_SHA256},+ "notice_repairs": repairs,+ "sources": inputs,+ "binary_runtime": info.get("crt_features", []),+ "inputs_sha256": sha256(retained / "python-inputs.tar.xz"),+ }def install_manimgx(python: Path, wheel: Path, work: Path) -> None:@@ -66,26 +335,58 @@ def install_manimgx(python: Path, wheel: Path, work: Path) -> None:requirements = work / "requirements.txt"run("uv", "export", "--frozen", "--package", "manimgx", "--no-default-groups",- "--no-emit-workspace", "--no-hashes", "--output-file", requirements,+ "--no-emit-workspace", "--output-file", requirements,) # fmt: skipfonts = sorted((ROOT / "fonts").glob("manimgx-fonts*"))run("uv", "pip", "install", "--python", python / INTERPRETER, "--break-system-packages",- "--compile-bytecode", "--requirements", requirements, wheel, *fonts,+ "--compile-bytecode", "--no-deps", "--require-hashes", "--requirements", requirements,+ ) # fmt: skip+ run(+ "uv", "pip", "install", "--python", python / INTERPRETER, "--break-system-packages",+ "--compile-bytecode", "--no-deps", wheel, *fonts,) # fmt: skip# the Python is manimgx's own: `manimgx self pip install` may add packages to itfor marker in python.glob("**/EXTERNALLY-MANAGED"):marker.unlink()-def build_pyapp(distribution: Path, version: str, work: Path) -> Path:+def launcher_sources(work: Path) -> Path:+ """The exact launcher input, including its own complete locked Cargo graph."""+ url = f"https://static.crates.io/crates/pyapp/pyapp-{PYAPP}.crate"+ with tarfile.open(fetch(url, PYAPP_SHA256, work)) as archive:+ archive.extractall(work, filter="data")+ source = work / f"pyapp-{PYAPP}"+ config = source / ".cargo" / "config.toml"+ config.parent.mkdir(exist_ok=True)+ # Keep upstream target flags, including Windows' static C runtime.+ with config.open("a", encoding="utf-8") as output:+ output.write("\n")+ output.flush()+ subprocess.run(+ ["cargo", "vendor", "--locked", "vendor"],+ cwd=source,+ stdout=output,+ check=True,+ )+ return source+++def sha256(path: Path) -> str:+ with path.open("rb") as file:+ return hashlib.file_digest(file, "sha256").hexdigest()+++def build_pyapp(distribution: Path, version: str, work: Path, source: Path) -> Path:"""PyApp, built with the distribution inside it: it unpacks it and runs `manimgx`."""# the distribution itself runs manimgx, installed in it already: no virtual environment,# no installation at runtimeenv = os.environ | {+ # Keep compiled output outside the source closure retained for the release.+ "CARGO_TARGET_DIR": str(work / "target"),"PYAPP_PROJECT_NAME": "manimgx","PYAPP_PROJECT_VERSION": version,- "PYAPP_PYTHON_VERSION": PYTHON,+ "PYAPP_PYTHON_VERSION": PYTHON.rsplit(".", 1)[0],"PYAPP_DISTRIBUTION_PATH": str(distribution),"PYAPP_DISTRIBUTION_PYTHON_PATH": INTERPRETER,"PYAPP_FULL_ISOLATION": "1",@@ -96,8 +397,8 @@ def build_pyapp(distribution: Path, version: str, work: Path) -> Path:"PYAPP_EXPOSE_CACHE": "1",}run(- "cargo", "install", "pyapp", "--version", PYAPP, "--locked", "--force",- "--root", work / "pyapp", env=env,+ "cargo", "install", "--path", source, "--locked", "--offline", "--force",+ "--root", work / "pyapp", env=env, cwd=source,) # fmt: skipbinary = work / "pyapp" / "bin" / ("pyapp.exe" if WINDOWS else "pyapp")executable = work / ("manimgx.exe" if WINDOWS else "manimgx")@@ -117,26 +418,102 @@ def main() -> None:version = wheel.name.split("-")[1]with tempfile.TemporaryDirectory() as temporary:work = Path(temporary)- python = install_python(work / "python")+ retained = ROOT / "release-sources" / f"executable-{SYSTEM}-{MACHINE}"+ python, python_input = install_python(work, retained)install_manimgx(python, wheel, work)distribution = work / "python.tar.gz"with tarfile.open(distribution, "w:gz") as archive:for path in python.iterdir():archive.add(path, arcname=path.name)- executable = build_pyapp(distribution, version, work)+ source = launcher_sources(work)+ # PyApp's build script copies the binary distribution into its source tree.+ # Retain the input before that generated payload is written.+ with tarfile.open(retained / "pyapp.tar.xz", "w:xz") as out:+ out.add(source, arcname="pyapp")+ executable = build_pyapp(distribution, version, work, source)+ target = next(+ line.removeprefix("host: ")+ for line in subprocess.check_output(+ ["rustc", "-vV"], text=True, encoding="utf-8"+ ).splitlines()+ if line.startswith("host: ")+ )+ notice = work / "LICENSE-PYAPP"+ run(+ sys.executable,+ ROOT / "scripts/release/licenses.py",+ "--crate",+ source,+ target,+ notice,+ )+ receipt = work / "build-inputs.json"+ receipt.write_text(+ json.dumps(+ {+ "wheel": {"name": wheel.name, "sha256": sha256(wheel)},+ "python": python_input,+ "launcher": {+ "version": PYAPP,+ "url": f"https://static.crates.io/crates/pyapp/pyapp-{PYAPP}.crate",+ "sha256": PYAPP_SHA256,+ "lock_sha256": sha256(source / "Cargo.lock"),+ "target": target,+ },+ "distribution_sha256": sha256(distribution),+ "executable_sha256": sha256(executable),+ "source_sha256": sha256(retained / "pyapp.tar.xz"),+ },+ indent=2,+ )+ + "\n",+ encoding="utf-8",+ )+ (retained / "manifest.json").write_bytes(receipt.read_bytes())smoke_test(executable)# an archive keeps the file executablename = f"manimgx-{SYSTEM}-{MACHINE}"+ files = (+ executable,+ notice,+ receipt,+ work / "LICENSE-PYTHON",+ work / "PYTHON.json",+ )if WINDOWS:created = DIST / f"{name}.zip"with zipfile.ZipFile(created, "w", zipfile.ZIP_DEFLATED) as out:- out.write(executable, executable.name)+ for path in files:+ out.write(path, path.name)else:created = DIST / f"{name}.tar.gz"with tarfile.open(created, "w:gz") as out:- out.add(executable, arcname=executable.name)+ for path in files:+ out.add(path, arcname=path.name)print(f"created {created}")+def verify_sources(directory: Path) -> None:+ """Every executable retained its unchanged launcher sources and Python inputs."""+ for target in ("linux-x86_64", "linux-arm64", "macos-arm64", "windows-x86_64"):+ source = directory / f"executable-{target}"+ receipt = json.loads((source / "manifest.json").read_text(encoding="utf-8"))+ if (+ sha256(source / "python-inputs.tar.xz")+ != receipt["python"]["inputs_sha256"]+ ):+ raise ValueError(+ f"{target}: the executable's retained Python inputs changed"+ )+ for name, entry in receipt["python"]["sources"].items():+ if sha256(directory / "python" / entry["sha256"]) != entry["sha256"]:+ raise ValueError(f"{target}: retained Python source changed: {name}")+ if sha256(source / "pyapp.tar.xz") != receipt["source_sha256"]:+ raise ValueError(f"{target}: the executable's retained source changed")++if __name__ == "__main__":- main()+ if sys.argv[1:2] == ["--verify-sources"]:+ verify_sources(Path(sys.argv[2]))+ else:+ main()diff --git a/scripts/release/licenses.py b/scripts/release/licenses.pyindex 959c1926..ec5d0d1a 100644--- a/scripts/release/licenses.py+++ b/scripts/release/licenses.py@@ -58,24 +58,26 @@ def run(*command: str, cwd: Path = ROOT) -> str:).stdout-def crates() -> dict[str, dict]:- """The packages compiled into any of the engine's builds, as `cargo tree` shows them: its+def crates(+ directory: Path = ENGINE, builds: tuple[tuple[str, list[str]], ...] = BUILDS+) -> dict[str, dict]:+ """The packages compiled into the selected builds, as `cargo tree` shows them: theirnormal dependencies, all the way down, with the features each build turns on (a buildscript's and a test's are not in it), the workspace's own among them."""metadata = json.loads(run(*("cargo", "metadata", "--format-version", "1", "--locked"),"--all-features",- cwd=ENGINE,+ cwd=directory,))packages = {(p["name"], p["version"]): p for p in metadata["packages"]}linked: dict[str, dict] = {}- for target, features in BUILDS:+ for target, features in builds:tree = run(*("cargo", "tree", "--locked", "--edges", "normal", "--target", target),*(*features, "--prefix", "none", "--format", "{p}"),- cwd=ENGINE,+ cwd=directory,)for name, version in re.findall(r"^(\S+) v(\S+)", tree, re.MULTILINE):linked[f"{name} {version}"] = packages[name, version]@@ -202,7 +204,11 @@ def uncovered(licenses: dict[str, str | None]) -> list[str]:def write(- linked: dict[str, dict], theirs: dict[tuple[str, tuple[str, ...]], list[str]]+ linked: dict[str, dict],+ theirs: dict[tuple[str, tuple[str, ...]], list[str]],+ *,+ header: str | None = None,+ include_local: bool = False,) -> tuple[str, list[str]]:"""The notice, and what LICENSES/ has no text for."""found: dict[str, list[str]] = {}@@ -222,7 +228,7 @@ def write(written = clean(file.read_text(encoding="utf-8", errors="replace"))found.setdefault(written, []).append(f"{declared}: {file.name}")# the workspace's own code is manimgx's (LICENSE)- if not shipped and package["source"] is not None:+ if not shipped and (include_local or package["source"] is not None):authors = [re.sub(r"\s*<.*?>", "", a) for a in package["authors"]]by = ", ".join(authors) or f"the {package['name']} authors"expression = package.get("license") or "?"@@ -235,7 +241,7 @@ def write(missing.append(declared)continuefound.setdefault(written, []).append(f"{declared}: no license file")- header = (+ header = header or ("What manimgx's wheels hold that others hold the copyright in: modules of its"" Python package, and the crates compiled into the engine (the extension, on"" each platform, Pyodide's, and the player for a page, which the extension"@@ -243,12 +249,14 @@ def write(" and notices they come with, each text once, after what it covers. FFmpeg is"" under the LGPL-2.1-or-later, and x264, in every wheel but Pyodide's, under"" the GPL-2.0-or-later, which makes such a wheel, as a whole, GPL-3.0-or-later."- " Its complete source, which builds it offline, is on the GitHub release of its"+ " Its complete source and build recipes are on the GitHub release of its"" version, https://github.com/academa-labs/manimgx/releases/tag/vX.Y.Z for"- " manimgx X.Y.Z: manimgx-X.Y.Z-source.tar.xz, manimgx's source distribution"+ " manimgx X.Y.Z: manimgx-X.Y.Z-source.tar.xz, manimgx's committed repository"" with every crate rust/Cargo.lock names and each archive a workspace's crate"- " fetches. The Linux wheels' lavapipe is in LICENSE-LAVAPIPE. Written by"- " scripts/release/licenses.py."+ " fetches, with the Linux builds' Mesa/glslang archives and exact distribution"+ " source RPMs. System build tools remain prerequisites. The Linux wheels' lavapipe"+ " is in LICENSE-LAVAPIPE. Written by"+ " scripts/release/licenses.py. The Windows wheels' DXC is in LICENSE-DXC.")parts = [textwrap.fill(header, 84, break_on_hyphens=False) + "\n"]for written, users in sorted(found.items(), key=lambda item: item[1][0]):@@ -259,6 +267,21 @@ def write(def main() -> None:+ if sys.argv[1:2] == ["--crate"]:+ directory, target, output = sys.argv[2:]+ linked = crates(Path(directory), ((target, []),))+ text, missing = write(+ linked,+ {},+ header=f"The crates compiled into the executable's launcher for {target}, "+ "as its own Cargo.lock and default features select them, with the license "+ "and notice files they supply. Its sources and lockfile accompany the release.",+ include_local=True,+ )+ if missing:+ sys.exit(f"LICENSES/ has no text for {', '.join(missing)}")+ Path(output).write_text(text, encoding="utf-8")+ returnlinked = crates()theirs = others()text, missing = write(linked, theirs)diff --git a/scripts/release/linux_sources.py b/scripts/release/linux_sources.pynew file mode 100644index 00000000..ff6cd21b--- /dev/null+++ b/scripts/release/linux_sources.py@@ -0,0 +1,138 @@+"""Keep the sources of the Linux wheel's bundled distribution libraries.++Run after auditwheel repair, inside the same manylinux image. auditwheel's SBOM names+the packages it actually copied. RPM identifies their exact source packages, and DNF+retrieves those versions. LLVM's checked archive is kept by build_lavapipe.sh. Compilers and+other build tools stay system prerequisites: this records source closure, not a hermetic+or bit-identical build environment.+"""++import hashlib+import json+import os+import platform+import subprocess+import sys+import tempfile+import zipfile+from pathlib import Path+++def bundled_packages(wheel: Path) -> set[str]:+ """The exact distribution packages whose libraries auditwheel put in the wheel."""+ with zipfile.ZipFile(wheel) as archive:+ libraries = [+ n for n in archive.namelist() if ".libs/" in n and not n.endswith("/")+ ]+ sboms = [+ n for n in archive.namelist() if n.endswith("/sboms/auditwheel.cdx.json")+ ]+ if not libraries:+ return set()+ if len(sboms) != 1:+ raise ValueError(+ "the repaired wheel's libraries have no unique auditwheel SBOM"+ )+ components = json.loads(archive.read(sboms[0]))["components"][1:]+ if len(components) != len(libraries):+ raise ValueError(+ "auditwheel could not identify every bundled library's package"+ )+ if any(not c["purl"].startswith("pkg:rpm/") for c in components):+ raise ValueError(+ "a bundled library was not supplied by the manylinux RPM image"+ )+ return {f"{c['name']}-{c['version']}" for c in components}+++def output(*args: str) -> str:+ return subprocess.check_output(+ args, text=True, env=os.environ | {"LC_ALL": "C"}+ ).strip()+++def digest(path: Path) -> str:+ with path.open("rb") as file:+ return hashlib.file_digest(file, "sha256").hexdigest()+++def collect(wheel: Path, sources: Path) -> None:+ packages = bundled_packages(wheel)+ destination = sources / f"linux-{platform.machine()}"+ destination.mkdir(parents=True, exist_ok=True)+ records = []+ for package in sorted(packages):+ # The installed NEVRA, including architecture, resolves exactly the binary which+ # auditwheel copied, rather than a newer source of the same name.+ name, epoch, version, release, arch, source = output(+ "rpm",+ "-q",+ "--qf",+ "%{NAME} %{EPOCH} %{VERSION} %{RELEASE} %{ARCH} %{SOURCERPM}",+ package,+ ).split()+ binary = (+ f"{name}-{0 if epoch == '(none)' else epoch}:{version}-{release}.{arch}"+ )+ with tempfile.TemporaryDirectory(dir=destination) as temporary:+ subprocess.run(+ [+ "dnf",+ "download",+ "--source",+ "--downloaddir",+ temporary,+ source.removesuffix(".rpm"),+ ],+ check=True,+ )+ archive = Path(temporary) / source+ # A repository cannot silently substitute another source version. Only the+ # exact signed RPM is published into the artifact; partial downloads stay private.+ if not archive.is_file():+ raise ValueError(+ f"DNF did not supply the installed package's source: {source}"+ )+ if "signatures OK" not in output("rpm", "--checksig", str(archive)):+ raise ValueError(f"the source RPM has no verified signature: {source}")+ sha256 = digest(archive)+ archive.replace(destination / source)+ records.append({"binary": binary, "source": source, "sha256": sha256})+ manifest = {+ "wheel": wheel.name,+ "sha256": digest(wheel),+ "packages": records,+ "build_system": platform.freedesktop_os_release(),+ }+ (destination / "manifest.json").write_text(+ json.dumps(manifest, indent=2) + "\n", encoding="utf-8"+ )+++def verify(sources: Path) -> None:+ """Both Linux builds supplied their sources, unchanged since their wheels were made."""+ for machine in ["x86_64", "aarch64"]:+ directory = sources / f"linux-{machine}"+ manifest = json.loads((directory / "manifest.json").read_text(encoding="utf-8"))+ for package in manifest["packages"]:+ if digest(directory / package["source"]) != package["sha256"]:+ raise ValueError(+ f"{machine}: the retained source changed: {package['source']}"+ )+++def main() -> None:+ if sys.argv[1] == "--verify":+ verify(Path(sys.argv[2]))+ return+ directory = Path(sys.argv[1])+ sources = Path(+ os.environ.get("MANIMGX_SOURCES")+ or Path(__file__).resolve().parents[2] / "sources"+ )+ (wheel,) = directory.glob("*.whl")+ collect(wheel, sources)+++if __name__ == "__main__":+ main()diff --git a/scripts/release/smoke_test.py b/scripts/release/smoke_test.pyindex dd7fa63f..e64f1e3e 100644--- a/scripts/release/smoke_test.py+++ b/scripts/release/smoke_test.py@@ -1,6 +1,3 @@-# /// script-# requires-python = ">=3.13"-# ///"""Render a scene with an installed manimgx: the check a built wheel or executable passesbefore it is kept.@@ -11,45 +8,122 @@ browser's wheel: Pyodide has no GPU, and starts no process); the browser's wheelcarries the player for a page, and the fonts its face is set in."""+import structimport subprocessimport sysimport tempfilefrom pathlib import Path+# The native decoder's 20 ms silence fixture, embedded so this artifact probe can be+# copied on its own. The release tests keep it identical to rust/ffmpeg/tests/silence.opus.+OPUS = bytes.fromhex(+ "4f676753000200000000000000000100000000000000846cd92401134f70"+ "7573486561640101000080bb00000000004f676753000000000000000000"+ "0001000000010000008758601a01104f7075735461677300000000000000"+ "004f6767530004c00300000000000001000000020000002993b0dd0103f8"+ "fffe"+)+SCENE = """+import io+import wave+import manimgx as m+import numpy as npclass Smoke(m.Scene):def construct(self) -> None:+ # Generate a PCM file, so the installed native decoder (not the array shortcut)+ # supplies the sound which the export must encode as AAC.+ pcm = np.tile(np.array([0, 8192, 0, -8192], dtype="<i2"), 1200)+ wav = io.BytesIO()+ with wave.open(wav, "wb") as out:+ out.setparams((1, 2, 48000, 0, "NONE", "not compressed"))+ out.writeframes(pcm.tobytes())+ sound = m.Sound(wav.getvalue())+ np.testing.assert_array_equal(sound.samples[:, 0], pcm / 32768)+ self.add_sound(sound)+ # The linked reference Opus decoder must run on every wheel target, too.+ opus = m.Sound(OPUS_BYTES).samples+ assert opus.shape == (960, 1)+ assert np.isfinite(opus).all() and (abs(opus) < 1e-6).all()self.play(m.Write(m.Text("manimgx")))"""+def scene_source() -> str:+ return SCENE.replace("OPUS_BYTES", repr(OPUS))++def main() -> None:if sys.argv[1:] == ["--take"]:return take()manimgx = sys.argv[1:] or [sys.executable, "-m", "manimgx"]with tempfile.TemporaryDirectory() as directory:scene = Path(directory) / "smoke.py"- scene.write_text(SCENE, encoding="utf-8")+ scene.write_text(scene_source(), encoding="utf-8")subprocess.run([*manimgx, "--version"], check=True)subprocess.run([*manimgx, "render", str(scene), "-r", "320x180"], check=True)video = scene.with_name("Smoke.mp4")if not video.is_file() or video.stat().st_size == 0:sys.exit(f"manimgx rendered no video: {video}")+ # Reopen the exported container with the installed audio decoder. This runs+ # through the executable's own Python too, without assuming a host installation.+ scene.write_text(+ "import manimgx as m\nimport numpy as np\n"+ "class Verify(m.Scene):\n"+ " def construct(self):\n"+ f" samples = m.Sound({str(video)!r}).samples\n"+ " assert samples.shape[1] == 1 and len(samples) >= 4800\n"+ " assert np.isfinite(samples).all() and np.any(samples)\n",+ encoding="utf-8",+ )+ subprocess.run([*manimgx, "inspect", str(scene)], check=True)def take() -> None:scene: dict[str, object] = {}- exec(SCENE, scene)+ exec(scene_source(), scene)chunks: list[bytes] = []film = scene["Smoke"]().render(take=chunks.append) # ty: ignore[call-non-callable]if not film.frame_count or not b"".join(chunks):sys.exit("manimgx recorded no take")+ validate_take(b"".join(chunks), film.frame_count)player()+def validate_take(data: bytes, frames: int) -> None:+ """Check the wire envelope without a GPU; Pyodide has the writer alone."""+ from manimgx import _engine, config++ messages: list[bytes] = []+ at = 0+ while at < len(data):+ (length,) = struct.unpack_from("<I", data, at)+ at += 4+ if not length or at + length > len(data):+ raise ValueError("the recorded take has an incomplete message")+ messages.append(data[at : at + length])+ at += length+ assert struct.unpack("<BIIId", messages[0]) == (+ 14,+ _engine.TAKE_VERSION,+ config.pixel_width,+ config.pixel_height,+ config.frame_rate,+ )+ assert messages[-1] == bytes([12, 0]), (+ "the recorded take did not finish successfully"+ )+ assert (+ sum(struct.unpack_from("<I", m, 1)[0] for m in messages if m[0] == 8) == frames+ )+ assert any(m[0] == 10 and m[5:9] == b"RIFF" for m in messages), (+ "the take has no sound"+ )++def player() -> None:from manimgx import _enginefrom manimgx.drawing.typesetting import FONTSdiff --git a/tests/test_licenses.py b/tests/test_licenses.pyindex 59681bea..d1533d65 100644--- a/tests/test_licenses.py+++ b/tests/test_licenses.py@@ -50,3 +50,22 @@ def test_code_ported_from_manim_ce_says_whose_it_is() -> None:gone = [f for f in PORTED_FROM_CE if not any(f in text for text in texts.values())]assert not unsaid, f"Manim CE's code without its copyright lines: {unsaid}"assert not gone, f"no module holds {gone} any more: drop it from PORTED_FROM_CE"+++def test_the_dxc_notice_describes_the_pinned_compiler_and_source() -> None:+ build = (ROOT / "rust" / "dxc" / "src" / "lib.rs").read_text(encoding="utf-8")+ notice = (ROOT / "LICENSE-DXC").read_text(encoding="utf-8")+ recipe = (ROOT / "rust" / "dxc" / "README.md").read_text(encoding="utf-8")+ version = re.search(r"/releases/download/(v[\d.]+)/", build)+ sources = re.findall(r"/archive/([a-f0-9]{40})\.tar\.gz", build)+ binary = re.search(r'BINARY_HASH: &str = "([a-f0-9]{64})"', build)+ assert version+ assert version[1] in notice+ assert sources+ for source in sources:+ assert source in notice+ assert source in recipe+ assert binary+ assert binary[1] in notice+ assert "University of Illinois/NCSA" in notice+ assert "ThirdPartyNotices.txt" in noticediff --git a/tests/test_release.py b/tests/test_release.pynew file mode 100644index 00000000..c32c9d0e--- /dev/null+++ b/tests/test_release.py@@ -0,0 +1,849 @@+"""A pending PyPI publisher identifies one project by its workflow and environment.+The release must route only that project's distributions to it, and publish the fonts+before anything that installs manimgx from PyPI.+"""++import base64+import hashlib+import io+import json+import runpy+import subprocess+import tarfile+import tomllib+import zipfile+from fnmatch import fnmatchcase+from pathlib import Path+from typing import TextIO++import pytest+import yaml+from scripts.release import create_executable, linux_sources, publish_npm, smoke_test++ROOT = Path(__file__).parents[1]+JOBS = yaml.safe_load(+ (ROOT / ".github/workflows/release.yaml").read_text(encoding="utf-8")+)["jobs"]+++def test_complete_source_exports_the_committed_project_without_checkout_artifacts(+ tmp_path: Path,+) -> None:+ checkout, output = tmp_path / "checkout", tmp_path / "source with spaces"+ checkout.mkdir()+ git = [+ "git",+ "-C",+ str(checkout),+ "-c",+ "core.autocrlf=false",+ "-c",+ "user.name=Source test",+ "-c",+ "[email protected]",+ ]+ subprocess.run([*git, "init", "--quiet"], check=True, capture_output=True)+ inputs = {+ "scripts/release/build_lavapipe.sh": b"#!/bin/sh\nexit 0\n",+ "scripts/release/llvm/regression.ll": b"; compiler regression\n",+ "browser/src/index.ts": b"export {}\n",+ "fonts/example/font.bin": b"\x00\xff\r\n",+ "justfile": b"build:\n true\n",+ }+ for name, content in inputs.items():+ path = checkout / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(content)+ subprocess.run([*git, "add", "."], check=True, capture_output=True)+ subprocess.run(+ [*git, "commit", "--quiet", "-m", "Source"], check=True, capture_output=True+ )+ revision = subprocess.check_output([*git, "rev-parse", "HEAD"], text=True).strip()+ (checkout / "untracked-binary").write_bytes(b"not source")+ command = [+ "just",+ "--justfile",+ str(ROOT / "justfile"),+ "--working-directory",+ str(checkout),+ "_source-tree",+ output.as_posix(),+ ]+ subprocess.run(command, check=True, capture_output=True, text=True)+ assert {+ p.relative_to(output).as_posix() for p in output.rglob("*") if p.is_file()+ } == {+ *inputs,+ "SOURCE_COMMIT",+ }+ assert {name: (output / name).read_bytes() for name in inputs} == inputs+ assert (output / "SOURCE_COMMIT").read_text(encoding="utf-8").strip() == revision+ (checkout / "justfile").write_bytes(b"uncommitted recipe\n")+ failed = subprocess.run(command, check=False, capture_output=True, text=True)+ assert failed.returncode != 0+ assert "Commit tracked changes" in failed.stderr+ assert (output / "justfile").read_bytes() == inputs["justfile"]+++def test_pending_publishers_have_distinct_environments() -> None:+ publishers = {"manimgx": JOBS["pypi"]["environment"]["name"]}+ fonts = JOBS["pypi-fonts"]+ assert fonts["environment"]["name"] == "${{ matrix.environment }}"+ for entry in fonts["strategy"]["matrix"]["include"]:+ assert entry["package"] not in publishers+ publishers[entry["package"]] = entry["environment"]++ # These are the identities registered on PyPI, including the first-release publishers.+ assert publishers == {+ "manimgx": "pypi",+ "manimgx-fonts": "pypi-fonts",+ "manimgx-fonts-cjk": "pypi-fonts-cjk",+ }+ assert len(set(publishers.values())) == len(publishers)+++def test_wheel_jobs_expand_platform_in_the_same_shell_on_every_os() -> None:+ wheel = yaml.safe_load(+ (ROOT / ".github/workflows/create-wheels.yaml").read_text(encoding="utf-8")+ )["jobs"]["wheel"]+ assert wheel["defaults"]["run"]["shell"] == "bash"+ build = next(step for step in wheel["steps"] if "PLATFORM" in step.get("env", {}))+ assert "${PLATFORM}" in build["run"]+++def test_native_and_embedded_browser_builds_require_the_committed_cargo_lock() -> None:+ project = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))+ assert project["tool"]["maturin"]["locked"] is True+ build = (ROOT / "rust/engine/build.rs").read_text(encoding="utf-8")+ assert '.args(["build", "--locked",' in build+++def test_windows_diagnostic_pairs_the_wheel_with_its_original_source() -> None:+ job = yaml.safe_load(+ (ROOT / ".github/workflows/windows-diagnostic.yaml").read_text(encoding="utf-8")+ )["jobs"]["diagnose"]+ steps = job["steps"]+ source = next(step for step in steps if step.get("id") == "source")+ checkout = next(+ step for step in steps if step.get("uses", "").startswith("actions/checkout@")+ )+ download = next(+ step+ for step in steps+ if step.get("uses", "").startswith("actions/download-artifact@")+ )+ assert source["env"]["WHEEL_RUN"] == download["with"]["run-id"]+ assert checkout["with"]["ref"] == "${{ steps.source.outputs.revision }}"+ assert ".head_sha" in source["run"]+ run = next(step for step in steps if "TEST_ARGS" in step.get("env", {}))+ assert 'shlex.split(os.environ["TEST_ARGS"])' in run["run"]+ assert "${{ inputs.testargs }}" not in run["run"]++[email protected]("package", ["manimgx-fonts", "manimgx-fonts-cjk"])+def test_font_artifacts_contain_only_their_own_package(+ package: str, tmp_path: Path+) -> None:+ dist = tmp_path / "dist"+ dist.mkdir()+ expected = set()+ for manifest in sorted((ROOT / "fonts").glob("*/pyproject.toml")):+ project = tomllib.loads(manifest.read_text(encoding="utf-8"))["project"]+ name = project["name"].replace("-", "_")+ version = project["version"]+ for suffix in [".tar.gz", "-py3-none-any.whl"]:+ filename = f"{name}-{version}{suffix}"+ (dist / filename).touch()+ if project["name"] == package:+ expected.add(filename)++ upload = next(+ step["with"]+ for step in JOBS["sdist"]["steps"]+ if step.get("with", {}).get("name") == package+ )+ assert expected+ assert {path.name for path in tmp_path.glob(upload["path"])} == expected++ download = next(+ step["with"]+ for step in JOBS["pypi-fonts"]["steps"]+ if step.get("uses", "").startswith("actions/download-artifact@")+ )+ assert download["name"] == "${{ matrix.package }}"+++def test_engine_publisher_excludes_fonts_and_github_only_artifacts() -> None:+ download = next(+ step["with"]+ for step in JOBS["pypi"]["steps"]+ if step.get("uses", "").startswith("actions/download-artifact@")+ )+ # The download action's brace alternatives select artifact names, not filenames.+ patterns = download["pattern"].strip("{}").split(",")+ wheels = {+ f"wheel-{entry['platform']}"+ for entry in yaml.safe_load(+ (ROOT / ".github/workflows/create-wheels.yaml").read_text(encoding="utf-8")+ )["jobs"]["wheel"]["strategy"]["matrix"]["include"]+ }+ artifacts = wheels | {+ "sdist",+ "source",+ "manimgx-fonts",+ "manimgx-fonts-cjk",+ "executable-linux-x86_64",+ }+ selected = {+ artifact+ for artifact in artifacts+ if any(fnmatchcase(artifact, pattern) for pattern in patterns)+ }+ assert selected == wheels | {"sdist"}+++def test_consumers_wait_for_the_font_packages() -> None:+ assert "pypi-fonts" in JOBS["pypi"]["needs"]+ for job in ["npm", "publish"]:+ assert "pypi" in JOBS[job]["needs"]+++def test_every_artifact_is_built_before_public_source_and_registry_uploads() -> None:+ def ancestors(name: str) -> set[str]:+ needs = JOBS[name].get("needs", [])+ parents = {needs} if isinstance(needs, str) else set(needs)+ return parents | {parent for item in parents for parent in ancestors(item)}++ builds = {"test", "wheels", "sdist", "executables", "npm-build", "docker-build"}+ assert builds <= ancestors("github-release")+ for publisher in ["pypi-fonts", "pypi", "npm", "docker"]:+ assert "github-release" in ancestors(publisher)+ public_source = "\n".join(+ step.get("run", "") for step in JOBS["github-release"]["steps"]+ )+ assert "--draft=false" in public_source+++def test_registry_uploads_use_built_artifacts_without_rebuilding() -> None:+ npm = JOBS["npm"]["steps"]+ assert any(step.get("with", {}).get("name") == "npm" for step in npm)+ assert not any("build-npm" in step.get("run", "") for step in npm)+ docker = JOBS["docker"]["steps"]+ assert any(step.get("with", {}).get("pattern") == "docker-*" for step in docker)+ command = "\n".join(step.get("run", "") for step in docker)+ assert "skopeo copy --all --preserve-digests" in command+ assert "docker buildx build" not in command+ image = (ROOT / "docker/Dockerfile").read_text(encoding="utf-8")+ release = image.split("FROM runtime AS release", 1)[1].split(+ "FROM runtime AS published", 1+ )[0]+ assert "--require-hashes --requirements /wheels/requirements.txt" in release+ assert "--no-deps /wheels/*.whl" in release++[email protected]("state", ["new", "identical", "different", "unauthorized"])+def test_npm_retry_requires_the_exact_tarball(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, state: str+) -> None:+ archive = tmp_path / "package.tgz"+ with tarfile.open(archive, "w:gz") as package:+ body = json.dumps({"name": "manimgx", "version": "0.1.0"}).encode()+ member = tarfile.TarInfo("package/package.json")+ member.size = len(body)+ package.addfile(member, io.BytesIO(body))+ integrity = (+ "sha512-"+ + base64.b64encode(hashlib.sha512(archive.read_bytes()).digest()).decode()+ )+ uploaded = []++ def run(command: list[str], **_options: object) -> subprocess.CompletedProcess[str]:+ if command[1] == "publish":+ uploaded.append(Path(command[2]).read_bytes())+ return subprocess.CompletedProcess(command, 0, "", "")+ assert command == ["npm", "view", "[email protected]", "dist.integrity", "--json"]+ if state == "new" and not uploaded:+ return subprocess.CompletedProcess(+ command, 1, '{"error":{"code":"E404"}}', ""+ )+ if state == "unauthorized":+ return subprocess.CompletedProcess(+ command, 1, '{"error":{"code":"E401"}}', ""+ )+ return subprocess.CompletedProcess(+ command, 0, json.dumps("other" if state == "different" else integrity), ""+ )++ monkeypatch.setattr(subprocess, "run", run)+ if state == "different":+ with pytest.raises(ValueError, match="different artifact bytes"):+ publish_npm.publish(archive)+ elif state == "unauthorized":+ with pytest.raises(RuntimeError, match="cannot inspect"):+ publish_npm.publish(archive)+ else:+ publish_npm.publish(archive)+ assert uploaded == ([archive.read_bytes()] if state == "new" else [])+++def test_release_smoke_records_decoded_audio_and_a_complete_versioned_take(+ tmp_path: Path,+) -> None:+ assert (ROOT / "rust/ffmpeg/tests/silence.opus").read_bytes() == smoke_test.OPUS+ # Docker and installed-wheel tests carry this script alone, outside the source tree.+ script = tmp_path / "smoke_test.py"+ script.write_bytes(Path(smoke_test.__file__).read_bytes())+ relocated = runpy.run_path(str(script))+ scene: dict[str, object] = {}+ exec(relocated["scene_source"](), scene)+ chunks: list[bytes] = []+ film = scene["Smoke"]().render(take=chunks.append) # ty: ignore[call-non-callable]+ take = b"".join(chunks)+ smoke_test.validate_take(take, film.frame_count)+ # A nonempty/truncated/failed take used to pass the artifact smoke gate.+ for bad in [take[:-6], take[:-1], take[:-1] + b"\x01"]:+ with pytest.raises((AssertionError, ValueError)):+ smoke_test.validate_take(bad, film.frame_count)++[email protected]("known", [0, 1, 2])+def test_linux_source_inventory_covers_every_library_that_was_bundled(+ tmp_path: Path, known: int+) -> None:+ wheel = tmp_path / "wheel.whl"+ with zipfile.ZipFile(wheel, "w") as archive:+ for name in ["libone.so", "libtwo.so"]:+ archive.writestr(f"manimgx.libs/{name}", b"library")+ archive.writestr(+ "manimgx.dist-info/sboms/auditwheel.cdx.json",+ json.dumps(+ {+ "components": [{"name": "manimgx"}]+ + [+ {+ "name": name,+ "version": "1.0-2.el8",+ "purl": f"pkg:rpm/almalinux/{name}@1.0-2.el8",+ }+ for name in ["one", "two"][:known]+ ]+ }+ ),+ )+ if known < 2:+ with pytest.raises(ValueError, match="every bundled library"):+ linux_sources.bundled_packages(wheel)+ else:+ assert linux_sources.bundled_packages(wheel) == {+ "one-1.0-2.el8",+ "two-1.0-2.el8",+ }+++def test_source_archive_waits_for_the_platform_builds_that_choose_its_sources() -> None:+ assert set(JOBS["sdist"]["needs"]) == {"wheels", "executables"}+ download = next(+ step["with"]+ for step in JOBS["sdist"]["steps"]+ if step.get("uses", "").startswith("actions/download-artifact@")+ )+ assert download["pattern"] == "sources-*"+++def test_executable_sources_reject_missing_and_changed_platform_archives(+ tmp_path: Path,+) -> None:+ pool = tmp_path / "python"+ pool.mkdir()+ shared = pool / "input"+ shared.write_bytes(b"actual common interpreter source")+ digest = create_executable.sha256(shared)+ shared = shared.rename(pool / digest)+ for platform in ("linux-x86_64", "linux-arm64", "macos-arm64", "windows-x86_64"):+ source = tmp_path / f"executable-{platform}"+ source.mkdir()+ archive = source / "pyapp.tar.xz"+ archive.write_bytes(b"the actual launcher sources and locked dependencies")+ (source / "python-inputs.tar.xz").write_bytes(archive.read_bytes())+ (source / "manifest.json").write_text(+ json.dumps(+ {+ "source_sha256": create_executable.sha256(archive),+ "python": {+ "inputs_sha256": create_executable.sha256(archive),+ "sources": {"cpython": {"sha256": digest}},+ },+ }+ ),+ encoding="utf-8",+ )+ if platform != "windows-x86_64":+ with pytest.raises(FileNotFoundError):+ create_executable.verify_sources(tmp_path)+ create_executable.verify_sources(tmp_path)+ shared.write_bytes(b"changed source")+ with pytest.raises(ValueError, match="retained Python source changed"):+ create_executable.verify_sources(tmp_path)+ shared.write_bytes(b"actual common interpreter source")+ python_inputs = source / "python-inputs.tar.xz"+ original = python_inputs.read_bytes()+ python_inputs.write_bytes(b"changed Python provenance")+ with pytest.raises(ValueError, match="retained Python inputs changed"):+ create_executable.verify_sources(tmp_path)+ python_inputs.write_bytes(original)+ archive.write_bytes(b"other sources")+ with pytest.raises(ValueError, match="retained source changed"):+ create_executable.verify_sources(tmp_path)+++def test_launcher_build_keeps_compiled_output_out_of_its_source_archive(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ source = tmp_path / "source"+ source.mkdir()+ (source / "Cargo.lock").write_text("locked sources", encoding="utf-8")++ def install(+ *command: str | Path,+ env: dict[str, str] | None = None,+ cwd: Path = ROOT,+ ) -> None:+ assert cwd == source+ assert env is not None+ target = Path(env["CARGO_TARGET_DIR"])+ assert not target.is_relative_to(source)+ assert env["PYAPP_PYTHON_VERSION"] == "3.14"+ assert "--offline" in command+ assert "--locked" in command+ target.mkdir()+ (target / "compiled.o").write_bytes(b"not source")+ binary = (+ tmp_path+ / "pyapp/bin"+ / ("pyapp.exe" if create_executable.WINDOWS else "pyapp")+ )+ binary.parent.mkdir(parents=True)+ binary.write_bytes(b"the built launcher")++ monkeypatch.setattr(create_executable, "run", install)+ executable = create_executable.build_pyapp(+ tmp_path / "python.tar.gz", "0.1.0", tmp_path, source+ )+ assert executable.read_bytes() == b"the built launcher"+ archive = tmp_path / "source.tar.xz"+ with tarfile.open(archive, "w:xz") as output:+ output.add(source, arcname="pyapp")+ with tarfile.open(archive) as packed:+ assert packed.getnames() == ["pyapp", "pyapp/Cargo.lock"]+++def test_launcher_vendoring_preserves_upstream_target_configuration(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ upstream = tmp_path / "upstream"+ (upstream / ".cargo").mkdir(parents=True)+ original = '[target.windows]\nrustflags = ["-C", "target-feature=+crt-static"]\n'+ (upstream / ".cargo/config.toml").write_text(original, encoding="utf-8")++ def download(*_args: object, **_kwargs: object) -> Path:+ with tarfile.open(tmp_path / create_executable.PYAPP_SHA256, "w:gz") as out:+ out.add(upstream, arcname=f"pyapp-{create_executable.PYAPP}")+ return tmp_path / create_executable.PYAPP_SHA256++ def vendor(command: list[str], *, cwd: Path, stdout: TextIO, check: bool) -> None:+ assert command == ["cargo", "vendor", "--locked", "vendor"]+ assert check+ assert (+ (cwd / ".cargo/config.toml")+ .read_text(encoding="utf-8")+ .startswith(original)+ )+ stdout.write('[source.crates-io]\nreplace-with = "vendored-sources"\n')++ monkeypatch.setattr(create_executable, "fetch", download)+ monkeypatch.setattr(create_executable.subprocess, "run", vendor)+ source = create_executable.launcher_sources(tmp_path)+ config = tomllib.loads((source / ".cargo/config.toml").read_text(encoding="utf-8"))+ assert config["target"]["windows"]["rustflags"] == [+ "-C",+ "target-feature=+crt-static",+ ]+ assert config["source"]["crates-io"]["replace-with"] == "vendored-sources"+++def test_source_archive_rejects_missing_platforms_and_changed_sources(+ tmp_path: Path,+) -> None:+ for machine in ["x86_64", "aarch64"]:+ directory = tmp_path / f"linux-{machine}"+ directory.mkdir()+ source = directory / "library-1.0.src.rpm"+ source.write_bytes(b"the verified source")+ (directory / "manifest.json").write_text(+ json.dumps(+ {+ "packages": [+ {+ "source": source.name,+ "sha256": linux_sources.digest(source),+ }+ ]+ }+ ),+ encoding="utf-8",+ )+ if machine == "x86_64":+ with pytest.raises(FileNotFoundError):+ linux_sources.verify(tmp_path)+ linux_sources.verify(tmp_path)+ source.write_bytes(b"a different source")+ with pytest.raises(ValueError, match="retained source changed"):+ linux_sources.verify(tmp_path)+++def test_a_wheel_without_bundled_distribution_libraries_has_no_source_rpms(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ wheel = tmp_path / "wheel.whl"+ with zipfile.ZipFile(wheel, "w") as archive:+ archive.writestr("manimgx/__init__.py", "")+ monkeypatch.setattr(+ linux_sources.platform, "freedesktop_os_release", lambda: {"ID": "almalinux"}+ )+ for machine in ["x86_64", "aarch64"]:+ monkeypatch.setattr(+ linux_sources.platform, "machine", lambda machine=machine: machine+ )+ linux_sources.collect(wheel, tmp_path)+ manifest = json.loads(+ (tmp_path / f"linux-{machine}" / "manifest.json").read_text(+ encoding="utf-8"+ )+ )+ assert manifest["packages"] == []+ assert manifest["sha256"] == linux_sources.digest(wheel)+ linux_sources.verify(tmp_path)++[email protected]("fault", ["", "version", "signature"])+def test_only_the_installed_librarys_verified_source_is_retained(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fault: str+) -> None:+ source = "libdrm-2.4.115-1.el8.src.rpm"+ wheel = tmp_path / "wheel.whl"+ wheel.write_bytes(b"the wheel")+ monkeypatch.setattr(+ linux_sources, "bundled_packages", lambda _: {"libdrm-2.4.115-1.el8"}+ )+ monkeypatch.setattr(linux_sources.platform, "machine", lambda: "aarch64")+ monkeypatch.setattr(+ linux_sources.platform, "freedesktop_os_release", lambda: {"ID": "almalinux"}+ )++ def output(*args: str) -> str:+ if "--checksig" in args:+ return "digests OK" if fault == "signature" else "digests signatures OK"+ assert args[-1] == "libdrm-2.4.115-1.el8"+ return f"libdrm 1 2.4.115 1.el8 aarch64 {source}"++ def download(+ command: list[str], *, check: bool+ ) -> subprocess.CompletedProcess[str]:+ assert check+ assert command[-1] == source.removesuffix(".rpm")+ filename = "libdrm-2.4.116.src.rpm" if fault == "version" else source+ (Path(command[-2]) / filename).write_bytes(b"the exact source RPM")+ return subprocess.CompletedProcess(command, 0)++ monkeypatch.setattr(linux_sources, "output", output)+ monkeypatch.setattr(linux_sources.subprocess, "run", download)+ store = tmp_path / "sources"+ if fault:+ with pytest.raises(+ ValueError, match=r"installed package's source|verified signature"+ ):+ linux_sources.collect(wheel, store)+ assert not list(store.rglob("*.rpm"))+ assert not list(store.rglob("manifest.json"))+ else:+ linux_sources.collect(wheel, store)+ archive = store / "linux-aarch64" / source+ manifest = json.loads(+ archive.with_name("manifest.json").read_text(encoding="utf-8")+ )+ assert manifest["sha256"] == linux_sources.digest(wheel)+ assert manifest["packages"] == [+ {+ "binary": "libdrm-1:2.4.115-1.el8.aarch64",+ "source": source,+ "sha256": linux_sources.digest(archive),+ }+ ]++[email protected]("target", create_executable.PYTHONS)[email protected]("failure", ["", "metadata", "notice", "unsafe"])+def test_standalone_python_retains_exact_input_metadata_and_every_declared_notice(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, target: str, failure: str+) -> None:+ system, machine = target.split("-", 1)+ monkeypatch.setattr(create_executable, "SYSTEM", system)+ monkeypatch.setattr(create_executable, "MACHINE", machine)+ triple, options, digest = create_executable.PYTHONS[target]+ metadata = {+ "python_version": create_executable.PYTHON,+ "target_triple": triple,+ "build_options": options,+ "license_path": "licenses/LICENSE.cpython.txt",+ "build_info": {+ "extensions": {+ "_zstd": [+ {+ "license_paths": ["licenses/LICENSE.zstd.txt"],+ }+ ]+ }+ },+ }+ if failure == "metadata":+ metadata["python_version"] = "3.14.0"+ elif failure == "notice":+ metadata["license_path"] = "licenses/LICENSE.missing.txt"+ elif failure == "unsafe":+ metadata["license_path"] = "../outside"+ original = json.dumps(metadata).encode()+ downloads = tmp_path / "fixtures"+ downloads.mkdir()++ def pack(name: str, files: dict[str, bytes]) -> Path:+ result = downloads / name+ with tarfile.open(result, "w:gz") as archive:+ for path, data in files.items():+ member = tarfile.TarInfo(path)+ member.size = len(data)+ archive.addfile(member, io.BytesIO(data))+ return result++ dependency = pack(+ "zstd", {"cpython-source-deps-zstd-1.5.7/LICENSE": b"actual zstd notice"}+ )+ recipe = {+ "zstd": {+ "version": "1.5.7",+ "url": "https://source.invalid/zstd",+ "sha256": "zstd",+ }+ }+ tcl_commit, tcl_sha = create_executable.PYTHON_WINDOWS_SOURCES["tcl"]+ tcl = pack(+ "tcl",+ {+ f"cpython-source-deps-{tcl_commit}/compat/zlib/LICENSE": b"actual Tcl zlib notice",+ f"cpython-source-deps-{tcl_commit}/libtommath/LICENSE": b"actual Tommath notice",+ },+ )+ source_inputs = {"zstd": {"url": recipe["zstd"]["url"], "sha256": "zstd"}}+ if system == "windows":+ source_inputs["tcl"] = {"url": "https://source.invalid/tcl", "sha256": tcl_sha}+ monkeypatch.setattr(+ create_executable, "python_sources", lambda _recipe: source_inputs+ )+ archives = {+ tcl_sha: tcl,+ digest: pack(+ "runtime",+ {+ "python/PYTHON.json": original,+ "python/install/bin/python3": b"runtime",+ "python/licenses/LICENSE.cpython.txt": b"actual Python notice",+ "python/build/compiled.o": b"not source, not runtime",+ },+ ),+ create_executable.PBS_SOURCE_SHA256: pack(+ "recipe",+ {+ f"python-build-standalone-{create_executable.PBS_COMMIT}/pythonbuild/downloads.json": json.dumps(+ recipe+ ).encode(),+ },+ ),+ "zstd": dependency,+ }++ def fetch(url: str, sha: str, directory: Path, *, source: bool = True) -> Path:+ assert source == (sha != digest)+ if not source:+ assert (+ f"{create_executable.PYTHON}+{create_executable.PBS_RELEASE}-{triple}-{options}"+ in url+ )+ directory.mkdir(parents=True, exist_ok=True)+ result = directory / sha+ result.write_bytes(archives[sha].read_bytes())+ return result++ monkeypatch.setattr(create_executable, "fetch", fetch)+ retained = tmp_path / "retained"+ if failure:+ with pytest.raises(+ ValueError,+ match={+ "metadata": "unexpected metadata",+ "notice": "omits declared notice",+ "unsafe": "unsafe Python notice path",+ }[failure],+ ):+ create_executable.install_python(tmp_path, retained)+ assert not (retained / "python-inputs.tar.xz").exists()+ return+ runtime, receipt = create_executable.install_python(tmp_path, retained)+ assert (runtime / "bin/python3").read_bytes() == b"runtime"+ assert not (runtime.parent / "build").exists()+ assert (runtime / "share/manimgx-python/PYTHON.json").read_bytes() == original+ assert (tmp_path / "PYTHON.json").read_bytes() == original+ notice = (tmp_path / "LICENSE-PYTHON").read_bytes()+ assert b"actual Python notice" in notice+ assert b"actual zstd notice" in notice+ assert receipt["sha256"] == digest+ assert (tmp_path / "python/zstd").read_bytes() == dependency.read_bytes()+ assert not (tmp_path / "python" / digest).exists()+ if system == "windows":+ assert b"actual Tcl zlib notice" in notice+ assert b"actual Tommath notice" in notice+ with tarfile.open(retained / "python-inputs.tar.xz") as archive:+ assert "python-inputs/python-build-standalone.tar.gz" in archive.getnames()+ assert "python-inputs/zstd.tar.gz" not in archive.getnames()+ assert not any(+ "install/" in name or "compiled.o" in name for name in archive.getnames()+ )+++def test_python_binary_acquisition_is_verified_and_never_retained_as_source(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("MANIMGX_SOURCES", str(tmp_path / "sources"))+ downloaded = tmp_path / "download"+ downloaded.write_bytes(b"verified input")+ digest = create_executable.sha256(downloaded)++ def run(+ *command: str | Path, env: dict[str, str] | None = None, cwd: Path = ROOT+ ) -> None:+ assert env is not None+ assert "MANIMGX_SOURCES" not in env+ assert command[-2:] == ("https://example.invalid/input", digest)+ (tmp_path / digest).write_bytes(downloaded.read_bytes())++ monkeypatch.setattr(create_executable, "run", run)+ assert (+ create_executable.fetch(+ "https://example.invalid/input", digest, tmp_path, source=False+ ).read_bytes()+ == b"verified input"+ )+ downloaded.write_bytes(b"changed input")+ with pytest.raises(ValueError, match="download changed"):+ create_executable.fetch(+ "https://example.invalid/input", digest, tmp_path, source=False+ )+++def test_executable_installs_authenticated_dependencies_before_local_artifacts(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ calls: list[tuple[str | Path, ...]] = []+ monkeypatch.setattr(create_executable, "run", lambda *args: calls.append(args))+ runtime, wheel = tmp_path / "python", tmp_path / "product.whl"+ create_executable.install_manimgx(runtime, wheel, tmp_path)+ export, dependencies, product = calls+ assert export[:2] == ("uv", "export")+ assert "--no-hashes" not in export+ assert "--no-emit-workspace" in export+ assert "--require-hashes" in dependencies+ assert "--no-deps" in dependencies+ assert "--requirements" in dependencies+ assert wheel not in dependencies+ assert "--no-deps" in product+ assert "--requirements" not in product+ assert product[-3:] == (+ wheel,+ ROOT / "fonts/manimgx-fonts",+ ROOT / "fonts/manimgx-fonts-cjk",+ )++[email protected]("changed", [False, True])+def test_uv_hash_gate_rejects_changed_dependency_bytes_before_installation(+ tmp_path: Path, changed: bool+) -> None:+ wheel = tmp_path / "audited_dependency-1.0-py3-none-any.whl"+ with zipfile.ZipFile(wheel, "w") as archive:+ archive.writestr("audited_dependency.py", "value = 'verified'\n")+ archive.writestr(+ "audited_dependency-1.0.dist-info/METADATA",+ "Metadata-Version: 2.1\nName: audited-dependency\nVersion: 1.0\n",+ )+ archive.writestr(+ "audited_dependency-1.0.dist-info/WHEEL",+ "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n",+ )+ archive.writestr("audited_dependency-1.0.dist-info/RECORD", "")+ digest = hashlib.sha256(wheel.read_bytes()).hexdigest()+ if changed:+ with zipfile.ZipFile(wheel, "a") as archive:+ archive.writestr("unexpected.py", "value = 'changed'\n")+ requirements = tmp_path / "requirements.txt"+ requirements.write_text(+ f"audited-dependency @ {wheel.as_uri()} --hash=sha256:{digest}\n",+ encoding="utf-8",+ )+ target = tmp_path / "installed"+ result = subprocess.run(+ [+ "uv",+ "pip",+ "install",+ "--target",+ str(target),+ "--no-index",+ "--no-deps",+ "--require-hashes",+ "--requirements",+ str(requirements),+ ],+ capture_output=True,+ text=True,+ check=False,+ )+ assert (result.returncode == 0) != changed, result.stdout + result.stderr+ assert (target / "audited_dependency.py").exists() != changed+ if changed:+ assert "Hash mismatch" in result.stderr++[email protected]("system", ["linux", "macos", "windows"])+def test_python_sources_follow_the_build_graph_not_alternative_license_entries(+ monkeypatch: pytest.MonkeyPatch, system: str+) -> None:+ monkeypatch.setattr(create_executable, "SYSTEM", system)+ keys = set(+ create_executable.PYTHON_COMMON_SOURCES+ + create_executable.PYTHON_UNIX_SOURCES+ + create_executable.PYTHON_LINUX_SOURCES+ ) | {"zlib-ng", "openssl-1.1"}+ recipe = {+ name: {"url": f"https://source.invalid/{name}", "sha256": name} for name in keys+ }+ sources = create_executable.python_sources(recipe)+ assert ("bdb" in sources) == (system == "linux")+ assert "openssl-1.1" not in sources+ assert "openssl-3.5" in sources+ assert ("zlib-ng" in sources) == (system == "windows")+ assert ("zlib" in sources) == (system == "linux")+ if system == "windows":+ assert sources["libffi"]["sha256"] != recipe["libffi"]["sha256"]+ assert "/16fad4855b3d8c03b5910e405ff3a04395b39a98" in sources["libffi"]["url"]+ assert "/53c758cbf2cc178b359abc03fdd912c5e66ed74f" in sources["tcl"]["url"]+ assert "/a6a5bee1ef4b526b0d11200c84bc02e85d8ecc83" in sources["tk"]["url"]+ else:+ assert sources["libffi"]["sha256"] == recipe["libffi"]["sha256"]