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(observer): remove error return on staking hooks #2968

Merged
merged 3 commits into from
Oct 4, 2024

Conversation

lumtis
Copy link
Member

@lumtis lumtis commented Oct 4, 2024

Description

Staking hook fix was missing on develop

102b872#diff-f6d8e75e5cf1f39354b3a150db855a69895dbf5e6da8d24c89213a17256440dcR143

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling in key methods to log errors instead of returning them directly, enhancing visibility into issues.
    • Updated test cases to reflect new expected behaviors when validators are absent, ensuring robust handling of edge cases.
  • New Features

    • Enhanced error messages in the CheckObserverSelfDelegation method for better context and clarity.

@lumtis lumtis added the no-changelog Skip changelog CI check label Oct 4, 2024
Copy link
Contributor

coderabbitai bot commented Oct 4, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request primarily focus on enhancing error handling within the keeper package of the observer module. Modifications were made to several methods in hooks.go to log errors instead of returning them directly, while tests in hooks_test.go were updated to reflect the new error handling behavior. Additionally, voting.go saw improvements in error messaging by utilizing the github.com/pkg/errors package to wrap existing errors with contextual information. These adjustments aim to improve the clarity and robustness of error reporting and testing.

Changes

File Path Change Summary
x/observer/keeper/hooks.go Updated error handling in AfterValidatorRemoved, AfterValidatorBeginUnbonding, AfterDelegationModified, and BeforeValidatorSlashed methods to log errors instead of returning them.
x/observer/keeper/hooks_test.go Modified test cases to assert no error for absent validators, validated observer set state, and updated assertions to reflect new expected outcomes.
x/observer/keeper/voting.go Added import for github.com/pkg/errors and updated error handling in CheckObserverSelfDelegation to wrap errors with additional context.

Sequence Diagram(s)

sequenceDiagram
    participant Hooks
    participant Logger
    participant Voting

    Hooks->>Logger: Log error "Error cleaning observer set"
    Hooks->>Hooks: Return nil

    Voting->>Voting: CheckObserverSelfDelegation
    Voting->>Voting: Wrap error with context
    Voting->>Logger: Log wrapped error
Loading

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

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.

@lumtis lumtis changed the title fix: remove error return on staking hooks fix(observer): remove error return on staking hooks Oct 4, 2024
@lumtis lumtis mentioned this pull request Oct 4, 2024
5 tasks
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

🧹 Outside diff range and nitpick comments (4)
x/observer/keeper/hooks.go (2)

38-44: Implement a comprehensive error handling strategy

The modifications across all methods in this file follow a consistent pattern of logging errors without returning them. While this approach maintains method signatures and backwards compatibility, it raises concerns about error propagation and system observability.

To address these concerns comprehensively, consider the following recommendations:

  1. Implement a uniform error handling strategy across all methods in this file.
  2. Create a custom error type that encapsulates both the original error and additional context.
  3. Refactor the error handling logic into a separate function to reduce duplication.
  4. Ensure that errors are both logged and returned to maintain proper error propagation.

Here's a suggested implementation that combines these recommendations:

type ObserverError struct {
    OriginalError error
    Context       string
}

func (e *ObserverError) Error() string {
    return fmt.Sprintf("%s: %v", e.Context, e.OriginalError)
}

func logAndWrapError(ctx sdk.Context, err error, message string) error {
    if err != nil {
        ctx.Logger().Error(message, "error", err)
        return &ObserverError{OriginalError: err, Context: message}
    }
    return nil
}

// Then in each method:
func (h Hooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) error {
    err := h.k.CleanSlashedValidator(ctx, valAddr, fraction)
    return logAndWrapError(ctx, err, "Error cleaning observer set")
}

This approach would provide a robust and consistent error handling mechanism throughout the file, improving both error reporting and system maintainability.


Line range hint 1-44: Summary: Revise error handling strategy across the codebase

The changes in this file represent a significant shift in error handling strategy, moving from returning errors to logging them. While this approach maintains method signatures, it introduces potential issues with error propagation and system observability.

Recommendations for next steps:

  1. Conduct a thorough review of the error handling strategy across the entire codebase.
  2. Implement a consistent and robust error handling mechanism that balances logging and error propagation.
  3. Consider introducing a custom error type that preserves context while allowing for detailed logging.
  4. Refactor common error handling logic into reusable functions to reduce code duplication.
  5. Update documentation to reflect the new error handling approach and its implications for system behavior and debugging.

These changes have far-reaching implications and should be carefully considered in the context of the entire system's architecture and operational requirements.

x/observer/keeper/voting.go (1)

138-143: Approval: Improved error context in CheckObserverSelfDelegation.

The modifications to error handling in the CheckObserverSelfDelegation function are commendable. The use of errors.Wrapf provides more detailed error context, which will significantly aid in debugging and error tracing.

However, for consistency and further improvement, consider the following suggestion:

-		return errors.Wrapf(types.ErrNotValidator, "validator : %s", valAddress)
+		return errors.Wrapf(types.ErrNotValidator, "validator: %s", valAddress)

-		return errors.Wrapf(types.ErrSelfDelegation, "self delegation : %s , valAddres : %s", selfdelAddr, valAddress)
+		return errors.Wrapf(types.ErrSelfDelegation, "self delegation: %s, valAddress: %s", selfdelAddr, valAddress)

This minor adjustment removes the space before the colon, corrects the spelling of "valAddress", and ensures consistent spacing in the error messages. These changes will maintain a uniform style throughout the codebase.

x/observer/keeper/hooks_test.go (1)

142-155: Approve changes with a suggestion for improved test isolation.

The new test case effectively covers the scenario where the validator is not found, ensuring that no error is returned and the observer set remains unchanged. This addition enhances the robustness of the test suite.

To further improve test isolation, consider the following suggestion:

 t.Run("should not error if validator not found", func(t *testing.T) {
-		k, ctx, _, _ := keepertest.ObserverKeeper(t)
+		k, ctx, _, _ := keepertest.ObserverKeeper(t)
+		ctx = ctx.WithBlockHeight(1) // Ensure a consistent block height for the test
 
 		r := rand.New(rand.NewSource(9))
 		validator := sample.Validator(t, r)
 		os := sample.ObserverSet(10)
 		k.SetObserverSet(ctx, os)
 
 		hooks := k.Hooks()
 		err := hooks.BeforeValidatorSlashed(ctx, validator.GetOperator(), sdk.NewDec(1))
 		require.NoError(t, err)
 		storedOs, found := k.GetObserverSet(ctx)
 		require.True(t, found)
 		require.Equal(t, os, storedOs)
 	})

This change ensures a consistent block height for the test, which can be crucial for deterministic behavior in blockchain-related tests.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 90924e9 and 3d2adf3.

📒 Files selected for processing (3)
  • x/observer/keeper/hooks.go (1 hunks)
  • x/observer/keeper/hooks_test.go (1 hunks)
  • x/observer/keeper/voting.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
x/observer/keeper/hooks.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/observer/keeper/hooks_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/observer/keeper/voting.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

🔇 Additional comments (1)
x/observer/keeper/voting.go (1)

5-5: Approval: Enhanced error handling import.

The addition of the "github.com/pkg/errors" package import is a positive change. This package provides more robust error handling capabilities, allowing for better error context and stack traces.

x/observer/keeper/hooks.go Show resolved Hide resolved
x/observer/keeper/hooks.go Show resolved Hide resolved
x/observer/keeper/hooks.go Show resolved Hide resolved
Copy link

codecov bot commented Oct 4, 2024

Codecov Report

Attention: Patch coverage is 50.00000% with 3 lines in your changes missing coverage. Please review.

Project coverage is 66.40%. Comparing base (90924e9) to head (2ffbb5a).
Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
x/observer/keeper/hooks.go 25.00% 3 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop    #2968   +/-   ##
========================================
  Coverage    66.40%   66.40%           
========================================
  Files          389      389           
  Lines        21762    21762           
========================================
  Hits         14451    14451           
  Misses        6584     6584           
  Partials       727      727           
Files with missing lines Coverage Δ
x/observer/keeper/voting.go 93.40% <100.00%> (ø)
x/observer/keeper/hooks.go 71.79% <25.00%> (ø)

@lumtis lumtis added this pull request to the merge queue Oct 4, 2024
Merged via the queue into develop with commit e124d34 Oct 4, 2024
34 of 35 checks passed
@lumtis lumtis deleted the fix/staking-hooks-error branch October 4, 2024 11:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-changelog Skip changelog CI check
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants