Skip to content

Validate that LoopCond nodes are inside a while loop frame - #129186

Merged
copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/62982-loopcond-empty-frame
Oct 23, 2026
Merged

copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/62982-loopcond-empty-frame

Conversation

@bodapatisaikrishna

@bodapatisaikrishna bodapatisaikrishna commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Calling tf.raw_ops.LoopCond(input=True) outside of a while loop frame aborts in debug builds (--config=dbg) with:

F tensorflow/core/graph/graph_partition.cc:649] Check failed: !frame_name.empty()
Aborted (core dumped)

Cause

A LoopCond op placed directly in the graph outside of an Enter op has an empty frame_name (""). In AddControlFlow (tensorflow/core/graph/graph_partition.cc), debug builds assert DCHECK(!frame_name.empty()) when populating frame_cond_map.

Solution

  • Replaced DCHECK(!frame_name.empty()) in AddControlFlow (tensorflow/core/graph/graph_partition.cc) with an explicit InvalidArgumentError return.
  • Added unit tests in tensorflow/core/graph/graph_partition_test.cc and tensorflow/python/kernel_tests/control_flow/control_flow_ops_py_test.py.

Fixes #62982.

@google-ml-butler google-ml-butler Bot added the size:S CL Change Size: Small label Oct 16, 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 ensures that a LoopCond node defined outside of a while loop frame fails gracefully with an InvalidArgumentError instead of causing a crash or abort during graph partitioning. It adds validation checks in control_flow.cc and graph_partition.cc, along with corresponding C++ and Python tests. A critical issue was identified in graph_partition.cc where the helper function FormatNodeForError is called but is not accessible, which will cause a compilation error. A suggestion was provided to format the error message using the node's name and type directly.

Comment on lines +649 to +653
if (frame_name.empty()) {
return absl::InvalidArgumentError(
absl::StrCat(FormatNodeForError(*node),
" must be inside a while loop frame."));
}

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.

high

The helper function FormatNodeForError is defined in an anonymous namespace inside tensorflow/core/graph/control_flow.cc and is not exported or declared in any header file. Calling it here in graph_partition.cc will result in a compilation error (undeclared identifier). Instead, you can format the error message using the node's name() and type_string() directly.

Suggested change
if (frame_name.empty()) {
return absl::InvalidArgumentError(
absl::StrCat(FormatNodeForError(*node),
" must be inside a while loop frame."));
}
if (frame_name.empty()) {
return absl::InvalidArgumentError(
absl::StrCat("Node '", node->name(), "' of type ",
node->type_string(),
" must be inside a while loop frame."));
}

@keerthanakadiri keerthanakadiri self-assigned this Oct 19, 2026
@keerthanakadiri keerthanakadiri added the comp:core issues related to core part of tensorflow label Oct 19, 2026
@keerthanakadiri
keerthanakadiri requested a review from a team October 19, 2026 04:50
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 19, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Oct 19, 2026
@keerthanakadiri keerthanakadiri added the prtype:bugfix PR to fix a bug label 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. Keep the fix at the abort site in graph_partition.cc and revert the control_flow.cc change

The added check in ValidateControlFlowInfo (tensorflow/core/graph/control_flow.cc) runs for every caller of BuildControlFlowInfo, not only graph partitioning. That includes XLA auto-clustering (tensorflow/compiler/jit/xla_cluster_util.cc), deadness analysis, function instantiation, Grappler, and while-loop functionalization. As a result, it breaks XlaCompilationTest.DontClusterTheSpecialIdentityDrivingConstsInLoop in tensorflow/compiler/jit/mark_for_compilation_pass_test.cc (lines 1746 and 1760), which intentionally constructs an incomplete graph containing a LoopCond node without an Enter node and caused the //tensorflow/compiler/jit:compilation_passes_test failure in the build-linux-x86-cuda and build-linux-x86-cuda13 CI jobs.

The abort reported in issue #62982 is the DCHECK(!frame_name.empty()) in AddControlFlow (tensorflow/core/graph/graph_partition.cc), and replacing that DCHECK with an InvalidArgumentError return resolves the issue without breaking callers of BuildControlFlowInfo. Please make the following changes:

  • Revert the change in tensorflow/core/graph/control_flow.cc and remove ValidateControlFlowTest.LoopCondOutsideWhileLoop from tensorflow/core/graph/control_flow_test.cc.
  • Keep the InvalidArgumentError check in AddControlFlow in tensorflow/core/graph/graph_partition.cc.
  • Add the C++ regression test to tensorflow/core/graph/graph_partition_test.cc (after PartitionIncompleteGraph, along with #include "absl/strings/match.h") so that it exercises Partition -> AddControlFlow directly:
TEST_F(GraphPartitionTest, LoopCondOutsideWhileLoop) {
  auto a1 = BoolInput(in_.WithOpName("A1"));
  LoopCond(in_.WithOpName("A2"), a1);

  Graph g(OpRegistry::Global());
  TF_ASSERT_OK(
      ConvertGraphDefToGraph(GraphConstructorOptions(), ToGraphDef(), &g));
  for (Node* node : g.nodes()) {
    node->set_assigned_device_name(DeviceName(node));
  }

  PartitionOptions popts;
  popts.node_to_loc = SplitByDevice;
  popts.new_name = [&g](const std::string& prefix) {
    return g.NewName(prefix);
  };
  popts.get_incarnation = [](const std::string&) { return 1; };

  std::unordered_map<std::string, GraphDef> partitions;
  absl::Status status = Partition(popts, &g, &partitions);
  EXPECT_EQ(error::INVALID_ARGUMENT, status.code()) << status;
  EXPECT_TRUE(absl::StrContains(status.message(),
                                "must be inside a while loop frame"))
      << status;
}
  1. Pin the error message and run in deprecated v1 graph mode in the Python test

In tensorflow/python/kernel_tests/control_flow/control_flow_ops_py_test.py, testLoopCondOutsideWhileLoop uses a bare self.assertRaises(errors_impl.InvalidArgumentError) with op construction inside the with block, and @test_util.run_v1_only skips the test whenever TF2 behavior is enabled. Please construct the op before the with block, assert the specific error message substring "must be inside a while loop frame" around sess.run(cond) using self.assertRaisesRegex, and use @test_util.run_deprecated_v1 (like testRunLoopTensor in the same file) so the test runs in graph mode under both TF1 and TF2 configurations (untested sketch):

  @test_util.run_deprecated_v1
  def testLoopCondOutsideWhileLoop(self):
    # LoopCond outside a while loop frame must fail with InvalidArgumentError
    # rather than aborting during graph partitioning (issue #62982).
    with self.cached_session() as sess:
      cond = gen_control_flow_ops.loop_cond(input=True)
      with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
                                  "must be inside a while loop frame"):
        sess.run(cond)
  1. Include graph_node_util.h directly in graph_partition.cc

tensorflow/core/graph/graph_partition.cc now calls FormatNodeForError, which is declared in tensorflow/core/graph/graph_node_util.h and is currently only available through a transitive include. Please add #include "tensorflow/core/graph/graph_node_util.h" in sorted order in tensorflow/core/graph/graph_partition.cc.

  1. Update the PR description

Please update the PR description to match the implementation:

  • Replace AddControlLoops with AddControlFlow.
  • Remove the ValidateControlFlowInfo bullet once the change in tensorflow/core/graph/control_flow.cc is dropped.
  • Remove the claim that release builds corrupt graph partitioning state; in AddControlFlow, root-frame edges are skipped before frame_cond_map is queried, so the empty-frame entry was never read in release builds.

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

Revert the empty frame check in ValidateControlFlowInfo to preserve
incomplete graph handling in XLA compilation passes, keep the validation
in AddControlFlow, and add a C++ partition regression test along with
pinned Python test assertions under deprecated v1.
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Reverted the check in ValidateControlFlowInfo, kept the validation in AddControlFlow, and added the partition regression test and updated the PR description. Thanks!

@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.

All four requests from the previous review have been resolved:

  • tensorflow/core/graph/control_flow.cc and tensorflow/core/graph/control_flow_test.cc are reverted to their original state on master, so callers of BuildControlFlowInfo outside graph partitioning keep their existing behavior.
  • AddControlFlow in tensorflow/core/graph/graph_partition.cc returns absl::InvalidArgumentError before mutating frame_cond_map.
  • GraphPartitionTest.LoopCondOutsideWhileLoop in tensorflow/core/graph/graph_partition_test.cc exercises Partition directly and checks both the error code and the error message.
  • testLoopCondOutsideWhileLoop in tensorflow/python/kernel_tests/control_flow/control_flow_ops_py_test.py runs under @test_util.run_deprecated_v1, constructs gen_control_flow_ops.loop_cond(input=True) outside the with block, and checks the error message substring.
  • #include "tensorflow/core/graph/graph_node_util.h" is included directly in tensorflow/core/graph/graph_partition.cc, and the pull request description matches the implementation.

One remaining change is required before approval:

Add direct includes for absl::InvalidArgumentError and absl::StrCat in tensorflow/core/graph/graph_partition.cc

The new check at tensorflow/core/graph/graph_partition.cc:650-654 calls absl::InvalidArgumentError and absl::StrCat, which are currently only available through transitive includes. Please add #include "absl/status/status.h" and #include "absl/strings/str_cat.h" in sorted order right after #include "absl/container/flat_hash_map.h" at tensorflow/core/graph/graph_partition.cc:26:

#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/core/framework/function.h"

Both headers are already used by other source files in tensorflow/core/graph, so no BUILD file change is needed.

Include absl/status/status.h and absl/strings/str_cat.h directly for
absl::InvalidArgumentError and absl::StrCat.
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Added the direct absl/status/status.h and absl/strings/str_cat.h includes. Thanks!

@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
copybara-service Bot merged commit eeea5cc into tensorflow:master Oct 23, 2026
17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Oct 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:core issues related to core part of tensorflow prtype:bugfix PR to fix a bug ready to pull PR ready for merge process size:S CL Change Size: Small

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

tf.raw_ops.LoopCond aborts in Debug build

4 participants