Repository navigation
refactor(container): share the PyNvVideoCodec install guard #15595
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
dmitry-tokarev-nv
merged 4 commits into
ai-dynamo:main
from
ericcurtin:ericcurtin/share-pynvvideocodec-guard
Oct 7, 2026
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
081bcfc
refactor(container): share the PyNvVideoCodec install guard
ericcurtin 73a310d
docs(container): shorten guard comments
ericcurtin 6e99032
test(container): drop empty-package guard case
ericcurtin 1d27fb1
fix(container): match denied codec families by prefix in the guard
ericcurtin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| """Install guard for PyNvVideoCodec, run beside the install in the runtime images. | ||
|
|
||
| PYTHONPATH=/tmp/compliance python3 -m compliance.check_pynvvideocodec --pinned 2.2.3 | ||
|
|
||
| The pin is passed in, not read from the requirements file, and a test asserts the | ||
| two agree. What counts as denied comes from policy/codec_policy.yaml. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
| import csv | ||
| import fnmatch | ||
| import glob | ||
| import os | ||
| import re | ||
| import sys | ||
| from importlib.metadata import distributions | ||
| from pathlib import Path | ||
|
|
||
| from .scan_codecs import CodecPolicy | ||
|
|
||
| DISTRIBUTION = "pynvvideocodec" | ||
| PACKAGE = "PyNvVideoCodec" | ||
| # An empty package directory passes the negative checks, so these must be present. | ||
| REQUIRED = ("libavformat", "libavutil") | ||
| DEFAULT_POLICY = Path(__file__).resolve().parent / "policy" / "codec_policy.yaml" | ||
|
|
||
|
|
||
| class GuardError(Exception): | ||
| """A check failed; the message is what the build log shows.""" | ||
|
|
||
|
|
||
| def _canonical(name: str | None) -> str: | ||
| return re.sub(r"[-_.]+", "-", name or "").lower() | ||
|
|
||
|
|
||
| def check(pinned: str, policy: CodecPolicy, path: list[str] | None = None) -> None: | ||
| """Raise GuardError unless exactly one pinned, policy-clean install is found. | ||
|
|
||
| ``path`` replaces sys.path as the place distributions are looked up. | ||
| """ | ||
| # All of sys.path, so a surviving base-image copy is counted too. | ||
| installed = [ | ||
| d | ||
| for d in distributions(**({} if path is None else {"path": path})) | ||
| if _canonical(d.metadata["Name"]) == DISTRIBUTION | ||
| ] | ||
| versions = sorted(d.version for d in installed) | ||
| print(f"{PACKAGE} distributions on sys.path:", versions) | ||
| if len(installed) != 1: | ||
| raise GuardError(f"expected exactly one {PACKAGE}, found {versions}") | ||
| if versions[0] != pinned: | ||
| raise GuardError( | ||
| f"{PACKAGE} is {versions[0]}, but the requirements file pins {pinned}" | ||
| ) | ||
|
|
||
| site = os.path.normpath(str(installed[0].locate_file(""))) | ||
| pkg = os.path.join(site, PACKAGE) | ||
| # Walked, not globbed: ``**`` skips hidden dirs such as auditwheel's ``.libs/``. | ||
| bundled = sorted( | ||
| os.path.relpath(os.path.join(d, f), pkg) | ||
| for d, _, files in os.walk(pkg) | ||
| for f in fnmatch.filter(files, "lib*.so*") | ||
| ) | ||
| print(f"{PACKAGE} bundles:", bundled) | ||
| for required in REQUIRED: | ||
| if not any(os.path.basename(n).startswith(required) for n in bundled): | ||
| raise GuardError( | ||
| f"{PACKAGE} bundles no {required}, so the checks below would " | ||
| f"pass vacuously; found {bundled}" | ||
| ) | ||
| denied = [n for n in bundled if policy.violates(Path(pkg, n).as_posix())] | ||
| if denied: | ||
| raise GuardError(f"{PACKAGE} bundles libraries the codec gate denies: {denied}") | ||
|
|
||
| # The tarball lands outside site-packages; its directory comes from the RECORD. | ||
| record = installed[0].read_text("RECORD") or "" | ||
| declared = [ | ||
| row[0] | ||
| for row in csv.reader(record.splitlines()) | ||
| if row and row[0].endswith((".tar.xz", ".tar.gz", ".tar.bz2")) | ||
| ] | ||
| if len(declared) != 1: | ||
| raise GuardError(f"expected one source tarball in the RECORD, found {declared}") | ||
| external = os.path.dirname(os.path.normpath(os.path.join(site, declared[0]))) | ||
| tarballs = sorted( | ||
| os.path.basename(p) for p in glob.glob(os.path.join(external, "ffmpeg-*.tar.*")) | ||
| ) | ||
| print("bundled FFmpeg source tarballs in", external, "->", tarballs) | ||
| if len(tarballs) != 1: | ||
| raise GuardError( | ||
| f"expected exactly one bundled FFmpeg source tarball, found {tarballs}" | ||
| ) | ||
|
|
||
|
|
||
| def main(argv: list[str] | None = None) -> int: | ||
| parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | ||
| parser.add_argument( | ||
| "--pinned", required=True, help="the version that must be installed" | ||
| ) | ||
| parser.add_argument("--policy", type=Path, default=DEFAULT_POLICY) | ||
| args = parser.parse_args(argv) | ||
| try: | ||
| check(args.pinned, CodecPolicy.load(args.policy)) | ||
| except GuardError as exc: | ||
| print(f"ERROR: {exc}", file=sys.stderr) | ||
| return 1 | ||
| return 0 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| sys.exit(main()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
157 changes: 157 additions & 0 deletions
157
container/compliance/tests/test_check_pynvvideocodec.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| """Tests for the PyNvVideoCodec install guard (compliance.check_pynvvideocodec). | ||
|
|
||
| Run from the repo root: | ||
|
|
||
| PYTHONPATH=container python -m pytest container/compliance/tests/test_check_pynvvideocodec.py | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
| import yaml | ||
| from compliance.check_pynvvideocodec import DEFAULT_POLICY, GuardError, check, main | ||
| from compliance.scan_codecs import CodecPolicy | ||
|
|
||
| pytestmark = [ | ||
| pytest.mark.pre_merge, | ||
| pytest.mark.post_merge, | ||
| pytest.mark.gpu_0, | ||
| pytest.mark.unit, | ||
| ] | ||
|
|
||
| PINNED = "2.2.3" | ||
| # The shipped policy, so a policy edit that changes a verdict fails here. | ||
| POLICY = CodecPolicy.load(DEFAULT_POLICY) | ||
| GOOD_LIBS = ("libavformat.so.61", "libavutil.so.59") | ||
|
|
||
|
|
||
| def _install( | ||
| root: Path, | ||
| *, | ||
| libs=GOOD_LIBS, | ||
| tarballs=("ffmpeg-7.1.tar.xz",), | ||
| declared=None, | ||
| version=PINNED, | ||
| name="PyNvVideoCodec", | ||
| ) -> Path: | ||
| """Lay out one wheel under ``root`` the way pip does; return its site dir.""" | ||
| site = root / "usr/local/lib/python3.12/dist-packages" | ||
| external = root / "usr/local/external/ffmpeg" | ||
| dist = site / f"{name}-{version}.dist-info" | ||
| dist.mkdir(parents=True) | ||
| (dist / "METADATA").write_text( | ||
| f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n" | ||
| ) | ||
| pkg = site / "PyNvVideoCodec" | ||
| pkg.mkdir(exist_ok=True) | ||
| for lib in libs: | ||
| (pkg / lib).parent.mkdir(parents=True, exist_ok=True) | ||
| (pkg / lib).write_bytes(b"\x7fELF") | ||
| external.mkdir(parents=True, exist_ok=True) | ||
| for tarball in tarballs: | ||
| (external / tarball).write_bytes(b"") | ||
| rows = declared if declared is not None else tarballs | ||
| (dist / "RECORD").write_text( | ||
| "".join(f"{os.path.relpath(external / t, site)},,\n" for t in rows) | ||
| ) | ||
| return site | ||
|
|
||
|
|
||
| def _check(*sites: Path, policy: CodecPolicy = POLICY) -> None: | ||
| check(PINNED, policy, [str(s) for s in sites]) | ||
|
|
||
|
|
||
| def test_a_clean_install_passes(tmp_path, capsys): | ||
| _check(_install(tmp_path)) | ||
| assert "libavformat.so.61" in capsys.readouterr().out | ||
|
|
||
|
|
||
| def test_a_version_other_than_the_pin_fails(tmp_path): | ||
| with pytest.raises(GuardError, match="pins 2.2.3"): | ||
| _check(_install(tmp_path, version="2.2.2")) | ||
|
|
||
|
|
||
| def test_a_second_distribution_fails(tmp_path): | ||
| # The base image's copy surviving beside the new one. | ||
| first = _install(tmp_path / "a") | ||
| second = _install(tmp_path / "b", version="2.1.0", name="pynvvideocodec") | ||
| with pytest.raises(GuardError, match="exactly one"): | ||
| _check(first, second) | ||
|
|
||
|
|
||
| def test_no_distribution_fails(tmp_path): | ||
| with pytest.raises(GuardError, match="exactly one"): | ||
| _check(tmp_path) | ||
|
|
||
|
|
||
| def test_a_second_ffmpeg_source_tarball_fails(tmp_path): | ||
| site = _install( | ||
| tmp_path, | ||
| tarballs=("ffmpeg-7.1.tar.xz", "ffmpeg-6.0.tar.xz"), | ||
| declared=("ffmpeg-7.1.tar.xz",), | ||
| ) | ||
| with pytest.raises(GuardError, match="exactly one bundled FFmpeg source tarball"): | ||
| _check(site) | ||
|
|
||
|
|
||
| def test_a_record_without_a_source_tarball_fails(tmp_path): | ||
| with pytest.raises(GuardError, match="source tarball in the RECORD"): | ||
| _check(_install(tmp_path, declared=())) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "lib", | ||
| [ | ||
| "libavcodec.so.61", | ||
| "libavcodec-1a2b3c4d.so.61", | ||
| "libavdevice.so.61", | ||
| "libavfilter.so.10", | ||
| "libswscale.so.8", | ||
| "libswresample.so.5", | ||
| "libpostproc.so.58", | ||
| "libx264.so.164", | ||
| "libx265.so.209", | ||
| "libfdk-aac.so.2", | ||
| ".libs/libx264-1a2b3c4d.so.164", | ||
|
dmitry-tokarev-nv marked this conversation as resolved.
Resolved
|
||
| ], | ||
| ) | ||
| def test_a_denied_library_fails(tmp_path, lib): | ||
| with pytest.raises(GuardError, match="denies"): | ||
| _check(_install(tmp_path, libs=(*GOOD_LIBS, lib))) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("libs", [(), ("libavformat.so.61",), ("libavutil.so.59",)]) | ||
|
ericcurtin marked this conversation as resolved.
Resolved
|
||
| def test_an_empty_or_partial_package_fails(tmp_path, libs): | ||
| # Both negative checks pass on a package that bundles nothing. | ||
| with pytest.raises(GuardError, match="bundles no"): | ||
| _check(_install(tmp_path, libs=libs)) | ||
|
|
||
|
|
||
| def test_the_waiver_is_scoped_to_the_package_directory(tmp_path): | ||
| # The policy waives libavutil beside the package, not a copy grafted elsewhere. | ||
| with pytest.raises(GuardError, match="denies"): | ||
| _check(_install(tmp_path, libs=(*GOOD_LIBS, ".libs/libavutil-1a2b3c4d.so.59"))) | ||
|
|
||
|
|
||
| def test_a_family_added_to_the_policy_reaches_the_guard(tmp_path): | ||
| site = _install(tmp_path, libs=(*GOOD_LIBS, "libfoo.so.1")) | ||
| _check(site) | ||
| doc = yaml.safe_load(DEFAULT_POLICY.read_text(encoding="utf-8")) | ||
| doc["deny_globs"].append("**/libfoo.so*") | ||
| edited = tmp_path / "policy.yaml" | ||
| edited.write_text(yaml.safe_dump(doc), encoding="utf-8") | ||
| with pytest.raises(GuardError, match="libfoo"): | ||
| _check(site, policy=CodecPolicy.load(edited)) | ||
|
|
||
|
|
||
| def test_main_exit_codes(tmp_path, monkeypatch, capsys): | ||
| site = _install(tmp_path) | ||
| monkeypatch.setattr("sys.path", [str(site)]) | ||
| assert main(["--pinned", PINNED]) == 0 | ||
| assert main(["--pinned", "9.9.9"]) == 1 | ||
| assert "ERROR:" in capsys.readouterr().err | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.