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(rpc): panic and publish health event only on create batch error #907

Merged
merged 13 commits into from
Jul 9, 2024

Conversation

zale144
Copy link
Contributor

@zale144 zale144 commented Jun 10, 2024

PR Standards

Opening a pull request should be able to meet the following requirements

--

PR naming convention: https://hackmd.io/@nZpxHZ0CT7O5ngTp0TP9mg/HJP_jrm7A


Close #902

<-- Briefly describe the content of this pull request -->

For Author:

  • Targeted PR against correct branch
  • included the correct type prefix in the PR title
  • Linked to Github issue with discussion and accepted design
  • Targets only one github issue
  • Wrote unit and integration tests
  • All CI checks have passed
  • Added relevant godoc comments

For Reviewer:

  • confirmed the correct type prefix in the PR title
  • Reviewers assigned
  • confirmed all author checklist items have been addressed

After reviewer approval:

  • In case targets main branch, PR should be squashed and merged.
  • In case PR targets a release branch, PR should be rebased.

Summary by CodeRabbit

  • New Features

    • Improved application stability by ensuring blocked processes are properly terminated during shutdown.
    • Enhanced error handling with error logging for better diagnosis and troubleshooting.
  • Performance Improvements

    • Added health status monitoring for improved system health tracking.

@zale144 zale144 self-assigned this Jun 10, 2024
@zale144 zale144 requested a review from a team as a code owner June 10, 2024 19:27
Copy link
Contributor

coderabbitai bot commented Jun 10, 2024

Walkthrough

The SubmitLoop function in the Manager struct in block/submit.go has been updated to enhance error handling, resource management, and context-awareness. Changes include closing channels to release blocked goroutines on shutdown, logging errors during panics, emitting health status events, and adding a context.Context parameter for better control.

Changes

Files Change Summaries
block/submit.go Modified SubmitLoop function to close channels, handle panics with logging, emit health status events, and include context.Context parameter. Updated HandleSubmissionTrigger to accept context.Context parameter and handle errors accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Manager
    participant Logger
    participant HealthModule

    Caller->>Manager: SubmitLoop(ctx)
    activate Manager
    Manager->>Manager: Initialize loop
    alt On panic
        Manager-->>Logger: Log error
    else On shutdown
        Manager-->>Manager: Close channels
    end
    Manager->>HealthModule: Emit health status event
    deactivate Manager
Loading

Assessment against linked issues

Objective Addressed Explanation
Update health endpoint when batch creation fails (#902)
Ensure proper resource management by closing channels on shutdown (#902)
Implement better error handling with logging during panics (#902)
Incorporate context.Context parameter for enhanced control flow (#902)

Poem

In fields of code where bytes do play,
Channels close at end of day.
Context guides through twists and bends,
Health reports, and errors mend.
Thus the manager, not discrete,
Keeps our node both strong and fleet. 🌱


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

Outside diff range and nitpick comments (1)
block/submit.go (1)

Line range hint 105-125: Review the use of panic for error handling.

Using panic for handling errors in production code can lead to abrupt termination of the application, which might not be desirable. Consider using more graceful error handling mechanisms.

- panic(fmt.Errorf("create next batch to submit: %w", err))
+ return fmt.Errorf("create next batch to submit: %w", err)
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2f49475 and 0187fea.

Files selected for processing (2)
  • block/submit.go (4 hunks)
  • settlement/dymension/dymension.go (2 hunks)
Additional comments not posted (3)
block/submit.go (2)

27-30: Ensure proper cleanup of resources.

The addition of channel closure in the defer block is a good practice to prevent resource leaks.


50-52: Improve error handling and logging.

The error handling in HandleSubmissionTrigger now logs errors more effectively, which aligns with the PR's objective to enhance visibility for node operators.

settlement/dymension/dymension.go (1)

29-31: Check the usage of new imports.

The new imports (pubsub and ctypes) are used appropriately in the eventHandler function to enhance event handling capabilities.

settlement/dymension/dymension.go Show resolved Hide resolved
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0187fea and 5b5eef9.

Files selected for processing (1)
  • block/submit.go (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • block/submit.go

block/submit.go Fixed Show fixed Hide fixed
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: 2

Outside diff range and nitpick comments (1)
block/submit.go (1)

55-55: Consider adding explicit coordination between accumulated size and batch creation.

The comment at line 55 mentions a lack of coordination between the accumulated size and the actual batch creation. This could lead to discrepancies and potential issues in batch processing. It might be beneficial to implement a mechanism that ensures these values are synchronized to prevent any inconsistencies.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5b5eef9 and 71db422.

Files selected for processing (1)
  • block/submit.go (2 hunks)
Additional context used
golangci-lint
block/submit.go

38-38: unreachable: unreachable code (govet)

GitHub Check: CodeQL
block/submit.go

[warning] 38-38: Unreachable statement
This statement is unreachable.

GitHub Check: golangci-lint
block/submit.go

[failure] 38-38:
unreachable: unreachable code (govet)

Additional comments not posted (1)
block/submit.go (1)

55-55: Review the error handling in batch creation.

The changes in HandleSubmissionTrigger include handling errors during batch creation. To ensure these changes are effective and do not introduce new issues, consider adding more comprehensive tests specifically for error scenarios in batch creation. This will help verify that the health events are published correctly and that the system behaves as expected under failure conditions.

block/submit.go Outdated Show resolved Hide resolved
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 71db422 and 207f594.

Files selected for processing (1)
  • block/submit.go (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • block/submit.go

block/submit.go Fixed Show resolved Hide resolved
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: 3

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 207f594 and be86c2a.

Files selected for processing (2)
  • block/submit.go (2 hunks)
  • block/submit_test.go (2 hunks)
Additional context used
GitHub Check: CodeQL
block/submit.go

[warning] 30-30: Redundant call to recover
This call to 'recover' has no effect because the enclosing function is never called using a defer statement.

Additional comments not posted (1)
block/submit_test.go (1)

20-20: The import statements are well-organized. However, ensure that all these libraries are used in the test file to avoid unnecessary dependencies.

Verification successful

All imports in the block/submit_test.go file are used within the file. Here are the findings:

  • context: Used in multiple context.Background() and context.WithTimeout() calls.
  • crypto/ed25519: Used in ed25519.GenerateKey().
  • crypto/rand: Used in rand.Reader.
  • fmt: Used in fmt.Errorf().
  • sync: Used in sync.WaitGroup.
  • testing: Used in various test functions.
  • time: Used in time.Second, time.Millisecond, and time.Sleep().
  • github.com/stretchr/testify/assert: Used in various assert functions.
  • github.com/stretchr/testify/mock: Used in mock.Anything and mock setup functions.

No unnecessary dependencies were found.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check for unused imports in the test file.

# Test: List imports and search for their usage in the file. Expect: Each import used at least once.
rg --type go "import" block/submit_test.go | rg --files-with-matches --type go --exec rg -F $(awk -F'/' '{print $NF}' | sed 's/"//g')

Length of output: 552



Script:

#!/bin/bash
# List all import statements in the block/submit_test.go file.
rg --type go "^import" -A 10 block/submit_test.go

Length of output: 213



Script:

#!/bin/bash
# Check for the usage of each import in the block/submit_test.go file.

# Define the imports to check
imports=("context" "ed25519" "rand" "fmt" "sync" "testing" "time" "assert" "mock")

# Loop through each import and search for its usage in the file
for import in "${imports[@]}"; do
    echo "Checking usage of import: $import"
    rg --type go "$import" block/submit_test.go || echo "No usage found for import: $import"
done

Length of output: 4579

block/submit.go Outdated Show resolved Hide resolved
block/submit.go Show resolved Hide resolved
block/submit_test.go Show resolved Hide resolved
@zale144 zale144 force-pushed the zale144/902-recover-update-health-on-create-batch branch from afe4e0b to be86c2a Compare June 24, 2024 15:20
block/submit.go Fixed Show resolved Hide resolved
block/submit.go Outdated Show resolved Hide resolved
block/submit.go Outdated Show resolved Hide resolved
Copy link
Contributor

@mtsitrin mtsitrin left a comment

Choose a reason for hiding this comment

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

as discussed, we need to stop production in this case.
maybe the entire blockManager's context can be closed

mtsitrin
mtsitrin previously approved these changes Jul 9, 2024
@mtsitrin mtsitrin requested a review from danwt July 9, 2024 12:08
block/manager.go Outdated
Comment on lines 46 to 47
// Context
cancelCtx context.CancelFunc
Copy link
Contributor

@danwt danwt Jul 9, 2024

Choose a reason for hiding this comment

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

This is a complete abuse / anti-pattern of how to write go code and how to use contexts

https://stackoverflow.com/questions/70042646/best-practices-on-go-context-cancelation-functions

You need to do something like instead https://stackoverflow.com/a/70042766

Copy link
Contributor

Choose a reason for hiding this comment

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

func operation1(ctx context.Context) {
   for {
     select {
     case <-ctx.Done():
       return
     default:
     }
     //...
   }
}

func operation2(ctx context.Context) {
  // Similar code to operatoin1()
}

func main() {
  ctx, cancel := context.WithCancel(context.Background())
  var wg sync.WaitGroup
  wg.Add(2)
  go func() {
    defer wg.Done()
    defer cancel()
    operation1(ctx)
  }()
  go func() {
    defer wg.Done()
    defer cancel()
    operation2(ctx)
  }()
  wg.Wait()
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sure there are more idiomatic ways to do this, but I think calling it "complete abuse" of how to write go code is a bit out of line.

Given the time constraints, I don't think these are the most critical issues to deal with right now.

block/manager.go Dismissed Show dismissed Hide dismissed
@mtsitrin mtsitrin merged commit b09c75a into main Jul 9, 2024
6 checks passed
@mtsitrin mtsitrin deleted the zale144/902-recover-update-health-on-create-batch branch July 9, 2024 16:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

health endpoint isn't updated if batch fails creation
3 participants