Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions container/compliance/check_pynvvideocodec.py
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())]
Comment thread
dmitry-tokarev-nv marked this conversation as resolved.
Resolved
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())
6 changes: 6 additions & 0 deletions container/compliance/scan_codecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,12 @@ def classify(self, abspath: str) -> tuple[str, str | None]:
return "exception", (exc.get("reason") or "").strip()
return "violation", None

def violates(self, abspath: str) -> bool:
"""True if `abspath` hits a deny glob and is neither allowed nor excepted."""
if _matches_any(abspath, self.deny_globs) is None:
return False
return self.classify(abspath)[0] == "violation"


def scan_filesystem(root: Path, policy: CodecPolicy):
"""Walk `root`, returning (violations, exceptions, allowed) lists of dicts."""
Expand Down
157 changes: 157 additions & 0 deletions container/compliance/tests/test_check_pynvvideocodec.py
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",
Comment thread
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",)])
Comment thread
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
91 changes: 4 additions & 87 deletions container/templates/sglang_runtime.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -191,93 +191,10 @@ RUN --mount=type=bind,source=./container/deps/requirements.sglang.txt,target=/tm
pip install --break-system-packages --force-reinstall --no-deps \
--requirement /tmp/requirements.sglang.txt

# Assert what the install left. The upstream SGLang image ships no
# PyNvVideoCodec, so nothing is removed first -- but that is a property of the
# current base rather than a guarantee, and checking the result is what keeps it
# honest. PINNED is duplicated from the requirements file deliberately: this stage
# must not parse the file it is checking; a test asserts the two agree.
RUN python3 - <<'PYEOF'
import csv
import glob
import os
import re
import sys
from importlib.metadata import distributions

PINNED = "2.2.3"
NAME = "pynvvideocodec"
# Mirrors the deny globs in container/compliance/policy/codec_policy.yaml. Kept as
# families rather than the four this package happens to have shed, so a future
# release vendoring libpostproc or libx264 is caught here -- beside the install
# that introduced it -- instead of as an unattributed scan violation later.
DENIED = (
"libavcodec",
"libavdevice",
"libavfilter",
"libswscale",
"libswresample",
"libpostproc",
"libx264",
"libx265",
"libfdk-aac",
)


def canonical(name):
return re.sub(r"[-_.]+", "-", name or "").lower()


# Enumerated over sys.path rather than one scheme directory: these images carry
# both /usr/local/lib/python3.12/dist-packages and /usr/lib/python3/dist-packages,
# and the wheel declares Root-Is-Purelib: false, so neither purelib nor platlib
# alone is guaranteed to be the install target or the only place a copy can hide.
# A surviving base copy beside the new one is the failure being looked for, which
# is also why this counts distributions instead of asking for one version.
installed = [d for d in distributions() if canonical(d.metadata["Name"]) == NAME]
versions = sorted(d.version for d in installed)
print("PyNvVideoCodec distributions on sys.path:", versions)
if len(installed) != 1:
sys.exit(f"ERROR: expected exactly one PyNvVideoCodec, found {versions}")
if versions[0] != PINNED:
sys.exit(f"ERROR: PyNvVideoCodec is {versions[0]}, but the requirements file "
f"pins {PINNED}")

site = os.path.normpath(str(installed[0].locate_file("")))
pkg = os.path.join(site, "PyNvVideoCodec")
bundled = sorted(
os.path.relpath(p, pkg)
for p in glob.glob(os.path.join(pkg, "**", "lib*.so*"), recursive=True)
)
print("PyNvVideoCodec bundles:", bundled)
# Positive first, and on both libraries: an empty package directory satisfies
# every negative check below while shipping no demuxer at all.
for required in ("libavformat", "libavutil"):
if not any(os.path.basename(n).startswith(required) for n in bundled):
sys.exit(
f"ERROR: PyNvVideoCodec bundles no {required}, so the checks below "
f"would pass vacuously; found {bundled}"
)
denied = [n for n in bundled if os.path.basename(n).startswith(DENIED)]
if denied:
sys.exit(f"ERROR: PyNvVideoCodec bundles libraries the codec gate denies: {denied}")

# The FFmpeg source tarball lands outside site-packages, so its directory is read
# from the wheel's own RECORD rather than guessed from a sysconfig path -- the
# RECORD is what the installer actually wrote, and it moves if the layout does.
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:
sys.exit(f"ERROR: 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:
sys.exit(f"ERROR: expected exactly one bundled FFmpeg source tarball, found {tarballs}")
PYEOF
# Assert what the install left. The pin is repeated from the requirements file
# on purpose; a test asserts the two agree.
RUN --mount=type=bind,source=./container/compliance,target=/tmp/compliance/compliance \
PYTHONPATH=/tmp/compliance python3 -m compliance.check_pynvvideocodec --pinned 2.2.3
{% else %}
# mooncake and PyNvVideoCodec are CUDA-only. The mooncake floor names the CUDA 13
# distribution, and PyNvVideoCodec decodes on NVDEC through libnvcuvid, so both
Expand Down
Loading
Loading