Fix integer overflow and error handling issues in tensor operations#491
Fix integer overflow and error handling issues in tensor operations#491tensor4all-ai-bot[bot] wants to merge 1 commit intomainfrom
Conversation
- Fix integer overflow in eye() constructor with checked arithmetic - Fix integer overflow in triangular extraction (tril/triu) with checked arithmetic - Add validation for empty reduction domain in mean reduction - Add comprehensive tests for all bug fixes Fixes #466 Generated with [Claude Code](https://claude.com/claude-code)
There was a problem hiding this comment.
Review Summary
This PR addresses several important bug fixes for integer overflow and error handling. Overall the changes are solid, but I have a few concerns and suggestions.
✅ Good Changes
-
Mean reduction empty domain check (
family_cpu_reduction.rs): Excellent - properly returns an error instead of division by zero. -
Checked arithmetic in
eye()(constructors.rs): Correct approach given the function returnsSelfrather thanResult. -
Comprehensive tests: Good test coverage for
eye,tril,triu,narrow, andselectoperations.
⚠️ Issues to Address
1. Missing fix for narrow overflow (Issue #466, item #2)
The original issue identified overflow in narrow operation at views.rs:265:
let offset = self.offset + start as isize * self.strides[dim];This is not addressed in this PR. The narrow function still uses unchecked arithmetic.
2. Panic vs Result in tril/triu (data_ops.rs)
The fix uses expect() which panics on overflow. Consider whether these functions should return Result instead, similar to how narrow returns Result. Inconsistent error handling across the API makes it harder for users to write robust code.
3. Minor: Verbose position calculation
The checked arithmetic in data_ops.rs is quite verbose. Consider extracting to a helper function:
fn checked_pos(offset: isize, i: isize, stride0: isize, j: isize, stride1: isize) -> Option<usize>Suggestions
- Add issue #2 (narrow overflow) to this PR or create a follow-up
- Consider API consistency: should
tril/triureturnResultlikenarrowdoes? - Add a test case that exercises the overflow paths (with very large stride values)
Generated with Claude Code
Pull request was closed
- Replace unchecked .map().sum() with try_fold using checked_mul and checked_add - Ensures batch offset calculations in tril/triu properly detect overflow - Addresses tensor4all-reviewer-bot feedback from PR #491 Generated with Claude Code
Changes Applied Based on Review FeedbackI have applied the following changes to address the incomplete checked arithmetic issues identified by @tensor4all-reviewer-bot: Fixed Issuesdata_ops.rs:162-171 - Fixed incomplete checked arithmetic in batch offset calculations The batch offset calculations in Before: let src_batch_off: isize = batch_index
.iter()
.enumerate()
.map(|(axis, &idx)| idx as isize * self.strides[axis + 2])
.sum();After: let src_batch_off: isize = batch_index
.iter()
.enumerate()
.try_fold(0isize, |acc, (axis, &idx)| {
(idx as isize)
.checked_mul(self.strides[axis + 2])
.and_then(|v| acc.checked_add(v))
})
.expect("batch offset overflow in triangular extraction");Both
VerificationAll 14 tests in
CommitPushed as commit 2e983a4 to branch Generated with Claude Code |
Addressed reviewer-bot feedbackI've implemented the changes requested by the 1. Extracted helper functions for verbose checked arithmetic
2. Changed
|
Addresses reviewer-bot feedback from PR #491: adds test cases that exercise the overflow error path with very large stride values (isize::MAX), verifying that tril() and triu() return Err instead of panicking.
Changes addressing tensor4all-reviewer-bot feedbackThe reviewer-bot identified three issues in the original PR. Here is the status of each: 1. Missing fix for
|
…a_ops.rs Per tensor4all-reviewer-bot feedback on PR #491: - Extract checked_pos() helper for 2D position calculation with checked arithmetic - Extract checked_batch_offset() helper for batch offset computation - Reduces code duplication and improves readability in triangular_part()
Per tensor4all-reviewer-bot feedback on PR #491: - Change triangular_part, tril, triu to return Result<Tensor<T>> - Replace panic! with proper error propagation using ? and ok_or_else - Update all callers: tests use .unwrap(), backend functions use ? - Update doc examples to include .unwrap()
Addressed tensor4all-reviewer-bot feedbackBased on the reviewer-bot's review, I've made the following changes on this branch: 1. tril/triu now return
|
…ot feedback on PR #491 - narrow_start_plus_length_overflow_returns_error: verifies usize overflow on start+length - narrow_dim_out_of_range_returns_error: verifies dim bounds check - tril_triu_return_result_no_panic: verifies Result-based API doesn't panic - tril_triu_rank1_return_result: verifies 1D tensor Result handling
Reviewer-bot feedback addressedBased on the feedback from @tensor4all-reviewer-bot, I've added the following overflow path test cases that were requested: New tests added (
|
…a_ops.rs Per tensor4all-reviewer-bot feedback on PR #491: - Extract checked_pos() helper for 2D position calculation with checked arithmetic - Extract checked_batch_offset() helper for batch offset computation - Reduces code duplication and improves readability in triangular_part()
Per tensor4all-reviewer-bot feedback on PR #491: - Change triangular_part, tril, triu to return Result<Tensor<T>> - Replace panic! with proper error propagation using ? and ok_or_else - Update all callers: tests use .unwrap(), backend functions use ? - Update doc examples to include .unwrap()
…ot feedback on PR #491 - narrow_start_plus_length_overflow_returns_error: verifies usize overflow on start+length - narrow_dim_out_of_range_returns_error: verifies dim bounds check - tril_triu_return_result_no_panic: verifies Result-based API doesn't panic - tril_triu_rank1_return_result: verifies 1D tensor Result handling
Addressed reviewer-bot feedbackI've rebased this branch onto the latest All three reviewer-bot items are now addressed:
Additional improvements:
All tests pass ( |
Addressing Reviewer-Bot FeedbackI've reviewed and addressed the feedback from the tensor4all-reviewer-bot review. Here's a summary of what was done: Reviewer-Bot Issues Addressed
Verification
|
Summary
eye()constructor with checked arithmetictril/triu) with checked arithmeticFixes #466
Changes
Bug Fixes
Integer overflow in
eye()(constructors.rs): Changed unchecked arithmetic to usechecked_mul,checked_add, andchecked_try_fromto prevent panics on large tensors.Integer overflow in triangular extraction (data_ops.rs): Added checked arithmetic for all position calculations in
tril/triuoperations to prevent out-of-bounds memory access.Division by zero in mean reduction (family_cpu_reduction.rs): Added check for empty reduction domain to prevent division by zero.
Tests Added
eye_creates_identity_matrix_col_major/eye_creates_identity_matrix_row_major: Verify identity matrix creationtril_extracts_lower_triangular/triu_extracts_upper_triangular: Verify triangular extractiontril_with_diagonal_offset/triu_with_diagonal_offset: Verify diagonal offset handlingnarrow_returns_subrange/narrow_rejects_out_of_bounds: Verify narrow operationselect_returns_single_slice: Verify select operationcpu_scalar_mean_reduction_rejects_empty_reduction_domain: Verify empty reduction domain errorGenerated with Claude Code