Skip to content

Validate batch_index slice bounds and shapes in Unbatch - #129230

Merged
copybara-service[bot] merged 2 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/65633-unbatch-slice-validation
Oct 30, 2026
Merged

copybara-service[bot] merged 2 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/65633-unbatch-slice-validation

Conversation

@bodapatisaikrishna

@bodapatisaikrishna bodapatisaikrishna commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Passing invalid batch_index entries (such as end < start, negative indices, or out-of-bounds ranges) to tf.raw_ops.Unbatch currently aborts the process with fatal CHECK failures inside Tensor::Slice and shaped.

This PR adds slice bounds and cumulative size checks in UnbatchResource::Compute and concat_split_util, and tightens shape inference for Unbatch to reject malformed batch_index and id inputs with InvalidArgumentError.

Fixes #65633

Add bounds validation for start/end slice indices and cumulative split sizes in UnbatchResource and concat_split_util to prevent fatal CHECK aborts during tensor slicing. Also validate batch_index and id ranks and dimensions in Unbatch and UnbatchGrad shape inference functions.

Fixes tensorflow#65633
@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Oct 17, 2026
@google-ml-butler
google-ml-butler Bot requested a review from cantonios October 17, 2026 15:56
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 17, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds validation checks to the Unbatch and UnbatchGrad operations to prevent invalid slice bounds, incorrect shapes, and negative split sizes, addressing potential crashes and adding comprehensive unit tests. The review feedback identifies critical opportunities to prevent potential integer overflows in concat_split_util.h and batch_kernels.cc by performing subtraction-based boundary checks before accumulating split sizes.

Comment on lines 128 to 134
for (const int64_t size : sizes) {
if (size < 0) {
return absl::InvalidArgumentError(
absl::StrCat("Split size must be non-negative, got ", size));
}
total_size += size;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

To prevent potential integer overflow when summing up the split sizes, we should check if size exceeds the remaining capacity of the input tensor's dimension 0 before performing the addition. If sizes contains extremely large values, total_size could overflow and wrap around to a negative value, bypassing the subsequent boundary check.

  for (const int64_t size : sizes) {
    if (size < 0) {
      return absl::InvalidArgumentError(
          absl::StrCat("Split size must be non-negative, got ", size));
    }
    if (size > input.shape().dim_size(0) - total_size) {
      return absl::InvalidArgumentError(
          "Sum of split sizes must not exceed dim0-size of input tensor");
    }
    total_size += size;
  }

Comment on lines +174 to +178
for (const int64_t size : sizes) {
if (size < 0) {
return absl::InvalidArgumentError(
absl::StrCat("Split size must be non-negative, got ", size));
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

Similarly, we should prevent potential integer overflow when accumulating the split sizes in SplitCPU. Checking if size exceeds the remaining capacity of the input tensor's dimension 0 before adding it to position ensures safe execution.

  for (const int64_t size : sizes) {
    if (size < 0) {
      return absl::InvalidArgumentError(
          absl::StrCat("Split size must be non-negative, got ", size));
    }
    if (size > input.shape().dim_size(0) - position) {
      return absl::InvalidArgumentError(
          "Sum of split sizes must not exceed dim0-size of input tensor");
    }

Comment on lines +931 to +936
const int64_t size = end - start;
total_size += size;
if (total_size > data_t.shape().dim_size(0)) {
return absl::InvalidArgumentError(
"Sum of split sizes must not exceed dim0-size of input tensor");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To prevent any potential integer overflow when accumulating total_size, perform the boundary check using subtraction (size > data_t.shape().dim_size(0) - total_size) instead of addition.

        const int64_t size = end - start;
        if (size > data_t.shape().dim_size(0) - total_size) {
          return absl::InvalidArgumentError(
              "Sum of split sizes must not exceed dim0-size of input tensor");
        }
        total_size += size;

@keerthanakadiri keerthanakadiri self-assigned this Oct 19, 2026
@keerthanakadiri
keerthanakadiri requested a review from a team October 19, 2026 05:09
@keerthanakadiri keerthanakadiri added the prtype:bugfix PR to fix a bug label Oct 19, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Oct 19, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1. Fix the failing cumulative-size test case, run in both graph and eager mode, and wrap lines to 80 columns (tensorflow/python/ops/batch_ops_test.py)

In testUnbatchInvalidSliceBounds, the fourth test case passes batch_index=[[0, 0, 2], [1, 2, 4]] for a batched_tensor whose first dimension has size 3. Because row 1 has end = 4 > 3, the kernel rejects it at the per-row end > data_t.shape().dim_size(0) check ("exceeds dimension 0 size 3") before reaching the cumulative split-size check, causing assertRaisesRegex(..., "Sum of split sizes must not exceed") to fail when batch_ops_test is executed. Use overlapping slice ranges whose end indices stay within dimension 0 (such as [[0, 0, 2], [1, 1, 3]]).

In addition, remove the if context.executing_eagerly(): guard and wrap each batch_ops.unbatch(...) call in self.evaluate(...) so these runtime checks are exercised in both graph and eager mode, and wrap lines to 80 columns so the PyLint check passes (lines 701, 714, 727, 740, and 741 currently exceed 80 characters):

  def testUnbatchInvalidSliceBounds(self):
    # Regression test for GitHub issue 65633: invalid slice bounds or
    # cumulative sizes in batch_index caused fatal CHECK failures.
    # Inverted slice range (end < start)
    with self.assertRaisesRegex(
        errors.InvalidArgumentError, "Expected 0 <= start <= end"
    ):
      self.evaluate(
          batch_ops.unbatch(
              batched_tensor=constant_op.constant(
                  [[1, 2], [3, 4]], dtype=dtypes.int32
              ),
              batch_index=constant_op.constant(
                  [[0, 2, 1]], dtype=dtypes.int64
              ),
              id=constant_op.constant(0, dtype=dtypes.int64),
              timeout_micros=0,
              container="",
              shared_name="",
          )
      )

    # Negative start index
    with self.assertRaisesRegex(
        errors.InvalidArgumentError, "Expected 0 <= start <= end"
    ):
      self.evaluate(
          batch_ops.unbatch(
              batched_tensor=constant_op.constant(
                  [[1, 2], [3, 4]], dtype=dtypes.int32
              ),
              batch_index=constant_op.constant(
                  [[0, -1, 1]], dtype=dtypes.int64
              ),
              id=constant_op.constant(0, dtype=dtypes.int64),
              timeout_micros=0,
              container="",
              shared_name="",
          )
      )

    # End index exceeds dim0
    with self.assertRaisesRegex(
        errors.InvalidArgumentError, "exceeds dimension 0 size"
    ):
      self.evaluate(
          batch_ops.unbatch(
              batched_tensor=constant_op.constant(
                  [[1, 2], [3, 4]], dtype=dtypes.int32
              ),
              batch_index=constant_op.constant(
                  [[0, 1, 5]], dtype=dtypes.int64
              ),
              id=constant_op.constant(0, dtype=dtypes.int64),
              timeout_micros=0,
              container="",
              shared_name="",
          )
      )

    # Cumulative split sizes exceed dim0 (overlapping rows)
    with self.assertRaisesRegex(
        errors.InvalidArgumentError, "Sum of split sizes must not exceed"
    ):
      self.evaluate(
          batch_ops.unbatch(
              batched_tensor=constant_op.constant(
                  [[1], [2], [3]], dtype=dtypes.int32
              ),
              batch_index=constant_op.constant(
                  [[0, 0, 2], [1, 1, 3]], dtype=dtypes.int64
              ),
              id=constant_op.constant(0, dtype=dtypes.int64),
              timeout_micros=0,
              container="",
              shared_name="",
          )
      )

2. Drop the UnbatchGrad changes and update the PR title and description (tensorflow/core/kernels/batch_kernels.cc, tensorflow/core/ops/batch_ops.cc, tensorflow/python/ops/batch_ops_test.py)

BatchOpsTest runs all test methods in both graph and eager mode. Adding static shape-inference checks to UnbatchGrad causes graph-mode op construction to raise ValueError in the existing tests testUnbatchGradInvalidId, testUnbatchGradInvalidBatchId, and testUnbatchGradInvalidArgs, which only catch errors.InvalidArgumentError and therefore fail in graph mode. Furthermore, the UnbatchGrad kernel and shape-function changes (along with the corresponding updates to those existing tests) are already handled in open PR #128345.

Please remove:

  • the batch_index_t.shape().dim_size(1) != 3 block in UnbatchGradResource::Compute (tensorflow/core/kernels/batch_kernels.cc:1193-1198);
  • the new shape-inference checks in REGISTER_OP("UnbatchGrad") (tensorflow/core/ops/batch_ops.cc:199-204);
  • testUnbatchGradShapeInference (tensorflow/python/ops/batch_ops_test.py:782-806).

Please also update the PR title and description so they describe Unbatch only.

3. Make the cumulative split-size check overflow-safe and add a regression test (tensorflow/core/kernels/batching_util/concat_split_util.h, tensorflow/python/ops/batch_ops_test.py)

In SplitEasyCases, total_size += size is computed before checking total_size > input.shape().dim_size(0). A zero-element tensor can legitimately have a large first dimension (for example shape [INT64_MAX, 0]). With rows [0, 0, INT64_MAX] and [1, 0, 1], each row passes the per-row bounds checks, but total_size + size overflows signed int64_t (undefined behavior) and wraps past the sum check into Tensor::Slice. Because total_size <= input.shape().dim_size(0) holds at the start of each iteration, check size > input.shape().dim_size(0) - total_size before adding size in SplitEasyCases (tensorflow/core/kernels/batching_util/concat_split_util.h):

  int64_t total_size = 0;
  for (const int64_t size : sizes) {
    if (size < 0) {
      return absl::InvalidArgumentError(
          absl::StrCat("Split size must be non-negative, got ", size));
    }
    if (size > input.shape().dim_size(0) - total_size) {
      return absl::InvalidArgumentError(
          "Sum of split sizes must not exceed dim0-size of input tensor");
    }
    total_size += size;
  }

Please also add a regression test in tensorflow/python/ops/batch_ops_test.py covering this overflow boundary:

  def testUnbatchSplitSizesOverflow(self):
    # Two valid rows whose sizes sum past INT64_MAX on a zero-element input.
    int64_max = np.iinfo(np.int64).max
    shape = constant_op.constant([int64_max, 0], dtype=dtypes.int64)
    with self.assertRaisesRegex(
        errors.InvalidArgumentError, "Sum of split sizes must not exceed"
    ):
      self.evaluate(
          batch_ops.unbatch(
              batched_tensor=array_ops.zeros(shape, dtypes.int32),
              batch_index=constant_op.constant(
                  [[0, 0, int64_max], [1, 0, 1]], dtype=dtypes.int64
              ),
              id=constant_op.constant(0, dtype=dtypes.int64),
              timeout_micros=0,
              container="",
              shared_name="",
          )
      )

4. Remove unreachable and duplicate checks (tensorflow/core/kernels/batch_kernels.cc, tensorflow/core/kernels/batching_util/concat_split_util.h)

  • In UnbatchResource::Compute (tensorflow/core/kernels/batch_kernels.cc:893-897), delete the batch_index_t.NumElements() != batch_index_t.dim_size(0) * 3 check. Once TensorShapeUtils::IsMatrix(batch_index_t.shape()) and batch_index_t.shape().dim_size(1) == 3 have passed, NumElements() equals dim_size(0) * 3 by definition, making this branch unreachable.
  • In UnbatchResource::Compute (tensorflow/core/kernels/batch_kernels.cc:931-936), remove the duplicate total_size accumulation and check. Split (batch_kernels.cc:941) always runs SplitEasyCases first on the same sizes vector and returns the exact same error message ("Sum of split sizes must not exceed dim0-size of input tensor"). Keep only the per-row start and end checks in UnbatchResource::Compute:
    if (nonempty_input) {
      auto batch_indices =
          batch_index_t.shaped<int64_t, 2>({batch_index_t.dim_size(0), 3});
      for (int i = 0; i < batch_index_t.dim_size(0); ++i) {
        const int64_t start = batch_indices(i, 1);
        const int64_t end = batch_indices(i, 2);
        if (start < 0 || end < start) {
          return absl::InvalidArgumentError(absl::StrCat(
              "Invalid start/end indices in batch_index at row ", i, ": start=",
              start, ", end=", end, ". Expected 0 <= start <= end."));
        }
        if (end > data_t.shape().dim_size(0)) {
          return absl::InvalidArgumentError(absl::StrCat(
              "Invalid end index in batch_index at row ", i, ": end=", end,
              " exceeds dimension 0 size ", data_t.shape().dim_size(0), "."));
        }
        sizes.push_back(end - start);
        batch_keys.push_back(batch_indices(i, 0));
      }

      TF_RETURN_IF_ERROR(Split(context, data_t, sizes, &split_inputs));
    }
  • In SplitCPU (tensorflow/core/kernels/batching_util/concat_split_util.h:175-178), delete the if (size < 0) check. SplitCPU is only called from Split after SplitEasyCases has already validated that every element of sizes is non-negative.

5. Build testUnbatchShapeInference inside a graph and pin the error messages (tensorflow/python/ops/batch_ops_test.py)

In testUnbatchShapeInference, with self.assertRaises((ValueError, errors.InvalidArgumentError)): accepts any error of either type and, in eager mode, hits the existing runtime kernel checks rather than the C++ shape function. Construct the ops inside with ops.Graph().as_default(): and use self.assertRaisesRegex(ValueError, ...) to pin each shape-function error message:

  def testUnbatchShapeInference(self):
    # Shape functions run only when the op is added to a graph.
    with ops.Graph().as_default():
      with self.assertRaisesRegex(ValueError, "Shape must be at least rank 1"):
        gen_batch_ops.unbatch(
            batched_tensor=constant_op.constant(1.0),
            batch_index=constant_op.constant([[0, 0, 1]], dtype=dtypes.int64),
            id=constant_op.constant(0, dtype=dtypes.int64),
            timeout_micros=0,
        )

      with self.assertRaisesRegex(ValueError, "Shape must be rank 2"):
        gen_batch_ops.unbatch(
            batched_tensor=constant_op.constant([1.0, 2.0]),
            batch_index=constant_op.constant([0, 0, 1], dtype=dtypes.int64),
            id=constant_op.constant(0, dtype=dtypes.int64),
            timeout_micros=0,
        )

      with self.assertRaisesRegex(ValueError, "Dimension must be 3"):
        gen_batch_ops.unbatch(
            batched_tensor=constant_op.constant([1.0, 2.0]),
            batch_index=constant_op.constant([[0, 1]], dtype=dtypes.int64),
            id=constant_op.constant(0, dtype=dtypes.int64),
            timeout_micros=0,
        )

      with self.assertRaisesRegex(ValueError, "Shape must be rank 0"):
        gen_batch_ops.unbatch(
            batched_tensor=constant_op.constant([1.0, 2.0]),
            batch_index=constant_op.constant([[0, 0, 1]], dtype=dtypes.int64),
            id=constant_op.constant([0], dtype=dtypes.int64),
            timeout_micros=0,
        )

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Oct 19, 2026
…flow

Make cumulative split size checks in SplitEasyCases overflow-safe
against signed int64 wrap-around, remove duplicate bounds checks, drop
UnbatchGrad shape-inference changes, and update tests to evaluate under
both graph and eager modes with pinned shape-function errors.
@bodapatisaikrishna bodapatisaikrishna changed the title Validate batch_index slice bounds and shapes in Unbatch ops Validate batch_index slice bounds and shapes in Unbatch Oct 19, 2026
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Updated to scope everything to Unbatch, made the cumulative size check overflow-safe with a regression test, and fixed the test cases and formatting. Thanks for the thorough review!

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Oct 19, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Oct 19, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Oct 23, 2026
copybara-service Bot pushed a commit that referenced this pull request Oct 30, 2026
…87f3.

FUTURE_COPYBARA_INTEGRATE_REVIEW=#129230 from bodapatisaikrishna:fix/65633-unbatch-slice-validation 5b51a0d
PiperOrigin-RevId: 1010504175
@copybara-service
copybara-service Bot merged commit e7add67 into tensorflow:master Oct 30, 2026
17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

prtype:bugfix PR to fix a bug ready to pull PR ready for merge process size:M CL Change Size: Medium

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

Some Check Failed errors in tf.raw_ops.Unbatch

4 participants