← Back to Pull requests

cuslide2: add pyramidal OME-TIFF semantics and nvImageCodec 0.9 readiness #1122

Merged
cdinea merged 28 files (2561 lines) on Jul 30, 2026 17:44 UTC
View on GitHub
cdinea cdinea commented on Jul 22, 2026 05:18 UTC
Author

What this PR changes

  • Add decode correctness updates for multiplex OME-TIFF (dynamic GRAY/RGB and UINT8/UINT16 selection)

  • Add dedicated OME-XML parser module (ome_xml.h/.cpp)

  • Add multi-file OME fileset handling using TiffData companion-file references

  • Use OME channel names and physical spacing metadata where available

  • Relax RGB-only optimization guards in TIFF/IFD read paths

  • Add OME parser unit tests

  • Update nvImageCodec integration for 0.9.0 compatibility (version header + SONAME discovery order)

  • Report TIFF resolution from tags 282/283/296 instead of hardcoded defaults, including RATIONAL decoding

  • Preserve pyramid sub-resolution levels on OME files whose TiffData only references full-resolution planes

  • Return an all-background raster for regions that do not intersect the image, matching cuslide

  • Stop destroying the nvImageCodec decoder at process exit, which intermittently aborted in free()
  • Scope notes

  • Explicit multiplex selector API expansion is intentionally out of scope for this PR.
  • Validation

  • Built cucim.kit.cuslide2 successfully in the prepared build environment

  • Added OME parser tests and integrated into cuslide2_tests

  • pre-commit run --hook-stage manual --all-files passes

  • Unit tests and the pyramidal OME-TIFF script pass as shown below
  • Running the pyramidal OME-TIFF script

    # Build the plugin
    export CUDACXX=$CONDA_PREFIX/pkgs/cuda-toolkit/bin/nvcc
    ./run build_local all release $CONDA_PREFIX
    python -m pip install --editable python/cucim
    
    # Run the script against an OME-TIFF
    export ENABLE_CUSLIDE2=1
    python scripts/test_pyramidal_ome_tiff.py <path-to>/retina_large.ome.tiff --no-cache
    

    The script needs no GPU-specific flags: it decodes each region on both CPU and
    GPU and compares the results, so a GPU is required for the comparison checks to
    run rather than be skipped. Pass --no-cache to exercise the direct decode path
    instead of the tile cache.

    If you rebuild the C++ but see unchanged behavior under pytest, note that the
    Python package loads the plugin from python/cucim/src/cucim/clara/, not from
    cpp/plugins/cucim.kit.cuslide2/build-release/lib/. Re-running
    ./run build_local refreshes that copy.

    Expected output, multi-plane OME-TIFF

    retina_large.ome.tiff, 2 resolution levels, SizeC=2, SizeZ=64, uint16:

    🧪 Synthetic uint16 decode checks
      ✅ Metadata dtype is uint16 (bits=16, typestr=<u2)
      ✅ Level-0 uint16 patch matches source ((10, 10), dtype=uint16)
      ✅ High-bit values preserved (max=12345)
      ✅ Level-1 uint16 plane matches source ((64, 64), dtype=uint16)
      ✅ Synthetic uint16 decode path validated
    ======================================================================
    🔬 Testing pyramidal OME-TIFF with cuslide2
    ======================================================================
    📊 Image summary
      Shape: [1567, 2048, 2]
      Dtype: <cucim.clara.DLDataType code:DLUInt(1) bits:16 lanes:1>
      Levels: 2
      Level 0: 2048x1567 (downsample: 1.000x)
      Level 1: 256x195 (downsample: 8.018x)
      ✅ Input reported as uint16 — decode checks will enforce dtype
    🧬 OME metadata checks
      ✅ Found OME metadata block
      size_c=2, size_z=64, size_t=1
      channel_names_count=2
    📐 Pyramid geometry checks
      ✅ Pyramid dims are non-increasing and match reported downsamples (2 distinct resolution(s) over 2 level(s))
    🧪 Multi-level decode checks
      ✅ GPU and CPU level 0 decode are identical
      ✅ GPU and CPU level 1 decode are identical
    🎯 Plane selection checks (C/Z/T kwargs)
        ✅ GPU and CPU plane decode are identical      # C=0,Z=0,T=0
        ✅ GPU and CPU plane decode are identical      # C=1,Z=0,T=0
    🔄 Batch decode validation
      ✅ Batch decode GPU and CPU are identical
    ✅ Pyramidal OME-TIFF test completed
    

    Two details worth checking in that output. Levels: 2 confirms the pyramid
    sub-resolution survives: OME TiffData entries reference only the
    full-resolution planes, so mapping planes alone collapses the list to level 0 and
    makes level 1 unreachable through read_region(). And the run must end at
    ✅ Pyramidal OME-TIFF test completed with exit status 0; a trailing
    free(): invalid pointer / Aborted was the exit-time teardown crash fixed here,
    which reproduced on roughly one run in five.

    Expected output, non-OME pyramidal TIFF

    The same script accepts ordinary WSIs. Against CMU-1.tif the OME and plane
    checks report as skipped, which is correct for a file with no OME-XML:

      Levels: 7
      Level 0: 46592x33792 (downsample: 1.000x)
      Level 6: 624x432 (downsample: 76.444x)
    🧬 OME metadata checks
      ⚠️  OME metadata block not found in img.metadata
      ✅ Pyramid dims are non-increasing and match reported downsamples (7 distinct resolution(s) over 7 level(s))
      ✅ GPU and CPU level 0 decode are identical
      ✅ GPU and CPU level 6 decode are identical
    ⚠️  Skipping C/Z/T plane checks (size_c not available)
      ✅ Batch decode GPU and CPU are identical
    ✅ Pyramidal OME-TIFF test completed
    

    Note that per-axis downsample ratios differ on real WSIs, so the geometry check
    compares against the mean of the axis ratios rather than assuming a single factor.

    Unit tests

    cd python/cucim
    ENABLE_CUSLIDE2=1 python -m pytest tests/unit/clara/test_tiff_read_region.py -q
    

    ..........................                                               [100%]
    26 passed
    

    All 26 pass with cuslide2 enabled and with the default plugin. The three
    test_tiff_stripe_outside cases previously failed under cuslide2 with
    Failed to decode IFD[0] with nvImageCodec. ROI: (-48,-40) 16x16: nvImageCodec
    fills out-of-bounds pixels for a partially overlapping region, which is why
    boundary reads passed, but rejects a region that does not intersect the image at
    all.

    Diff: 2561 lines (+2233 / -328) across 28 files Reviewer: KyleFromNVIDIA Review duration: 12265m
    All Vouch review confidence checks passed
    Residual risk 0.18 = Change Risk (0.72) × (1 − Review Confidence (0.75)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 2561 lines diff across 28 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.51 · 5 substantive comment(s)
    0.51
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    75%
    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.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    52 items
    copy-pr-bot[bot] copy-pr-bot[bot] commented on Jul 22, 2026 05:18 UTC
    Bot

    This pull request requires additional validation before any workflows can run on NVIDIA's runners.

    Pull request vetters can view their responsibilities here.

    Contributors can view more details about this message here.

    KyleFromNVIDIA KyleFromNVIDIA commented on code on Jul 24, 2026 20:11 UTC
    Code Review
    VERSION:1
    @@ -1 +1 @@
    -26.08.00
    +26.10.00

    Please rebase your PR to avoid changes to VERSION, dependencies.yaml, and .github/workflows/*.yaml that update the version. This branch is targeting 26.08 and should not be merged with anything from main.

    KyleFromNVIDIA KyleFromNVIDIA requested changes on Jul 24, 2026 20:12 UTC
    Changes Requested Reviewer

    Requested changes.

    KyleFromNVIDIA KyleFromNVIDIA approved these changes on Jul 28, 2026 14:20 UTC
    Approved Reviewer

    Approved these changes.

    jakirkham jakirkham commented on Jul 28, 2026 18:15 UTC
    Contributor

    /ok to test 57aa61598203ec068971feb89ba37ac97547bfdd

    gigony gigony commented on code on Jul 29, 2026 04:55 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_tiff_parser.cpp:1
    @@ -351,7 +275,7 @@ NvImageCodecTiffParserManager::NvImageCodecTiffParserManager()
             exec_params.struct_next = nullptr;
             exec_params.device_allocator = nullptr;
             exec_params.pinned_allocator = nullptr;
    -        exec_params.max_num_cpu_threads = compute_max_decoder_threads();
    +        exec_params.max_num_cpu_threads = 0;

    I'm wondering why we're setting this to 0 now.

    gigony gigony commented on code on Jul 29, 2026 05:10 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_tiff_parser.cpp:1
    @@ -631,9 +589,11 @@ bool TiffFileParser::parse_tiff_structure()
             // Extract TIFF metadata using available methods
             extract_tiff_tags(ifd_info);
     
    -        // codec_name returns "tiff" (container format), not compression type.
    -        // Individual TIFF tags are queried via NVIMGCODEC_METADATA_KIND_TIFF_TAG,
    -        // and TIFF_TAG_LIST enumeration is available in v0.8.0+.
    +        // Current limitation (nvImageCodec v0.6.0):
    +        // - codec_name returns "tiff" (container format) not compression type
    +        // - Individual TIFF tags not exposed through metadata API
    +        // - Only vendor-specific metadata blobs available (MED_APERIO, MED_PHILIPS, etc.)
    +        //

    I am wondering if nvImageCodec v0.9 still has these limitation.

    gigony gigony commented on code on Jul 29, 2026 05:11 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_tiff_parser.cpp:1
    @@ -958,6 +931,13 @@ void TiffFileParser::extract_ifd_metadata(IfdInfo& ifd_info)
             }
         }
     
    +    // WORKAROUND for nvImageCodec 0.6.0: Philips TIFF metadata limitation
    +    // ========================================================================
    +    // nvImageCodec 0.6.0 does NOT expose:
    +    // 1. Individual TIFF tags (SOFTWARE, ImageDescription, etc.)
    +    // 2. Philips format detection for some files
    +    //
    +

    Is this still specific to nvImageCodec v0.9.0, or does the code also work with nvImageCodec v0.6.0?

    gigony gigony commented on code on Jul 29, 2026 05:23 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/types.h:1
    @@ -1,5 +1,5 @@
     /*
    - * SPDX-FileCopyrightText: Copyright (c) 2020-2026, NVIDIA CORPORATION.
    + * SPDX-FileCopyrightText: Copyright (c) 2020-2021, NVIDIA CORPORATION.

     * SPDX-FileCopyrightText: Copyright (c) 2020-2026, NVIDIA CORPORATION.
    

    gigony gigony approved these changes on Jul 29, 2026 05:25 UTC
    Approved Reviewer

    Thanks @cdinea for adding ome-tiff support!
    Overall, it looks good to me.

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 10:50 UTC
    Code Review
    cpp/cmake/deps/nvimgcodec.cmake:1
    @@ -6,6 +6,22 @@
     #
     
     if (NOT TARGET deps::nvimgcodec)
    +    set(NVIMGCODEC_SONAME_CANDIDATES
    +        "libnvimgcodec.so.0.9.0"
    +        "libnvimgcodec.so.0.8.0"

    In the conda yaml file you set requirements >= 0.9 for nvimagecodec. Why do we need 0.8 here then?

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 10:53 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/cmake/deps/nvimgcodec.cmake:1
    @@ -9,6 +9,22 @@ if (NOT TARGET deps::nvimgcodec)
         set(NVIMGCODEC_LIB_PATH "")
         set(NVIMGCODEC_INCLUDE_PATH "")
     
    +    set(NVIMGCODEC_SONAME_CANDIDATES
    +        "libnvimgcodec.so.0.9.0"
    +        "libnvimgcodec.so.0.8.0"

    Similar question as above. Also maybe the cmake structure can be simplified so nvimagecodec search is done in a single place? But this is a question for a future pull request

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:05 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_decoder.cpp:1
    @@ -285,7 +340,7 @@ bool decode_ifd_region_nvimgcodec(const IfdInfo& ifd_info,
     
             nvimgcodecCodeStreamView_t view{};
             view.struct_type = NVIMGCODEC_STRUCTURE_TYPE_CODE_STREAM_VIEW;
    -        view.struct_size = sizeof(nvimgcodecCodeStreamView_t);
    +        view.struct_size = offsetof(nvimgcodecCodeStreamView_t, limit_images);

    This doesn't look right. Why would we ask for offset of struct member instead of the whole struct size? And also limit_images was removed in 0.9 so I have no idea how is this working right now

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:08 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_decoder.cpp:1
    @@ -331,24 +386,24 @@ bool decode_ifd_region_nvimgcodec(const IfdInfo& ifd_info,
             output_image_info.struct_size = sizeof(nvimgcodecImageInfo_t);
             output_image_info.struct_next = nullptr;
     
    -        // Use UNCHANGED to preserve original format (RGB or grayscale)
    +        const DecodePixelSpec decode_spec = resolve_decode_pixel_spec(ifd_info);
    +        // Use UNCHANGED to preserve original planar packing and channel ordering.
             output_image_info.sample_format = NVIMGCODEC_SAMPLEFORMAT_I_UNCHANGED;
    -        output_image_info.color_spec = NVIMGCODEC_COLORSPEC_SRGB;
    +        output_image_info.color_spec = decode_spec.color_spec;
             output_image_info.chroma_subsampling = NVIMGCODEC_SAMPLING_NONE;
             output_image_info.num_planes = 1;
             output_image_info.buffer_kind = buffer_kind;
     
    -        uint32_t num_channels = ifd_info.num_channels > 0 ? ifd_info.num_channels : 3;
    -        size_t row_stride = width * num_channels;
    +        uint32_t num_channels = decode_spec.num_channels;
    +        size_t row_stride = width * num_channels * decode_spec.bytes_per_sample;

    This can overflow for large width, I would static cast widt to size_t if you store it in that type anyway

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:09 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_decoder.cpp:1
    @@ -623,9 +678,9 @@ std::vector<BatchDecodeResult> decode_batch_regions_nvimgcodec(
                 }
     
                 const auto& region = regions[i];
    -            // Use num_channels from IFD info, fallback to 3 (RGB)
    -            uint32_t num_channels = (ifd_info.num_channels > 0) ? ifd_info.num_channels : 3;
    -            size_t row_stride = region.width * num_channels;
    +            const DecodePixelSpec decode_spec = resolve_decode_pixel_spec(ifd_info);
    +            uint32_t num_channels = decode_spec.num_channels;
    +            size_t row_stride = region.width * num_channels * decode_spec.bytes_per_sample;

    The same overflow can happen here

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:10 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_tiff_parser.cpp:1
    @@ -54,7 +52,7 @@ namespace cuslide2::nvimgcodec
     // nvImageCodec extension path auto-detection
     // ============================================================================
     //
    -// Workaround for a known nvImageCodec pre-0.8.0 bug: when the library is installed
    +// Workaround for older nvImageCodec extension-path behavior: when the library is installed

    With this pull request you support only nvimagecodec 0.9, right? Is this workaround still needed? If yes please update the comment

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:13 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_tiff_parser.cpp:1
    @@ -66,8 +64,8 @@ namespace cuslide2::nvimgcodec
     //      NvimgcodecLoadSymbol() + dladdr() (not the stub address)
     //   3. Probes <lib_dir>/extensions/ and <lib_dir>/../extensions/
     //
    -// NOTE: nvImageCodec 0.8.0 fixes the extension search path for conda installs.
    -// This workaround is kept as a safety net for non-standard install layouts.
    +// Keep this path probe in place for compatibility across mixed environments,
    +// including older deployments where extension auto-discovery is incomplete.

    But the old have different API (e.g. limit_images in old view). And I didn't see any compile time checks for nvimagecodec macros, so I assume that the old nvimagecodec will no longer compile. I would either verify that it works with the old nvimagecodec, or drop the old code

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:17 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_tiff_parser.cpp:1
    @@ -360,21 +284,32 @@ NvImageCodecTiffParserManager::NvImageCodecTiffParserManager()
             exec_params.backends = nullptr;
     
             status = nvimgcodecDecoderCreate(instance_, &decoder_, &exec_params, nullptr);
    -
             if (status != NVIMGCODEC_STATUS_SUCCESS)
             {
    -            nvimgcodecInstanceDestroy(instance_);
    -            instance_ = nullptr;
    -            status_message_ = fmt::format("Failed to create decoder for metadata extraction (status: {})",
    -                                         static_cast<int>(status));
    -            #ifdef DEBUG
    -            fmt::print("⚠️  {}\n", status_message_);
    -            #endif // DEBUG
    -            return;
    +            // If CUDA initialization is unavailable (for example, no GPU device
    +            // in the current runtime), retry with CPU-only decoder so metadata
    +            // extraction and CPU decode paths can still run.

    What kind of metadata extraction do you want? In the cpu only env getting metadata connected to an image (size, datatype, color spec, etc) should work. But I don't think getting tiff tags would work, as this is done with nvtiff, which I assume need some cuda libs. But I will check with rest of the team and come back.

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:21 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/nvimgcodec_dynlink/nvimgcodec_version.h:1

    You should update to the full new headers, using old headers can easily cause a nontrivial bug.

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:33 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_tiff_parser.cpp:1
    @@ -631,9 +589,11 @@ bool TiffFileParser::parse_tiff_structure()
             // Extract TIFF metadata using available methods
             extract_tiff_tags(ifd_info);
     
    -        // codec_name returns "tiff" (container format), not compression type.
    -        // Individual TIFF tags are queried via NVIMGCODEC_METADATA_KIND_TIFF_TAG,
    -        // and TIFF_TAG_LIST enumeration is available in v0.8.0+.
    +        // Current limitation (nvImageCodec v0.6.0):
    +        // - codec_name returns "tiff" (container format) not compression type
    +        // - Individual TIFF tags not exposed through metadata API
    +        // - Only vendor-specific metadata blobs available (MED_APERIO, MED_PHILIPS, etc.)
    +        //

    We do support generic tags in the API, here is python example: https://docs.nvidia.com/cuda/nvimagecodec/samples/metadata.html#Generic-tiff-tag-reading
    iirc this was already supported in 0.8? Lev can know more details on this and how to querry the tags

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:36 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_tiff_parser.cpp:1
    @@ -750,6 +710,19 @@ bool TiffFileParser::parse_tiff_structure()
             #endif // DEBUG
         }
     
    +    if (ifd_infos_.empty())

    There is already error message in the else above - I would move the details from this error message there. I don't see a reason for having two similar error messages when the ifd_infos is empty. And having more details when only some ifd infos are missing would be great too

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:38 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/nvimgcodec/nvimgcodec_tiff_parser.cpp:1
    @@ -1005,7 +985,7 @@ void TiffFileParser::extract_tiff_tags(IfdInfo& ifd_info)
         }
     
         // ========================================================================
    -    // Direct TIFF Tag Retrieval by ID (nvImageCodec 0.7.0+)
    +    // nvImageCodec 0.7.0+: Direct TIFF Tag Retrieval by ID

    I would remove mentions for the old nvimagecodec (as the API is not compatible) and just keep the code for the newest version

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:56 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ifd.cpp:1
    @@ -191,11 +200,27 @@ IFD::IFD(TIFF* tiff, uint16_t index, const ::cuslide2::nvimgcodec::IfdInfo& ifd_
                 fmt::print("   Not tiled (strip-based or whole image)\n");
                 #endif
             }
    +
    +        if (!photo_str.empty())
    +        {
    +            try
    +            {
    +                photometric_ = static_cast<uint16_t>(std::stoul(photo_str));
    +            }
    +            catch (...)
    +            {
    +                // Keep fallback below.
    +            }
    +        }
         }
     
         // Set format defaults
         planar_config_ = cuslide::tiff::PLANARCONFIG_CONTIG;  // nvImageCodec outputs interleaved
    -    photometric_ = cuslide::tiff::PHOTOMETRIC_RGB;
    +    if (photometric_ == 0)
    +    {
    +        photometric_ = (samples_per_pixel_ == 1) ? cuslide::tiff::PHOTOMETRIC_MINISBLACK

    I would change the check to samples_per_pixel_ <= 2 - in case there is grayscale with alpha image (this is a rather rare case, but it doesn't cost us anything to implement

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 11:58 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ifd.cpp:1
    @@ -272,10 +298,11 @@ bool IFD::read([[maybe_unused]] const TIFF* tiff,
         const uint64_t location_len = request->location_len;
     
         uint32_t batch_size = request->batch_size;
    -    int32_t n_ch = samples_per_pixel_;
    +    int32_t n_ch = static_cast<int32_t>(std::max<uint32_t>(1, samples_per_pixel_));

    can samples_per_pixel ever be zero?

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 12:06 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ome_xml.cpp:1
    @@ -0,0 +1,171 @@
    +/*
    + * SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION.
    + * SPDX-License-Identifier: Apache-2.0
    + */
    +
    +#include "ome_xml.h"
    +
    +#include <algorithm>
    +#include <string_view>
    +
    +#include <pugixml.hpp>
    +
    +namespace cuslide::tiff::ome
    +{
    +
    +namespace
    +{
    +std::string_view local_name(const char* name)
    +{
    +    if (!name)
    +    {
    +        return {};
    +    }
    +    std::string_view value(name);
    +    auto pos = value.find(':');
    +    return (pos == std::string_view::npos) ? value : value.substr(pos + 1);
    +}
    +
    +pugi::xml_node find_child_by_local_name(const pugi::xml_node& node, std::string_view name)
    +{
    +    for (auto child : node.children())
    +    {
    +        if (local_name(child.name()) == name)
    +        {
    +            return child;
    +        }
    +    }
    +    return {};
    +}
    +} // namespace
    +
    +bool parse(const std::string& xml_text, Model* out_model, std::string* out_error)
    +{
    +    if (!out_model)
    +    {
    +        if (out_error)
    +        {
    +            *out_error = "Output model pointer is null";
    +        }
    +        return false;
    +    }
    +
    +    *out_model = Model{};
    +
    +    pugi::xml_document doc;
    +    pugi::xml_parse_result parsed = doc.load_string(xml_text.c_str());
    +    if (!parsed)
    +    {
    +        if (out_error)
    +        {
    +            *out_error = parsed.description();
    +        }
    +        return false;
    +    }
    +
    +    pugi::xml_node ome_node = doc.document_element();
    +    if (local_name(ome_node.name()) != "OME")
    +    {
    +        if (out_error)
    +        {
    +            *out_error = "XML root is not OME";
    +        }
    +        return false;
    +    }
    +
    +    pugi::xml_node image_node = find_child_by_local_name(ome_node, "Image");
    +    if (!image_node)
    +    {
    +        if (out_error)
    +        {
    +            *out_error = "OME Image node not found";
    +        }
    +        return false;
    +    }
    +
    +    pugi::xml_node pixels_node = find_child_by_local_name(image_node, "Pixels");
    +    if (!pixels_node)
    +    {
    +        if (out_error)
    +        {
    +            *out_error = "OME Pixels node not found";
    +        }
    +        return false;
    +    }
    +
    +    Model model;
    +    model.image_id = image_node.attribute("ID").as_string("");
    +    model.image_name = image_node.attribute("Name").as_string("");
    +
    +    Pixels pixels;
    +    pixels.size_x = pixels_node.attribute("SizeX").as_uint(0);
    +    pixels.size_y = pixels_node.attribute("SizeY").as_uint(0);
    +    pixels.size_c = std::max<uint32_t>(1, pixels_node.attribute("SizeC").as_uint(1));

    you already set the default value with as_uint(1). is the max still needed? If the xml has zero as size, maybe it should be left at that value?

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 12:08 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ome_xml.cpp:1
    @@ -0,0 +1,171 @@
    +/*
    + * SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION.
    + * SPDX-License-Identifier: Apache-2.0
    + */
    +
    +#include "ome_xml.h"
    +
    +#include <algorithm>
    +#include <string_view>
    +
    +#include <pugixml.hpp>
    +
    +namespace cuslide::tiff::ome
    +{
    +
    +namespace
    +{
    +std::string_view local_name(const char* name)
    +{
    +    if (!name)
    +    {
    +        return {};
    +    }
    +    std::string_view value(name);
    +    auto pos = value.find(':');
    +    return (pos == std::string_view::npos) ? value : value.substr(pos + 1);
    +}
    +
    +pugi::xml_node find_child_by_local_name(const pugi::xml_node& node, std::string_view name)
    +{
    +    for (auto child : node.children())
    +    {
    +        if (local_name(child.name()) == name)
    +        {
    +            return child;
    +        }
    +    }
    +    return {};
    +}
    +} // namespace
    +
    +bool parse(const std::string& xml_text, Model* out_model, std::string* out_error)
    +{
    +    if (!out_model)
    +    {
    +        if (out_error)
    +        {
    +            *out_error = "Output model pointer is null";
    +        }
    +        return false;
    +    }
    +
    +    *out_model = Model{};
    +
    +    pugi::xml_document doc;
    +    pugi::xml_parse_result parsed = doc.load_string(xml_text.c_str());
    +    if (!parsed)
    +    {
    +        if (out_error)
    +        {
    +            *out_error = parsed.description();
    +        }
    +        return false;
    +    }
    +
    +    pugi::xml_node ome_node = doc.document_element();
    +    if (local_name(ome_node.name()) != "OME")
    +    {
    +        if (out_error)
    +        {
    +            *out_error = "XML root is not OME";
    +        }
    +        return false;
    +    }
    +
    +    pugi::xml_node image_node = find_child_by_local_name(ome_node, "Image");
    +    if (!image_node)
    +    {
    +        if (out_error)
    +        {
    +            *out_error = "OME Image node not found";
    +        }
    +        return false;
    +    }
    +
    +    pugi::xml_node pixels_node = find_child_by_local_name(image_node, "Pixels");
    +    if (!pixels_node)
    +    {
    +        if (out_error)
    +        {
    +            *out_error = "OME Pixels node not found";
    +        }
    +        return false;
    +    }
    +
    +    Model model;
    +    model.image_id = image_node.attribute("ID").as_string("");
    +    model.image_name = image_node.attribute("Name").as_string("");
    +
    +    Pixels pixels;
    +    pixels.size_x = pixels_node.attribute("SizeX").as_uint(0);
    +    pixels.size_y = pixels_node.attribute("SizeY").as_uint(0);
    +    pixels.size_c = std::max<uint32_t>(1, pixels_node.attribute("SizeC").as_uint(1));
    +    pixels.size_z = std::max<uint32_t>(1, pixels_node.attribute("SizeZ").as_uint(1));
    +    pixels.size_t = std::max<uint32_t>(1, pixels_node.attribute("SizeT").as_uint(1));
    +    pixels.type = pixels_node.attribute("Type").as_string("");
    +    pixels.dimension_order = pixels_node.attribute("DimensionOrder").as_string("XYCZT");
    +
    +    if (auto attr = pixels_node.attribute("PhysicalSizeX"))
    +    {
    +        pixels.physical_size_x = attr.as_double();
    +        pixels.has_physical_size_x = true;
    +    }
    +    if (auto attr = pixels_node.attribute("PhysicalSizeY"))
    +    {
    +        pixels.physical_size_y = attr.as_double();
    +        pixels.has_physical_size_y = true;
    +    }
    +    pixels.physical_size_x_unit = pixels_node.attribute("PhysicalSizeXUnit").as_string("");
    +    pixels.physical_size_y_unit = pixels_node.attribute("PhysicalSizeYUnit").as_string("");
    +
    +    uint32_t channel_idx = 0;
    +    for (auto child : pixels_node.children())
    +    {
    +        const auto child_name = local_name(child.name());
    +        if (child_name == "Channel")
    +        {
    +            Channel channel;
    +            channel.index = channel_idx++;
    +            channel.id = child.attribute("ID").as_string("");
    +            channel.name = child.attribute("Name").as_string("");
    +            channel.samples_per_pixel = std::max<uint32_t>(1, child.attribute("SamplesPerPixel").as_uint(1));
    +            pixels.channels.emplace_back(std::move(channel));
    +        }
    +        else if (child_name == "TiffData")
    +        {
    +            TiffDataEntry entry;
    +            entry.ifd = child.attribute("IFD").as_uint(0);
    +            entry.first_c = child.attribute("FirstC").as_uint(0);
    +            entry.first_z = child.attribute("FirstZ").as_uint(0);
    +            entry.first_t = child.attribute("FirstT").as_uint(0);
    +            entry.plane_count = std::max<uint32_t>(1, child.attribute("PlaneCount").as_uint(1));
    +
    +            pugi::xml_node uuid_node = find_child_by_local_name(child, "UUID");
    +            if (uuid_node)
    +            {
    +                entry.uuid = uuid_node.child_value();
    +                entry.file_name = uuid_node.attribute("FileName").as_string("");
    +            }
    +
    +            pixels.tiff_data.emplace_back(std::move(entry));
    +        }
    +    }
    +
    +    if (pixels.size_x == 0 || pixels.size_y == 0)

    I would move this check up, where you read the size_x and y

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 12:10 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ome_xml.h:1
    @@ -0,0 +1,64 @@
    +/*
    + * SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION.
    + * SPDX-License-Identifier: Apache-2.0
    + */
    +
    +#pragma once
    +
    +#include <cstdint>
    +#include <string>
    +#include <vector>
    +
    +namespace cuslide::tiff::ome
    +{
    +
    +struct Channel
    +{
    +    uint32_t index = 0;
    +    std::string id;
    +    std::string name;
    +    uint32_t samples_per_pixel = 1;
    +};
    +
    +struct TiffDataEntry
    +{
    +    uint32_t ifd = 0;
    +    uint32_t first_c = 0;
    +    uint32_t first_z = 0;
    +    uint32_t first_t = 0;
    +    uint32_t plane_count = 1;
    +    std::string uuid;
    +    std::string file_name;
    +};
    +
    +struct Pixels
    +{
    +    uint32_t size_x = 0;
    +    uint32_t size_y = 0;
    +    uint32_t size_c = 1;
    +    uint32_t size_z = 1;
    +    uint32_t size_t = 1;
    +    std::string type;
    +    std::string dimension_order = "XYCZT";
    +    double physical_size_x = 0.0;
    +    double physical_size_y = 0.0;
    +    std::string physical_size_x_unit;
    +    std::string physical_size_y_unit;
    +    bool has_physical_size_x = false;
    +    bool has_physical_size_y = false;
    +    std::vector<Channel> channels;
    +    std::vector<TiffDataEntry> tiff_data;
    +};
    +
    +struct Model
    +{
    +    bool valid = false;
    +    Pixels pixels;
    +    std::string image_id;
    +    std::string image_name;
    +};
    +
    +bool parse(const std::string& xml_text, Model* out_model, std::string* out_error = nullptr);

    You always populate out_model - I would change its type from pointer to reference

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 12:15 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/tiff.cpp:1
    @@ -82,44 +70,30 @@ static void parse_string_array(const char* values, json& arr, PhilipsMetadataTyp
             {
                 if (text[next_pos - 1] != '\\')
                 {
    -                try
    -                {
    -                    std::string val(text.substr(pos + 1, next_pos - pos - 1));
    -                    switch (type)
    -                    {
    -                    case PhilipsMetadataType::IString:
    -                        arr.emplace_back(std::move(val));
    -                        break;
    -                    case PhilipsMetadataType::IDouble:
    -                        arr.emplace_back(std::stod(val));
    -                        break;
    -                    case PhilipsMetadataType::IUInt16:
    -                    case PhilipsMetadataType::IUInt32:
    -                    case PhilipsMetadataType::IUInt64:
    -                        arr.emplace_back(std::stoul(val));
    -                        break;
    -                    }
    -                }
    -                catch (const std::exception&)

    the exception will be propagated up when parsing fails. Is this expected? It will also mean that this function will return on the first error, rather than continuing and ignoring errors as it did before

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 12:18 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/tiff.cpp:1
    @@ -249,20 +221,13 @@ static std::string strip_string(const std::string& str)
         }
     }
     
    -static constexpr size_t kMaxImageDescriptionBytes = 1 * 1024 * 1024; // 1 MB
    -
     static void parse_aperio_svs_metadata(std::shared_ptr<IFD>& first_ifd, json& metadata)
     {
         (void)metadata;
         std::string& desc = first_ifd->image_description();
     
    -    if (desc.size() > kMaxImageDescriptionBytes)

    Why are you removing the limit now? And why was it needed before? Maybe you should just increase the limit?

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 12:20 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/tiff.cpp:1
    @@ -379,6 +344,8 @@ TIFF::TIFF(const cucim::filesystem::Path& file_path) : file_path_(file_path)
     
         // Initialize metadata container
         metadata_ = new json{};
    +    parser_file_hashes_.clear();
    +    parser_file_hashes_.push_back(file_handle_shared_ ? file_handle_shared_->hash_value : 0);

    can file_handle_shared_ ever be null? It looks like it is reset only if there is an error (and in that case, new exception is thrown after cleanup so this code won't be reached)

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 12:28 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/tiff.cpp:1
    @@ -548,19 +633,20 @@ void TIFF::resolve_vendor_format()
         {
             bool is_aperio = false;
     
    +        // Method 1: Check ImageDescription starts with "Aperio "
             auto& image_desc = first_ifd->image_description();
             std::string_view prefix("Aperio ");
    -        if (image_desc.size() >= prefix.size() &&
    -            std::mismatch(prefix.begin(), prefix.end(), image_desc.begin()).first == prefix.end())
    +        auto res = std::mismatch(prefix.begin(), prefix.end(), image_desc.begin());
    +        if (res.first == prefix.end())

    NIT: it looks like the res is only used in this if. So maybe you can just call missmatch().first as you did before?

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 12:29 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/tiff.cpp:1
    @@ -548,19 +633,20 @@ void TIFF::resolve_vendor_format()
         {
             bool is_aperio = false;
     
    +        // Method 1: Check ImageDescription starts with "Aperio "
             auto& image_desc = first_ifd->image_description();
             std::string_view prefix("Aperio ");
    -        if (image_desc.size() >= prefix.size() &&
    -            std::mismatch(prefix.begin(), prefix.end(), image_desc.begin()).first == prefix.end())
    +        auto res = std::mismatch(prefix.begin(), prefix.end(), image_desc.begin());
    +        if (res.first == prefix.end())
             {
                 is_aperio = true;
             }
     
    -        // Method 2: Check metadata_blobs for Aperio (MED_APERIO)
    +        // Method 2: Check metadata_blobs for Aperio (kind=5 in v0.8.0)
             if (!is_aperio && nvimgcodec_parser_)
             {
                 const auto& metadata_blobs = nvimgcodec_parser_->get_metadata_blobs(0);
    -            if (metadata_blobs.find(kMetadataKindMedAperio) != metadata_blobs.end())
    +            if (metadata_blobs.find(5) != metadata_blobs.end())  // MED_APERIO = 5

    IMO the old named constant were more readable, what was the reason for removing them?

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 12:32 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/tiff.cpp:1
    @@ -715,6 +805,208 @@ void TIFF::resolve_vendor_format()
         }
     }
     
    +void TIFF::_populate_ome_tiff_metadata(uint16_t ifd_count, void* metadata, std::shared_ptr<IFD>& first_ifd)
    +{
    +    (void)ifd_count;
    +    json* json_metadata = reinterpret_cast<json*>(metadata);
    +
    +    ome::Model model;
    +    std::string parse_error;
    +    if (!ome::parse(first_ifd->image_description(), &model, &parse_error) || !model.valid)
    +    {
    +        return;
    +    }
    +
    +    ome_size_c_ = std::max<int64_t>(1, model.pixels.size_c);

    you already set the size to at least 1 in the ome::parse, there is no need to repeat it here

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 12:34 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/ome_xml.h:1
    @@ -0,0 +1,64 @@
    +/*
    + * SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION.
    + * SPDX-License-Identifier: Apache-2.0
    + */
    +
    +#pragma once
    +
    +#include <cstdint>
    +#include <string>
    +#include <vector>
    +
    +namespace cuslide::tiff::ome
    +{
    +
    +struct Channel
    +{
    +    uint32_t index = 0;
    +    std::string id;
    +    std::string name;
    +    uint32_t samples_per_pixel = 1;
    +};
    +
    +struct TiffDataEntry
    +{
    +    uint32_t ifd = 0;
    +    uint32_t first_c = 0;
    +    uint32_t first_z = 0;
    +    uint32_t first_t = 0;
    +    uint32_t plane_count = 1;
    +    std::string uuid;
    +    std::string file_name;
    +};
    +
    +struct Pixels
    +{
    +    uint32_t size_x = 0;
    +    uint32_t size_y = 0;
    +    uint32_t size_c = 1;
    +    uint32_t size_z = 1;
    +    uint32_t size_t = 1;
    +    std::string type;
    +    std::string dimension_order = "XYCZT";
    +    double physical_size_x = 0.0;
    +    double physical_size_y = 0.0;
    +    std::string physical_size_x_unit;
    +    std::string physical_size_y_unit;
    +    bool has_physical_size_x = false;
    +    bool has_physical_size_y = false;
    +    std::vector<Channel> channels;
    +    std::vector<TiffDataEntry> tiff_data;
    +};
    +
    +struct Model
    +{
    +    bool valid = false;
    +    Pixels pixels;
    +    std::string image_id;
    +    std::string image_name;
    +};
    +
    +bool parse(const std::string& xml_text, Model* out_model, std::string* out_error = nullptr);

    Also in the main lib you always pass out_error. So maybe it can be changed to reference as well? Then you won't need the checks for nullptr. The only place where nullptr is passed is in a single test - but imo you can pass there a valid string

    mkepa-nv mkepa-nv commented on code on Jul 29, 2026 12:35 UTC
    Code Review
    cpp/plugins/cucim.kit.cuslide2/src/cuslide/tiff/tiff.cpp:1
    @@ -715,6 +805,208 @@ void TIFF::resolve_vendor_format()
         }
     }
     
    +void TIFF::_populate_ome_tiff_metadata(uint16_t ifd_count, void* metadata, std::shared_ptr<IFD>& first_ifd)
    +{
    +    (void)ifd_count;
    +    json* json_metadata = reinterpret_cast<json*>(metadata);
    +
    +    ome::Model model;
    +    std::string parse_error;
    +    if (!ome::parse(first_ifd->image_description(), &model, &parse_error) || !model.valid)
    +    {
    +        return;
    +    }
    +
    +    ome_size_c_ = std::max<int64_t>(1, model.pixels.size_c);
    +    ome_size_z_ = std::max<int64_t>(1, model.pixels.size_z);
    +    ome_size_t_ = std::max<int64_t>(1, model.pixels.size_t);
    +
    +    ome_channel_names_.clear();
    +    ome_channel_name_to_index_.clear();
    +    if (!model.pixels.channels.empty())
    +    {
    +        ome_channel_names_.reserve(model.pixels.channels.size());
    +        for (const auto& channel : model.pixels.channels)
    +        {
    +            std::string channel_name = channel.name.empty() ? fmt::format("C{}", channel.index) : channel.name;
    +            if (!ome_channel_name_to_index_.count(channel_name))
    +            {
    +                ome_channel_name_to_index_.emplace(channel_name, static_cast<int64_t>(ome_channel_names_.size()));
    +            }
    +            ome_channel_names_.emplace_back(std::move(channel_name));
    +        }
    +    }
    +    else

    Is this is a valid file if the channels are missing?

    mkepa-nv mkepa-nv requested changes on Jul 29, 2026 13:01 UTC
    Changes Requested Reviewer

    Requested changes.

    jakirkham jakirkham commented on Jul 29, 2026 21:30 UTC
    Contributor

    /ok to test ce00b564c98f5d209cfd0a1679ed81c608f3039a

    jakirkham jakirkham commented on Jul 29, 2026 22:03 UTC
    Contributor

    /ok to test eac5aeec3ac69e9d6c5b6999cbcfe949f72dfec8

    jakirkham jakirkham commented on Jul 29, 2026 22:30 UTC
    Contributor

    /ok to test aef0ca15476ad240a44f46ebb5d4cb222c370565

    jakirkham jakirkham commented on Jul 29, 2026 22:38 UTC
    Contributor

    /ok to test 15752d3e3a45ebc16ff336cfa32b7db91e3c8342

    jakirkham jakirkham commented on Jul 30, 2026 00:11 UTC
    Contributor

    /ok to test aeca33b5ea643257248a3d55839ebfbadc1ae24d

    cdinea cdinea commented on Jul 30, 2026 01:44 UTC
    Author

    /ok to test 729d27a0d3848edbacccdf54f49c852b2c3c32cb

    jakirkham jakirkham commented on Jul 30, 2026 03:35 UTC
    Contributor

    /ok to test 729d27a0d3848edbacccdf54f49c852b2c3c32cb

    cdinea cdinea commented on Jul 30, 2026 05:36 UTC
    Author

    /ok to test e011f4429f5d0ebbaed344e4e8764d76989d4a6a

    cdinea cdinea commented on Jul 30, 2026 15:17 UTC
    Author

    /ok to test

    copy-pr-bot[bot] copy-pr-bot[bot] commented on Jul 30, 2026 15:17 UTC
    Bot

    /ok to test

    @cdinea, there was an error processing your request: E1

    See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/1/

    cdinea cdinea commented on Jul 30, 2026 15:20 UTC
    Author

    /ok to test

    78b8b15

    cdinea cdinea commented on Jul 30, 2026 15:21 UTC
    Author

    /ok to test 78b8b15

    mkepa-nv mkepa-nv approved these changes on Jul 30, 2026 16:34 UTC
    Approved Reviewer

    There are a few of my comments left not addressed. But they are more nitpicks / code style, so I approve

    grlee77 grlee77 commented on Jul 30, 2026 16:59 UTC
    Contributor

    /ok to test 05bd513

    jakirkham jakirkham commented on Jul 30, 2026 17:44 UTC
    Contributor

    /merge

    Assignees
    cdinea cdinea
    Labels
    risk: low confidence: 75.1% 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: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    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: 75.1% · Lower = rushed or shallow review
    75.1%
    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: 17.8% · Safe to merge
    17.8%
    Repository