Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: auto_merge not working properly with orchestrator backend #1871

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from

Conversation

duy0611
Copy link

@duy0611 duy0611 commented Jan 15, 2025

When running with Digger backend mode, PR is merged when auto_merge is enabled even though not all impacted projects have been applied. This is caused because Digger batch does not have context whether all the needed jobs have been triggered when using digger apply with -p flag.

Unlike in backendless mode, where all the jobs are run sequentially and the parent one does have context if all the impacted projects have been applied, in backend mode jobs are triggered via the Batch one, which does not have this context. This PR addresses the issue by adding one more column to store this context, which will then be used in the subsequent run.

Summary by CodeRabbit

Release Notes: Project Coverage Enhancement

  • New Features

    • Added support for covering all impacted projects during job processing.
    • Enhanced project impact tracking across GitHub and GitLab integrations.
  • Database Changes

    • Introduced new cover_all_impacted_projects column in digger batches, enabling more granular control over project coverage during batch processing.
  • Improvements

    • Updated job conversion and batch creation workflows to include new project coverage parameter.
    • Refined automatic merge conditions for pull requests to consider additional criteria.

When running with Digger backend mode, PR is merged when `auto_merge`
is enabled even though not all impacted projects have been applied.
This is caused because Digger batch does not have context whether all
the needed jobs have been triggered when using `digger apply` with `-p` flag.
Unlike in backendless mode, where all the jobs are run sequentially and the parent one
does have context if all the impacted projects have been applied, in backend mode
jobs are triggered via the Batch one, which does have this context. This PR addresses
the issue by adding one more column to store this context, which will then be used in the
subsequent run.
Copy link
Contributor

coderabbitai bot commented Jan 15, 2025

Walkthrough

The pull request introduces a new boolean parameter coverAllImpactedProjects across multiple backend components. This parameter is added to various function signatures related to job processing, batch creation, and event handling in GitHub and GitLab integrations. The changes span multiple files, including controllers, models, migrations, and utility functions, indicating a systematic approach to implementing a new feature that allows more granular control over project coverage during job execution.

Changes

File Change Summary
backend/controllers/github.go Updated function signatures to include coverAllImpactedProjects in event handling and job triggering methods.
backend/controllers/projects.go Modified AutomergePRforBatchIfEnabled to check CoverAllImpactedProjects before merging.
backend/controllers/github_test.go Updated test functions to include coverAllImpactedProjects parameter in ConvertJobsToDiggerJobs calls.
backend/models/scheduler.go Added CoverAllImpactedProjects field to DiggerBatch struct.
backend/models/storage.go Updated CreateDiggerBatch method signature to include coverAllImpactedProjects.
backend/models/storage_test.go Modified test cases to pass coverAllImpactedProjects parameter in CreateDiggerBatch calls.
backend/migrations/20250115155205.sql Added cover_all_impacted_projects column to digger_batches table.
backend/utils/graphs.go Modified ConvertJobsToDiggerJobs to accept coverAllImpactedProjects parameter.
ee/backend/controllers/gitlab.go Updated event handling functions to return coverAllImpactedProjects.
ee/backend/hooks/github.go Enhanced DriftReconcilliationHook to include coverAllImpactedProjects in job conversion.

Possibly related issues

Possibly related PRs

Poem

🐰 A Rabbit's Ode to Project Coverage

Hop, hop, through code's winding maze,
New flag unfurled in digger's ways
CoverAllImpactedProjects shines bright
Ensuring jobs run with all their might!

🚀 Code rabbit's wisdom, clear and true!

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (10)
backend/controllers/github.go (1)

401-401: Consider reducing parameter passing complexity.

The introduction of coverAllImpactedProjects as an additional return value increases the number of variables passed between functions. Consider grouping related parameters into a struct to enhance code readability and maintainability.

Apply this diff to define a struct and update the function signature:

+type EventConversionResult struct {
+  JobsForImpactedProjects []Job
+  CoverAllImpactedProjects bool
+}

-func ConvertGithubPullRequestEventToJobs(...) ([]Job, bool, error) {
+func ConvertGithubPullRequestEventToJobs(...) (EventConversionResult, error) {

-  jobsForImpactedProjects, coverAllImpactedProjects, err := dg_github.ConvertGithubPullRequestEventToJobs(...)
+  result, err := dg_github.ConvertGithubPullRequestEventToJobs(...)
backend/models/storage_test.go (1)

155-155: Add test cases for the new coverAllImpactedProjects parameter.

The test only verifies batch creation with coverAllImpactedProjects set to true. Consider adding test cases that verify the behavior when this parameter is false to ensure both scenarios work correctly.

Would you like me to help generate additional test cases to cover both scenarios?

backend/tasks/runs_test.go (1)

147-147: Enhance test coverage for batch creation with coverAllImpactedProjects.

The test should verify that the state machine transitions correctly based on the value of coverAllImpactedProjects. Consider adding test cases that cover both true and false scenarios.

Would you like me to help generate additional test cases to verify the state machine behavior with different coverAllImpactedProjects values?

backend/utils/graphs.go (2)

18-18: Consider documenting the new parameter in the function signature.

Add a comment explaining the purpose and impact of the coverAllImpactedProjects parameter to help future maintainers understand its significance.


47-50: Enhance error handling for batch creation.

The error message could be more descriptive. Consider including the value of coverAllImpactedProjects in the error message to help with debugging.

-		return nil, nil, fmt.Errorf("failed to create batch: %v", err)
+		return nil, nil, fmt.Errorf("failed to create batch (coverAllImpactedProjects=%v): %v", coverAllImpactedProjects, err)
ee/backend/hooks/github.go (2)

Line range hint 124-129: Enhance error handling for job conversion.

Consider logging the value of coverAllImpactedProjects when an error occurs to help with debugging.

 	if err != nil {
-		log.Printf("Error converting event to jobs: %v", err)
+		log.Printf("Error converting event to jobs (coverAllImpactedProjects=%v): %v", coverAllImpactedProjects, err)
 		utils.InitCommentReporter(ghService, issueNumber, fmt.Sprintf(":x: Error converting event to jobs: %v", err))
 		return fmt.Errorf("error converting event to jobs")
 	}

Line range hint 155-159: Improve error reporting for job conversion.

The error message in the comment reporter could be more descriptive to help users understand the issue.

 	if err != nil {
 		log.Printf("ConvertJobsToDiggerJobs error: %v", err)
-		utils.InitCommentReporter(ghService, issueNumber, fmt.Sprintf(":x: ConvertJobsToDiggerJobs error: %v", err))
+		utils.InitCommentReporter(ghService, issueNumber, fmt.Sprintf(":x: Failed to process jobs for all impacted projects: %v", err))
 		return fmt.Errorf("error convertingjobs")
 	}
backend/controllers/projects.go (1)

734-734: Simplify boolean comparison and verify auto-merge condition.

The boolean comparison can be simplified. Additionally, the new condition ensures safer auto-merge behavior by requiring all impacted projects to be covered.

Apply this diff to simplify the boolean comparison:

-if batch.Status == orchestrator_scheduler.BatchJobSucceeded && batch.BatchType == orchestrator_scheduler.DiggerCommandApply && batch.CoverAllImpactedProjects == true && automerge == true {
+if batch.Status == orchestrator_scheduler.BatchJobSucceeded && batch.BatchType == orchestrator_scheduler.DiggerCommandApply && batch.CoverAllImpactedProjects && automerge {
🧰 Tools
🪛 golangci-lint (1.62.2)

734-734: S1002: should omit comparison to bool constant, can be simplified to batch.CoverAllImpactedProjects

(gosimple)

backend/controllers/github_test.go (1)

735-735: Add test cases for coverAllImpactedProjects=false.

The test suite only covers scenarios where coverAllImpactedProjects is true. Consider adding test cases that verify the behavior when coverAllImpactedProjects is false, especially for auto-merge scenarios.

Also applies to: 764-764, 797-797, 842-842

ee/backend/controllers/gitlab.go (1)

337-337: Consider improving parameter clarity in ConvertJobsToDiggerJobs.

The function calls have two boolean parameters next to each other (false, coverAllImpactedProjects). This could lead to confusion and potential errors when maintaining the code.

Consider one of these improvements:

  1. Use named parameters or a config struct to make the intent clearer
  2. Reorder parameters to separate the boolean flags
  3. Add comments explaining the purpose of each boolean parameter

Example with a config struct:

type ConversionConfig struct {
    IsForceApply bool
    CoverAllImpactedProjects bool
}

func ConvertJobsToDiggerJobs(
    command scheduler.DiggerCommand,
    // ... other parameters ...
-   forceApply bool,
-   coverAllImpactedProjects bool,
+   config ConversionConfig,
) (uint, error)

Also applies to: 528-528

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1e88db8 and 3c4e108.

⛔ Files ignored due to path filters (1)
  • backend/migrations/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (12)
  • backend/controllers/github.go (5 hunks)
  • backend/controllers/github_test.go (5 hunks)
  • backend/controllers/projects.go (2 hunks)
  • backend/controllers/projects_test.go (3 hunks)
  • backend/migrations/20250115155205.sql (1 hunks)
  • backend/models/scheduler.go (2 hunks)
  • backend/models/storage.go (2 hunks)
  • backend/models/storage_test.go (2 hunks)
  • backend/tasks/runs_test.go (2 hunks)
  • backend/utils/graphs.go (2 hunks)
  • ee/backend/controllers/gitlab.go (5 hunks)
  • ee/backend/hooks/github.go (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • backend/migrations/20250115155205.sql
🧰 Additional context used
🪛 golangci-lint (1.62.2)
backend/controllers/projects.go

734-734: S1002: should omit comparison to bool constant, can be simplified to batch.CoverAllImpactedProjects

(gosimple)

🔇 Additional comments (12)
backend/controllers/github.go (4)

9-20: Necessary imports added.

The added import statements are necessary for the updated functionalities and are correctly included.


526-526: Passing coverAllImpactedProjects appropriately.

Including coverAllImpactedProjects in the call to ConvertJobsToDiggerJobs ensures that the batch creation process is aware of the coverage context.


831-831: Ensure consistent error handling with new return values.

The function generic.ConvertIssueCommentEventToJobs now returns coverAllImpactedProjects. Verify that any errors or exceptions related to this new return value are properly handled downstream to prevent unintended behavior.


934-934: Consistent usage of coverAllImpactedProjects in batch processing.

Passing coverAllImpactedProjects into ConvertJobsToDiggerJobs aligns with the updated logic, ensuring batch creation correctly accounts for all impacted projects.

backend/controllers/projects_test.go (3)

4-6: Import statements consolidated.

Duplicate imports of net/http and testing have been removed, improving code cleanliness.


72-77: Test setup enhanced with new fields.

Added fields such as GithubInstallationId, RepoFullName, RepoOwner, RepoName, BatchType, and CoverAllImpactedProjects provide a more comprehensive context for the tests.


103-113: Extended test coverage for CoverAllImpactedProjects.

The new test case where CoverAllImpactedProjects is set to false effectively verifies the behavior of AutomergePRforBatchIfEnabled when not all impacted projects are covered, ensuring the merge action is appropriately controlled.

backend/models/scheduler.go (1)

6-8: Reorganized import statements.

Moved log and time imports to the top, adhering to Go's import grouping conventions.

backend/models/storage.go (1)

621-640: LGTM! Clean integration of coverage tracking.

The coverAllImpactedProjects field is properly integrated into the batch creation process, maintaining a clean and consistent structure.

ee/backend/controllers/gitlab.go (3)

6-12: LGTM! Import statements are well-organized.

The added standard library imports are necessary for the implemented functionality.


241-241: LGTM! Function call updated to support auto_merge fix.

The addition of coverAllImpactedProjects parameter aligns with the PR objectives to fix auto_merge functionality in backend mode.


484-484: LGTM! Consistent implementation with pull request handling.

The addition of coverAllImpactedProjects parameter maintains consistency with the pull request event handling changes.

RepoName string
BatchType orchestrator_scheduler.DiggerCommand
ReportTerraformOutputs bool
CoverAllImpactedProjects bool
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

CoverAllImpactedProjects is not included in serialization

The MapToJsonStruct method in DiggerBatch does not include the CoverAllImpactedProjects field in its serialization output, which could lead to data loss. The field needs to be added to the SerializedBatch struct returned by the method.

🔗 Analysis chain

Verify serialization of CoverAllImpactedProjects.

Ensure that the new field CoverAllImpactedProjects in the DiggerBatch struct is correctly handled during serialization, especially in the MapToJsonStruct method, to prevent data inconsistencies.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for serialization of 'CoverAllImpactedProjects' in methods.

# Look for occurrences where DiggerBatch is converted without including 'CoverAllImpactedProjects'.
ast-grep --pattern $'func ($_ *DiggerBatch) MapToJsonStruct() {...}' --json | jq '.captures[] | select(.value | test("CoverAllImpactedProjects")) | .value'

Length of output: 224


Script:

#!/bin/bash
# Find the MapToJsonStruct method implementation and surrounding context
rg -U "func.*MapToJsonStruct.*DiggerBatch" -A 20

# Search for struct definition and JSON tags
rg "CoverAllImpactedProjects.*\`json:" 

# Look for test files that might verify serialization
rg "TestDiggerBatch.*MapToJsonStruct" -l

Length of output: 133


Script:

#!/bin/bash
# Show the content of scheduler.go
cat backend/models/scheduler.go

# Find any JSON-related code in the models directory
rg "json" backend/models/ -A 5 -B 5

# Look for test files in the models directory
fd ".*_test.go" backend/models/

Length of output: 12644

@duy0611 duy0611 changed the title fix: auto_merge not working properly iwith orchestrator backend fix: auto_merge not working properly with orchestrator backend Jan 15, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
backend/controllers/projects_test.go (1)

104-113: Consider extracting repeated config to a constant.

While the test case correctly verifies auto-merge behavior when all projects are covered, the digger config string is duplicated multiple times in the test. Consider extracting it to a constant for better maintainability.

+ const autoMergeEnabledConfig = "" +
+   "projects:\n" +
+   "  - name: dev\n" +
+   "    dir: dev\n" +
+   "auto_merge: true"

  func TestAutomergeWhenBatchIsSuccessfulStatus(t *testing.T) {
    // ... existing code ...
-   batch.DiggerConfig = "" +
-     "projects:\n" +
-     "  - name: dev\n" +
-     "    dir: dev\n" +
-     "auto_merge: true"
+   batch.DiggerConfig = autoMergeEnabledConfig
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3c4e108 and da512e3.

📒 Files selected for processing (1)
  • backend/controllers/projects_test.go (3 hunks)
🔇 Additional comments (3)
backend/controllers/projects_test.go (3)

4-6: Clean import organization looks good!

The consolidation of import statements improves code organization.


99-102: Test case correctly verifies auto-merge prevention.

Good test coverage for the scenario where not all impacted projects are covered, ensuring auto-merge is prevented.


72-77: Verify field initialization aligns with production code.

The addition of CoverAllImpactedProjects and its initialization look good. This change aligns with the PR objectives to fix auto-merge behavior.

Let's verify the field is consistently initialized in production code:

✅ Verification successful

Field initialization and usage verified successfully

The CoverAllImpactedProjects field is consistently used in both production and test code:

  • Used in auto-merge logic alongside other required conditions
  • Test cases cover both true/false scenarios with appropriate assertions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for CoverAllImpactedProjects initialization patterns
rg -A 3 "CoverAllImpactedProjects.*=.*" --type go

Length of output: 1083

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant