From 65c23ed366fc97afb3b206cf0dfe27cd7d970331 Mon Sep 17 00:00:00 2001 From: Pranav Kant Date: Thu, 10 Sep 2026 11:45:58 -0700 Subject: [PATCH 1/5] [BazelBot] Support nested failures Push fixes into active fix branch if we see another failure --- google-bazel-bot/bazel-bot/bazelbot_server.py | 124 ++++- .../bazel-bot/bazelbot_server_test.py | 472 ++++++++++++++++-- google-bazel-bot/bazel-bot/utils.py | 95 +++- 3 files changed, 601 insertions(+), 90 deletions(-) diff --git a/google-bazel-bot/bazel-bot/bazelbot_server.py b/google-bazel-bot/bazel-bot/bazelbot_server.py index 496c4edf9..e13f73d28 100644 --- a/google-bazel-bot/bazel-bot/bazelbot_server.py +++ b/google-bazel-bot/bazel-bot/bazelbot_server.py @@ -55,41 +55,55 @@ def __init__( self.last_processed_state: utils.BuildState = utils.BuildState.UNKNOWN self.last_processed_sha: str = "" self.poll_interval = poll_interval + # Branch containing fixes that have not been merged + # All subsequent failures are merged into this branch as separate commits + self.active_fix_branch: str | None = None + + def reset_active_fix_branch(self) -> None: + self.active_fix_branch = None def wait(self, seconds): """Sleeps for a given number of seconds""" time.sleep(seconds) - def process_failure_with_bant(self, build_data: utils.BuildInfo) -> bool: - self.git_repo.create_branch_for_fix(build_data.commit) + def process_failure_with_bant( + self, build_data: utils.BuildInfo, fix_branch: str + ) -> bool: + base_sha = self.git_repo.repo.head.commit.hexsha if not self.command_processor.run_bant(targets=build_data.failed_targets): logger.warning("Running bant failed.") + self.git_repo.reset_hard(base_sha) return False if not self.validate_before_publishing(): logger.info("Validation before publishing failed.") + self.git_repo.reset_hard(base_sha) return False self.git_repo.commit( f"[Bazel] Fix build for {build_data.commit[:7]}\n\n" f"Buildkite error link: {build_data.buildkite_url}" ) - if not self.git_repo.push_fix(build_data): + if not self.git_repo.push_fix(build_data, branch_name=fix_branch): logger.warning("Failed to publish bant fix.") return False return True - def repair_build(self, build: utils.BuildInfo) -> bool: + def repair_build( + self, + build: utils.BuildInfo, + fix_branch: str | None = None, + ) -> bool: if build.state != utils.BuildState.FAILED: logger.info(f"Build for {build.commit} is not failed. Nothing to repair.") return False record = RepairSummaryRecord(build.commit, "", time.time()) - if self.process_failure_with_bant(build): + if self.process_failure_with_bant(build, fix_branch): logger.info(f"Successfully repaired build for {build.commit}) using bant.") record.fixed_by = FixTool.BANT - elif self.process_failure_with_ai(build): + elif self.process_failure_with_ai(build, fix_branch): logger.info( f"Successfully repaired build for {build.commit} using AI agent." ) @@ -129,19 +143,25 @@ def validate_before_publishing(self) -> bool: return True - def process_failure_with_ai(self, build_data): + def process_failure_with_ai( + self, + build_data: utils.BuildInfo, + fix_branch: str, + ) -> bool: logger.info("Invoking AI Agent...") attempt_num = 0 agent_exhausted_tries = 0 past_fixes = [] + base_sha = self.git_repo.repo.head.commit.hexsha - # Push an empty branch to indicate that AI fix is in progress - self.git_repo.create_branch_for_fix(build_data.commit) - self.git_repo.commit( - f"AI is working on fixing build for {build_data.commit[:7]}. Check back later!\n\n" - f"Buildkite error link: {build_data.buildkite_url}" - ) - self.git_repo.push_fix(build_data, False) + # Push an empty branch to indicate that AI fix is in progress ONLY + # We only do this if there is no active branch + if not self.active_fix_branch: + self.git_repo.commit( + f"AI is working on fixing build for {build_data.commit[:7]}. Check back later!\n\n" + f"Buildkite error link: {build_data.buildkite_url}" + ) + self.git_repo.push_fix(build_data, False, branch_name=fix_branch) while True: if attempt_num == MAX_AGENT_ITERATIONS: @@ -150,7 +170,7 @@ def process_failure_with_ai(self, build_data): ) break - self.git_repo.create_branch_for_fix(build_data.commit) + self.git_repo.reset_hard(base_sha) # For local testing, users must use their personal access tokens access_token = ( @@ -199,20 +219,22 @@ def process_failure_with_ai(self, build_data): if not self.validate_before_publishing(): logger.info("Validation before publishing failed.") - self.git_repo.create_branch_for_fix(build_data.commit) + self.git_repo.reset_hard(base_sha) self.git_repo.commit( f"AI failed to fix the build for {build_data.commit[:7]}. You " f"will need to fix it manually\n\n" f"Buildkite error link: {build_data.buildkite_url}" ) - self.git_repo.push_fix(build_data, False) + self.git_repo.push_fix(build_data, False, branch_name=fix_branch) return False self.git_repo.commit( f"Fix Bazel build for {build_data.commit[:7]}\n\n" f"Buildkite error link: {build_data.buildkite_url}" ) - if not self.git_repo.push_fix(build_data, self.git_repo.can_create_pr): + if not self.git_repo.push_fix( + build_data, self.git_repo.can_create_pr, branch_name=fix_branch + ): logger.warning( f"Failed to publish AI changes for commit: {build_data.commit}" ) @@ -232,15 +254,57 @@ def set_state_from_latest_build(self) -> bool: return False def get_build_info_for_commit(self, commit_sha: str) -> utils.BuildInfo | None: - logger.info(f"Finding build state for commit {commit_sha} locally ...") + # Build 1: Bazel build with a clean checkout of commit_sha + # Build 2: Bazel build of commit_sha + active_fix_branch containing fixes for previous errors + logger.info( + f"Finding build state for commit {commit_sha} locally (build 1: clean commit)..." + ) current_build = utils.BuildInfo(commit=commit_sha) self.git_repo.checkout_commit(commit_sha) build_result = self.command_processor.run_bazel_build() - current_build.state = ( - utils.BuildState.PASSED if build_result.success else utils.BuildState.FAILED + + if build_result.success: + logger.info( + f"Build 1 for commit {commit_sha} passed. Resetting active fix branch." + ) + self.reset_active_fix_branch() + current_build.state = utils.BuildState.PASSED + return current_build + + logger.info(f"Build 1 for commit {commit_sha} failed.") + current_build.failed_targets = utils.parse_targets(build_result.stderr) + if not self.active_fix_branch: + current_build.state = utils.BuildState.FAILED + return current_build + + logger.info( + f"Rebasing active fix branch {self.active_fix_branch} on top of commit {commit_sha}..." ) - if not build_result.success: - current_build.failed_targets = utils.parse_targets(build_result.stderr) + if not self.git_repo.rebase_branch(self.active_fix_branch, commit_sha): + logger.warning( + f"Failed to rebase active fix branch {self.active_fix_branch} on top of commit {commit_sha}." + ) + self.reset_active_fix_branch() + current_build.state = utils.BuildState.FAILED + return current_build + + logger.info( + f"Finding build state for commit {commit_sha} locally (build 2: with active fix branch {self.active_fix_branch})..." + ) + build_result2 = self.command_processor.run_bazel_build() + if build_result2.success: + logger.info( + f"Build 2 for commit {commit_sha} with fix branch {self.active_fix_branch} passed." + ) + current_build.state = utils.BuildState.PASSED + current_build.failed_targets = [] + else: + logger.info( + f"Build 2 for commit {commit_sha} with fix branch {self.active_fix_branch} failed." + ) + current_build.state = utils.BuildState.FAILED + current_build.failed_targets = utils.parse_targets(build_result2.stderr) + return current_build def run(self) -> None: @@ -277,6 +341,7 @@ def run(self) -> None: current_build.state == utils.BuildState.RUNNING or current_build.state == utils.BuildState.SCHEDULED ): + # TODO: Remove: We should never run into this now since we are building locally logger.debug( f"Build for {current_build.commit} is still running. Waiting for completion." ) @@ -291,10 +356,21 @@ def run(self) -> None: logger.info( f"Detected 'passed' -> '{current_build.state}' transition for {current_build.commit}). Repairing ..." ) - if not self.repair_build(current_build): + branch_name = ( + self.active_fix_branch + or self.git_repo.create_branch_for_fix( + current_build.commit + ) + ) + + if self.repair_build(current_build, branch_name): + self.active_fix_branch = branch_name + current_build.state = utils.BuildState.PASSED + else: logger.warning( f"Failed to repair build #{current_build.commit} (commit: {current_build.commit}). Giving up and waiting for user to fix it manually." ) + self.reset_active_fix_branch() else: logger.info( f"{self.last_processed_sha} also not passing. Waiting for transition from passed->failed state." diff --git a/google-bazel-bot/bazel-bot/bazelbot_server_test.py b/google-bazel-bot/bazel-bot/bazelbot_server_test.py index 77c6378d1..eb6eead4d 100644 --- a/google-bazel-bot/bazel-bot/bazelbot_server_test.py +++ b/google-bazel-bot/bazel-bot/bazelbot_server_test.py @@ -249,12 +249,11 @@ def test_process_failure_with_ai(self, mock_asyncio_run): cmd_processor.run_bazel_build.return_value = utils.BazelBuildSuccess() git_repo.push_fix.return_value = True - result = bot.process_failure_with_ai(build_info) + result = bot.process_failure_with_ai(build_info, "bazel-sha1") self.assertTrue(result) - git_repo.create_branch_for_fix.assert_called_with("sha1") git_repo.commit.assert_called() - git_repo.push_fix.assert_called_with(build_info, True) + git_repo.push_fix.assert_called_with(build_info, True, branch_name="bazel-sha1") @mock.patch("bazelbot_server.bazel_agent.query_agent") @mock.patch("bazelbot_server.asyncio.run") @@ -291,7 +290,7 @@ def test_process_failure_with_ai_past_fixes( cmd_processor.run_bazel_build.return_value = utils.BazelBuildSuccess() git_repo.push_fix.return_value = True - result = bot.process_failure_with_ai(build_info) + result = bot.process_failure_with_ai(build_info, "bazel-sha1") self.assertTrue(result) self.assertEqual(mock_query_agent.call_count, 2) @@ -319,13 +318,12 @@ def test_process_failure_with_bant(self): bot.validate_before_publishing = mock.MagicMock(return_value=True) git_repo.push_fix.return_value = True - result = bot.process_failure_with_bant(build_info) + result = bot.process_failure_with_bant(build_info, "bazel-sha1") self.assertTrue(result) - git_repo.create_branch_for_fix.assert_called_with("sha1") cmd_processor.run_bant.assert_called_with(targets=["//target:foo"]) git_repo.commit.assert_called() - git_repo.push_fix.assert_called() + git_repo.push_fix.assert_called_with(build_info, branch_name="bazel-sha1") def test_validate_before_publishing(self): cmd_processor = mock.MagicMock() @@ -375,25 +373,27 @@ def test_repair_build_logic(self): # Mock methods bot.process_failure_with_bant = mock.MagicMock() bot.process_failure_with_ai = mock.MagicMock() + git_repo.get_branch_name.return_value = "bazel-sha1" # 1. Bant succeeds bot.process_failure_with_bant.return_value = True - self.assertTrue(bot.repair_build(build_info)) + self.assertTrue(bot.repair_build(build_info, "bazel-sha1")) bot.process_failure_with_ai.assert_not_called() # 2. Bant fails, AI succeeds bot.process_failure_with_bant.return_value = False bot.process_failure_with_ai.return_value = True - self.assertTrue(bot.repair_build(build_info)) + self.assertTrue(bot.repair_build(build_info, "bazel-sha1")) bot.process_failure_with_ai.assert_called_once() # 3. Both fail bot.process_failure_with_ai.return_value = False - self.assertFalse(bot.repair_build(build_info)) + self.assertFalse(bot.repair_build(build_info, "bazel-sha1")) def test_run_logic(self): cmd_processor = mock.MagicMock() git_repo = mock.MagicMock() + git_repo.create_branch_for_fix.return_value = "bazel-sha2" creds = mock.MagicMock() build_processor = mock.MagicMock() @@ -428,9 +428,12 @@ def test_run_logic(self): # Verifications - # 1. repair_build should be called only for sha2 (PASSED -> FAILED transition) - self.assertEqual(bot.repair_build.call_count, 1) - bot.repair_build.assert_called_with(builds[1]) # sha2 + # 1. Both sha2 (root) and sha3 (nested/consecutive) should be repaired + self.assertEqual(bot.repair_build.call_count, 2) + bot.repair_build.assert_has_calls([ + mock.call(builds[1], "bazel-sha2"), + mock.call(builds[2], "bazel-sha2"), + ]) # 2. Verify state updates self.assertEqual(bot.last_processed_sha, "sha4") @@ -491,54 +494,419 @@ def test_call_with_retry_no_retry_on_unspecified_exception(self, mock_sleep): self.assertEqual(mock_func.call_count, 1) mock_sleep.assert_not_called() + def test_close_existing_prs_with_active_fix_branch(self): + git_repo = utils.LocalGitRepo.__new__(utils.LocalGitRepo) + git_repo.gh_pr_creator = "bot" + git_repo.gh_pr_repo = mock.MagicMock() + + class MockPR: + def __init__(self, ref, url): + self.head = mock.MagicMock(ref=ref) + self.url = url + self.state = "open" + + def edit(self, state): + self.state = state + + @property + def pull_request(self): + return True + + def as_pull_request(self): + return self + + pr1 = MockPR("bazel-sha1", "http://pr1") + pr2 = MockPR("bazel-sha2", "http://pr2") + git_repo.gh_pr_repo.get_issues.return_value = [pr1, pr2] + + git_repo.close_existing_prs(active_fix_branch="bazel-sha1") + + self.assertEqual(pr1.state, "open") + self.assertEqual(pr2.state, "closed") + + def test_get_build_info_clean_pass_resets_fix_branch(self): + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + creds = mock.MagicMock() + build_processor = mock.MagicMock() + + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, creds, build_processor, 10 + ) + bot.active_fix_branch = "bazel-old" + + cmd_processor.run_bazel_build.return_value = mock.MagicMock(success=True) + + info = bot.get_build_info_for_commit("sha1") + + self.assertEqual(info.commit, "sha1") + self.assertEqual(info.state, utils.BuildState.PASSED) + self.assertIsNone(bot.active_fix_branch) + git_repo.checkout_commit.assert_called_with("sha1") + self.assertEqual(cmd_processor.run_bazel_build.call_count, 1) + + def test_get_build_info_clean_fail_no_active_fix(self): + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + creds = mock.MagicMock() + build_processor = mock.MagicMock() + + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, creds, build_processor, 10 + ) + bot.active_fix_branch = None + + cmd_processor.run_bazel_build.return_value = mock.MagicMock( + success=False, stderr="ERROR: (from target //broken:target)" + ) + + info = bot.get_build_info_for_commit("sha1") + + self.assertEqual(info.commit, "sha1") + self.assertEqual(info.state, utils.BuildState.FAILED) + self.assertEqual(info.failed_targets, ["//broken:target"]) + self.assertIsNone(bot.active_fix_branch) + self.assertEqual(cmd_processor.run_bazel_build.call_count, 1) + + def test_get_build_info_nested_pass_carries_fix(self): + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + creds = mock.MagicMock() + build_processor = mock.MagicMock() + + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, creds, build_processor, 10 + ) + bot.active_fix_branch = "bazel-sha1" + + git_repo.rebase_branch.return_value = True + cmd_processor.run_bazel_build.side_effect = [ + mock.MagicMock(success=False, stderr="err1"), + mock.MagicMock(success=True, stderr=""), + ] + + info = bot.get_build_info_for_commit("sha2") + + self.assertEqual(info.commit, "sha2") + self.assertEqual(info.state, utils.BuildState.PASSED) + self.assertEqual(info.failed_targets, []) + self.assertEqual(bot.active_fix_branch, "bazel-sha1") + git_repo.rebase_branch.assert_called_with("bazel-sha1", "sha2") + self.assertEqual(cmd_processor.run_bazel_build.call_count, 2) + + def test_get_build_info_nested_fail_returns_failure(self): + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + creds = mock.MagicMock() + build_processor = mock.MagicMock() + + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, creds, build_processor, 10 + ) + bot.active_fix_branch = "bazel-sha1" + + git_repo.rebase_branch.return_value = True + cmd_processor.run_bazel_build.side_effect = [ + mock.MagicMock(success=False, stderr="err1"), + mock.MagicMock(success=False, stderr="ERROR: (from target //nested:fail)"), + ] + + info = bot.get_build_info_for_commit("sha2") + + self.assertEqual(info.commit, "sha2") + self.assertEqual(info.state, utils.BuildState.FAILED) + self.assertEqual(info.failed_targets, ["//nested:fail"]) + self.assertEqual(bot.active_fix_branch, "bazel-sha1") + self.assertEqual(cmd_processor.run_bazel_build.call_count, 2) + + def test_get_build_info_rebase_fail_resets_fix_branch(self): + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + creds = mock.MagicMock() + build_processor = mock.MagicMock() + + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, creds, build_processor, 10 + ) + bot.active_fix_branch = "bazel-sha1" + + git_repo.rebase_branch.return_value = False + cmd_processor.run_bazel_build.return_value = mock.MagicMock( + success=False, stderr="ERROR: (from target //t:one)" + ) + + info = bot.get_build_info_for_commit("sha2") + + self.assertEqual(info.commit, "sha2") + self.assertEqual(info.state, utils.BuildState.FAILED) + self.assertIsNone(bot.active_fix_branch) + self.assertEqual(cmd_processor.run_bazel_build.call_count, 1) + + def test_run_logic_nested_failure_repair(self): + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + git_repo.create_branch_for_fix.return_value = "bazel-sha2" + creds = mock.MagicMock() + build_processor = mock.MagicMock() + + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, creds, build_processor, 10 + ) + bot.last_processed_sha = "init_sha" + bot.last_processed_state = utils.BuildState.PASSED + + builds = [ + utils.BuildInfo(commit="sha1", state=utils.BuildState.PASSED), + utils.BuildInfo(commit="sha2", state=utils.BuildState.FAILED), # Root failure + utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), # Clean with fix + utils.BuildInfo(commit="sha4", state=utils.BuildState.FAILED), # Nested failure! + utils.BuildInfo(commit="sha5", state=utils.BuildState.PASSED), + ] + build_processor.get_builds_to_process.return_value = builds + + bot.repair_build = mock.MagicMock(return_value=True) + bot.wait = mock.MagicMock(side_effect=StopIteration) + + try: + bot.run() + except StopIteration: + pass + + # Both sha2 (root) and sha4 (nested) should be repaired! + self.assertEqual(bot.repair_build.call_count, 2) + bot.repair_build.assert_has_calls([ + mock.call(builds[1], "bazel-sha2"), + mock.call(builds[3], "bazel-sha2"), + ]) + self.assertEqual(bot.active_fix_branch, "bazel-sha2") + self.assertEqual(bot.last_processed_sha, "sha5") + self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) + + @mock.patch("bazelbot_server.asyncio.run") + def test_process_failure_with_ai_with_active_fix_branch(self, mock_asyncio_run): + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + creds = mock.MagicMock() + build_processor = mock.MagicMock() + + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, creds, build_processor, 10 + ) + bot.active_fix_branch = "bazel-sha1" + build_info = utils.BuildInfo("sha2", utils.BuildState.FAILED, [], 2) + + agent_result = mock.MagicMock() + agent_result.status = bazel_agent.AgentErrors.SUCCESS + agent_result.summary = "Fixed" + mock_asyncio_run.return_value = agent_result + + # Case 1: active_fix_branch is set, fix succeeds + cmd_processor.run_bazel_build.return_value = mock.MagicMock(success=True) + git_repo.push_fix.return_value = True + + result = bot.process_failure_with_ai( + build_info, "bazel-sha1" + ) + + self.assertTrue(result) + # Should only push once (the successful fix), NOT the "AI is working" commit + self.assertEqual(git_repo.push_fix.call_count, 1) + git_repo.push_fix.assert_called_with(build_info, git_repo.can_create_pr, branch_name="bazel-sha1") + + # Case 2: active_fix_branch is set, validation fails -> should NOT push "AI failed" commit + git_repo.push_fix.reset_mock() + bot.validate_before_publishing = mock.MagicMock(return_value=False) + + result = bot.process_failure_with_ai( + build_info, "bazel-sha1" + ) + + self.assertFalse(result) + git_repo.push_fix.assert_not_called() + + @mock.patch("utils.github.GithubIntegration") + @mock.patch("utils.github.Auth") + @mock.patch("utils.call_with_retry") + @mock.patch("utils.git.Repo") + @mock.patch("os.path.exists") + def test_push_fix_updates_existing_pr_body( + self, mock_exists, mock_repo, mock_call_with_retry, mock_auth, mock_github_integration + ): + mock_exists.return_value = False + creds = mock.MagicMock() + creds.gh_fork_repo_name = "fork/repo" + creds.gh_pr_repo_name = "pr/repo" + creds.use_github_app = True + repo = utils.LocalGitRepo("/path/to/repo", creds, can_create_pr=True) + repo_instance = mock_repo.return_value + + mock_call_with_retry.side_effect = lambda exceptions, f, *args, **kwargs: f(*args, **kwargs) + repo.fork_github_integration.get_access_token.return_value.token = "token" + + class MockPR: + def __init__(self, ref, body): + self.head = mock.MagicMock(ref=ref) + self.body = body + self.url = "http://pr1" + self.state = "open" + + def edit(self, **kwargs): + if "body" in kwargs: + self.body = kwargs["body"] + if "state" in kwargs: + self.state = kwargs["state"] + + @property + def pull_request(self): + return True + + def as_pull_request(self): + return self + + existing_pr = MockPR( + "bazel-sha1", + "This fixes sha1 (#100).\n\nBuildkite error link: http://bk1\n", + ) + repo.gh_pr_repo.get_issues.return_value = [existing_pr] + + build_info2 = utils.BuildInfo("sha2", pr_number=200) + result = repo.push_fix(build_info2, True, branch_name="bazel-sha1") + + self.assertTrue(result) + # Verify body has both fixes + self.assertIn("This fixes sha1 (#100)", existing_pr.body) + self.assertIn("This fixes sha2 (#200)", existing_pr.body) + # Verify create_pull was NOT called + repo.gh_pr_repo.create_pull.assert_not_called() + def test_call_with_retry_empty_exceptions(self): mock_func = mock.MagicMock() with self.assertRaises(ValueError): utils.call_with_retry((), mock_func) mock_func.assert_not_called() - @mock.patch("utils.subprocess.run") - def test_run_bazel_build_runs_all_configs(self, mock_run): - mock_run.return_value = mock.MagicMock(returncode=0, stdout="ok", stderr="") - cmd_processor = utils.CommandProcessor("/path/to/repo") - configs = ( - utils.BazelBuildConfig(name="default", args=("//...",)), - utils.BazelBuildConfig(name="second", args=("--flag", "//foo/...")), - ) - result = cmd_processor.run_bazel_build(configs=configs) - - self.assertTrue(result.success) - self.assertEqual(mock_run.call_count, len(configs)) - for call, config in zip(mock_run.call_args_list, configs): - self.assertEqual(call.args[0][1:], list(config.args)) - self.assertEqual( - call.kwargs["env"]["BAZEL_OUTPUT_BASE"], - "/tmp/bazel_build_" + config.name, - ) - - @mock.patch("utils.subprocess.run") - def test_run_bazel_build_propagates_failure(self, mock_run): - configs = ( - utils.BazelBuildConfig(name="default", args=("//...",)), - utils.BazelBuildConfig(name="second", args=("--flag", "//foo/...")), - utils.BazelBuildConfig(name="third", args=("//bar/...",)), - ) - mock_run.side_effect = [ - mock.MagicMock(returncode=0, stdout="", stderr=""), - mock.MagicMock( - returncode=1, stdout="out", stderr="ERROR (from target //foo:bar)" - ), + def test_run_logic_consecutive_failures_both_repaired(self): + """Tests that when the first build fails and the second commit also fails (back-to-back), + both are repaired sequentially, with the second repair carrying the active fix branch.""" + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + git_repo.create_branch_for_fix.return_value = "bazel-sha1" + creds = mock.MagicMock() + build_processor = mock.MagicMock() + + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, creds, build_processor, 10 + ) + bot.last_processed_sha = "init_sha" + bot.last_processed_state = utils.BuildState.PASSED + + builds = [ + utils.BuildInfo(commit="sha1", state=utils.BuildState.FAILED), + utils.BuildInfo(commit="sha2", state=utils.BuildState.FAILED), + utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), ] - cmd_processor = utils.CommandProcessor("/path/to/repo") - result = cmd_processor.run_bazel_build(configs) + build_processor.get_builds_to_process.return_value = builds - self.assertFalse(result.success) - self.assertEqual(mock_run.call_count, 2) - self.assertEqual(result.config, configs[1]) - self.assertEqual(result.stdout, "out") - self.assertEqual(result.stderr, "ERROR (from target //foo:bar)") - self.assertEqual(utils.parse_targets(result.stderr), ["//foo:bar"]) + bot.repair_build = mock.MagicMock(return_value=True) + bot.wait = mock.MagicMock(side_effect=StopIteration) + try: + bot.run() + except StopIteration: + pass + + # Both consecutive failures must be repaired + self.assertEqual(bot.repair_build.call_count, 2) + bot.repair_build.assert_has_calls([ + mock.call(builds[0], "bazel-sha1"), + mock.call(builds[1], "bazel-sha1"), + ]) + self.assertEqual(bot.active_fix_branch, "bazel-sha1") + self.assertEqual(bot.last_processed_sha, "sha3") + self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) + + def test_run_logic_consecutive_failures_first_repair_fails(self): + """Tests that when the first build fails and repair fails, its state remains FAILED, + so the next consecutive failure does not trigger repair (waiting for manual intervention).""" + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + git_repo.create_branch_for_fix.return_value = "bazel-sha1" + creds = mock.MagicMock() + build_processor = mock.MagicMock() + + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, creds, build_processor, 10 + ) + bot.last_processed_sha = "init_sha" + bot.last_processed_state = utils.BuildState.PASSED + + builds = [ + utils.BuildInfo(commit="sha1", state=utils.BuildState.FAILED), + utils.BuildInfo(commit="sha2", state=utils.BuildState.FAILED), + utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), + ] + build_processor.get_builds_to_process.return_value = builds + + # First repair fails + bot.repair_build = mock.MagicMock(return_value=False) + bot.wait = mock.MagicMock(side_effect=StopIteration) + + try: + bot.run() + except StopIteration: + pass + + # Only sha1 was attempted; sha2 was skipped because state was FAILED + self.assertEqual(bot.repair_build.call_count, 1) + bot.repair_build.assert_called_once_with( + builds[0], "bazel-sha1" + ) + self.assertIsNone(bot.active_fix_branch) + self.assertEqual(bot.last_processed_sha, "sha3") + self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) + + def test_run_logic_nested_failure_after_gap_of_commits(self): + """Tests scenario where first build fails and is repaired, followed by a gap of + 2-3 passing commits, and then another build fails (nested failure).""" + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + git_repo.create_branch_for_fix.return_value = "bazel-sha1" + creds = mock.MagicMock() + build_processor = mock.MagicMock() + + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, creds, build_processor, 10 + ) + bot.last_processed_sha = "init_sha" + bot.last_processed_state = utils.BuildState.PASSED + + builds = [ + utils.BuildInfo(commit="sha1", state=utils.BuildState.FAILED), # Root failure + utils.BuildInfo(commit="sha2", state=utils.BuildState.PASSED), # Gap commit 1 + utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), # Gap commit 2 + utils.BuildInfo(commit="sha4", state=utils.BuildState.PASSED), # Gap commit 3 + utils.BuildInfo(commit="sha5", state=utils.BuildState.FAILED), # Nested failure after 3-commit gap + utils.BuildInfo(commit="sha6", state=utils.BuildState.PASSED), + ] + build_processor.get_builds_to_process.return_value = builds + + bot.repair_build = mock.MagicMock(return_value=True) + bot.wait = mock.MagicMock(side_effect=StopIteration) + + try: + bot.run() + except StopIteration: + pass + + # Both sha1 (root) and sha5 (nested after gap of 3 commits) should be repaired + self.assertEqual(bot.repair_build.call_count, 2) + bot.repair_build.assert_has_calls([ + mock.call(builds[0], "bazel-sha1"), + mock.call(builds[4], "bazel-sha1"), + ]) + self.assertEqual(bot.active_fix_branch, "bazel-sha1") + self.assertEqual(bot.last_processed_sha, "sha6") + self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) if __name__ == "__main__": unittest.main() diff --git a/google-bazel-bot/bazel-bot/utils.py b/google-bazel-bot/bazel-bot/utils.py index 293340498..fbd3cc2fd 100644 --- a/google-bazel-bot/bazel-bot/utils.py +++ b/google-bazel-bot/bazel-bot/utils.py @@ -360,16 +360,38 @@ def refresh_main_branch(self) -> str: self.repo.remotes.origin.fetch ) self.repo.git.reset("--hard", f"{self.remote_name}/{self.main_branch}") - return self.repo.head.commit.hexsha def diff(self) -> str: return self.repo.git.diff(None) - def create_branch_for_fix(self, commit_hash: str) -> None: - """Prepares the local git repository for applying fixes.""" - self.checkout_commit(commit_hash) - self.repo.create_head(self.get_branch_name(commit_hash), force=True).checkout() + def create_branch_for_fix(self, commit_hash: str) -> str: + """Prepares the local git repository for applying fixes from current HEAD.""" + branch_name = self.get_branch_name(commit_hash) + self.repo.create_head(branch_name, force=True).checkout() + return branch_name + + def rebase_branch(self, branch_name: str, new_base: str) -> bool: + """Rebases branch_name onto new_base. Returns True on success, False on conflict/error.""" + try: + self.repo.git.checkout(branch_name) + self.repo.git.rebase(new_base) + return True + except git.GitCommandError as e: + logger.error(f"Failed to rebase {branch_name} onto {new_base}: {e}") + try: + self.repo.git.rebase("--abort") + except git.GitCommandError: + pass + return False + + def reset_hard(self, commit_or_branch: str | None = None) -> None: + """Hard resets the repository and cleans untracked files.""" + if commit_or_branch: + self.repo.git.reset("--hard", commit_or_branch) + else: + self.repo.git.reset("--hard") + self.repo.git.clean("-fd") def checkout_commit(self, commit_hash: str): """Prepares the local git repository for applying fixes.""" @@ -384,24 +406,40 @@ def commit(self, message: str) -> None: def is_repo_dirty(self, untracked_files=False) -> bool: return self.repo.is_dirty(untracked_files=untracked_files) - # This needs to be revisited when we have support for nested failures. - def close_existing_prs(self) -> None: + def close_existing_prs(self, active_fix_branch: str | None = None): + active_pr = None for open_pr in self.gh_pr_repo.get_issues( creator=self.gh_pr_creator, state="open" ): + if active_fix_branch: + pr = None + head_ref = None + if getattr(open_pr, "pull_request", None) and hasattr(open_pr, "as_pull_request"): + pr = open_pr.as_pull_request() + head_ref = getattr(getattr(pr, "head", None), "ref", None) + elif hasattr(open_pr, "head"): + pr = open_pr + head_ref = getattr(open_pr.head, "ref", None) + if head_ref == active_fix_branch: + logger.info(f"Skipping active PR for branch {active_fix_branch}: {open_pr.url}") + active_pr = pr or open_pr + continue print(f"Closing unmerged PR from previous fix attempt: {open_pr.url}") open_pr.edit(state="closed") + return active_pr def push_fix( self, build_data: "BuildInfo", create_pr: bool | None = None, + branch_name: str | None = None, ) -> bool: """Pushes the branch and creates a GitHub PR against it.""" if create_pr is None: create_pr = self.can_create_pr commit_hash = build_data.commit - branch_name = self.get_branch_name(commit_hash) + if not branch_name: + branch_name = self.get_branch_name(commit_hash) # 1. Get access token try: @@ -451,19 +489,17 @@ def push_fix( ) return True - # 4. Close existing PRs (if any) + # 4. Close existing PRs (if any) and locate active PR + active_pr = None try: - call_with_retry( + active_pr = call_with_retry( (github.GithubException,), self.close_existing_prs, + active_fix_branch=branch_name, ) except github.GithubException as e: logger.warning(f"Failed to close existing PRs: {e}. Proceeding anyway.") - # 5. Create new Pull Request - logger.info( - f"Creating Pull Request for branch {branch_name} from {self.creds.gh_fork_repo_name} to {self.creds.gh_pr_repo_name}..." - ) buildkite_url = build_data.buildkite_url pr_number_suffix = f" (#{build_data.pr_number})" if build_data.pr_number else "" pr_body = ( @@ -471,6 +507,32 @@ def push_fix( f"Buildkite error link: {buildkite_url}\n" ) + # If a PR already exists for active_branch, update its body by appending the new fix + if active_pr: + current_body = getattr(active_pr, "body", "") or "" + if commit_hash not in current_body: + updated_body = f"{current_body.rstrip()}\n\n{pr_body.strip()}\n" + logger.info( + f"Updating PR body for existing PR for branch {branch_name} to include fix for {commit_hash[:7]}..." + ) + try: + call_with_retry( + (github.GithubException,), + active_pr.edit, + body=updated_body, + ) + except github.GithubException as e: + logger.error(f"Failed to update PR body: {e}") + else: + logger.info( + f"PR body for {branch_name} already mentions {commit_hash[:7]}." + ) + return True + + # 5. No active PR exists - create new Pull Request + logger.info( + f"Creating Pull Request for branch {branch_name} from {self.creds.gh_fork_repo_name} to {self.creds.gh_pr_repo_name}..." + ) try: if not self.creds.use_github_app: if create_pr and not self.creds.gh_pr_user_token: @@ -490,6 +552,11 @@ def push_fix( logger.info(f"Pull Request Created: {pr.html_url}") return True except github.GithubException as e: + if getattr(e, "status", None) == 422 and "A pull request already exists" in str(getattr(e, "data", "")): + logger.info( + f"Pull request already exists for branch {branch_name}. Updated via push." + ) + return True logger.error(f"All attempts to create PR failed: {e}") return False From e9abe6d3868b2e30072157de31d90dbabaeaf1de Mon Sep 17 00:00:00 2001 From: Pranav Kant Date: Wed, 30 Sep 2026 15:42:53 -0700 Subject: [PATCH 2/5] change test to allow pushing empty ai failed to fix commit --- google-bazel-bot/bazel-bot/bazelbot_server_test.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/google-bazel-bot/bazel-bot/bazelbot_server_test.py b/google-bazel-bot/bazel-bot/bazelbot_server_test.py index eb6eead4d..da3df4298 100644 --- a/google-bazel-bot/bazel-bot/bazelbot_server_test.py +++ b/google-bazel-bot/bazel-bot/bazelbot_server_test.py @@ -713,7 +713,7 @@ def test_process_failure_with_ai_with_active_fix_branch(self, mock_asyncio_run): self.assertEqual(git_repo.push_fix.call_count, 1) git_repo.push_fix.assert_called_with(build_info, git_repo.can_create_pr, branch_name="bazel-sha1") - # Case 2: active_fix_branch is set, validation fails -> should NOT push "AI failed" commit + # Case 2: active_fix_branch is set, validation fails -> should push "AI failed" commit git_repo.push_fix.reset_mock() bot.validate_before_publishing = mock.MagicMock(return_value=False) @@ -722,7 +722,9 @@ def test_process_failure_with_ai_with_active_fix_branch(self, mock_asyncio_run): ) self.assertFalse(result) - git_repo.push_fix.assert_not_called() + git_repo.push_fix.assert_called_once_with( + build_info, False, branch_name="bazel-sha1" + ) @mock.patch("utils.github.GithubIntegration") @mock.patch("utils.github.Auth") From ce42a399d57b2386366280786f4a10a3d1887318 Mon Sep 17 00:00:00 2001 From: Pranav Kant Date: Fri, 16 Oct 2026 10:45:50 -0700 Subject: [PATCH 3/5] refactor and create a new PR for every fix --- google-bazel-bot/bazel-bot/bazelbot_server.py | 54 +++--- .../bazel-bot/bazelbot_server_test.py | 166 ++++++------------ google-bazel-bot/bazel-bot/utils.py | 76 ++------ 3 files changed, 94 insertions(+), 202 deletions(-) diff --git a/google-bazel-bot/bazel-bot/bazelbot_server.py b/google-bazel-bot/bazel-bot/bazelbot_server.py index e13f73d28..63d25ea72 100644 --- a/google-bazel-bot/bazel-bot/bazelbot_server.py +++ b/google-bazel-bot/bazel-bot/bazelbot_server.py @@ -56,7 +56,6 @@ def __init__( self.last_processed_sha: str = "" self.poll_interval = poll_interval # Branch containing fixes that have not been merged - # All subsequent failures are merged into this branch as separate commits self.active_fix_branch: str | None = None def reset_active_fix_branch(self) -> None: @@ -66,9 +65,7 @@ def wait(self, seconds): """Sleeps for a given number of seconds""" time.sleep(seconds) - def process_failure_with_bant( - self, build_data: utils.BuildInfo, fix_branch: str - ) -> bool: + def process_failure_with_bant(self, build_data: utils.BuildInfo) -> bool: base_sha = self.git_repo.repo.head.commit.hexsha if not self.command_processor.run_bant(targets=build_data.failed_targets): logger.warning("Running bant failed.") @@ -84,26 +81,24 @@ def process_failure_with_bant( f"[Bazel] Fix build for {build_data.commit[:7]}\n\n" f"Buildkite error link: {build_data.buildkite_url}" ) - if not self.git_repo.push_fix(build_data, branch_name=fix_branch): + if not self.git_repo.push_fix( + build_data, close_existing_prs=not self.active_fix_branch + ): logger.warning("Failed to publish bant fix.") return False return True - def repair_build( - self, - build: utils.BuildInfo, - fix_branch: str | None = None, - ) -> bool: + def repair_build(self, build: utils.BuildInfo) -> bool: if build.state != utils.BuildState.FAILED: logger.info(f"Build for {build.commit} is not failed. Nothing to repair.") return False record = RepairSummaryRecord(build.commit, "", time.time()) - if self.process_failure_with_bant(build, fix_branch): + if self.process_failure_with_bant(build): logger.info(f"Successfully repaired build for {build.commit}) using bant.") record.fixed_by = FixTool.BANT - elif self.process_failure_with_ai(build, fix_branch): + elif self.process_failure_with_ai(build): logger.info( f"Successfully repaired build for {build.commit} using AI agent." ) @@ -143,25 +138,19 @@ def validate_before_publishing(self) -> bool: return True - def process_failure_with_ai( - self, - build_data: utils.BuildInfo, - fix_branch: str, - ) -> bool: + def process_failure_with_ai(self, build_data: utils.BuildInfo) -> bool: logger.info("Invoking AI Agent...") attempt_num = 0 agent_exhausted_tries = 0 past_fixes = [] base_sha = self.git_repo.repo.head.commit.hexsha - # Push an empty branch to indicate that AI fix is in progress ONLY - # We only do this if there is no active branch - if not self.active_fix_branch: - self.git_repo.commit( - f"AI is working on fixing build for {build_data.commit[:7]}. Check back later!\n\n" - f"Buildkite error link: {build_data.buildkite_url}" - ) - self.git_repo.push_fix(build_data, False, branch_name=fix_branch) + # Push an empty branch to indicate that AI fix is in progress + self.git_repo.commit( + f"AI is working on fixing build for {build_data.commit[:7]}. Check back later!\n\n" + f"Buildkite error link: {build_data.buildkite_url}" + ) + self.git_repo.push_fix(build_data, False) while True: if attempt_num == MAX_AGENT_ITERATIONS: @@ -225,7 +214,7 @@ def process_failure_with_ai( f"will need to fix it manually\n\n" f"Buildkite error link: {build_data.buildkite_url}" ) - self.git_repo.push_fix(build_data, False, branch_name=fix_branch) + self.git_repo.push_fix(build_data, False) return False self.git_repo.commit( @@ -233,7 +222,9 @@ def process_failure_with_ai( f"Buildkite error link: {build_data.buildkite_url}" ) if not self.git_repo.push_fix( - build_data, self.git_repo.can_create_pr, branch_name=fix_branch + build_data, + self.git_repo.can_create_pr, + close_existing_prs=not self.active_fix_branch, ): logger.warning( f"Failed to publish AI changes for commit: {build_data.commit}" @@ -356,14 +347,11 @@ def run(self) -> None: logger.info( f"Detected 'passed' -> '{current_build.state}' transition for {current_build.commit}). Repairing ..." ) - branch_name = ( - self.active_fix_branch - or self.git_repo.create_branch_for_fix( - current_build.commit - ) + branch_name = self.git_repo.create_branch_for_fix( + current_build.commit ) - if self.repair_build(current_build, branch_name): + if self.repair_build(current_build): self.active_fix_branch = branch_name current_build.state = utils.BuildState.PASSED else: diff --git a/google-bazel-bot/bazel-bot/bazelbot_server_test.py b/google-bazel-bot/bazel-bot/bazelbot_server_test.py index da3df4298..c123a955e 100644 --- a/google-bazel-bot/bazel-bot/bazelbot_server_test.py +++ b/google-bazel-bot/bazel-bot/bazelbot_server_test.py @@ -249,11 +249,13 @@ def test_process_failure_with_ai(self, mock_asyncio_run): cmd_processor.run_bazel_build.return_value = utils.BazelBuildSuccess() git_repo.push_fix.return_value = True - result = bot.process_failure_with_ai(build_info, "bazel-sha1") + result = bot.process_failure_with_ai(build_info) self.assertTrue(result) git_repo.commit.assert_called() - git_repo.push_fix.assert_called_with(build_info, True, branch_name="bazel-sha1") + git_repo.push_fix.assert_called_with( + build_info, True, close_existing_prs=True + ) @mock.patch("bazelbot_server.bazel_agent.query_agent") @mock.patch("bazelbot_server.asyncio.run") @@ -290,7 +292,7 @@ def test_process_failure_with_ai_past_fixes( cmd_processor.run_bazel_build.return_value = utils.BazelBuildSuccess() git_repo.push_fix.return_value = True - result = bot.process_failure_with_ai(build_info, "bazel-sha1") + result = bot.process_failure_with_ai(build_info) self.assertTrue(result) self.assertEqual(mock_query_agent.call_count, 2) @@ -318,12 +320,14 @@ def test_process_failure_with_bant(self): bot.validate_before_publishing = mock.MagicMock(return_value=True) git_repo.push_fix.return_value = True - result = bot.process_failure_with_bant(build_info, "bazel-sha1") + result = bot.process_failure_with_bant(build_info) self.assertTrue(result) cmd_processor.run_bant.assert_called_with(targets=["//target:foo"]) git_repo.commit.assert_called() - git_repo.push_fix.assert_called_with(build_info, branch_name="bazel-sha1") + git_repo.push_fix.assert_called_with( + build_info, close_existing_prs=True + ) def test_validate_before_publishing(self): cmd_processor = mock.MagicMock() @@ -373,27 +377,26 @@ def test_repair_build_logic(self): # Mock methods bot.process_failure_with_bant = mock.MagicMock() bot.process_failure_with_ai = mock.MagicMock() - git_repo.get_branch_name.return_value = "bazel-sha1" # 1. Bant succeeds bot.process_failure_with_bant.return_value = True - self.assertTrue(bot.repair_build(build_info, "bazel-sha1")) + self.assertTrue(bot.repair_build(build_info)) bot.process_failure_with_ai.assert_not_called() # 2. Bant fails, AI succeeds bot.process_failure_with_bant.return_value = False bot.process_failure_with_ai.return_value = True - self.assertTrue(bot.repair_build(build_info, "bazel-sha1")) + self.assertTrue(bot.repair_build(build_info)) bot.process_failure_with_ai.assert_called_once() # 3. Both fail bot.process_failure_with_ai.return_value = False - self.assertFalse(bot.repair_build(build_info, "bazel-sha1")) + self.assertFalse(bot.repair_build(build_info)) def test_run_logic(self): cmd_processor = mock.MagicMock() git_repo = mock.MagicMock() - git_repo.create_branch_for_fix.return_value = "bazel-sha2" + git_repo.create_branch_for_fix.side_effect = lambda sha: f"bazel-{sha}" creds = mock.MagicMock() build_processor = mock.MagicMock() @@ -428,12 +431,13 @@ def test_run_logic(self): # Verifications - # 1. Both sha2 (root) and sha3 (nested/consecutive) should be repaired + # 1. Both sha2 (root) and sha3 (nested/consecutive) should be repaired on their own branches self.assertEqual(bot.repair_build.call_count, 2) bot.repair_build.assert_has_calls([ - mock.call(builds[1], "bazel-sha2"), - mock.call(builds[2], "bazel-sha2"), + mock.call(builds[1]), + mock.call(builds[2]), ]) + self.assertEqual(bot.active_fix_branch, "bazel-sha3") # 2. Verify state updates self.assertEqual(bot.last_processed_sha, "sha4") @@ -494,36 +498,6 @@ def test_call_with_retry_no_retry_on_unspecified_exception(self, mock_sleep): self.assertEqual(mock_func.call_count, 1) mock_sleep.assert_not_called() - def test_close_existing_prs_with_active_fix_branch(self): - git_repo = utils.LocalGitRepo.__new__(utils.LocalGitRepo) - git_repo.gh_pr_creator = "bot" - git_repo.gh_pr_repo = mock.MagicMock() - - class MockPR: - def __init__(self, ref, url): - self.head = mock.MagicMock(ref=ref) - self.url = url - self.state = "open" - - def edit(self, state): - self.state = state - - @property - def pull_request(self): - return True - - def as_pull_request(self): - return self - - pr1 = MockPR("bazel-sha1", "http://pr1") - pr2 = MockPR("bazel-sha2", "http://pr2") - git_repo.gh_pr_repo.get_issues.return_value = [pr1, pr2] - - git_repo.close_existing_prs(active_fix_branch="bazel-sha1") - - self.assertEqual(pr1.state, "open") - self.assertEqual(pr2.state, "closed") - def test_get_build_info_clean_pass_resets_fix_branch(self): cmd_processor = mock.MagicMock() git_repo = mock.MagicMock() @@ -645,7 +619,7 @@ def test_get_build_info_rebase_fail_resets_fix_branch(self): def test_run_logic_nested_failure_repair(self): cmd_processor = mock.MagicMock() git_repo = mock.MagicMock() - git_repo.create_branch_for_fix.return_value = "bazel-sha2" + git_repo.create_branch_for_fix.side_effect = lambda sha: f"bazel-{sha}" creds = mock.MagicMock() build_processor = mock.MagicMock() @@ -672,13 +646,17 @@ def test_run_logic_nested_failure_repair(self): except StopIteration: pass - # Both sha2 (root) and sha4 (nested) should be repaired! + # Both sha2 (root) and sha4 (nested) should be repaired on separate branches! self.assertEqual(bot.repair_build.call_count, 2) bot.repair_build.assert_has_calls([ - mock.call(builds[1], "bazel-sha2"), - mock.call(builds[3], "bazel-sha2"), + mock.call(builds[1]), + mock.call(builds[3]), ]) - self.assertEqual(bot.active_fix_branch, "bazel-sha2") + git_repo.create_branch_for_fix.assert_has_calls([ + mock.call("sha2"), + mock.call("sha4"), + ]) + self.assertEqual(bot.active_fix_branch, "bazel-sha4") self.assertEqual(bot.last_processed_sha, "sha5") self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) @@ -700,38 +678,38 @@ def test_process_failure_with_ai_with_active_fix_branch(self, mock_asyncio_run): agent_result.summary = "Fixed" mock_asyncio_run.return_value = agent_result - # Case 1: active_fix_branch is set, fix succeeds + # Case 1: active_fix_branch is set, fix succeeds -> keeps existing PRs open cmd_processor.run_bazel_build.return_value = mock.MagicMock(success=True) git_repo.push_fix.return_value = True - result = bot.process_failure_with_ai( - build_info, "bazel-sha1" - ) + result = bot.process_failure_with_ai(build_info) self.assertTrue(result) - # Should only push once (the successful fix), NOT the "AI is working" commit - self.assertEqual(git_repo.push_fix.call_count, 1) - git_repo.push_fix.assert_called_with(build_info, git_repo.can_create_pr, branch_name="bazel-sha1") + self.assertEqual(git_repo.push_fix.call_count, 2) + git_repo.push_fix.assert_has_calls([ + mock.call(build_info, False), + mock.call(build_info, git_repo.can_create_pr, close_existing_prs=False), + ]) - # Case 2: active_fix_branch is set, validation fails -> should push "AI failed" commit + # Case 2: active_fix_branch is set, validation fails -> pushes "AI failed" commit git_repo.push_fix.reset_mock() bot.validate_before_publishing = mock.MagicMock(return_value=False) - result = bot.process_failure_with_ai( - build_info, "bazel-sha1" - ) + result = bot.process_failure_with_ai(build_info) self.assertFalse(result) - git_repo.push_fix.assert_called_once_with( - build_info, False, branch_name="bazel-sha1" - ) + self.assertEqual(git_repo.push_fix.call_count, 2) + git_repo.push_fix.assert_has_calls([ + mock.call(build_info, False), + mock.call(build_info, False), + ]) @mock.patch("utils.github.GithubIntegration") @mock.patch("utils.github.Auth") @mock.patch("utils.call_with_retry") @mock.patch("utils.git.Repo") @mock.patch("os.path.exists") - def test_push_fix_updates_existing_pr_body( + def test_push_fix_skips_closing_prs_when_stacked( self, mock_exists, mock_repo, mock_call_with_retry, mock_auth, mock_github_integration ): mock_exists.return_value = False @@ -740,46 +718,17 @@ def test_push_fix_updates_existing_pr_body( creds.gh_pr_repo_name = "pr/repo" creds.use_github_app = True repo = utils.LocalGitRepo("/path/to/repo", creds, can_create_pr=True) - repo_instance = mock_repo.return_value mock_call_with_retry.side_effect = lambda exceptions, f, *args, **kwargs: f(*args, **kwargs) repo.fork_github_integration.get_access_token.return_value.token = "token" - - class MockPR: - def __init__(self, ref, body): - self.head = mock.MagicMock(ref=ref) - self.body = body - self.url = "http://pr1" - self.state = "open" - - def edit(self, **kwargs): - if "body" in kwargs: - self.body = kwargs["body"] - if "state" in kwargs: - self.state = kwargs["state"] - - @property - def pull_request(self): - return True - - def as_pull_request(self): - return self - - existing_pr = MockPR( - "bazel-sha1", - "This fixes sha1 (#100).\n\nBuildkite error link: http://bk1\n", - ) - repo.gh_pr_repo.get_issues.return_value = [existing_pr] + repo.gh_pr_repo.create_pull.return_value = mock.MagicMock(html_url="http://pr2") build_info2 = utils.BuildInfo("sha2", pr_number=200) - result = repo.push_fix(build_info2, True, branch_name="bazel-sha1") + result = repo.push_fix(build_info2, True, close_existing_prs=False) self.assertTrue(result) - # Verify body has both fixes - self.assertIn("This fixes sha1 (#100)", existing_pr.body) - self.assertIn("This fixes sha2 (#200)", existing_pr.body) - # Verify create_pull was NOT called - repo.gh_pr_repo.create_pull.assert_not_called() + repo.gh_pr_repo.get_issues.assert_not_called() + repo.gh_pr_repo.create_pull.assert_called_once() def test_call_with_retry_empty_exceptions(self): mock_func = mock.MagicMock() @@ -789,10 +738,10 @@ def test_call_with_retry_empty_exceptions(self): def test_run_logic_consecutive_failures_both_repaired(self): """Tests that when the first build fails and the second commit also fails (back-to-back), - both are repaired sequentially, with the second repair carrying the active fix branch.""" + both are repaired sequentially on their own stacked branches.""" cmd_processor = mock.MagicMock() git_repo = mock.MagicMock() - git_repo.create_branch_for_fix.return_value = "bazel-sha1" + git_repo.create_branch_for_fix.side_effect = lambda sha: f"bazel-{sha}" creds = mock.MagicMock() build_processor = mock.MagicMock() @@ -820,10 +769,10 @@ def test_run_logic_consecutive_failures_both_repaired(self): # Both consecutive failures must be repaired self.assertEqual(bot.repair_build.call_count, 2) bot.repair_build.assert_has_calls([ - mock.call(builds[0], "bazel-sha1"), - mock.call(builds[1], "bazel-sha1"), + mock.call(builds[0]), + mock.call(builds[1]), ]) - self.assertEqual(bot.active_fix_branch, "bazel-sha1") + self.assertEqual(bot.active_fix_branch, "bazel-sha2") self.assertEqual(bot.last_processed_sha, "sha3") self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) @@ -832,7 +781,7 @@ def test_run_logic_consecutive_failures_first_repair_fails(self): so the next consecutive failure does not trigger repair (waiting for manual intervention).""" cmd_processor = mock.MagicMock() git_repo = mock.MagicMock() - git_repo.create_branch_for_fix.return_value = "bazel-sha1" + git_repo.create_branch_for_fix.side_effect = lambda sha: f"bazel-{sha}" creds = mock.MagicMock() build_processor = mock.MagicMock() @@ -860,9 +809,7 @@ def test_run_logic_consecutive_failures_first_repair_fails(self): # Only sha1 was attempted; sha2 was skipped because state was FAILED self.assertEqual(bot.repair_build.call_count, 1) - bot.repair_build.assert_called_once_with( - builds[0], "bazel-sha1" - ) + bot.repair_build.assert_called_once_with(builds[0]) self.assertIsNone(bot.active_fix_branch) self.assertEqual(bot.last_processed_sha, "sha3") self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) @@ -872,7 +819,7 @@ def test_run_logic_nested_failure_after_gap_of_commits(self): 2-3 passing commits, and then another build fails (nested failure).""" cmd_processor = mock.MagicMock() git_repo = mock.MagicMock() - git_repo.create_branch_for_fix.return_value = "bazel-sha1" + git_repo.create_branch_for_fix.side_effect = lambda sha: f"bazel-{sha}" creds = mock.MagicMock() build_processor = mock.MagicMock() @@ -903,12 +850,13 @@ def test_run_logic_nested_failure_after_gap_of_commits(self): # Both sha1 (root) and sha5 (nested after gap of 3 commits) should be repaired self.assertEqual(bot.repair_build.call_count, 2) bot.repair_build.assert_has_calls([ - mock.call(builds[0], "bazel-sha1"), - mock.call(builds[4], "bazel-sha1"), + mock.call(builds[0]), + mock.call(builds[4]), ]) - self.assertEqual(bot.active_fix_branch, "bazel-sha1") + self.assertEqual(bot.active_fix_branch, "bazel-sha5") self.assertEqual(bot.last_processed_sha, "sha6") self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) + if __name__ == "__main__": unittest.main() diff --git a/google-bazel-bot/bazel-bot/utils.py b/google-bazel-bot/bazel-bot/utils.py index fbd3cc2fd..2c1685852 100644 --- a/google-bazel-bot/bazel-bot/utils.py +++ b/google-bazel-bot/bazel-bot/utils.py @@ -406,40 +406,24 @@ def commit(self, message: str) -> None: def is_repo_dirty(self, untracked_files=False) -> bool: return self.repo.is_dirty(untracked_files=untracked_files) - def close_existing_prs(self, active_fix_branch: str | None = None): - active_pr = None + def close_existing_prs(self) -> None: for open_pr in self.gh_pr_repo.get_issues( creator=self.gh_pr_creator, state="open" ): - if active_fix_branch: - pr = None - head_ref = None - if getattr(open_pr, "pull_request", None) and hasattr(open_pr, "as_pull_request"): - pr = open_pr.as_pull_request() - head_ref = getattr(getattr(pr, "head", None), "ref", None) - elif hasattr(open_pr, "head"): - pr = open_pr - head_ref = getattr(open_pr.head, "ref", None) - if head_ref == active_fix_branch: - logger.info(f"Skipping active PR for branch {active_fix_branch}: {open_pr.url}") - active_pr = pr or open_pr - continue print(f"Closing unmerged PR from previous fix attempt: {open_pr.url}") open_pr.edit(state="closed") - return active_pr def push_fix( self, build_data: "BuildInfo", create_pr: bool | None = None, - branch_name: str | None = None, + close_existing_prs: bool = True, ) -> bool: """Pushes the branch and creates a GitHub PR against it.""" if create_pr is None: create_pr = self.can_create_pr commit_hash = build_data.commit - if not branch_name: - branch_name = self.get_branch_name(commit_hash) + branch_name = self.get_branch_name(commit_hash) # 1. Get access token try: @@ -489,17 +473,20 @@ def push_fix( ) return True - # 4. Close existing PRs (if any) and locate active PR - active_pr = None - try: - active_pr = call_with_retry( - (github.GithubException,), - self.close_existing_prs, - active_fix_branch=branch_name, - ) - except github.GithubException as e: - logger.warning(f"Failed to close existing PRs: {e}. Proceeding anyway.") + # 4. Close existing PRs (if any) + if close_existing_prs: + try: + call_with_retry( + (github.GithubException,), + self.close_existing_prs, + ) + except github.GithubException as e: + logger.warning(f"Failed to close existing PRs: {e}. Proceeding anyway.") + # 5. Create new Pull Request + logger.info( + f"Creating Pull Request for branch {branch_name} from {self.creds.gh_fork_repo_name} to {self.creds.gh_pr_repo_name}..." + ) buildkite_url = build_data.buildkite_url pr_number_suffix = f" (#{build_data.pr_number})" if build_data.pr_number else "" pr_body = ( @@ -507,32 +494,6 @@ def push_fix( f"Buildkite error link: {buildkite_url}\n" ) - # If a PR already exists for active_branch, update its body by appending the new fix - if active_pr: - current_body = getattr(active_pr, "body", "") or "" - if commit_hash not in current_body: - updated_body = f"{current_body.rstrip()}\n\n{pr_body.strip()}\n" - logger.info( - f"Updating PR body for existing PR for branch {branch_name} to include fix for {commit_hash[:7]}..." - ) - try: - call_with_retry( - (github.GithubException,), - active_pr.edit, - body=updated_body, - ) - except github.GithubException as e: - logger.error(f"Failed to update PR body: {e}") - else: - logger.info( - f"PR body for {branch_name} already mentions {commit_hash[:7]}." - ) - return True - - # 5. No active PR exists - create new Pull Request - logger.info( - f"Creating Pull Request for branch {branch_name} from {self.creds.gh_fork_repo_name} to {self.creds.gh_pr_repo_name}..." - ) try: if not self.creds.use_github_app: if create_pr and not self.creds.gh_pr_user_token: @@ -552,11 +513,6 @@ def push_fix( logger.info(f"Pull Request Created: {pr.html_url}") return True except github.GithubException as e: - if getattr(e, "status", None) == 422 and "A pull request already exists" in str(getattr(e, "data", "")): - logger.info( - f"Pull request already exists for branch {branch_name}. Updated via push." - ) - return True logger.error(f"All attempts to create PR failed: {e}") return False From 56453d917c58748f3336524d5ec955c997396772 Mon Sep 17 00:00:00 2001 From: Pranav Kant Date: Thu, 5 Nov 2026 11:01:23 -0800 Subject: [PATCH 4/5] simplify tests --- google-bazel-bot/bazel-bot/bazelbot_server.py | 4 +- .../bazel-bot/bazelbot_server_test.py | 530 +++++++----------- google-bazel-bot/bazel-bot/utils.py | 6 +- 3 files changed, 207 insertions(+), 333 deletions(-) diff --git a/google-bazel-bot/bazel-bot/bazelbot_server.py b/google-bazel-bot/bazel-bot/bazelbot_server.py index 63d25ea72..628295b39 100644 --- a/google-bazel-bot/bazel-bot/bazelbot_server.py +++ b/google-bazel-bot/bazel-bot/bazelbot_server.py @@ -275,8 +275,10 @@ def get_build_info_for_commit(self, commit_sha: str) -> utils.BuildInfo | None: logger.warning( f"Failed to rebase active fix branch {self.active_fix_branch} on top of commit {commit_sha}." ) + # Failed git rebase operation -> not buildable + # Let's reset the active fix branch so next revision doesn't have any rebase self.reset_active_fix_branch() - current_build.state = utils.BuildState.FAILED + current_build.state = utils.BuildState.UNKNOWN return current_build logger.info( diff --git a/google-bazel-bot/bazel-bot/bazelbot_server_test.py b/google-bazel-bot/bazel-bot/bazelbot_server_test.py index c123a955e..da5e71d4f 100644 --- a/google-bazel-bot/bazel-bot/bazelbot_server_test.py +++ b/google-bazel-bot/bazel-bot/bazelbot_server_test.py @@ -393,59 +393,6 @@ def test_repair_build_logic(self): bot.process_failure_with_ai.return_value = False self.assertFalse(bot.repair_build(build_info)) - def test_run_logic(self): - cmd_processor = mock.MagicMock() - git_repo = mock.MagicMock() - git_repo.create_branch_for_fix.side_effect = lambda sha: f"bazel-{sha}" - creds = mock.MagicMock() - build_processor = mock.MagicMock() - - # Initialize bot with known state - bot = bazelbot_server.BazelRepairBot( - cmd_processor, git_repo, creds, build_processor, 10 - ) - bot.last_processed_sha = "init_sha" - bot.last_processed_state = utils.BuildState.PASSED - - # Define the sequence of builds - builds = [ - utils.BuildInfo(commit="sha1", state=utils.BuildState.PASSED), - utils.BuildInfo(commit="sha2", state=utils.BuildState.FAILED), - utils.BuildInfo(commit="sha3", state=utils.BuildState.FAILED), - utils.BuildInfo(commit="sha4", state=utils.BuildState.PASSED), - ] - - build_processor.get_builds_to_process.return_value = builds - - # Mock repair_build to verify calls - bot.repair_build = mock.MagicMock(return_value=True) - - # Mock wait to break the loop - bot.wait = mock.MagicMock(side_effect=StopIteration) - - # Run the bot - try: - bot.run() - except StopIteration: - pass - - # Verifications - - # 1. Both sha2 (root) and sha3 (nested/consecutive) should be repaired on their own branches - self.assertEqual(bot.repair_build.call_count, 2) - bot.repair_build.assert_has_calls([ - mock.call(builds[1]), - mock.call(builds[2]), - ]) - self.assertEqual(bot.active_fix_branch, "bazel-sha3") - - # 2. Verify state updates - self.assertEqual(bot.last_processed_sha, "sha4") - self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) - - # Verify get_builds_to_process was called with initial sha - build_processor.get_builds_to_process.assert_called_with("init_sha") - def test_buildkite_url(self): info_with_num = utils.BuildInfo("sha1", build_number=123) self.assertEqual( @@ -498,167 +445,104 @@ def test_call_with_retry_no_retry_on_unspecified_exception(self, mock_sleep): self.assertEqual(mock_func.call_count, 1) mock_sleep.assert_not_called() - def test_get_build_info_clean_pass_resets_fix_branch(self): - cmd_processor = mock.MagicMock() - git_repo = mock.MagicMock() - creds = mock.MagicMock() - build_processor = mock.MagicMock() - - bot = bazelbot_server.BazelRepairBot( - cmd_processor, git_repo, creds, build_processor, 10 - ) - bot.active_fix_branch = "bazel-old" - - cmd_processor.run_bazel_build.return_value = mock.MagicMock(success=True) - - info = bot.get_build_info_for_commit("sha1") - - self.assertEqual(info.commit, "sha1") - self.assertEqual(info.state, utils.BuildState.PASSED) - self.assertIsNone(bot.active_fix_branch) - git_repo.checkout_commit.assert_called_with("sha1") - self.assertEqual(cmd_processor.run_bazel_build.call_count, 1) - - def test_get_build_info_clean_fail_no_active_fix(self): - cmd_processor = mock.MagicMock() - git_repo = mock.MagicMock() - creds = mock.MagicMock() - build_processor = mock.MagicMock() - - bot = bazelbot_server.BazelRepairBot( - cmd_processor, git_repo, creds, build_processor, 10 - ) - bot.active_fix_branch = None - - cmd_processor.run_bazel_build.return_value = mock.MagicMock( - success=False, stderr="ERROR: (from target //broken:target)" - ) - - info = bot.get_build_info_for_commit("sha1") - - self.assertEqual(info.commit, "sha1") - self.assertEqual(info.state, utils.BuildState.FAILED) - self.assertEqual(info.failed_targets, ["//broken:target"]) - self.assertIsNone(bot.active_fix_branch) - self.assertEqual(cmd_processor.run_bazel_build.call_count, 1) - - def test_get_build_info_nested_pass_carries_fix(self): - cmd_processor = mock.MagicMock() - git_repo = mock.MagicMock() - creds = mock.MagicMock() - build_processor = mock.MagicMock() - - bot = bazelbot_server.BazelRepairBot( - cmd_processor, git_repo, creds, build_processor, 10 - ) - bot.active_fix_branch = "bazel-sha1" - - git_repo.rebase_branch.return_value = True - cmd_processor.run_bazel_build.side_effect = [ - mock.MagicMock(success=False, stderr="err1"), - mock.MagicMock(success=True, stderr=""), + def test_get_build_info_scenarios(self): + """Parameterized test covering clean and nested get_build_info evaluation scenarios.""" + scenarios = [ + { + "name": "clean_pass_resets_fix_branch", + "initial_active_branch": "bazel-old", + "build_results": [mock.MagicMock(success=True)], + "rebase_result": None, + "expected_state": utils.BuildState.PASSED, + "expected_targets": [], + "expected_active_branch": None, + "expected_build_count": 1, + }, + { + "name": "clean_fail_without_active_fix", + "initial_active_branch": None, + "build_results": [ + mock.MagicMock( + success=False, stderr="ERROR: (from target //broken:target)" + ) + ], + "rebase_result": None, + "expected_state": utils.BuildState.FAILED, + "expected_targets": ["//broken:target"], + "expected_active_branch": None, + "expected_build_count": 1, + }, + { + "name": "nested_pass_carries_fix", + "initial_active_branch": "bazel-sha1", + "build_results": [ + mock.MagicMock(success=False, stderr="err1"), + mock.MagicMock(success=True, stderr=""), + ], + "rebase_result": True, + "expected_state": utils.BuildState.PASSED, + "expected_targets": [], + "expected_active_branch": "bazel-sha1", + "expected_build_count": 2, + }, + { + "name": "nested_fail_returns_failure", + "initial_active_branch": "bazel-sha1", + "build_results": [ + mock.MagicMock(success=False, stderr="err1"), + mock.MagicMock( + success=False, stderr="ERROR: (from target //nested:fail)" + ) + ], + "rebase_result": True, + "expected_state": utils.BuildState.FAILED, + "expected_targets": ["//nested:fail"], + "expected_active_branch": "bazel-sha1", + "expected_build_count": 2, + }, + { + "name": "rebase_fail_resets_fix_branch", + "initial_active_branch": "bazel-sha1", + "build_results": [ + mock.MagicMock( + success=False, stderr="ERROR: (from target //t:one)" + ) + ], + "rebase_result": False, + "expected_state": utils.BuildState.UNKNOWN, + "expected_targets": ["//t:one"], + "expected_active_branch": None, + "expected_build_count": 1, + }, ] - info = bot.get_build_info_for_commit("sha2") - - self.assertEqual(info.commit, "sha2") - self.assertEqual(info.state, utils.BuildState.PASSED) - self.assertEqual(info.failed_targets, []) - self.assertEqual(bot.active_fix_branch, "bazel-sha1") - git_repo.rebase_branch.assert_called_with("bazel-sha1", "sha2") - self.assertEqual(cmd_processor.run_bazel_build.call_count, 2) - - def test_get_build_info_nested_fail_returns_failure(self): - cmd_processor = mock.MagicMock() - git_repo = mock.MagicMock() - creds = mock.MagicMock() - build_processor = mock.MagicMock() - - bot = bazelbot_server.BazelRepairBot( - cmd_processor, git_repo, creds, build_processor, 10 - ) - bot.active_fix_branch = "bazel-sha1" - - git_repo.rebase_branch.return_value = True - cmd_processor.run_bazel_build.side_effect = [ - mock.MagicMock(success=False, stderr="err1"), - mock.MagicMock(success=False, stderr="ERROR: (from target //nested:fail)"), - ] - - info = bot.get_build_info_for_commit("sha2") - - self.assertEqual(info.commit, "sha2") - self.assertEqual(info.state, utils.BuildState.FAILED) - self.assertEqual(info.failed_targets, ["//nested:fail"]) - self.assertEqual(bot.active_fix_branch, "bazel-sha1") - self.assertEqual(cmd_processor.run_bazel_build.call_count, 2) - - def test_get_build_info_rebase_fail_resets_fix_branch(self): - cmd_processor = mock.MagicMock() - git_repo = mock.MagicMock() - creds = mock.MagicMock() - build_processor = mock.MagicMock() - - bot = bazelbot_server.BazelRepairBot( - cmd_processor, git_repo, creds, build_processor, 10 - ) - bot.active_fix_branch = "bazel-sha1" - - git_repo.rebase_branch.return_value = False - cmd_processor.run_bazel_build.return_value = mock.MagicMock( - success=False, stderr="ERROR: (from target //t:one)" - ) - - info = bot.get_build_info_for_commit("sha2") - - self.assertEqual(info.commit, "sha2") - self.assertEqual(info.state, utils.BuildState.FAILED) - self.assertIsNone(bot.active_fix_branch) - self.assertEqual(cmd_processor.run_bazel_build.call_count, 1) - - def test_run_logic_nested_failure_repair(self): - cmd_processor = mock.MagicMock() - git_repo = mock.MagicMock() - git_repo.create_branch_for_fix.side_effect = lambda sha: f"bazel-{sha}" - creds = mock.MagicMock() - build_processor = mock.MagicMock() - - bot = bazelbot_server.BazelRepairBot( - cmd_processor, git_repo, creds, build_processor, 10 - ) - bot.last_processed_sha = "init_sha" - bot.last_processed_state = utils.BuildState.PASSED - - builds = [ - utils.BuildInfo(commit="sha1", state=utils.BuildState.PASSED), - utils.BuildInfo(commit="sha2", state=utils.BuildState.FAILED), # Root failure - utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), # Clean with fix - utils.BuildInfo(commit="sha4", state=utils.BuildState.FAILED), # Nested failure! - utils.BuildInfo(commit="sha5", state=utils.BuildState.PASSED), - ] - build_processor.get_builds_to_process.return_value = builds - - bot.repair_build = mock.MagicMock(return_value=True) - bot.wait = mock.MagicMock(side_effect=StopIteration) - - try: - bot.run() - except StopIteration: - pass - - # Both sha2 (root) and sha4 (nested) should be repaired on separate branches! - self.assertEqual(bot.repair_build.call_count, 2) - bot.repair_build.assert_has_calls([ - mock.call(builds[1]), - mock.call(builds[3]), - ]) - git_repo.create_branch_for_fix.assert_has_calls([ - mock.call("sha2"), - mock.call("sha4"), - ]) - self.assertEqual(bot.active_fix_branch, "bazel-sha4") - self.assertEqual(bot.last_processed_sha, "sha5") - self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) + for s in scenarios: + with self.subTest(scenario=s["name"]): + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, mock.MagicMock(), mock.MagicMock(), 10 + ) + bot.active_fix_branch = s["initial_active_branch"] + + cmd_processor.run_bazel_build.side_effect = s["build_results"] + if s["rebase_result"] is not None: + git_repo.rebase_branch.return_value = s["rebase_result"] + + info = bot.get_build_info_for_commit("sha_test") + + self.assertEqual(info.commit, "sha_test") + self.assertEqual(info.state, s["expected_state"]) + self.assertEqual(info.failed_targets, s["expected_targets"]) + self.assertEqual(bot.active_fix_branch, s["expected_active_branch"]) + self.assertEqual( + cmd_processor.run_bazel_build.call_count, s["expected_build_count"] + ) + + if s["rebase_result"] is not None: + git_repo.rebase_branch.assert_called_with( + s["initial_active_branch"], "sha_test" + ) @mock.patch("bazelbot_server.asyncio.run") def test_process_failure_with_ai_with_active_fix_branch(self, mock_asyncio_run): @@ -736,126 +620,112 @@ def test_call_with_retry_empty_exceptions(self): utils.call_with_retry((), mock_func) mock_func.assert_not_called() - def test_run_logic_consecutive_failures_both_repaired(self): - """Tests that when the first build fails and the second commit also fails (back-to-back), - both are repaired sequentially on their own stacked branches.""" - cmd_processor = mock.MagicMock() - git_repo = mock.MagicMock() - git_repo.create_branch_for_fix.side_effect = lambda sha: f"bazel-{sha}" - creds = mock.MagicMock() - build_processor = mock.MagicMock() - - bot = bazelbot_server.BazelRepairBot( - cmd_processor, git_repo, creds, build_processor, 10 - ) - bot.last_processed_sha = "init_sha" - bot.last_processed_state = utils.BuildState.PASSED - - builds = [ - utils.BuildInfo(commit="sha1", state=utils.BuildState.FAILED), - utils.BuildInfo(commit="sha2", state=utils.BuildState.FAILED), - utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), - ] - build_processor.get_builds_to_process.return_value = builds - - bot.repair_build = mock.MagicMock(return_value=True) - bot.wait = mock.MagicMock(side_effect=StopIteration) - - try: - bot.run() - except StopIteration: - pass - - # Both consecutive failures must be repaired - self.assertEqual(bot.repair_build.call_count, 2) - bot.repair_build.assert_has_calls([ - mock.call(builds[0]), - mock.call(builds[1]), - ]) - self.assertEqual(bot.active_fix_branch, "bazel-sha2") - self.assertEqual(bot.last_processed_sha, "sha3") - self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) - - def test_run_logic_consecutive_failures_first_repair_fails(self): - """Tests that when the first build fails and repair fails, its state remains FAILED, - so the next consecutive failure does not trigger repair (waiting for manual intervention).""" - cmd_processor = mock.MagicMock() - git_repo = mock.MagicMock() - git_repo.create_branch_for_fix.side_effect = lambda sha: f"bazel-{sha}" - creds = mock.MagicMock() - build_processor = mock.MagicMock() - - bot = bazelbot_server.BazelRepairBot( - cmd_processor, git_repo, creds, build_processor, 10 - ) - bot.last_processed_sha = "init_sha" - bot.last_processed_state = utils.BuildState.PASSED - - builds = [ - utils.BuildInfo(commit="sha1", state=utils.BuildState.FAILED), - utils.BuildInfo(commit="sha2", state=utils.BuildState.FAILED), - utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), + def test_run_logic_scenarios(self): + """Parameterized test covering run() loop scenarios with consecutive/nested failures and rebase failures.""" + scenarios = [ + { + "name": "consecutive_failures_both_repaired", + "initial_active_branch": None, + "builds": [ + utils.BuildInfo(commit="sha1", state=utils.BuildState.FAILED), + utils.BuildInfo(commit="sha2", state=utils.BuildState.FAILED), + utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), + ], + "repair_side_effect": [True, True], + "rebase_result": None, + "bazel_build_result": None, + "expected_repairs": ["sha1", "sha2"], + "expected_active_branch": "bazel-sha2", + "expected_last_sha": "sha3", + "expected_last_state": utils.BuildState.PASSED, + }, + { + "name": "consecutive_failures_first_repair_fails", + "initial_active_branch": None, + "builds": [ + utils.BuildInfo(commit="sha1", state=utils.BuildState.FAILED), + utils.BuildInfo(commit="sha2", state=utils.BuildState.FAILED), + utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), + ], + "repair_side_effect": [False], + "rebase_result": None, + "bazel_build_result": None, + "expected_repairs": ["sha1"], + "expected_active_branch": None, + "expected_last_sha": "sha3", + "expected_last_state": utils.BuildState.PASSED, + }, + { + "name": "nested_failure_after_gap_both_repaired", + "initial_active_branch": None, + "builds": [ + utils.BuildInfo(commit="sha1", state=utils.BuildState.FAILED), + utils.BuildInfo(commit="sha2", state=utils.BuildState.PASSED), + utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), + utils.BuildInfo(commit="sha4", state=utils.BuildState.FAILED), + utils.BuildInfo(commit="sha5", state=utils.BuildState.PASSED), + ], + "repair_side_effect": [True, True], + "rebase_result": None, + "bazel_build_result": None, + "expected_repairs": ["sha1", "sha4"], + "expected_active_branch": "bazel-sha4", + "expected_last_sha": "sha5", + "expected_last_state": utils.BuildState.PASSED, + }, + { + "name": "rebase_failure_skips_revision", + "initial_active_branch": "bazel-sha1", + "builds": [ + utils.BuildInfo(commit="sha2", state=utils.BuildState.UNKNOWN), + utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), + ], + "repair_side_effect": [], + "rebase_result": False, + "bazel_build_result": mock.MagicMock(success=False, stderr="err"), + "expected_repairs": [], + "expected_active_branch": None, + "expected_last_sha": "sha3", + "expected_last_state": utils.BuildState.PASSED, + }, ] - build_processor.get_builds_to_process.return_value = builds - - # First repair fails - bot.repair_build = mock.MagicMock(return_value=False) - bot.wait = mock.MagicMock(side_effect=StopIteration) - - try: - bot.run() - except StopIteration: - pass - - # Only sha1 was attempted; sha2 was skipped because state was FAILED - self.assertEqual(bot.repair_build.call_count, 1) - bot.repair_build.assert_called_once_with(builds[0]) - self.assertIsNone(bot.active_fix_branch) - self.assertEqual(bot.last_processed_sha, "sha3") - self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) - - def test_run_logic_nested_failure_after_gap_of_commits(self): - """Tests scenario where first build fails and is repaired, followed by a gap of - 2-3 passing commits, and then another build fails (nested failure).""" - cmd_processor = mock.MagicMock() - git_repo = mock.MagicMock() - git_repo.create_branch_for_fix.side_effect = lambda sha: f"bazel-{sha}" - creds = mock.MagicMock() - build_processor = mock.MagicMock() - bot = bazelbot_server.BazelRepairBot( - cmd_processor, git_repo, creds, build_processor, 10 - ) - bot.last_processed_sha = "init_sha" - bot.last_processed_state = utils.BuildState.PASSED - - builds = [ - utils.BuildInfo(commit="sha1", state=utils.BuildState.FAILED), # Root failure - utils.BuildInfo(commit="sha2", state=utils.BuildState.PASSED), # Gap commit 1 - utils.BuildInfo(commit="sha3", state=utils.BuildState.PASSED), # Gap commit 2 - utils.BuildInfo(commit="sha4", state=utils.BuildState.PASSED), # Gap commit 3 - utils.BuildInfo(commit="sha5", state=utils.BuildState.FAILED), # Nested failure after 3-commit gap - utils.BuildInfo(commit="sha6", state=utils.BuildState.PASSED), - ] - build_processor.get_builds_to_process.return_value = builds - - bot.repair_build = mock.MagicMock(return_value=True) - bot.wait = mock.MagicMock(side_effect=StopIteration) - - try: - bot.run() - except StopIteration: - pass - - # Both sha1 (root) and sha5 (nested after gap of 3 commits) should be repaired - self.assertEqual(bot.repair_build.call_count, 2) - bot.repair_build.assert_has_calls([ - mock.call(builds[0]), - mock.call(builds[4]), - ]) - self.assertEqual(bot.active_fix_branch, "bazel-sha5") - self.assertEqual(bot.last_processed_sha, "sha6") - self.assertEqual(bot.last_processed_state, utils.BuildState.PASSED) + for s in scenarios: + with self.subTest(scenario=s["name"]): + cmd_processor = mock.MagicMock() + git_repo = mock.MagicMock() + git_repo.create_branch_for_fix.side_effect = lambda sha: f"bazel-{sha}" + build_processor = mock.MagicMock() + + bot = bazelbot_server.BazelRepairBot( + cmd_processor, git_repo, mock.MagicMock(), build_processor, 10 + ) + bot.last_processed_sha = "init_sha" + bot.last_processed_state = utils.BuildState.PASSED + bot.active_fix_branch = s["initial_active_branch"] + + if s["rebase_result"] is not None: + git_repo.rebase_branch.return_value = s["rebase_result"] + if s["bazel_build_result"] is not None: + cmd_processor.run_bazel_build.return_value = s["bazel_build_result"] + + build_processor.get_builds_to_process.return_value = s["builds"] + bot.repair_build = mock.MagicMock(side_effect=s["repair_side_effect"]) + bot.wait = mock.MagicMock(side_effect=StopIteration) + + try: + bot.run() + except StopIteration: + pass + + actual_repairs = [ + call.args[0].commit for call in bot.repair_build.call_args_list + ] + self.assertEqual(actual_repairs, s["expected_repairs"]) + self.assertEqual(bot.active_fix_branch, s["expected_active_branch"]) + self.assertEqual(bot.last_processed_sha, s["expected_last_sha"]) + self.assertEqual(bot.last_processed_state, s["expected_last_state"]) + build_processor.get_builds_to_process.assert_called_with("init_sha") if __name__ == "__main__": diff --git a/google-bazel-bot/bazel-bot/utils.py b/google-bazel-bot/bazel-bot/utils.py index 2c1685852..ad52442d2 100644 --- a/google-bazel-bot/bazel-bot/utils.py +++ b/google-bazel-bot/bazel-bot/utils.py @@ -371,11 +371,13 @@ def create_branch_for_fix(self, commit_hash: str) -> str: self.repo.create_head(branch_name, force=True).checkout() return branch_name - def rebase_branch(self, branch_name: str, new_base: str) -> bool: + def rebase_branch( + self, branch_name: str, new_base: str, strategy_option: str = "ours" + ) -> bool: """Rebases branch_name onto new_base. Returns True on success, False on conflict/error.""" try: self.repo.git.checkout(branch_name) - self.repo.git.rebase(new_base) + self.repo.git.rebase("-X", strategy_option, new_base) return True except git.GitCommandError as e: logger.error(f"Failed to rebase {branch_name} onto {new_base}: {e}") From 16520768d23603cdd37b8c2e89a7c175af651510 Mon Sep 17 00:00:00 2001 From: Pranav Kant Date: Thu, 5 Nov 2026 12:31:51 -0800 Subject: [PATCH 5/5] clean directory before rebasing --- google-bazel-bot/bazel-bot/utils.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/google-bazel-bot/bazel-bot/utils.py b/google-bazel-bot/bazel-bot/utils.py index ad52442d2..4fcec80e5 100644 --- a/google-bazel-bot/bazel-bot/utils.py +++ b/google-bazel-bot/bazel-bot/utils.py @@ -376,7 +376,8 @@ def rebase_branch( ) -> bool: """Rebases branch_name onto new_base. Returns True on success, False on conflict/error.""" try: - self.repo.git.checkout(branch_name) + self.repo.git.checkout("-f", branch_name) + self.repo.git.clean("-fd") self.repo.git.rebase("-X", strategy_option, new_base) return True except git.GitCommandError as e: