kornia/kornia-rs

[Bug]: Inconsistent overflow handling in the tensor shape multiplication

Open

#747 创建于 2026年2月23日

在 GitHub 查看
 (7 评论) (0 反应) (1 负责人)Rust (188 fork)auto 404
bughelp wantedtriage

仓库指标

Star
 (675 star)
PR 合并指标
 (PR 指标待抓取)

描述

🐛 Describe the bug

The tensor constructors are computing the total number of elements using:

    shape.iter().product::<usize>()

this is happening in - 'from_shape_vec' 'from_shape_slice' 'from_shape_val' 'from_shape_fn' 'reshape' 'get_strides_from_shape'

In debug builds, integer overflow will cause a panic. However in release builds ('cargo test --release --features ci'), 'usize' multiplication wraps silently. This means that shape validation relies on wrapped arithmetic in release build, this will lead to inconsistent behaviour compared to debug builds.

🔄 Steps to Reproduce

1. Build in release mode.
2. Call 'from_shape_vec' with a shape that overflows 'usize' when multiplied.

💻 Minimal Code Example

use kornia_tensor::Tensor3;

#[test]
fn overflow_shape_example() -> Result<(), TensorError> {
    let shape = [usize::MAX, 2, 3];
    let data: Vec<u8> = vec![];

    // In debug it panics due to overflow
    // In release multiplication wraps silently
    let _ = Tensor3::<u8, 3, CpuAllocator>::from_shape_vec(shape, data, CpuAllocator)?;
    Ok(())
}

✅ Expected behavior

Shape multiplication should use checked arithmetic and return an error (eg. a new 'TensorError::SizeOverflow' ) instead of panicking in debug or silently wrapping in release builds leading to incorrect internal values.

❌ Actual behavior

Debug build - panic due to integer overflow. Release build - multiplication wraps and the wrapped value is used for validating and stride computation.

🔧 Environment

- kornia-rs version: main @ dc8d84f
- Rust version (`rustc -V`): rustc 1.93.1
- Cargo version (`cargo -V`): cargo 1.93.1
- OS (e.g., Linux, macOS, Windows): Linux (Ubuntu 24.04)
- Target architecture (if cross-compiling): x86_64-unknown-linux-gnu
- Python version (if using Python bindings):

📝 Additional context

Other parts of the repository already use checked arithmetic for buffer sizing (eg. PCD parsing), so applying checked multiplication would be in line with the existing pattern.

I can prepare a small PR introducing -

  • A 'TensorError::SizeOverflow' variant
  • Checked multiplication for numel and stride computations
  • Unit tests for overflow behaviour

Please let me know if this approach aligns with the project.

🤝 Contribution Intent

  • I plan to submit a PR to fix this bug
  • I'm reporting this bug but not planning to fix it

贡献者指南