← Back to Pull requests

cuslide2: make `pip install cucim-cu13` work and add tests for this #1219

Merged
grlee77 merged 8 files (320 lines) on Nov 19, 2026 23:12 UTC
View on GitHub
grlee77 grlee77 commented on Nov 09, 2026 17:45 UTC
Author

Summary

closes #1211

With cuCIM installed from PyPI, the cuslide2 plugin (ENABLE_CUSLIDE2=1) does not work as the
README describes:

1. libnvimgcodec is not found. CuImage(path) raises dlopen libnvimgcodec.so failed! for
every TIFF, although nvidia-nvimgcodec-cu13 is installed. That wheel puts libnvimgcodec.so.0
in site-packages/nvidia/nvimgcodec/. The plugin only calls dlopen with bare library names,
and its RPATH (rewritten by auditwheel to cucim_cu13.libs) does not include that directory.
2. nvJPEG2000 and nvTIFF are not installed. cuCIM requires the nvImageCodec wheel without its
optional extras. When nvImageCodec cannot load nvTIFF and nvJPEG2000 ("Failed to load nvtiff
library!"), cuslide2 reads the wrong pyramid for every TIFF (extra levels for the macro,
thumbnail and label images; tile sizes of (0, 0)), returns all-zero regions without an
error
for Aperio JPEG 2000 (compression 33003) and standard JPEG 2000 (34712) images, and
raises an error for Aperio RGB JPEG 2000 (33005).
3. The README and the test scripts do not work with pip installs, and the scripts report success
on zero-filled images.

Tested with cucim-cu13==26.10.0 from PyPI in a fresh virtual environment (Python 3.13,
nvidia-nvimgcodec-cu13==0.9.0.20), and with the nightly 26.12.0a34 wheel, which behaves the same
way. With nvidia-nvimgcodec-cu13[nvjpeg2k,nvtiff] and the library directory on LD_LIBRARY_PATH,
the same files are read correctly (the same pyramids, tile sizes and region means as the legacy
plugin).

Changes

1. Depend on the nvImageCodec extras (dependencies.yaml, regenerated pyproject.toml):
nvidia-nvimgcodec-cu12/-cu13[nvjpeg,nvjpeg2k,nvtiff]>=0.9.0,<0.10.0. Constraints files cannot
contain extras, so they keep the plain requirement.
2. Find libnvimgcodec in the pip package (nvimgcodec_wrap.cc). The default search (system,
conda, LD_LIBRARY_PATH) is tried first, as before. If it fails, the plugin also tries
<directory of the plugin>/../../nvidia/nvimgcodec/, which is where the pip package is relative
to site-packages/cucim/clara/. The error message now lists every path that was tried and names
the pip and conda packages. The warning about missing TIFF tags now mentions the nvTIFF and
nvJPEG2000 libraries.
3. Tests on synthetic images (python/cucim/tests/unit/clara/test_cuslide2_plugin.py).
Pyramidal, tiled RGB TIFF files are written with tifffile (Deflate, LZW, JPEG, JPEG 2000), so no
sample data is downloaded. In a new process with ENABLE_CUSLIDE2=1, each test checks the level
count, level dimensions and tile sizes, and that regions read on the CPU and on the GPU match the
source image (exactly for the lossless codecs, within a small mean error for the lossy ones) and
are not all zero. The tests are skipped only if the package has no cuslide2 plugin. If it has
one, a missing nvImageCodec, nvTIFF or nvJPEG2000 library is a test failure.
4. README and scripts. The README lists the requirements for cuslide2 with pip.
scripts/test_common.py used only the plugin directory of a source build (so the scripts failed
with pip and conda installs); it now falls back to the installed package. The scripts now fail on
tile sizes of (0, 0) (before: "skipping caching assertions") and on all-zero decoded tiles
(before, GPU and CPU both returned zeros and matched).

Testing

  • The new tests pass (4 passed) against a source build with the nvImageCodec, nvJPEG2000, nvTIFF and

  • nvJPEG libraries. With nvJPEG2000 and nvTIFF removed from the library path, they fail: no TIFF
    tags are returned, and read_region raises Failed to decode IFD[0] with nvImageCodec.
  • The library lookup was checked on its own: nvimgcodec_wrap.cc was compiled with

  • -Wall -Wextra -Werror into a shared object placed in a layout like site-packages/cucim/clara/
    next to site-packages/nvidia/nvimgcodec/ (from the nvidia-nvimgcodec-cu13 wheel), with no
    LD_LIBRARY_PATH. It loads the library through the new fallback, and with the nvidia directory
    removed it fails with the message that lists the paths.

    Not in this PR

  • The plugin still returns zeros without an error for a JPEG 2000 file when a decoder is missing and

  • nvImageCodec reports success after the per-tile failures. The extras remove the cause for pip
    installs; checking that a decoder is registered before decoding is left for a later change.
  • cuslide2 cannot read strip-based JPEG associated images (the Philips TIFF macro image).
  • Diff: 320 lines (+290 / -30) across 8 files Reviewer: gforsyth Review duration: 14727m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.48) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.48 · 320 lines diff across 8 files
    0.48
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.86 · 5 substantive comment(s)
    0.86
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    84%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.345
    Real PR Conversation Timeline
    11 items
    jakirkham jakirkham commented on code on Nov 10, 2026 19:09 UTC
    Code Review
    README.md:1
    @@ -115,8 +115,29 @@ To enable the cuslide2 plugin, set the `ENABLE_CUSLIDE2` environment variable:
     ENABLE_CUSLIDE2=1 python your_script.py
     ```
     
    +### Requirements
    +
    +The plugin decodes with [nvImageCodec](https://developer.nvidia.com/nvimagecodec)
    +(`>=0.9.0,<0.10.0`) and needs its nvJPEG2000 and nvTIFF libraries to read JPEG 2000
    +and TIFF files, in addition to nvJPEG for JPEG.
    +
    +- **pip:** `pip install cucim-cu13` (or `cucim-cu12`) installs
    +  `nvidia-nvimgcodec-cu13[nvjpeg,nvjpeg2k,nvtiff]` (`-cu12` for CUDA 12). The plugin
    +  finds the nvImageCodec library in the `nvidia/nvimgcodec` directory of
    +  `site-packages`, and `LD_LIBRARY_PATH` does not have to be set. If you
    +  installed `nvidia-nvimgcodec-cu13` without these extras, install them with
    +  `pip install "nvidia-nvimgcodec-cu13[nvjpeg,nvjpeg2k,nvtiff]"`. Without them,
    +  nvImageCodec prints `Failed to load nvtiff library!` or
    +  `Failed to load nvjpeg2k library!`, and cuslide2 reports the wrong number of
    +  levels and tile sizes of `(0, 0)` or fails to read JPEG 2000 files.

    Should we note this is true for Conda as well?

    gigony gigony commented on code on Nov 16, 2026 07:49 UTC
    Code Review
    scripts/test_common.py:1
    @@ -37,12 +37,27 @@ def setup_environment(config_name: str = "cucim_test") -> str:
             Plugin library path as a string.
         """
         repo_root = Path(__file__).parent.parent
    -    plugin_lib = (
    -        repo_root / "cpp" / "plugins" / "cucim.kit.cuslide2" / "build-release" / "lib"
    -    )
     
    -    if not plugin_lib.exists():
    -        plugin_lib = repo_root / "install" / "lib"
    +    # Use the plugin of a source build of this repository if there is one.
    +    # Otherwise (pip or conda install) use the directory of the installed
    +    # package that provides the plugins.
    +    plugin_lib = None
    +    for candidate in (
    +        repo_root / "cpp" / "plugins" / "cucim.kit.cuslide2" / "build-release" / "lib",
    +        repo_root / "install" / "lib",
    +    ):
    +        if list(candidate.glob("cucim.kit.cuslide2@*.so")):
    +            plugin_lib = candidate
    +            break
    +    if plugin_lib is None:
    +        from cucim.clara import _get_plugin_root
    +
    +        plugin_lib = Path(_get_plugin_root())

    [P2-1] Locate the installed plugin before importing cuCIM

    AI-assisted review comment (finding 1/2).

    With a pip or conda install and no source-built plugin, the documented python scripts/test_aperio_svs.py --download command reaches this new import before setup_environment() writes CUCIM_CONFIG_PATH. Loading cucim.clara loads the native library, whose static CuImage::config_ reads the configuration immediately. The later environment update cannot select cuslide2, so this script can exercise the legacy plugin while reporting a cuslide2 test. Please locate the installed package without importing cuCIM, then complete plugin configuration before the first import.

    Validation: The exact helper confirmed the import/configuration order with an import recorder. Native initialization order was verified in source. The proposed patch passed git apply --check, Python syntax checks, and isolated default/enable-flag selection probes. Full cuCIM and GPU execution remain unrun.

    <details>
    <summary>Detailed reasoning, proposed patch, and regression coverage</summary>

    Evidence

    The new installed-package branch is scripts/test_common.py:52-60. The configuration file and environment variable are created later at scripts/test_common.py:84-98. The default download command is documented at README.md:145-149.

    The Python package imports its native extension at python/cucim/src/cucim/clara/__init__.py:9-10. The load-time configuration object is initialized at cpp/src/cuimage.cpp:147-151, and its constructor reads the file and environment at cpp/src/config/config.cpp:24-43. Image initialization later uses that stored plugin list at cpp/src/cuimage.cpp:1068-1071.

    The exact Python helper was executed with a fake installed plugin and a recorder at the cucim.clara import boundary. Without the enable flag, all three selection variables were absent at import. Only after the import did the helper set CUCIM_CONFIG_PATH. Setting ENABLE_CUSLIDE2=1 before starting Python avoids this particular default-command failure. The source-build path does not introduce this early import.

    This is a new installed-package-path problem. The baseline helper did not import cuCIM while discovering the plugin directory.

    Original hunk

        if plugin_lib is None:
            from cucim.clara import _get_plugin_root
    
            plugin_lib = Path(_get_plugin_root())
            if not list(plugin_lib.glob("cucim.kit.cuslide2@*.so")):
                raise RuntimeError(
                    f"No cuslide2 plugin (cucim.kit.cuslide2@*.so) found in the "
                    f"installed cuCIM package ({plugin_lib}) or in a source build."
                )
    

    Suggested fix

    Resolve the top-level package location with find_spec("cucim"), which does not import this top-level package, then search its clara directory. Avoid find_spec("cucim.clara"), which would import the parent package. The proposal retains source-build precedence and the existing configuration logic. It assumes the package has not already been imported before this setup helper runs.

    --- a/scripts/test_common.py
    +++ b/scripts/test_common.py
    @@ -10,6 +10,7 @@
     import tempfile
     import time
     from importlib import metadata as importlib_metadata
    +from importlib.util import find_spec
     from pathlib import Path
     
     import numpy as np
    @@ -50,13 +51,19 @@
                 plugin_lib = candidate
                 break
         if plugin_lib is None:
    -        from cucim.clara import _get_plugin_root
    -
    -        plugin_lib = Path(_get_plugin_root())
    -        if not list(plugin_lib.glob("cucim.kit.cuslide2@*.so")):
    +        # Locate the package without importing cuCIM: its library reads the
    +        # plugin configuration at load time, before setup below is complete.
    +        spec = find_spec("cucim")
    +        package_dirs = [] if spec is None else spec.submodule_search_locations or []
    +        for package_dir in package_dirs:
    +            candidate = Path(package_dir) / "clara"
    +            if list(candidate.glob("cucim.kit.cuslide2@*.so")):
    +                plugin_lib = candidate
    +                break
    +        if plugin_lib is None:
                 raise RuntimeError(
    -                f"No cuslide2 plugin (cucim.kit.cuslide2@*.so) found in the "
    -                f"installed cuCIM package ({plugin_lib}) or in a source build."
    +                "No cuslide2 plugin (cucim.kit.cuslide2@*.so) found in the "
    +                "installed cuCIM package or in a source build."
                 )
     
         dist_version = None
    

    Regression coverage

    Run the script in a fresh interpreter with an installed plugin, no source build, and no selection environment variables. Verify that cuslide2 is selected before opening an image. Cover the default download command, an explicit enable flag, source-build discovery, and a missing installed plugin.

    </details>

    gigony gigony commented on code on Nov 16, 2026 07:49 UTC
    Code Review
    python/cucim/tests/unit/clara/test_cuslide2_plugin.py:1
    @@ -0,0 +1,154 @@
    +#
    +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
    +# SPDX-License-Identifier: Apache-2.0
    +#
    +
    +"""Basic tests of the cuslide2 plugin on synthetic TIFF files.
    +
    +The images are written with tifffile, so no sample data has to be downloaded.
    +The plugin is selected with ``ENABLE_CUSLIDE2=1``, which is read when the
    +plugins are loaded, so every check runs in a new Python process.
    +
    +The tests are skipped when the package has no cuslide2 plugin. If it is
    +present, it is expected to work: a missing nvImageCodec, nvJPEG2000 or nvTIFF
    +library is a failure, not a reason to skip.
    +"""
    +
    +import glob
    +import json
    +import os
    +import subprocess
    +import sys
    +import textwrap
    +
    +import numpy as np
    +import pytest
    +
    +tifffile = pytest.importorskip("tifffile")
    +imagecodecs = pytest.importorskip("imagecodecs")
    +
    +TILE = 128
    +SHAPE = (512, 640, 3)  # (height, width, channels) of the base level
    +
    +
    +def _has_cuslide2_plugin():
    +    from cucim.clara import _get_plugin_root
    +
    +    return bool(
    +        glob.glob(os.path.join(_get_plugin_root(), "cucim.kit.cuslide2@*.so"))
    +    )
    +
    +
    +pytestmark = pytest.mark.skipif(
    +    not _has_cuslide2_plugin(), reason="cucim.kit.cuslide2 is not installed"
    +)
    +
    +
    +def _make_image(shape=SHAPE):
    +    """A smooth, non-constant image (lossy codecs keep it within a few levels)."""
    +    h, w, c = shape
    +    y, x = np.mgrid[:h, :w]
    +    chans = [
    +        128 + 100 * np.sin(x / 37.0 + k) * np.cos(y / 53.0 - k)
    +        for k in range(c)
    +    ]
    +    return np.clip(np.stack(chans, axis=-1), 0, 255).astype(np.uint8)
    +
    +
    +def _write_pyramid(path, image, compression, compressionargs=None, n_levels=3):
    +    """Write a tiled, pyramidal (one reduced-resolution IFD per level) RGB TIFF."""
    +    with tifffile.TiffWriter(path) as tif:
    +        for level in range(n_levels):
    +            data = image[:: 2**level, :: 2**level]
    +            tif.write(
    +                data,
    +                photometric="rgb",
    +                tile=(TILE, TILE),
    +                compression=compression,
    +                compressionargs=compressionargs,
    +                subfiletype=0 if level == 0 else 1,
    +            )
    +
    +
    +# (id, compression, compressionargs, max mean absolute error)
    +CODECS = [
    +    ("deflate", "adobe_deflate", None, 0),
    +    ("lzw", "lzw", None, 0),
    +    ("jpeg", "jpeg", {"level": 95}, 4),
    +    ("jpeg2000", "jpeg2000", {"level": 0}, 1),
    +]
    +
    +_CHECK = textwrap.dedent(
    +    """
    +    import json, sys
    +    import numpy as np
    +    from cucim import CuImage
    +
    +    path = sys.argv[1]
    +    img = CuImage(path)
    +    res = img.resolutions
    +    out = {
    +        "level_count": res["level_count"],
    +        "level_dimensions": [list(d) for d in res["level_dimensions"]],
    +        "level_tile_sizes": [list(d) for d in res["level_tile_sizes"]],
    +        "regions": {},
    +    }
    +    for device in ("cpu", "cuda"):
    +        region = img.read_region((100, 70), (200, 150), level=0, device=device)
    +        if device == "cuda":
    +            import cupy as cp
    +            arr = cp.asnumpy(cp.asarray(region))
    +        else:
    +            arr = np.asarray(region)
    +        out["regions"][device] = arr.tolist()
    +    print("RESULT" + json.dumps(out))
    +    """
    +)
    +
    +
    +def _run_cuslide2(path):
    +    env = dict(os.environ, ENABLE_CUSLIDE2="1")

    [P2-2] Pin the subprocess to the cuslide2 plugin

    AI-assisted review comment (finding 2/2).

    If the caller exports CUCIM_PLUGINS=cucim.kit.cuslide@<version>.so, this subprocess inherits it. Config::override_from_envs() applies that explicit list after ENABLE_CUSLIDE2, so the test runs the legacy plugin even though cuslide2 is installed. Its metadata and pixel assertions do not identify the decoder. This can hide a broken cuslide2 installation. Please set CUCIM_PLUGINS to the discovered cuslide2 filename in the child environment.

    Validation: The actual C++ environment-selection method was compiled with minimal enclosing storage, and the exact Python launcher was checked with an intercepted subprocess. The proposed patch passed git apply --check, Python syntax checks, and an inherited-legacy-override probe. No GPU decoder was executed.

    <details>
    <summary>Detailed reasoning, proposed patch, and regression coverage</summary>

    Evidence

    The child environment is assembled at python/cucim/tests/unit/clara/test_cuslide2_plugin.py:109-116. The module's skip check only establishes that a cuslide2 file exists at python/cucim/tests/unit/clara/test_cuslide2_plugin.py:34-44. The assertions at python/cucim/tests/unit/clara/test_cuslide2_plugin.py:138-154 check output properties without proving which plugin produced them.

    The configuration implementation first translates the default plugin list for ENABLE_CUSLIDE2, then replaces that list from CUCIM_PLUGINS: cpp/src/config/config.cpp:173-220. A host executable compiled from that exact selection method chose cucim.kit.cuslide2@26.12.00.so with only the enable flag, and cucim.kit.cuslide@26.12.00.so when the legacy override was also present. The exact _run_cuslide2() function, with subprocess execution intercepted, forwarded both conflicting variables unchanged.

    The selection precedence is existing behavior. The new regression test fails to isolate itself from that supported override. This does not establish that current CI exports the conflicting variable, or that all four cases passed through the legacy decoder in this review.

    Original hunk

    def _run_cuslide2(path):
        env = dict(os.environ, ENABLE_CUSLIDE2="1")
        proc = subprocess.run(
            [sys.executable, "-c", _CHECK, str(path)],
            env=env,
            capture_output=True,
            text=True,
            timeout=600,
        )
    

    Suggested fix

    Select the actual installed cuslide2 filename explicitly in the child environment. The proposal rejects ambiguous installations containing multiple cuslide2 versions so the test cannot silently choose an arbitrary library.

    --- a/python/cucim/tests/unit/clara/test_cuslide2_plugin.py
    +++ b/python/cucim/tests/unit/clara/test_cuslide2_plugin.py
    @@ -107,7 +107,15 @@
     
     
     def _run_cuslide2(path):
    -    env = dict(os.environ, ENABLE_CUSLIDE2="1")
    +    from cucim.clara import _get_plugin_root
    +
    +    plugins = glob.glob(os.path.join(_get_plugin_root(), "cucim.kit.cuslide2@*.so"))
    +    assert len(plugins) == 1, f"Expected one cuslide2 plugin, found {plugins}"
    +    env = dict(
    +        os.environ,
    +        ENABLE_CUSLIDE2="1",
    +        CUCIM_PLUGINS=os.path.basename(plugins[0]),
    +    )
         proc = subprocess.run(
             [sys.executable, "-c", _CHECK, str(path)],
             env=env,
    

    Regression coverage

    Run with an inherited legacy CUCIM_PLUGINS value and verify that the child still selects cuslide2. Remove a cuslide2 codec dependency and confirm the new tests fail instead of falling back to the legacy plugin. Keep the normal clean-environment case.

    </details>

    gigony gigony commented on Nov 16, 2026 07:49 UTC
    Reviewer

    AI-assisted review comments for findings P2-1 and P2-2.

    gigony gigony commented on Nov 18, 2026 22:20 UTC
    Contributor

    Hi, @gforsyth. Could you please review conda-package-related change here?
    Thanks!

    gforsyth gforsyth approved these changes on Nov 19, 2026 14:01 UTC
    Approved Reviewer

    Approved these changes.

    grlee77 grlee77 commented on code on Nov 19, 2026 15:49 UTC
    Code Review
    scripts/test_common.py:1
    @@ -37,12 +37,27 @@ def setup_environment(config_name: str = "cucim_test") -> str:
             Plugin library path as a string.
         """
         repo_root = Path(__file__).parent.parent
    -    plugin_lib = (
    -        repo_root / "cpp" / "plugins" / "cucim.kit.cuslide2" / "build-release" / "lib"
    -    )
     
    -    if not plugin_lib.exists():
    -        plugin_lib = repo_root / "install" / "lib"
    +    # Use the plugin of a source build of this repository if there is one.
    +    # Otherwise (pip or conda install) use the directory of the installed
    +    # package that provides the plugins.
    +    plugin_lib = None
    +    for candidate in (
    +        repo_root / "cpp" / "plugins" / "cucim.kit.cuslide2" / "build-release" / "lib",
    +        repo_root / "install" / "lib",
    +    ):
    +        if list(candidate.glob("cucim.kit.cuslide2@*.so")):
    +            plugin_lib = candidate
    +            break
    +    if plugin_lib is None:
    +        from cucim.clara import _get_plugin_root
    +
    +        plugin_lib = Path(_get_plugin_root())

    Addressed in df1d5840. The helper now uses find_spec("cucim") to locate the installed package. It checks both the wheel and Conda plugin locations and sets up plugin selection before the first cuCIM import, so the default download command selects cuslide2 when the native library loads.

    grlee77 grlee77 commented on code on Nov 19, 2026 15:50 UTC
    Code Review
    python/cucim/tests/unit/clara/test_cuslide2_plugin.py:1
    @@ -0,0 +1,154 @@
    +#
    +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
    +# SPDX-License-Identifier: Apache-2.0
    +#
    +
    +"""Basic tests of the cuslide2 plugin on synthetic TIFF files.
    +
    +The images are written with tifffile, so no sample data has to be downloaded.
    +The plugin is selected with ``ENABLE_CUSLIDE2=1``, which is read when the
    +plugins are loaded, so every check runs in a new Python process.
    +
    +The tests are skipped when the package has no cuslide2 plugin. If it is
    +present, it is expected to work: a missing nvImageCodec, nvJPEG2000 or nvTIFF
    +library is a failure, not a reason to skip.
    +"""
    +
    +import glob
    +import json
    +import os
    +import subprocess
    +import sys
    +import textwrap
    +
    +import numpy as np
    +import pytest
    +
    +tifffile = pytest.importorskip("tifffile")
    +imagecodecs = pytest.importorskip("imagecodecs")
    +
    +TILE = 128
    +SHAPE = (512, 640, 3)  # (height, width, channels) of the base level
    +
    +
    +def _has_cuslide2_plugin():
    +    from cucim.clara import _get_plugin_root
    +
    +    return bool(
    +        glob.glob(os.path.join(_get_plugin_root(), "cucim.kit.cuslide2@*.so"))
    +    )
    +
    +
    +pytestmark = pytest.mark.skipif(
    +    not _has_cuslide2_plugin(), reason="cucim.kit.cuslide2 is not installed"
    +)
    +
    +
    +def _make_image(shape=SHAPE):
    +    """A smooth, non-constant image (lossy codecs keep it within a few levels)."""
    +    h, w, c = shape
    +    y, x = np.mgrid[:h, :w]
    +    chans = [
    +        128 + 100 * np.sin(x / 37.0 + k) * np.cos(y / 53.0 - k)
    +        for k in range(c)
    +    ]
    +    return np.clip(np.stack(chans, axis=-1), 0, 255).astype(np.uint8)
    +
    +
    +def _write_pyramid(path, image, compression, compressionargs=None, n_levels=3):
    +    """Write a tiled, pyramidal (one reduced-resolution IFD per level) RGB TIFF."""
    +    with tifffile.TiffWriter(path) as tif:
    +        for level in range(n_levels):
    +            data = image[:: 2**level, :: 2**level]
    +            tif.write(
    +                data,
    +                photometric="rgb",
    +                tile=(TILE, TILE),
    +                compression=compression,
    +                compressionargs=compressionargs,
    +                subfiletype=0 if level == 0 else 1,
    +            )
    +
    +
    +# (id, compression, compressionargs, max mean absolute error)
    +CODECS = [
    +    ("deflate", "adobe_deflate", None, 0),
    +    ("lzw", "lzw", None, 0),
    +    ("jpeg", "jpeg", {"level": 95}, 4),
    +    ("jpeg2000", "jpeg2000", {"level": 0}, 1),
    +]
    +
    +_CHECK = textwrap.dedent(
    +    """
    +    import json, sys
    +    import numpy as np
    +    from cucim import CuImage
    +
    +    path = sys.argv[1]
    +    img = CuImage(path)
    +    res = img.resolutions
    +    out = {
    +        "level_count": res["level_count"],
    +        "level_dimensions": [list(d) for d in res["level_dimensions"]],
    +        "level_tile_sizes": [list(d) for d in res["level_tile_sizes"]],
    +        "regions": {},
    +    }
    +    for device in ("cpu", "cuda"):
    +        region = img.read_region((100, 70), (200, 150), level=0, device=device)
    +        if device == "cuda":
    +            import cupy as cp
    +            arr = cp.asnumpy(cp.asarray(region))
    +        else:
    +            arr = np.asarray(region)
    +        out["regions"][device] = arr.tolist()
    +    print("RESULT" + json.dumps(out))
    +    """
    +)
    +
    +
    +def _run_cuslide2(path):
    +    env = dict(os.environ, ENABLE_CUSLIDE2="1")

    Addressed in df1d5840. The test launcher now sets CUCIM_PLUGINS to the absolute path of the discovered cuslide2 library in the child environment. This replaces any inherited legacy plugin selection. Discovery covers both wheel and Conda installs.

    gigony gigony approved these changes on Nov 19, 2026 22:25 UTC
    Approved Reviewer

    Thank you @grlee77 for the change!
    It looks good to me!

    grlee77 grlee77 commented on Nov 19, 2026 23:12 UTC
    Author

    /merge

    Reviewers
    Assignees
    grlee77 grlee77
    Labels
    risk: low confidence: 84.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 47.8% (MEDIUM) · Higher = larger blast radius
    47.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 84.7% · Lower = rushed or shallow review
    84.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.3% · Safe to merge
    7.3%
    Repository