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

chore(storage): cleanup NotFound errors #2065

Open
wants to merge 26 commits into
base: main
Choose a base branch
from

Conversation

abi87
Copy link
Collaborator

@abi87 abi87 commented Oct 11, 2024

Introducing beacondb.ErrNotFound to duly handle cases where queried object from storage is not found.
Currently, whenever an item is not found we:

  • either return the collections.ErrNotFound as is to the client
  • or we map collections.ErrNotFound to the default value, nil error pair.

There are a few things that I don't like in this arrangement:

  • I am not a fan of letting the db layer doing much transformation; I think this layer should concern with efficient layout of objects only.
  • I am not a fan of the double treatment (error or mapping). Moreover it seems to me that the mapping works well for pointers type, where nil is returned, but not for non pointer types, where default value should be returned. The latter is confusing since default value may be a perfectly reasonable value and should not be used as flag value for 'item not found'
  • We leak cosmos sdk errors to the client, so if the client needs to perform some logic around 'object found/not found/other errors' we end up importing cosmos sdk packages where we don't really want to.

This PR is a step towards solving the issue: The PR inspects errors returned by cosmos sdk collections and maps collections.ErrNotFound to a package level ErrNotFound

This PR is a pure refactoring; it only cares of making sure that collections.ErrNotFound is not returned to the clients anymore. Changes to the mapping will be carried out in separate PRs to simplify code review.

Note: This PR focuses on errors from getting from or iterating over collections. Cosmos sdk errors from item settings are not modified since they cannot return collections.ErrNotFound errors.

TODO: consider handling absence of validators as ErrNotFound as well?

@abi87 abi87 self-assigned this Oct 11, 2024
Copy link

codecov bot commented Oct 11, 2024

Codecov Report

Attention: Patch coverage is 12.71186% with 206 lines in your changes missing coverage. Please review.

Project coverage is 23.38%. Comparing base (0ea12a8) to head (c1a1986).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
mod/storage/pkg/beacondb/registry.go 15.49% 59 Missing and 1 partial ⚠️
mod/storage/pkg/beacondb/eth1.go 0.00% 50 Missing ⚠️
mod/storage/pkg/beacondb/history.go 0.00% 21 Missing ⚠️
mod/storage/pkg/beacondb/withdrawals.go 0.00% 18 Missing ⚠️
mod/storage/pkg/beacondb/versioning.go 0.00% 13 Missing ⚠️
mod/storage/pkg/beacondb/slashing.go 0.00% 10 Missing ⚠️
mod/storage/pkg/deposit/store.go 0.00% 7 Missing ⚠️
mod/state-transition/pkg/core/state/statedb.go 0.00% 6 Missing ⚠️
mod/storage/pkg/beacondb/fork.go 0.00% 6 Missing ⚠️
mod/storage/pkg/beacondb/randao.go 0.00% 6 Missing ⚠️
... and 3 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2065      +/-   ##
==========================================
- Coverage   23.47%   23.38%   -0.10%     
==========================================
  Files         357      358       +1     
  Lines       16055    16228     +173     
  Branches       12       12              
==========================================
+ Hits         3769     3795      +26     
- Misses      12116    12263     +147     
  Partials      170      170              
Files with missing lines Coverage Δ
mod/storage/pkg/block/store.go 83.63% <93.75%> (+11.54%) ⬆️
mod/storage/pkg/encoding/ssz.go 27.58% <0.00%> (ø)
mod/storage/pkg/errors/errors.go 50.00% <50.00%> (ø)
mod/state-transition/pkg/core/state/statedb.go 0.00% <0.00%> (ø)
mod/storage/pkg/beacondb/fork.go 0.00% <0.00%> (ø)
mod/storage/pkg/beacondb/randao.go 0.00% <0.00%> (ø)
mod/storage/pkg/deposit/store.go 0.00% <0.00%> (ø)
mod/storage/pkg/beacondb/slashing.go 0.00% <0.00%> (ø)
mod/storage/pkg/beacondb/versioning.go 0.00% <0.00%> (ø)
mod/storage/pkg/beacondb/withdrawals.go 0.00% <0.00%> (ø)
... and 3 more

return deposits, nil
default:
return nil, err
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

technically a change since upon err we don't return deposits cumulated so far. However err client does drop all deposits upon error, so we're fine

@abi87 abi87 force-pushed the storage-cleanup-err-not-found branch 5 times, most recently from 0108886 to b535cdf Compare October 11, 2024 13:39
@abi87 abi87 force-pushed the storage-cleanup-err-not-found branch from b535cdf to bba5071 Compare October 11, 2024 13:44
@@ -108,7 +110,6 @@ func (kv *KVStore[DepositT]) Prune(start, end uint64) error {
kv.mu.Lock()
defer kv.mu.Unlock()
for i := range end {
// This only errors if the key passed in cannot be encoded.
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I think this comment is wrong. There are a few internal errors possible, depending on the backend chosen

@abi87 abi87 force-pushed the storage-cleanup-err-not-found branch 4 times, most recently from ef0e1da to cf7c9b9 Compare October 11, 2024 16:14
@abi87 abi87 force-pushed the storage-cleanup-err-not-found branch from cf7c9b9 to 3917a9a Compare October 11, 2024 16:44
@abi87 abi87 marked this pull request as ready for review October 11, 2024 17:04
Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

Walkthrough

This pull request introduces several modifications across multiple files in the beacondb package, primarily focusing on enhancing error handling in various methods. Key improvements include the restructuring of retrieval logic and the addition of new methods for better clarity and maintainability. Specific methods now utilize structured error handling, providing more informative error messages. Additionally, a new helper function for error mapping has been introduced to standardize error reporting throughout the package.

Changes

File Path Change Summary
mod/storage/pkg/beacondb/errors.go Introduced custom error ErrNotFound and MapError function for standardized error handling.
mod/storage/pkg/beacondb/eth1.go Improved error handling in GetLatestExecutionPayloadHeader, added getLatestExecutionPayloadVersion method, updated error handling in GetEth1DepositIndex and GetEth1Data.
mod/storage/pkg/beacondb/fork.go Enhanced error handling in GetFork method using structured error reporting.
mod/storage/pkg/beacondb/history.go Enhanced error handling in GetBlockRootAtIndex, GetLatestBlockHeader, and StateRootAtIndex methods using structured error handling.
mod/storage/pkg/beacondb/randao.go Updated GetRandaoMixAtIndex for improved error handling with structured messages.
mod/storage/pkg/beacondb/registry.go Enhanced error handling in several methods, added AddValidatorBartio method, and refactored balance retrieval logic.
mod/storage/pkg/beacondb/slashing.go Updated error handling in GetSlashings, GetSlashingAtIndex, and GetTotalSlashing methods using structured error reporting.
mod/storage/pkg/block/store.go Introduced new error variable ErrNotFound for standardized error handling in slot retrieval methods.
mod/storage/pkg/block/store_test.go Updated MockBeaconBlock methods to return common.Root type and refined error handling in test cases.
mod/state-transition/go.mod Updated dependency versions and added new dependencies, including local path replacements.
mod/state-transition/pkg/core/state/statedb.go Added import for storageerrors, improved error handling in UpdateSlashingAtIndex method, ensuring robust error checks and preventing nil dereferences.

Possibly related PRs

Suggested labels

Merge me daddy

Suggested reviewers

  • itsdevbear
  • ocnc
  • nidhi-singh02

Poem

🐇 In the land of code, where errors roam,
A hop and a skip, we make it home.
With clearer messages, our paths align,
Error handling shines, oh so fine!
So let’s celebrate with a joyful cheer,
For every fix brings us closer, my dear! 🌟


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.

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.

@abi87 abi87 changed the title chore(storage): cleanup not found errors chore(storage): cleanup NotFound errors Oct 11, 2024
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: 20

🧹 Outside diff range comments (2)
mod/storage/pkg/deposit/store.go (2)

Line range hint 66-69: Incorrect use of 'range' on 'uint64'; use a standard for loop instead

In GetDepositsByIndex, the loop uses for i := range numView, but numView is a uint64. The range keyword cannot be applied directly to an integer, which will result in a compilation error.

To fix this, use a standard for loop:

-func (kv *KVStore[DepositT]) GetDepositsByIndex(
-	startIndex uint64,
-	numView uint64,
-) ([]DepositT, error) {
-	kv.mu.RLock()
-	defer kv.mu.RUnlock()
-	deposits := []DepositT{}
-	for i := range numView {
+func (kv *KVStore[DepositT]) GetDepositsByIndex(
+	startIndex uint64,
+	numView uint64,
+) ([]DepositT, error) {
+	kv.mu.RLock()
+	defer kv.mu.RUnlock()
+	deposits := []DepositT{}
+	for i := uint64(0); i < numView; i++ {

Line range hint 104-108: Incorrect use of 'range' on 'uint64'; use a standard for loop in Prune method

In the Prune method, the loop uses for i := range end, but end is a uint64. The range keyword cannot be applied directly to an integer, which will result in a compilation error.

To fix this, use a standard for loop to iterate from start to end:

 func (kv *KVStore[DepositT]) Prune(start, end uint64) error {
 	var ctx = context.TODO()
 	kv.mu.Lock()
 	defer kv.mu.Unlock()
-	for i := range end {
+	for i := start; i < end; i++ {
 		if err := kv.store.Remove(ctx, start+i); err != nil {
 			return err
 		}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 05ce9dc and 64d2f3e.

📒 Files selected for processing (13)
  • mod/storage/pkg/beacondb/eth1.go (5 hunks)
  • mod/storage/pkg/beacondb/fork.go (2 hunks)
  • mod/storage/pkg/beacondb/history.go (4 hunks)
  • mod/storage/pkg/beacondb/kvstore.go (2 hunks)
  • mod/storage/pkg/beacondb/randao.go (2 hunks)
  • mod/storage/pkg/beacondb/registry.go (7 hunks)
  • mod/storage/pkg/beacondb/slashing.go (3 hunks)
  • mod/storage/pkg/beacondb/versioning.go (3 hunks)
  • mod/storage/pkg/beacondb/withdrawals.go (2 hunks)
  • mod/storage/pkg/block/store.go (5 hunks)
  • mod/storage/pkg/block/store_test.go (2 hunks)
  • mod/storage/pkg/deposit/store.go (1 hunks)
  • mod/storage/pkg/encoding/ssz.go (3 hunks)
🧰 Additional context used
🔇 Additional comments (32)
mod/storage/pkg/beacondb/fork.go (3)

23-28: LGTM: New imports are appropriate for the changes.

The addition of the "errors" and "fmt" packages is necessary and appropriate for the improved error handling in the GetFork method.


45-53: LGTM: Improved error handling in GetFork method.

The changes in the GetFork method significantly improve error handling:

  1. It now distinguishes between different error types.
  2. It provides more informative error messages.
  3. It uses errors.Is() for proper error type checking.

These improvements align well with the PR objectives and Go best practices.


50-50: Verify the existence and import of ErrNotFound.

The code uses ErrNotFound, but this error type is not defined in the current file. Please ensure that ErrNotFound is properly defined and imported from the correct package.

To verify the existence and import of ErrNotFound, please run the following script:

mod/storage/pkg/beacondb/randao.go (2)

23-29: LGTM: Import changes are appropriate.

The new imports (errors, fmt, and cosmossdk.io/collections) are necessary for the enhanced error handling in the GetRandaoMixAtIndex function. These additions improve the code's functionality and readability.


Line range hint 1-64: Overall assessment: Changes align well with PR objectives.

The modifications to this file successfully implement the new error handling mechanism described in the PR objectives. The introduction of ErrNotFound and the improved error reporting in GetRandaoMixAtIndex provide a more uniform and informative approach to handling "not found" cases.

These changes contribute to the overall goal of ensuring that collections.ErrNotFound is no longer returned to clients, instead exposing a non-Cosmos SDK error (ErrNotFound) to the rest of the codebase.

mod/storage/pkg/block/store_test.go (3)

42-42: LGTM: Improved type safety in HashTreeRoot method

The change from [32]byte to common.Root enhances type safety and aligns with the refactoring objectives of the PR. This modification ensures consistency in return types across the codebase.


50-50: LGTM: Consistent type improvement in GetStateRoot method

The change from [32]byte to common.Root in the GetStateRoot method maintains consistency with the HashTreeRoot method modification. This change contributes to the overall refactoring effort and improves type safety.


84-89: LGTM: Improved error handling precision

The change from require.ErrorContains to require.ErrorIs enhances the precision of error checking in the test cases. This modification aligns with the PR objectives of improving error handling and provides more accurate test results by checking for specific error types.

mod/storage/pkg/beacondb/slashing.go (1)

Line range hint 1-108: Overall, excellent improvements in error handling.

The changes in this file effectively address the PR's objectives by improving error handling in the GetSlashingAtIndex and GetTotalSlashing methods. The new switch statement approach provides clearer, more idiomatic Go code and ensures that collections.ErrNotFound is not directly returned to clients.

These modifications enhance the clarity and maintainability of the code while aligning perfectly with the stated goal of introducing a new error type (beacondb.ErrNotFound) and providing a more uniform error handling mechanism.

Great job on this refactoring effort!

mod/storage/pkg/block/store.go (5)

24-24: LGTM: Import statement addition is appropriate.

The addition of the "errors" import is necessary for creating the new error variable, which aligns with the PR objectives to improve error handling.


33-33: LGTM: New error variable improves error handling consistency.

The introduction of ErrSlotNotFound aligns with the PR objectives by providing a standardized error for slot not found cases. This will enhance error handling consistency across the package.


87-91: LGTM: Improved error handling in GetSlotByBlockRoot.

The modification enhances error reporting by using the new ErrSlotNotFound error and including the block root in the error message. This change provides more context and aligns with the PR objectives for improved error handling.


104-105: LGTM: Consistent error handling improvements across methods.

The changes in GetSlotByExecutionNumber and GetSlotByStateRoot methods follow the same pattern as GetSlotByBlockRoot. They use the new ErrSlotNotFound error and include the relevant identifier in the error message. This consistency improves the overall error handling in the package.

Also applies to: 118-122


24-24: Summary: Successful implementation of improved error handling.

The changes in this file consistently enhance error handling across the KVStore methods. The introduction of ErrSlotNotFound and the inclusion of relevant identifiers in error messages align well with the PR objectives. These modifications will provide more informative error reporting, facilitating easier debugging and improving the overall robustness of the package.

Great job on maintaining consistency across all affected methods!

Also applies to: 33-33, 87-91, 104-105, 118-122

mod/storage/pkg/encoding/ssz.go (5)

24-24: LGTM: Improved error handling with standardized error.

The addition of the errors import and the new errNotImplemented variable enhances the error handling in the package. This change aligns well with the PR objective of improving error handling and provides a consistent way to represent unimplemented functionality.

Also applies to: 31-31


53-53: LGTM: Improved error message for unimplemented method.

The update to use errNotImplemented in the panic message of EncodeJSON enhances error clarity and consistency. The use of fmt.Errorf for error wrapping is a good practice.


58-58: LGTM: Consistent error handling for unimplemented method.

The update to DecodeJSON follows the same pattern as EncodeJSON, using errNotImplemented in the panic message. This maintains consistency in error handling across the struct's methods.


102-102: LGTM: Consistent error handling across codec types.

The update to EncodeJSON in SSZInterfaceCodec mirrors the changes made in SSZValueCodec, ensuring consistency in error handling across different codec types.


Line range hint 1-118: Overall assessment: Consistent improvement in error handling.

The changes in this file successfully implement a more consistent and clear approach to error handling for unimplemented methods. This aligns well with the PR objectives of improving error handling and clarity. The use of a standardized error variable and consistent error wrapping across different codec types enhances the maintainability and readability of the code.

While the current changes are appropriate and improve the codebase, consider the suggestion for future refactoring to return errors instead of using panics, as it could further enhance the API's usability and error handling capabilities.

mod/storage/pkg/beacondb/kvstore.go (2)

36-37: 🧹 Nitpick (assertive)

Approve the addition of ErrNotFound and suggest its usage

The addition of ErrNotFound is a good step towards improving error handling in the beacondb package. This aligns well with the PR objectives.

To fully leverage this new error type, consider updating relevant methods in this file (and other files in the package) to use ErrNotFound instead of returning nil or other generic errors when an object is not found. This will provide more consistent and informative error handling throughout the package.

Let's check if there are any potential places in this file where ErrNotFound could be used:

#!/bin/bash
# Search for potential places to use ErrNotFound
rg --type go -i 'not found|nil' mod/storage/pkg/beacondb/kvstore.go

36-37: 🧹 Nitpick (assertive)

Review other files for potential usage of ErrNotFound

While the addition of ErrNotFound is beneficial, its full potential isn't realized in this file alone.

Consider reviewing other files in the beacondb package to identify methods that currently return nil or use generic errors for "not found" scenarios. Updating these methods to use ErrNotFound would improve consistency and error handling across the package.

Let's check for potential usage sites in other files of the package:

✅ Verification successful

Run a corrected search for ErrNotFound in other files within the beacondb package

The previous script encountered an error and did not yield the expected results. Let's perform a more targeted search to identify potential usage sites of ErrNotFound:


Run a corrected search for ErrNotFound in other files within the beacondb package

The previous script encountered an error due to an invalid flag. Let's perform a corrected search to identify potential usage sites of ErrNotFound:


ErrNotFound is consistently used across the beacondb package

The addition of ErrNotFound in kvstore.go aligns with its established usage in other files within the beacondb package, ensuring consistent error handling for "not found" scenarios.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential places to use ErrNotFound in other files
rg --type go -i 'not found|nil' mod/storage/pkg/beacondb/ | grep -v 'kvstore.go'

Length of output: 241


Script:

# Searching for 'ErrNotFound' in Go files within beacondb package, excluding kvstore.go
rg --type go 'ErrNotFound' mod/storage/pkg/beacondb/ --invert-file 'kvstore.go'

Length of output: 523


Script:

# Searching for 'ErrNotFound' in Go files within beacondb package, excluding kvstore.go
rg --type go 'ErrNotFound' mod/storage/pkg/beacondb/ -g '!kvstore.go'

Length of output: 2586

mod/storage/pkg/beacondb/versioning.go (3)

24-26: Addition of Necessary Imports

The imports errors and fmt are added to support enhanced error handling in the methods below. This inclusion is appropriate and necessary for the new error wrapping and formatting.


50-62: Improved Error Handling in GetGenesisValidatorsRoot

The introduction of the switch statement effectively differentiates between collections.ErrNotFound and other errors, providing clearer and more informative error messages. Mapping collections.ErrNotFound to beacondb.ErrNotFound standardizes error handling across the codebase and improves client understanding.


72-85: Enhanced Error Handling in GetSlot

The revised error handling in the GetSlot method mirrors the improvements made in GetGenesisValidatorsRoot. The use of errors.Is to check for collections.ErrNotFound and the subsequent mapping to ErrNotFound enhances consistency and clarity in error reporting.

mod/storage/pkg/beacondb/withdrawals.go (2)

23-29: Imports are appropriately updated

The addition of "errors", "fmt", "cosmossdk.io/collections", and "github.com/berachain/beacon-kit/mod/primitives/pkg/math" imports is necessary for the enhanced error handling and mathematical operations introduced in the code.


36-50: Verify the definition and usage of ErrNotFound

In the GetNextWithdrawalIndex method, ErrNotFound is returned when collections.ErrNotFound is encountered. Please ensure that ErrNotFound is properly defined in the beacondb package and accessible in this context.

Run the following script to verify the definition of ErrNotFound:

✅ Verification successful

ErrNotFound is Properly Defined and Accessible

The ErrNotFound variable is correctly defined in mod/storage/pkg/beacondb/kvstore.go and is accessible in withdrawals.go. No issues were found regarding its definition and usage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that 'ErrNotFound' is defined in the 'beacondb' package.

# Search for the definition of 'ErrNotFound' in the 'beacondb' package.
rg --type go --max-depth 1 -A 2 'var ErrNotFound' mod/storage/pkg/beacondb/

Length of output: 284

mod/storage/pkg/beacondb/eth1.go (1)

94-98: Add validation for payloadHeader.Version()

In the SetLatestExecutionPayloadHeader method (lines 94-98), you use payloadHeader.Version() without validating the returned version:

version = payloadHeader.Version()

If there's a possibility that Version() could return an invalid value, consider adding validation to ensure the version is acceptable before proceeding.

Check whether Version() can return invalid data:

#!/bin/bash
# Description: Verify the implementation of the Version() method.

# Search for the Version method in the ExecutionPayloadHeader implementation.
rg --type go 'func \(.*ExecutionPayloadHeader\) Version\(' -A 5

# Review for potential issues or lack of validation.
mod/storage/pkg/beacondb/registry.go (5)

24-25: Approved: Necessary imports added

The addition of "errors" and "fmt" imports is appropriate for the enhanced error handling in the code.


149-165: Approved: Enhanced error handling in 'ValidatorByIndex'

The introduction of a switch-case structure for error handling in the ValidatorByIndex method improves clarity and consistency. Returning a zero-value ValidatorT alongside the error provides a clear indication of failure without risking the use of uninitialized data.


245-245: Approved: Proper error propagation in 'GetValidatorsByEffectiveBalance'

The error from ValidatorByIndex is appropriately propagated, ensuring any issues encountered during validator retrieval are correctly handled. This enhances the robustness of the method.


261-276: Approved: Enhanced error handling in 'GetBalance'

The updated error handling using a switch-case structure provides more informative feedback. Wrapping the errors with additional context helps in debugging and maintaining the code.


327-333: Approved: Use of 'GetSlot' method and error handling

Utilizing the GetSlot method improves encapsulation and abstraction within the codebase. The enhanced error handling ensures that failures in retrieving the slot are properly reported and handled.

Comment on lines 50 to 64
switch {
case err == nil:
return common.Bytes32(bz), nil
case errors.Is(err, collections.ErrNotFound):
return common.Bytes32{}, fmt.Errorf(
"failed retrieving randao mix at index %d: %w",
index,
ErrNotFound,
)
default:
return common.Bytes32{}, fmt.Errorf(
"failed retrieving randao mix at index %d: %w",
index,
err,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM: Improved error handling and alignment with PR objectives.

The changes to GetRandaoMixAtIndex function significantly improve error handling and align well with the PR objectives. The introduction of the ErrNotFound error type and the use of a switch statement for error handling provide more granular and informative error reporting.

Suggestions for minor improvements:

  1. Consider extracting the error message formatting into a separate function to improve readability and reduce duplication.
  2. Add a comment explaining the significance of ErrNotFound and how it differs from collections.ErrNotFound.

Here's a suggested refactor to address the above points:

func formatRandaoMixError(index uint64, err error) error {
    return fmt.Errorf("failed retrieving randao mix at index %d: %w", index, err)
}

func (kv *KVStore[...]) GetRandaoMixAtIndex(index uint64) (common.Bytes32, error) {
    bz, err := kv.randaoMix.Get(kv.ctx, index)
    switch {
    case err == nil:
        return common.Bytes32(bz), nil
    case errors.Is(err, collections.ErrNotFound):
        // ErrNotFound is used to indicate that the randao mix was not found in the database,
        // as opposed to collections.ErrNotFound which is specific to the collections package.
        return common.Bytes32{}, formatRandaoMixError(index, ErrNotFound)
    default:
        return common.Bytes32{}, formatRandaoMixError(index, err)
    }
}

Comment on lines 84 to 89
_, err = blockStore.GetSlotByBlockRoot(common.Root{byte(8)})
require.ErrorIs(t, err, block.ErrSlotNotFound)
_, err = blockStore.GetSlotByExecutionNumber(2)
require.ErrorContains(t, err, "not found")
require.ErrorIs(t, err, block.ErrSlotNotFound)
_, err = blockStore.GetSlotByStateRoot(common.Root{byte(8)})
require.ErrorIs(t, err, block.ErrSlotNotFound)
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

Align Error Types with PR Objectives

The test in mod/storage/pkg/block/store_test.go is currently using block.ErrSlotNotFound. To maintain consistency with the PR's objective of introducing beacondb.ErrNotFound, please update the test to use beacondb.ErrNotFound instead.

  • File: mod/storage/pkg/block/store_test.go
  • Lines: 84-89
🔗 Analysis chain

Verify error type consistency with PR objectives

The PR objectives mention introducing a new error type beacondb.ErrNotFound, but the test cases are using block.ErrSlotNotFound. Could you please verify if this is intentional or if there's a need to align the error types across the codebase?

To check for consistency, you can run the following script:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of error types across the codebase

# Search for beacondb.ErrNotFound
echo "Occurrences of beacondb.ErrNotFound:"
rg --type go "beacondb\.ErrNotFound"

# Search for block.ErrSlotNotFound
echo "Occurrences of block.ErrSlotNotFound:"
rg --type go "block\.ErrSlotNotFound"

# Search for any other ErrNotFound variations
echo "Other ErrNotFound variations:"
rg --type go "ErrNotFound" | grep -v "beacondb\.ErrNotFound" | grep -v "block\.ErrSlotNotFound"

Length of output: 4147

Comment on lines 91 to 97
switch {
case err == nil:
return math.Gwei(total), nil
case errors.Is(err, collections.ErrNotFound):
return 0, nil
} else if err != nil {
return 0, err
default:
return 0, fmt.Errorf("failed retrieving total slashing: %w", err)
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consistent error handling improvement, with a minor suggestion for alignment.

The switch statement for error handling in GetTotalSlashing is a great improvement and consistent with the changes in GetSlashingAtIndex. It effectively addresses the PR objectives by ensuring that collections.ErrNotFound is not directly returned to clients.

For consistency with the GetSlashingAtIndex method, consider expanding the error message to include more context:

 	default:
-		return 0, fmt.Errorf("failed retrieving total slashing: %w", err)
+		return 0, fmt.Errorf("failed retrieving total slashing amount: %w", err)
 	}

This minor change aligns the error message style with GetSlashingAtIndex, providing slightly more descriptive context.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
switch {
case err == nil:
return math.Gwei(total), nil
case errors.Is(err, collections.ErrNotFound):
return 0, nil
} else if err != nil {
return 0, err
default:
return 0, fmt.Errorf("failed retrieving total slashing: %w", err)
switch {
case err == nil:
return math.Gwei(total), nil
case errors.Is(err, collections.ErrNotFound):
return 0, nil
default:
return 0, fmt.Errorf("failed retrieving total slashing amount: %w", err)
}

Comment on lines 60 to 70
switch {
case err == nil:
return math.Gwei(amount), nil
case errors.Is(err, collections.ErrNotFound):
return 0, nil
} else if err != nil {
return 0, err
default:
return 0, fmt.Errorf(
"failed retrieving slashing at index %d: %w",
index,
err,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Improved error handling looks good, with a minor suggestion.

The switch statement for error handling is a great improvement. It's more idiomatic Go and easier to read. The error cases are now more explicitly handled, which aligns well with the PR objectives.

Consider using a named return value for amount to make the code slightly more concise:

-func (kv *KVStore[
-	BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT,
-	ForkT, ValidatorT, ValidatorsT,
-]) GetSlashingAtIndex(
-	index uint64,
-) (math.Gwei, error) {
-	amount, err := kv.slashings.Get(kv.ctx, index)
+func (kv *KVStore[
+	BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT,
+	ForkT, ValidatorT, ValidatorsT,
+]) GetSlashingAtIndex(
+	index uint64,
+) (amount math.Gwei, err error) {
+	var rawAmount uint64
+	rawAmount, err = kv.slashings.Get(kv.ctx, index)
 	switch {
 	case err == nil:
-		return math.Gwei(amount), nil
+		amount = math.Gwei(rawAmount)
+		return
 	case errors.Is(err, collections.ErrNotFound):
-		return 0, nil
+		return
 	default:
-		return 0, fmt.Errorf(
+		err = fmt.Errorf(
 			"failed retrieving slashing at index %d: %w",
 			index,
 			err,
 		)
+		return
 	}
 }

This change would eliminate the need for explicit return statements with values, as the named return values are automatically returned.

Committable suggestion was skipped due to low confidence.

}

// DecodeJSON is not implemented and will panic if called.
func (SSZInterfaceCodec[T]) DecodeJSON(_ []byte) (T, error) {
panic("not implemented")
panic(fmt.Errorf("DecodeJSON %w", errNotImplemented))
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM: Consistent error handling maintained.

The update to DecodeJSON in SSZInterfaceCodec completes the consistent application of the new error handling approach across all relevant methods.

For future consideration: Instead of using panic, you might want to return the error directly. This would allow callers to handle the error more gracefully. For example:

func (SSZInterfaceCodec[T]) DecodeJSON(_ []byte) (T, error) {
    var zero T
    return zero, fmt.Errorf("DecodeJSON %w", errNotImplemented)
}

This change would make the API more idiomatic and easier to use, but it's outside the scope of the current PR.

Comment on lines 38 to 63
var h ExecutionPayloadHeaderT
v, err := kv.getLatestExecutionPayloadVersion()
if err != nil {
var t ExecutionPayloadHeaderT
return t, err
return h, fmt.Errorf(
"failed retrieving latest execution payload header: %w",
err,
)
}

kv.latestExecutionPayloadCodec.SetActiveForkVersion(v)
h, err = kv.latestExecutionPayloadHeader.Get(kv.ctx)
switch {
case err == nil:
return h, nil
case errors.Is(err, collections.ErrNotFound):
return h, fmt.Errorf(
"failed retrieving latest execution payload header: %w",
ErrNotFound,
)
default:
return h, fmt.Errorf(
"failed retrieving latest execution payload header: %w",
err,
)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Simplify error messages for clarity

In the GetLatestExecutionPayloadHeader method (lines 38-63), the error messages can be simplified to improve readability. Currently, the same error message prefix is used multiple times.

Consider defining a constant error message prefix or using a helper function to reduce repetition.

const errMsg = "failed retrieving latest execution payload header"

func (kv *KVStore[...]) GetLatestExecutionPayloadHeader() (ExecutionPayloadHeaderT, error) {
    // ...
    if err != nil {
        return h, fmt.Errorf("%s: %w", errMsg, err)
    }
    // ...
    switch {
    case err == nil:
        return h, nil
    case errors.Is(err, collections.ErrNotFound):
        return h, fmt.Errorf("%s: %w", errMsg, ErrNotFound)
    default:
        return h, fmt.Errorf("%s: %w", errMsg, err)
    }
}

mod/storage/pkg/beacondb/eth1.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/eth1.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/registry.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/registry.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: 8

🧹 Outside diff range comments (1)
mod/storage/pkg/beacondb/withdrawals.go (1)

Line range hint 54-61: Apply error mapping in SetNextWithdrawalValidatorIndex

Similar to the previous suggestion, SetNextWithdrawalValidatorIndex returns errors directly from kv.nextWithdrawalValidatorIndex.Set(kv.ctx, index.Unwrap()) without using mapErrors(err). For uniform error handling, consider mapping errors in this method as well.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 64d2f3e and 022b099.

📒 Files selected for processing (9)
  • mod/storage/pkg/beacondb/eth1.go (5 hunks)
  • mod/storage/pkg/beacondb/fork.go (2 hunks)
  • mod/storage/pkg/beacondb/helpers.go (1 hunks)
  • mod/storage/pkg/beacondb/history.go (4 hunks)
  • mod/storage/pkg/beacondb/randao.go (2 hunks)
  • mod/storage/pkg/beacondb/registry.go (7 hunks)
  • mod/storage/pkg/beacondb/slashing.go (3 hunks)
  • mod/storage/pkg/beacondb/versioning.go (3 hunks)
  • mod/storage/pkg/beacondb/withdrawals.go (2 hunks)
🧰 Additional context used
🔇 Additional comments (28)
mod/storage/pkg/beacondb/helpers.go (2)

1-20: LGTM: License header is correctly included.

The BUSL-1.1 license header is properly included at the beginning of the file, which is a good practice for maintaining clear licensing information.


21-27: LGTM: Package declaration and imports are appropriate.

The package is correctly declared as beacondb, and the necessary imports for "errors" and "cosmossdk.io/collections" are included. These imports align with the function's requirements.

mod/storage/pkg/beacondb/randao.go (2)

23-27: LGTM: Import changes align with new error handling.

The addition of the fmt package import is appropriate for the new error formatting in GetRandaoMixAtIndex.


48-48: Verify the implementation of mapErrors function.

The mapErrors function is crucial for converting collections.ErrNotFound to beacondb.ErrNotFound. Please ensure that this function is correctly implemented to fulfill the PR objectives.

Run the following script to verify the mapErrors implementation:

✅ Verification successful

mapErrors Function Implementation Verified

The mapErrors function is correctly implemented in mod/storage/pkg/beacondb/helpers.go and effectively converts collections.ErrNotFound to beacondb.ErrNotFound.

  • Defined in helpers.go with proper error handling.
  • Utilized in registry.go to maintain consistent error mapping.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of mapErrors function

# Test: Search for the mapErrors function definition
echo "Searching for mapErrors function definition:"
rg --type go -A 10 'func mapErrors'

# Test: Check if mapErrors handles collections.ErrNotFound
echo "Checking if mapErrors handles collections.ErrNotFound:"
rg --type go -A 5 'case errors.Is\(.*?, collections.ErrNotFound\)'

Length of output: 1934

mod/storage/pkg/beacondb/versioning.go (3)

24-25: Importing the 'fmt' package is appropriate for error formatting.

The addition of the fmt package is necessary since fmt.Errorf is used for wrapping errors in the updated methods below.


64-71: Consistent error handling in 'GetSlot' method enhances clarity.

Applying mapErrors(err) and wrapping the error with contextual information using fmt.Errorf improves the consistency and clarity of error reporting in the GetSlot method.


48-53: Ensure 'mapErrors' correctly maps storage errors to 'beacondb.ErrNotFound'.

The use of mapErrors(err) standardizes error handling by mapping underlying storage errors to the new beacondb.ErrNotFound. Please verify that mapErrors properly maps collections.ErrNotFound to beacondb.ErrNotFound as intended in the PR objectives.

Run the following script to confirm the error mapping:

✅ Verification successful

'mapErrors' correctly maps 'collections.ErrNotFound' to 'beacondb.ErrNotFound'.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that 'mapErrors' function maps 'collections.ErrNotFound' to 'beacondb.ErrNotFound'.

# Search for the 'mapErrors' function implementation that maps the errors.
ast-grep --lang go --pattern $'func mapErrors(err error) error {
	if err == collections.ErrNotFound {
		return ErrNotFound
	}
	$$$
}'

Length of output: 134


Script:

#!/bin/bash
# Description: Locate the 'mapErrors' function implementation.

ast-grep --lang go --pattern $'func mapErrors($_) $_ { $$$ }'

Length of output: 623


Script:

#!/bin/bash
# Description: Find all return statements that return 'ErrNotFound' in the codebase.

rg 'return ErrNotFound' --type go

Length of output: 92

mod/storage/pkg/beacondb/withdrawals.go (1)

66-70: Avoid using potentially uninitialized idx in error message

As previously noted, when an error occurs in retrieving idx, the variable idx may not hold a meaningful value. Including it in the error message could be misleading.

mod/storage/pkg/beacondb/slashing.go (2)

86-88: Consistent error mapping in 'GetTotalSlashing'

Ensure that mapErrors is correctly used in GetTotalSlashing to map errors as intended, maintaining consistency across methods.


58-64: Verify 'mapErrors' correctly maps errors as per PR objectives

Ensure that the mapErrors function properly maps collections.ErrNotFound to beacondb.ErrNotFound to fulfill the PR's goal of providing a uniform error handling mechanism to clients.

You can run the following script to verify the error mapping:

mod/storage/pkg/beacondb/history.go (7)

23-25: Importing fmt package for error formatting

The addition of the fmt package is appropriate, as it is used for formatting error messages with fmt.Errorf.


48-54: Improved error handling with contextual messages

In the GetBlockRootAtIndex method, the updated error handling provides more context by including the index in the error message. This enhances debugging and user feedback.


76-84: Enhanced error handling in GetLatestBlockHeader

The method now includes detailed error messages when retrieving the latest block header fails, improving clarity and maintainability.


106-112: Improved error messages in StateRootAtIndex

The updated error handling provides detailed context, including the index, which aids in debugging and error tracing.


78-82: Verify unwrapping of wrapped errors for consistent handling

Ensure that the wrapped errors can be unwrapped by callers to identify specific error types, enabling consistent error handling across the codebase.

Use the following script to check error unwrapping:

#!/bin/bash
# Description: Check that wrapped errors can be unwrapped and specific error types are handled.

# Locate usages of fmt.Errorf with %w in the codebase.
rg --type go 'fmt\.Errorf\([^)]*%w[^)]*\)' -A 2

# Verify that callers use errors.Is or errors.As to handle specific errors.

108-112: Confirm error unwrapping for proper error propagation

When errors are wrapped, it's important that they can be unwrapped by calling code to check for errors like beacondb.ErrNotFound.

Execute the following script to confirm error unwrapping:

#!/bin/bash
# Description: Ensure that wrapped errors are properly propagated and can be unwrapped.

# Search for error wrapping with fmt.Errorf and %w.
rg --type go 'fmt\.Errorf\([^)]*%w[^)]*\)' -A 2

# Check that error handling in the codebase uses errors.Is or errors.As appropriately.

50-54: Ensure errors can be unwrapped for type checking

When wrapping errors using fmt.Errorf with the %w verb, verify that callers can unwrap the error using errors.Is or errors.As to check for specific error types like beacondb.ErrNotFound.

You can run the following script to verify error unwrapping:

mod/storage/pkg/beacondb/eth1.go (5)

23-25: Approved: Import statements are appropriate

The necessary packages are imported, and the import statements are clean and concise.


35-54: Approved: Implementation of GetLatestExecutionPayloadHeader

The GetLatestExecutionPayloadHeader method correctly initializes variables and handles errors consistently. The use of the helper function getLatestExecutionPayloadVersion improves code modularity and readability.


56-68: Approved: Addition of getLatestExecutionPayloadVersion method

The new method getLatestExecutionPayloadVersion encapsulates the logic for retrieving the latest execution payload version, enhancing the maintainability of the code. Error handling is clear and consistent with the rest of the codebase.


122-130: Approved: Consistent error handling in GetEth1Data

The GetEth1Data method implements error handling with clear and informative messages. The use of mapErrors standardizes error mapping across the codebase.


79-84: Consider verifying error handling for SetActiveForkVersion

In SetLatestExecutionPayloadHeader, the call to kv.latestExecutionPayloadCodec.SetActiveForkVersion(payloadHeader.Version()) does not handle any potential errors. If SetActiveForkVersion can fail or might do so in future implementations, it's advisable to handle any possible errors returned from it.

Please confirm whether SetActiveForkVersion can fail, and if so, consider adding error handling. You can run the following script to check if SetActiveForkVersion returns an error:

mod/storage/pkg/beacondb/registry.go (6)

24-25: Added imports are appropriate

The addition of errors and fmt packages is necessary for the updated error handling.


94-108: Previous comment on formatting 'pubkey' in error messages is still valid

The issue regarding the formatting of pubkey in error messages has not been addressed. Please refer to the previous review comment for details.


123-137: Previous comment on formatting 'cometBFTAddress' in error messages is still valid

The issue regarding the formatting of cometBFTAddress in error messages has not been addressed. Please refer to the previous review comment for details.


149-149: Error handling in ValidatorByIndex is correctly implemented

The addition of error mapping and detailed error messages enhances the robustness of the ValidatorByIndex function.

Also applies to: 152-156, 158-158


237-237: Validator retrieval by index is correctly updated

The use of kv.ValidatorByIndex(math.U64(idx)) ensures correct retrieval of validators.


253-261: Enhanced error handling in GetBalance function

The inclusion of error mapping and improved error messages enhances the function's reliability.

mod/storage/pkg/beacondb/randao.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/fork.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/withdrawals.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/withdrawals.go Show resolved Hide resolved
mod/storage/pkg/beacondb/registry.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/registry.go Outdated Show resolved Hide resolved
@abi87 abi87 force-pushed the storage-cleanup-err-not-found branch from 022b099 to 5261a79 Compare October 13, 2024 13:43
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: 7

🧹 Outside diff range comments (1)
mod/storage/pkg/beacondb/withdrawals.go (1)

Line range hint 46-53: Consider applying consistent error mapping to setter methods

For consistency with the getter methods, consider applying the mapErrors function to the SetNextWithdrawalIndex and SetNextWithdrawalValidatorIndex methods. This would align with the PR's goal of improving error handling across the package.

For SetNextWithdrawalIndex, consider applying this change:

 func (kv *KVStore[
 	BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT,
 	ForkT, ValidatorT, ValidatorsT,
 ]) SetNextWithdrawalIndex(
 	index uint64,
 ) error {
-	return kv.nextWithdrawalIndex.Set(kv.ctx, index)
+	err := kv.nextWithdrawalIndex.Set(kv.ctx, index)
+	return mapErrors(err)
 }

Apply a similar change to SetNextWithdrawalValidatorIndex.

Also applies to: 75-82

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 5261a79 and 034f7d1.

📒 Files selected for processing (9)
  • mod/storage/pkg/beacondb/eth1.go (5 hunks)
  • mod/storage/pkg/beacondb/fork.go (2 hunks)
  • mod/storage/pkg/beacondb/helpers.go (1 hunks)
  • mod/storage/pkg/beacondb/history.go (4 hunks)
  • mod/storage/pkg/beacondb/randao.go (2 hunks)
  • mod/storage/pkg/beacondb/registry.go (14 hunks)
  • mod/storage/pkg/beacondb/slashing.go (4 hunks)
  • mod/storage/pkg/beacondb/versioning.go (3 hunks)
  • mod/storage/pkg/beacondb/withdrawals.go (2 hunks)
🧰 Additional context used
🔇 Additional comments (29)
mod/storage/pkg/beacondb/helpers.go (1)

33-42: 🛠️ Refactor suggestion

Consider using a type switch for more idiomatic error handling

While the current implementation is correct, using a type switch instead of errors.Is() would make the code more idiomatic and potentially more efficient. This aligns better with Go's error handling patterns.

Consider refactoring the function as follows:

 func mapErrors(err error) error {
-	switch {
-	case err == nil:
+	switch err {
+	case nil:
 		return nil
-	case errors.Is(err, collections.ErrNotFound):
+	case collections.ErrNotFound:
 		return ErrNotFound
 	default:
 		return err
 	}
 }

This change maintains the same functionality while improving code idiomaticity and potential performance.

Likely invalid or redundant comment.

mod/storage/pkg/beacondb/randao.go (1)

48-54: 🧹 Nitpick (assertive)

LGTM: Improved error handling with suggestions for further enhancement.

The changes align well with the PR objectives by improving error handling and providing more context in the error message. The use of mapErrors likely handles the conversion of collections.ErrNotFound to beacondb.ErrNotFound as intended.

Suggestions for further improvement:

  1. Consider extracting the error formatting into a separate function for better readability and maintainability:
func formatRandaoMixError(index uint64, err error) error {
    return fmt.Errorf("failed retrieving randao mix at index %d: %w", index, err)
}

// Usage in GetRandaoMixAtIndex
if err != nil {
    return common.Bytes32{}, formatRandaoMixError(index, err)
}
  1. Add a comment explaining the purpose of mapErrors function, especially its role in handling collections.ErrNotFound.

To ensure the mapErrors function is correctly handling collections.ErrNotFound, please run the following verification script:

✅ Verification successful

Verification Successful: mapErrors correctly handles collections.ErrNotFound.

The mapErrors function is properly implemented to map collections.ErrNotFound to beacondb.ErrNotFound, aligning with the PR objectives.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of mapErrors function

# Test: Search for the mapErrors function definition
echo "Searching for mapErrors function definition:"
rg --type go -A 10 'func mapErrors'

# Test: Check if collections.ErrNotFound is being handled
echo "Checking if collections.ErrNotFound is being handled:"
rg --type go 'case errors\.Is\(.*collections\.ErrNotFound'

Length of output: 1012

mod/storage/pkg/beacondb/withdrawals.go (1)

34-42: Improved error handling and consistency

The changes in GetNextWithdrawalIndex align well with the PR objectives. The introduction of mapErrors and the new error formatting enhance error handling consistency and provide more informative error messages. This improvement addresses the past review comment about standardizing error messages.

mod/storage/pkg/beacondb/history.go (2)

76-84: Improved error handling looks good!

The changes in GetLatestBlockHeader are consistent with the improvements made in other methods. The new error handling provides more context, which aligns with the PR objectives.


48-48: Please clarify the implementation of mapErrors and ErrNotFound.

The changes consistently use a mapErrors function, which seems to be addressing the ErrNotFound case mentioned in the PR objectives. However, the implementation of mapErrors and the definition of ErrNotFound are not visible in this file.

Could you please provide more information on:

  1. The implementation of the mapErrors function?
  2. The definition and location of the ErrNotFound error type?

This information will help ensure that the error handling is implemented correctly and consistently across the package.

To verify the implementation, please run the following script:

Also applies to: 77-77, 106-106

✅ Verification successful

Verification Successful.

The implementations of mapErrors and ErrNotFound are correctly defined and utilized within the codebase. No issues were found regarding their usage or definitions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for mapErrors function and ErrNotFound definition
echo "Searching for mapErrors function:"
rg --type go -A 5 'func mapErrors'
echo "Searching for ErrNotFound definition:"
rg --type go -A 2 'var ErrNotFound'

Length of output: 802

mod/storage/pkg/beacondb/fork.go (2)

23-25: Addition of "fmt" import is appropriate.

The import of the "fmt" package is necessary for error formatting using fmt.Errorf, which enhances the clarity of error messages.


42-47: Enhanced error handling in GetFork method.

The use of mapErrors(err) to map internal errors to beacondb.ErrNotFound, along with wrapping the error using fmt.Errorf, improves error transparency. This change aligns with the PR objective to provide a uniform error handling mechanism.

mod/storage/pkg/beacondb/versioning.go (3)

24-25: Importing "fmt" package for error formatting

The addition of the "fmt" package is appropriate to support error wrapping with fmt.Errorf.


48-53: Enhanced error handling in GetGenesisValidatorsRoot()

The updated error handling improves clarity by mapping errors and providing informative messages. This change aids in debugging and maintains consistency across the codebase.


64-71: Consistent error handling in GetSlot()

The inclusion of error mapping and wrapping enhances error reporting, aligning with best practices.

mod/storage/pkg/beacondb/slashing.go (4)

24-25: Appropriate addition of the 'fmt' package

The inclusion of the fmt package is necessary for enhanced error formatting introduced in the updated code.


35-42: Consistent use of 'mapErrors' for error mapping

The implementation of mapErrors(err) enhances consistency in error handling across the codebase. The updated error messages provide clear context when iteration fails in GetSlashings.


63-69: Improved error handling in 'GetSlashingAtIndex'

The use of mapErrors(err) along with detailed error messages improves clarity when retrieving slashing amounts by index fails. This change aligns with the PR objectives of refining error handling.


91-93: Enhanced error reporting in 'GetTotalSlashing'

Applying mapErrors(err) and providing a formatted error message ensures that any failures during the retrieval of the total slashing amount are clearly communicated.

mod/storage/pkg/beacondb/eth1.go (6)

23-25: Approved

The import statements have been correctly updated to include only the necessary packages.


35-54: Approved

The GetLatestExecutionPayloadHeader function properly retrieves the latest execution payload version and header with appropriate error handling. The separation of concerns by introducing the getLatestExecutionPayloadVersion helper function enhances code readability and maintainability.


56-68: Approved

The getLatestExecutionPayloadVersion helper function encapsulates the retrieval of the latest execution payload version with consistent error handling, improving code reusability.


79-86: Approved

The SetLatestExecutionPayloadHeader function correctly sets the latest execution payload version and header. The use of local variables for context and version improves code clarity.


95-104: Approved

The GetEth1DepositIndex function includes appropriate retrieval logic with consistent error mapping and handling.


122-130: Approved

The GetEth1Data function correctly retrieves the Eth1 data with proper error handling and mapping.

mod/storage/pkg/beacondb/registry.go (9)

103-106: Corrected formatting of pubkey in error message

The error message now uses %x to format pubkey, which is appropriate for byte slices.


125-128: Corrected formatting of cometBFTAddress in error message

The error message now correctly formats cometBFTAddress using %x, suitable for byte slices.


141-150: Enhanced error handling in ValidatorByIndex

The error mapping and detailed error message improve the clarity of error reporting.


163-166: Improved error message in GetValidators

The error message now more accurately describes the operation, enhancing clarity.


177-180: Improved error message in GetValidators iteration

The error message now clearly indicates that the iteration over validators failed.


229-232: Enhanced error message in GetValidatorsByEffectiveBalance

The error message has been clarified to indicate the failure in iterating validators by effective balance.


257-265: Enhanced error handling in GetBalance

The added error mapping and detailed error message improve error reporting in the GetBalance method.


288-291: Improved error handling in GetBalances

The error mapping and clear error message enhance robustness.


318-321: Improved error message in GetTotalActiveBalances

The error message now more clearly indicates the failure in iterating validators' effective balances.

mod/storage/pkg/beacondb/helpers.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/withdrawals.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/history.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/history.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/registry.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/registry.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/registry.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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 034f7d1 and b0f9050.

📒 Files selected for processing (1)
  • mod/storage/pkg/beacondb/errors.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
mod/storage/pkg/beacondb/errors.go (2)

1-27: LGTM: Package declaration and imports are correct.

The file includes appropriate license information, correct package declaration, and relevant imports for the implemented functionality.


1-44: Overall assessment: Well-implemented error handling improvements.

This new file successfully introduces the ErrNotFound error type and implements error mapping as per the PR objectives. The code is well-structured, follows Go best practices, and effectively standardizes error handling for the Beacon database.

Key points:

  1. Custom ErrNotFound error is appropriately defined.
  2. The mapErrors function effectively maps collections.ErrNotFound to ErrNotFound.
  3. The implementation reduces direct dependencies on Cosmos SDK error types.

The suggested minor improvements (adding a comment for ErrNotFound and renaming mapErrors to mapError) would further enhance the code's clarity and consistency.

mod/storage/pkg/beacondb/errors.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/errors.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: 6

🧹 Outside diff range comments (3)
mod/storage/pkg/beacondb/randao.go (1)

Line range hint 23-54: Summary: Partial alignment with PR objectives

The changes in this file improve error handling and message formatting, which is a step in the right direction. However, to fully align with the PR objectives:

  1. Ensure that beacondb.ErrNotFound is used explicitly when appropriate.
  2. Clarify the role of the mapError function in error handling.
  3. Verify that collections.ErrNotFound is no longer returned to clients.

Consider addressing these points to complete the implementation of the PR objectives.

mod/storage/pkg/beacondb/slashing.go (2)

Line range hint 59-64: Return beacondb.ErrNotFound instead of default value

In GetSlashingAtIndex, to align with the PR objective of introducing beacondb.ErrNotFound for uniform error handling, consider returning this specific error when collections.ErrNotFound is encountered, rather than returning 0 and nil. This change explicitly informs the client that the object was not found.

Suggested change:

     amount, err := kv.slashings.Get(kv.ctx, index)
     if errors.Is(err, collections.ErrNotFound) {
-        return 0, nil
+        return 0, beacondb.ErrNotFound
     } else if err != nil {
         return 0, err
     }
     return math.Gwei(amount), nil

Line range hint 76-81: Return beacondb.ErrNotFound when total slashing amount is missing

In GetTotalSlashing, consider returning beacondb.ErrNotFound when collections.ErrNotFound is encountered, instead of returning 0 and nil. This approach aligns with the PR's goal of standardizing error handling and clearly indicates to clients that the total slashing amount was not found.

Suggested change:

     total, err := kv.totalSlashing.Get(kv.ctx)
     if errors.Is(err, collections.ErrNotFound) {
-        return 0, nil
+        return 0, beacondb.ErrNotFound
     } else if err != nil {
         return 0, err
     }
     return math.Gwei(total), nil
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between b0f9050 and 86da4a8.

📒 Files selected for processing (9)
  • mod/storage/pkg/beacondb/errors.go (1 hunks)
  • mod/storage/pkg/beacondb/eth1.go (5 hunks)
  • mod/storage/pkg/beacondb/fork.go (2 hunks)
  • mod/storage/pkg/beacondb/history.go (4 hunks)
  • mod/storage/pkg/beacondb/randao.go (2 hunks)
  • mod/storage/pkg/beacondb/registry.go (14 hunks)
  • mod/storage/pkg/beacondb/slashing.go (2 hunks)
  • mod/storage/pkg/beacondb/versioning.go (3 hunks)
  • mod/storage/pkg/beacondb/withdrawals.go (2 hunks)
🧰 Additional context used
📓 Learnings (2)
mod/storage/pkg/beacondb/errors.go (2)
Learnt from: abi87
PR: berachain/beacon-kit#2065
File: mod/storage/pkg/beacondb/errors.go:29-29
Timestamp: 2024-10-13T16:17:45.589Z
Learning: When defining error variables like `ErrNotFound` in the `beacondb` package, the user prefers not to add comments if the error is self-explanatory.
Learnt from: abi87
PR: berachain/beacon-kit#2065
File: mod/storage/pkg/beacondb/helpers.go:0-0
Timestamp: 2024-10-13T15:05:46.809Z
Learning: In the Go code at `mod/storage/pkg/beacondb/helpers.go`, using `errors.Is` in the `mapErrors` function is preferred over direct error equality checks, as it handles wrapped errors and provides more general error matching.
mod/storage/pkg/beacondb/registry.go (1)
Learnt from: abi87
PR: berachain/beacon-kit#2065
File: mod/storage/pkg/beacondb/registry.go:330-331
Timestamp: 2024-10-13T14:18:59.472Z
Learning: When reviewing PRs that are purely for refactoring, avoid suggesting logic changes or code modifications that are out of scope.
🔇 Additional comments (34)
mod/storage/pkg/beacondb/errors.go (3)

1-20: LGTM: Appropriate license header.

The BUSL-1.1 license header is correctly included and formatted, which is crucial for open-source projects.


29-29: LGTM: Clear and concise error definition.

The ErrNotFound error is well-defined and aligns with the PR objectives. It provides a clear, package-specific error message without unnecessary comments, as per your preference.


31-44: LGTM: Well-implemented error mapping function.

The mapError function effectively achieves the goal of standardizing error handling by mapping collections.ErrNotFound to the custom ErrNotFound. Notable points:

  1. The function is well-commented, explaining its purpose clearly.
  2. It correctly uses errors.Is for error checking, which is the preferred method as it handles wrapped errors.
  3. The function name is already in singular form (mapError), which is appropriate for its functionality.

The implementation aligns well with the PR objectives and follows good practices in Go error handling.

mod/storage/pkg/beacondb/randao.go (1)

50-54: Approved: Improved error message formatting

The error message formatting has been improved as suggested in a previous review comment. This change enhances the clarity of error reporting.

mod/storage/pkg/beacondb/history.go (4)

23-27: LGTM: Import changes are appropriate.

The addition of the "fmt" package to the import list is necessary for the new error formatting using fmt.Errorf. This change aligns with the modifications made in the methods below.


76-84: LGTM: Improved error handling in GetLatestBlockHeader.

The changes in this method are consistent with the improvements made in GetBlockRootAtIndex. The new error handling provides more context, which aligns with the PR objectives. The use of mapError is consistent, and the error message is clear and informative.


Line range hint 1-114: Summary: Improved error handling with some points needing attention.

Overall, the changes in this file consistently improve error handling by providing more context in error messages, which aligns with the PR objectives. However, there are a few points that need attention:

  1. The mapError function is used throughout the file but is not defined here. Please ensure it's properly defined and imported.
  2. The PR objectives mention introducing beacondb.ErrNotFound, but it's not directly used in the reviewed code. Clarify if this is intentional or if it should be incorporated.
  3. Consider standardizing the error message format across all methods for consistency (e.g., "failed to retrieve" vs "failed retrieving").

These improvements enhance the clarity and specificity of error reporting in the specified methods, but addressing the above points would further strengthen the implementation.

To verify the ErrNotFound definition:

#!/bin/bash
# Search for the definition of ErrNotFound
rg --type go 'var ErrNotFound'

48-54: Improved error handling, but clarification needed on mapError.

The new error handling provides more context by including the index in the error message, which aligns with the PR objectives. However, there are a couple of points that need attention:

  1. The mapError function is used but not defined in this file. Please ensure it's properly defined and imported.
  2. The PR objectives mention introducing beacondb.ErrNotFound, but it's not directly used here. Is this intentional?

To verify the mapError function:

✅ Verification successful

mapError is properly defined and accessible.

The mapError function is defined in mod/storage/pkg/beacondb/errors.go and is correctly used within history.go. Since both files are part of the same beacondb package, there is no need for additional imports, and the usage aligns with Go's package structure.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the definition of mapError function
rg --type go 'func mapError'

Length of output: 213


Script:

#!/bin/bash
# Search for any occurrences of mapError in Go files
rg --type go 'mapError'

Length of output: 1684

mod/storage/pkg/beacondb/fork.go (2)

23-25: Importing 'fmt' package is appropriate

The addition of the fmt package is necessary for error formatting.


42-46: Ensure to return zero value of ForkT on error

As previously noted, when an error occurs, returning the potentially invalid f may lead to unintended behavior. It's safer to return the zero value of ForkT to prevent propagation of invalid data.

mod/storage/pkg/beacondb/versioning.go (3)

24-25: Approved: Necessary import added

The import of the fmt package is required for the enhanced error handling using fmt.Errorf below.


48-54: Verify mapError correctly maps collections.ErrNotFound to beacondb.ErrNotFound

Ensure that the mapError(err) function properly converts collections.ErrNotFound to beacondb.ErrNotFound as per the PR objective to clean up NotFound errors. This change ensures that clients receive the uniform error type beacondb.ErrNotFound when an object is not found.

You can verify this by checking the implementation of mapError. Run the following script to confirm:

#!/bin/bash
# Description: Verify that mapError correctly maps collections.ErrNotFound to beacondb.ErrNotFound

# Search for the implementation of mapError
rg --type go -A5 -B5 'func mapError\(err error\) error'

# Check if collections.ErrNotFound is mapped to beacondb.ErrNotFound within mapError

64-70: Ensure consistent error mapping in GetSlot method

As with GetGenesisValidatorsRoot, confirm that mapError(err) in the GetSlot method correctly maps collections.ErrNotFound to beacondb.ErrNotFound. This maintains uniform error handling across the codebase.

You can verify this by reviewing the mapError implementation:

✅ Verification successful

Error mapping in GetSlot is consistent and correctly implemented.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that mapError correctly maps collections.ErrNotFound to beacondb.ErrNotFound

# Search for the implementation of mapError
rg --type go -A5 -B5 'func mapError\(err error\) error'

# Ensure that collections.ErrNotFound is being mapped appropriately

Length of output: 831

mod/storage/pkg/beacondb/withdrawals.go (2)

23-27: Appropriate Addition of Imports

The fmt package is correctly imported for formatting error messages, and math is imported for math.ValidatorIndex. These additions are necessary and properly included.


34-42: Enhanced Error Handling in GetNextWithdrawalIndex

The method now uses mapError(err) to process errors and provides a clear, formatted error message when retrieval fails. This improves error clarity and consistency across the codebase.

mod/storage/pkg/beacondb/slashing.go (2)

24-25: Importing necessary packages for error handling

The addition of the "errors" and "fmt" packages is appropriate for improved error handling and formatting.


37-42: Ensure mapError correctly maps errors

The use of err = mapError(err) is essential for consistent error handling. Please verify that the mapError function correctly transforms collections.ErrNotFound into beacondb.ErrNotFound or handles errors as intended, in line with the PR objectives.

You can run the following script to locate and review the implementation of mapError:

✅ Verification successful

Verification Successful: mapError correctly maps collections.ErrNotFound to beacondb.ErrNotFound.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Locate and display the implementation of the mapError function.

# Search for the definition of mapError in Go source files.
rg --type go '^func mapError\(err error\) error' -A 5

Length of output: 407

mod/storage/pkg/beacondb/eth1.go (5)

23-25: Imports are appropriate

The necessary packages are imported correctly.


35-54: GetLatestExecutionPayloadHeader is correctly implemented

The function effectively retrieves the latest execution payload header with proper error handling.


60-68: getLatestExecutionPayloadVersion is correctly implemented

The helper function encapsulates the retrieval of the latest execution payload version and handles errors appropriately.


95-104: GetEth1DepositIndex is correctly implemented

The function retrieves the Eth1 deposit index with appropriate error handling.


122-130: GetEth1Data is correctly implemented

The function retrieves the Eth1 data and handles errors properly.

mod/storage/pkg/beacondb/registry.go (12)

24-25: Importing the "fmt" package

The addition of the "fmt" package is appropriate, as it is required for the formatted error messages introduced in this refactoring.


38-43: Improved error handling in AddValidator

The use of mapError(err) followed by a check for err != nil enhances error handling. The formatted error message provides clear context about the failure when adding a validator.


61-66: Consistent error handling in AddValidatorBartio

The introduction of mapError(err) and a descriptive error message improves the clarity and consistency of error handling when adding a Bartio validator.


100-106: Proper formatting of pubkey in error messages

Formatting pubkey with %x displays the public key in hexadecimal format, which enhances readability and ensures correct representation of the BLSPubkey.


122-128: Proper formatting of cometBFTAddress in error messages

Using %x to format cometBFTAddress correctly displays the address in hexadecimal, which is appropriate for byte slices and improves the clarity of error messages.


141-148: Enhanced error handling in ValidatorByIndex

Mapping the error and providing a detailed error message when retrieval fails improves debuggability and user understanding.


161-166: Improved error handling in GetValidators

The error handling enhancements, including the use of mapError(err) and a clear error message, make it easier to diagnose issues when peeking the next validator index fails.


175-180: Consistent error handling during validators iteration

The addition of error mapping and a descriptive error message in the iteration process enhances consistency and aids in troubleshooting.


227-232: Improved error handling in GetValidatorsByEffectiveBalance

The updates ensure that any errors encountered during iteration are mapped and clearly reported, improving maintainability and debugging.


257-265: Enhanced error handling in GetBalance

Mapping the error and providing a specific error message when retrieving a balance fails enhances the clarity of error reporting.


286-291: Improved error handling during balances iteration

The consistent use of mapError(err) and detailed error messages improves error handling when iterating over balances.


316-321: Consistent error handling in GetTotalActiveBalances

The addition of error mapping and a clear message when iterating over validators' effective balances aligns with the refactoring objective and enhances error clarity.

mod/storage/pkg/beacondb/randao.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/randao.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/history.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/versioning.go Show resolved Hide resolved
mod/storage/pkg/beacondb/versioning.go Show resolved Hide resolved
mod/storage/pkg/beacondb/eth1.go Show resolved Hide resolved
@abi87 abi87 changed the base branch from main to update-mockery-v2-46-3 October 15, 2024 14:43
Base automatically changed from update-mockery-v2-46-3 to main October 15, 2024 14:52
@abi87 abi87 enabled auto-merge (squash) October 15, 2024 15:16
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: 11

🧹 Outside diff range comments (3)
mod/storage/pkg/block/store.go (1)

Line range hint 1-124: Overall: Excellent improvements in error handling and consistency.

The changes in this file successfully implement the new storage.ErrNotFound error type across all relevant methods, aligning perfectly with the PR objectives. The error messages now provide more context by including specific identifiers (block root, execution number, state root), which will greatly aid in debugging.

To further improve code maintainability and reduce duplication, consider introducing a helper function for error creation:

func newNotFoundError(identifier string, value interface{}) error {
    return fmt.Errorf("%w, %s: %v", storage.ErrNotFound, identifier, value)
}

This function could then be used in all three methods:

return 0, newNotFoundError("block root", blockRoot)
return 0, newNotFoundError("execution number", executionNumber)
return 0, newNotFoundError("state root", stateRoot)

This approach would centralize the error creation logic and make future modifications easier.

mod/storage/pkg/beacondb/withdrawals.go (1)

Line range hint 75-82: Consistent error mapping in SetNextWithdrawalValidatorIndex

In GetNextWithdrawalValidatorIndex, errors are mapped using storage.MapError(err) before handling. However, in SetNextWithdrawalValidatorIndex, errors from kv.nextWithdrawalValidatorIndex.Set(kv.ctx, index.Unwrap()) are returned directly without mapping. For consistency in error handling across methods, consider mapping errors here as well.

Apply this diff to map errors:

 func (kv *KVStore[
     BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT,
     ForkT, ValidatorT, ValidatorsT,
 ]) SetNextWithdrawalValidatorIndex(
     index math.ValidatorIndex,
 ) error {
-    return kv.nextWithdrawalValidatorIndex.Set(kv.ctx, index.Unwrap())
+    err := kv.nextWithdrawalValidatorIndex.Set(kv.ctx, index.Unwrap())
+    return storage.MapError(err)
 }
mod/storage/pkg/beacondb/slashing.go (1)

Line range hint 64-79: Align error handling with PR objectives by returning beacondb.ErrNotFound

According to the PR objectives, the goal is to expose a beacondb.ErrNotFound error when an object is not found, instead of returning default values with a nil error. In the GetSlashingAtIndex and GetTotalSlashing methods, when collections.ErrNotFound is encountered, the functions currently return a zero value (0) and nil error. This can lead to confusion for clients, as it does not clearly indicate that the object was not found.

To align with the PR objectives and provide a more uniform error handling mechanism, consider returning beacondb.ErrNotFound when an object is not found.

Apply this diff to update the error handling:

 func (kv *KVStore[
 	BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT,
 	ForkT, ValidatorT, ValidatorsT,
 ]) GetSlashingAtIndex(
 	index uint64,
 ) (math.Gwei, error) {
 	amount, err := kv.slashings.Get(kv.ctx, index)
-	if errors.Is(err, collections.ErrNotFound) {
-		return 0, nil
+	err = storage.MapError(err)
+	if errors.Is(err, beacondb.ErrNotFound) {
+		return 0, err
+	} else if err != nil {
+		return 0, err
 	}
 	return math.Gwei(amount), nil
 }

 // GetTotalSlashing retrieves the total slashing amount from the store.
 func (kv *KVStore[
 	BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT,
 	ForkT, ValidatorT, ValidatorsT,
 ]) GetTotalSlashing() (math.Gwei, error) {
 	total, err := kv.totalSlashing.Get(kv.ctx)
-	if errors.Is(err, collections.ErrNotFound) {
-		return 0, nil
+	err = storage.MapError(err)
+	if errors.Is(err, beacondb.ErrNotFound) {
+		return 0, err
+	} else if err != nil {
+		return 0, err
 	}
 	return math.Gwei(total), nil
 }

This change ensures that when an object is not found, the functions return beacondb.ErrNotFound, making it clear to clients that the requested data is missing.

Also applies to: 89-102

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 86da4a8 and 35e893c.

📒 Files selected for processing (11)
  • mod/storage/pkg/beacondb/eth1.go (5 hunks)
  • mod/storage/pkg/beacondb/fork.go (2 hunks)
  • mod/storage/pkg/beacondb/history.go (4 hunks)
  • mod/storage/pkg/beacondb/randao.go (2 hunks)
  • mod/storage/pkg/beacondb/registry.go (14 hunks)
  • mod/storage/pkg/beacondb/slashing.go (2 hunks)
  • mod/storage/pkg/beacondb/versioning.go (3 hunks)
  • mod/storage/pkg/beacondb/withdrawals.go (2 hunks)
  • mod/storage/pkg/block/store.go (4 hunks)
  • mod/storage/pkg/block/store_test.go (3 hunks)
  • mod/storage/pkg/errors.go (1 hunks)
🧰 Additional context used
📓 Learnings (1)
mod/storage/pkg/beacondb/registry.go (1)
Learnt from: abi87
PR: berachain/beacon-kit#2065
File: mod/storage/pkg/beacondb/registry.go:330-331
Timestamp: 2024-10-13T14:18:59.472Z
Learning: When reviewing PRs that are purely for refactoring, avoid suggesting logic changes or code modifications that are out of scope.
🔇 Additional comments (25)
mod/storage/pkg/errors.go (3)

1-21: LGTM: License header and package declaration.

The license header is complete and the package declaration is appropriate for the file's purpose.


23-29: LGTM: Imports and error variable declaration.

The imports are appropriate for the file's functionality. The ErrNotFound variable is well-defined and aligns with the PR objective of introducing a new error type for improved error handling in cases where queried objects are not found.


1-44: Overall assessment: Well-implemented error handling.

This new file successfully introduces the ErrNotFound error type and the MapError function, fulfilling the PR objective of improving error handling for cases where queried objects are not found. The implementation is clean, follows Go best practices, and effectively reduces dependencies on the Cosmos SDK package.

The changes align perfectly with the PR's goal of ensuring that collections.ErrNotFound is no longer returned to clients, instead providing a more uniform error handling mechanism through beacondb.ErrNotFound.

Great job on this refactoring effort!

mod/storage/pkg/beacondb/randao.go (3)

23-28: LGTM: Import changes are appropriate.

The new imports for "fmt" and the storage package are correctly added and necessary for the changes made in the GetRandaoMixAtIndex method.


Line range hint 1-55: Overall improvements with room for alignment

The changes in this file improve error handling and provide more informative error messages. The use of storage.MapError and formatted error messages enhances the clarity of error reporting. However, to fully align with the PR objectives of introducing beacondb.ErrNotFound, consider implementing the suggested changes in the previous comment.

These modifications will ensure that the code meets the stated goal of not returning collections.ErrNotFound to clients and provides a more uniform error handling mechanism across the codebase.


49-55: 🛠️ Refactor suggestion

Suggestion: Explicitly handle collections.ErrNotFound

While the changes improve error handling, they don't fully align with the PR objectives of introducing beacondb.ErrNotFound. Consider explicitly checking for collections.ErrNotFound and returning beacondb.ErrNotFound to better meet the PR goals.

Here's a suggested implementation:

bz, err := kv.randaoMix.Get(kv.ctx, index)
if errors.Is(err, collections.ErrNotFound) {
    return common.Bytes32{}, fmt.Errorf(
        "failed retrieving randao mix at index %d: %w",
        index,
        beacondb.ErrNotFound,
    )
} else if err != nil {
    return common.Bytes32{}, fmt.Errorf(
        "failed retrieving randao mix at index %d: %w",
        index,
        err,
    )
}
return common.Bytes32(bz), nil

This change ensures that collections.ErrNotFound is no longer returned to clients, as specified in the PR objectives.

To verify the current implementation of storage.MapError, please run the following script:

mod/storage/pkg/block/store_test.go (2)

29-29: LGTM: Import added for storage package

The addition of the storage package import is in line with the PR objectives and enables the use of storage.ErrNotFound in the test cases.


85-90: LGTM: Improved error handling in test cases

The changes to use require.ErrorIs with storage.ErrNotFound align well with the PR objectives and provide more precise error checking. This addresses the concern raised in previous reviews about aligning error types.

To ensure consistency across the codebase, let's verify the usage of error types:

✅ Verification successful

Verified: Consistent use of storage.ErrNotFound in test cases

The use of require.ErrorIs with storage.ErrNotFound in store_test.go is consistent and aligns with the project's error handling standards.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of error types across the codebase

# Search for storage.ErrNotFound
echo "Occurrences of storage.ErrNotFound:"
rg --type go "storage\.ErrNotFound"

# Search for any other ErrNotFound variations
echo "Other ErrNotFound variations:"
rg --type go "ErrNotFound" | grep -v "storage\.ErrNotFound"

Length of output: 2093

mod/storage/pkg/beacondb/history.go (1)

23-28: Overall improvements in error handling

The changes made to this file significantly improve error handling across multiple functions. Key improvements include:

  1. Consistent use of storage.MapError to handle potential ErrNotFound cases.
  2. More informative error messages that include context (such as index numbers) to aid in debugging.
  3. Structured error creation using fmt.Errorf, which allows for better error wrapping and context preservation.

These changes align well with the PR objectives of introducing a new error type and improving error handling. The code is now more consistent and provides clearer information when errors occur.

To further enhance consistency, consider applying the suggested minor wording changes in the error messages across all functions.

Also applies to: 49-55, 77-85, 107-113

mod/storage/pkg/block/store.go (1)

29-29: LGTM: New import added correctly.

The new import for the storage package is correctly added and aliased. This import is necessary for using the ErrNotFound error, which aligns with the PR objective of introducing a new error type.

mod/storage/pkg/beacondb/fork.go (1)

44-48: Previous issue still applies: Return zero value of ForkT on error

As previously noted, when an error occurs, you are returning f along with the error. The value of f may be invalid or undefined when err is not nil. Returning this potentially invalid f could lead to unintended behavior in the caller's code. It's safer to return the zero value of ForkT to ensure no invalid data is propagated.

mod/storage/pkg/beacondb/versioning.go (3)

24-25: Necessary import added for error formatting

The addition of the fmt package import is appropriate, enabling the use of fmt.Errorf for enhanced error messages.


49-54: Enhanced error handling in GetGenesisValidatorsRoot

The inclusion of storage.MapError(err) and wrapping the error with fmt.Errorf provides better error context and aids in debugging. This is a good practice for consistent error handling.


65-72: Improved error handling in GetSlot

Applying storage.MapError(err) and formatting the error message with fmt.Errorf enhances clarity and consistency in error reporting.

mod/storage/pkg/beacondb/withdrawals.go (2)

23-28: Imports are correctly updated

The necessary packages have been imported to support error formatting and mapping. This enhances error handling consistency across the module.


35-43: Proper error handling in GetNextWithdrawalIndex

The method correctly maps errors using storage.MapError(err) and returns a formatted error message with appropriate context. This improves the clarity of error reporting.

mod/storage/pkg/beacondb/slashing.go (2)

24-29: Necessary imports added

The added imports (errors, fmt, and storage) are appropriate and necessary for the enhanced error handling in the code.


38-43: Improved error handling with storage.MapError

Using storage.MapError(err) improves the clarity and consistency of error handling, aligning with the PR objectives to avoid exposing collections.ErrNotFound to clients.

mod/storage/pkg/beacondb/eth1.go (5)

37-56: Correct Implementation of GetLatestExecutionPayloadHeader

The method GetLatestExecutionPayloadHeader correctly retrieves the latest execution payload header with appropriate error handling. The use of storage.MapError ensures that storage-specific errors are properly mapped, and the error messages provide clear context if retrieval fails.


58-70: Proper Error Handling in getLatestExecutionPayloadVersion

The helper method getLatestExecutionPayloadVersion effectively abstracts the retrieval of the latest execution payload version. It includes appropriate error mapping and returns clear, informative error messages, enhancing maintainability and readability.


81-86: Previous Refactor Suggestions Still Applicable

The earlier refactor suggestions regarding the SetLatestExecutionPayloadHeader method are still valid:

  • Simplify the use of the ctx variable: Since ctx is assigned kv.ctx and used only once, consider using kv.ctx directly to enhance readability.
  • Reuse the version variable: You have already assigned version = payloadHeader.Version(). When setting the active fork version, consider reusing the version variable instead of calling payloadHeader.Version() again.

100-104: Avoid Including Uninitialized Variables in Error Messages

Including idx in the error message when it may not have been successfully retrieved (and defaults to zero) could be misleading. The previous suggestion to exclude idx from the error message remains applicable.


124-132: Consistent and Clear Error Handling in GetEth1Data

The method GetEth1Data correctly retrieves the eth1 data with appropriate error handling. The use of storage.MapError ensures consistent error mapping, and the error message provides clear information in case of failure.

mod/storage/pkg/beacondb/registry.go (2)

Line range hint 24-266: Code changes enhance error handling and clarity

The addition of storage.MapError(err) and the consistent wrapping of errors using fmt.Errorf across the methods improve the error handling mechanism. These changes provide more informative error messages and enhance the maintainability of the code.


Line range hint 287-343: Error handling improvements are appropriate

The updates to the error handling in the balance-related methods, including GetBalances and GetTotalActiveBalances, streamline the error reporting and align with the rest of the codebase's practices.

mod/storage/pkg/errors.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/history.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/history.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/history.go Outdated Show resolved Hide resolved
mod/storage/pkg/block/store.go Outdated Show resolved Hide resolved
mod/storage/pkg/block/store.go Outdated Show resolved Hide resolved
mod/storage/pkg/block/store.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/withdrawals.go Outdated Show resolved Hide resolved
mod/storage/pkg/beacondb/registry.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: 10

🧹 Outside diff range comments (1)
mod/storage/pkg/block/store.go (1)

Line range hint 1-124: Overall LGTM with a suggestion for further improvement.

The changes in this file consistently improve error handling across different methods by using the new errors.ErrNotFound type and providing more context in error messages. This aligns well with the PR objectives of introducing a new error type and improving error handling.

To further enhance maintainability and consistency, consider implementing the following suggestion across all methods:

  1. Define constants for error message formats at the package level.
  2. Use these constants in the respective error handling sections.

Example:

const (
    errMsgBlockRootNotFound       = "%w, block root: %s"
    errMsgExecutionNumberNotFound = "%w, execution number: %d"
    errMsgStateRootNotFound       = "%w, state root: %s"
)

// Then use these constants in the respective methods:
return 0, fmt.Errorf(errMsgBlockRootNotFound, errors.ErrNotFound, blockRoot)

This approach will centralize error message definitions, making future updates easier and ensuring consistency across the package.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 30b680f and fbd9772.

📒 Files selected for processing (11)
  • mod/storage/pkg/beacondb/eth1.go (5 hunks)
  • mod/storage/pkg/beacondb/fork.go (2 hunks)
  • mod/storage/pkg/beacondb/history.go (4 hunks)
  • mod/storage/pkg/beacondb/randao.go (2 hunks)
  • mod/storage/pkg/beacondb/registry.go (14 hunks)
  • mod/storage/pkg/beacondb/slashing.go (2 hunks)
  • mod/storage/pkg/beacondb/versioning.go (3 hunks)
  • mod/storage/pkg/beacondb/withdrawals.go (2 hunks)
  • mod/storage/pkg/block/store.go (4 hunks)
  • mod/storage/pkg/block/store_test.go (3 hunks)
  • mod/storage/pkg/errors/errors.go (1 hunks)
🧰 Additional context used
📓 Learnings (1)
mod/storage/pkg/beacondb/registry.go (1)
Learnt from: abi87
PR: berachain/beacon-kit#2065
File: mod/storage/pkg/beacondb/registry.go:330-331
Timestamp: 2024-10-13T14:18:59.472Z
Learning: When reviewing PRs that are purely for refactoring, avoid suggesting logic changes or code modifications that are out of scope.
🔇 Additional comments (35)
mod/storage/pkg/errors/errors.go (5)

1-20: LGTM: License header is present and correctly formatted.

The Business Source License (BSL) 1.1 is properly included at the beginning of the file, providing clear terms of use and necessary disclaimers.


21-27: LGTM: Package declaration and imports are appropriate.

The package name errors is suitable for an error handling package. The imports are relevant to the functionality provided in this file, including the standard errors package and cosmossdk.io/collections.


29-29: LGTM: ErrNotFound declaration is well-defined.

The ErrNotFound variable is appropriately declared as a package-level variable with a clear and descriptive error message. This approach allows for consistent error handling across the package and follows Go naming conventions for errors.


31-44: LGTM: MapError function is well-implemented and aligns with PR objectives.

The MapError function effectively achieves the goal of replacing collections.ErrNotFound with the custom ErrNotFound. The implementation is clear, concise, and handles all cases appropriately:

  1. Returns nil for nil errors.
  2. Maps collections.ErrNotFound to ErrNotFound.
  3. Returns the original error for all other cases.

This implementation aligns perfectly with the PR objectives of providing a more uniform error handling mechanism and reducing direct dependencies on Cosmos SDK error types.


1-44: Excellent implementation that fully meets PR objectives.

This new errors.go file successfully introduces a custom error handling mechanism for storage-related operations, aligning perfectly with the PR objectives. Key points:

  1. The custom ErrNotFound error provides a clear, storage-specific error message.
  2. The MapError function effectively replaces collections.ErrNotFound with ErrNotFound, reducing direct dependencies on Cosmos SDK error types.
  3. The implementation allows for more uniform error handling across the package.

This change will indeed improve the ability of clients to understand when an object is not found through a specific error rather than through silent mapping in the storage package.

mod/storage/pkg/beacondb/randao.go (1)

23-28: LGTM: Necessary imports added

The new imports for "fmt" and "errors" are correctly added to support the changes in the GetRandaoMixAtIndex method.

mod/storage/pkg/beacondb/history.go (2)

23-28: LGTM: Import statements updated appropriately.

The new imports for "fmt" and the custom errors package are correctly added to support the enhanced error handling introduced in this PR.


Line range hint 1-116: Overall LGTM: Error handling improvements align well with PR objectives.

The changes in this file successfully implement the improved error handling as described in the PR objectives. Key improvements include:

  1. Introduction of errors.MapError, which likely handles the mapping to the new beacondb.ErrNotFound type.
  2. More informative error messages that include context (such as index values) where applicable.
  3. Consistent error handling approach across multiple methods.

These changes will provide clearer indications to clients when objects are not found, addressing the main goal of the PR. The suggested minor wording adjustments for consistency will further enhance the overall quality of the error messages.

Great job on this refactoring effort!

mod/storage/pkg/block/store.go (4)

29-29: LGTM: New import aligns with PR objective.

The addition of the errors package import is necessary for using the new errors.ErrNotFound type, which aligns with the PR objective of introducing a new error type for improved error handling.


85-89: LGTM: Error handling improved with more context.

The changes align with the PR objective by using the new errors.ErrNotFound error type. The error message now includes the block root, providing more context for debugging.

As previously suggested, consider using a constant for the error message format to improve maintainability:

const errMsgBlockRootNotFound = "%w, block root: %s"

return 0, fmt.Errorf(errMsgBlockRootNotFound, errors.ErrNotFound, blockRoot)

102-103: LGTM: Error handling improved with more context.

The changes align with the PR objective by using the new errors.ErrNotFound error type. The error message now includes the execution number, providing more context for debugging.

As previously suggested, consider using a constant for the error message format to improve maintainability:

const errMsgExecutionNumberNotFound = "%w, execution number: %d"

return 0, fmt.Errorf(errMsgExecutionNumberNotFound, errors.ErrNotFound, executionNumber)

116-120: LGTM: Error handling improved with more context.

The changes align with the PR objective by using the new errors.ErrNotFound error type. The error message now includes the state root, providing more context for debugging.

As previously suggested, consider using a constant for the error message format to improve maintainability:

const errMsgStateRootNotFound = "%w, state root: %s"

return 0, fmt.Errorf(errMsgStateRootNotFound, errors.ErrNotFound, stateRoot)
mod/storage/pkg/beacondb/fork.go (1)

44-49: Previous issue regarding returning potentially invalid f on error remains unaddressed

mod/storage/pkg/beacondb/versioning.go (3)

24-28: Approved: Correct import and error mapping implementation

The addition of the fmt import and the usage of errors.MapError(err) enhance the error handling by properly mapping and formatting errors.


46-54: Approved: Improved error handling in GetGenesisValidatorsRoot

The GetGenesisValidatorsRoot method now correctly maps errors and provides a descriptive error message when retrieval fails.


65-72: Approved: Improved error handling in GetSlot

The GetSlot method now correctly maps errors and provides a descriptive error message when retrieval fails.

mod/storage/pkg/beacondb/withdrawals.go (3)

23-28: Imports Add Necessary Packages

The addition of the fmt and errors packages is appropriate and necessary for the enhanced error handling implemented in the methods.


35-43: Improved Error Handling in GetNextWithdrawalIndex

The use of errors.MapError(err) and the detailed error message enhances the clarity and consistency of error handling in the GetNextWithdrawalIndex method.


64-72: Enhanced Error Handling in GetNextWithdrawalValidatorIndex

The introduction of errors.MapError(err) and the informative error message improves the robustness of the GetNextWithdrawalValidatorIndex method.

mod/storage/pkg/beacondb/slashing.go (3)

24-26: Addition of imports is appropriate

The added imports of "errors" and "fmt" are necessary for the updated error handling and formatting.


Line range hint 58-64: Consistent error handling in 'GetSlashingAtIndex'

The error handling in GetSlashingAtIndex is clear and returns zero when the slashing at the specified index is not found, which aligns with the PR objectives.


Line range hint 76-82: Consistent error handling in 'GetTotalSlashing'

The updated error handling in GetTotalSlashing appropriately returns zero when no total slashing is found, maintaining consistency across methods.

mod/storage/pkg/beacondb/eth1.go (2)

37-56: Well-structured error handling in GetLatestExecutionPayloadHeader

The revisions to the GetLatestExecutionPayloadHeader method improve error handling by utilizing the new getLatestExecutionPayloadVersion helper function. This enhances code readability and ensures consistent error messages across the codebase.


58-70: Effective use of helper function getLatestExecutionPayloadVersion

Introducing the getLatestExecutionPayloadVersion method encapsulates the logic for retrieving the latest execution payload version. This refactoring reduces code duplication and simplifies error handling, making the code more maintainable.

mod/storage/pkg/beacondb/registry.go (11)

24-25: Addition of necessary imports for error handling

The inclusion of the "fmt" and "github.com/berachain/beacon-kit/mod/storage/pkg/errors" packages is appropriate for the enhanced error handling implemented in the code.

Also applies to: 29-29


39-44: Improved error handling in AddValidator

The mapping of errors using errors.MapError(err) and the detailed error message improve the clarity and robustness of the AddValidator method.


62-67: Consistent error handling in AddValidatorBartio

Applying errors.MapError(err) and providing a descriptive error message enhances consistency and maintainability in error handling across methods.


101-107: Appropriate error formatting in ValidatorIndexByPubkey

Using %x to format the pubkey in the error message ensures that the public key is displayed correctly as a hexadecimal string, improving readability.


123-129: Correct error formatting in ValidatorIndexByCometBFTAddress

Formatting cometBFTAddress with %x in the error message appropriately represents the address in hexadecimal form, enhancing clarity.


142-151: Enhanced error handling in ValidatorByIndex

The addition of error mapping and a detailed error message provides better insight when retrieval by index fails, improving debugging efficiency.


162-167: Improved error handling in GetValidators

Mapping errors and providing descriptive error messages when peeking the next validator index and iterating over validators enhance the robustness of the method.

Also applies to: 176-181


228-233: Consistent error handling in GetValidatorsByEffectiveBalance

The method now consistently handles errors during iteration, and the enhancements improve maintainability and error reporting.

Also applies to: 242-242


258-266: Robust error handling in GetBalance

Mapping the error and providing a detailed message when retrieving a balance ensures that issues are clearly communicated.


287-292: Enhanced error reporting in GetBalances

The improved error handling during balance iteration aligns with the error handling strategy used in other methods, promoting consistency.


317-322: Refined error handling and encapsulation in GetTotalActiveBalances

The changes include:

  • Error mapping and descriptive messages enhance clarity when iterations fail.
  • Refactoring to use the GetSlot() method improves encapsulation and aligns with best practices.

These adjustments collectively improve the method's readability and maintainability.

Also applies to: 325-343

Comment on lines +49 to +55
err = errors.MapError(err)
if err != nil {
return common.Bytes32{}, err
return common.Bytes32{}, fmt.Errorf(
"failed retrieving randao mix at index %d: %w",
index,
err,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Improved error handling, but consider explicit ErrNotFound check

The changes improve error handling by using errors.MapError and providing a formatted error message. This aligns with the PR objectives to enhance error reporting.

However, to fully meet the PR objectives, consider explicitly checking for collections.ErrNotFound and returning beacondb.ErrNotFound. This would ensure that collections.ErrNotFound is never returned to clients, as specified in the PR summary.

Here's a suggested implementation:

bz, err := kv.randaoMix.Get(kv.ctx, index)
if errors.Is(err, collections.ErrNotFound) {
    return common.Bytes32{}, fmt.Errorf(
        "failed retrieving randao mix at index %d: %w",
        index,
        beacondb.ErrNotFound,
    )
} else if err != nil {
    return common.Bytes32{}, fmt.Errorf(
        "failed retrieving randao mix at index %d: %w",
        index,
        err,
    )
}
return common.Bytes32(bz), nil

This change would make the use of beacondb.ErrNotFound explicit and ensure that collections.ErrNotFound is never returned to clients.

Comment on lines +49 to +55
err = errors.MapError(err)
if err != nil {
return common.Root{}, err
return common.Root{}, fmt.Errorf(
"failed retrieving block root at index %d: %w",
index,
err,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM with a minor suggestion for consistency.

The error handling improvements in GetBlockRootAtIndex align well with the PR objectives. The use of errors.MapError likely handles the mapping to the new ErrNotFound type, and the error message now includes the index, providing more context.

For consistency with other error messages, consider updating the error message:

-			"failed retrieving block root at index %d: %w",
+			"failed to retrieve block root at index %d: %w",

This minor change would make the error messages more uniform across the file.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
err = errors.MapError(err)
if err != nil {
return common.Root{}, err
return common.Root{}, fmt.Errorf(
"failed retrieving block root at index %d: %w",
index,
err,
)
err = errors.MapError(err)
if err != nil {
return common.Root{}, fmt.Errorf(
"failed to retrieve block root at index %d: %w",
index,
err,
)

Comment on lines +107 to +113
err = errors.MapError(err)
if err != nil {
return common.Root{}, err
return common.Root{}, fmt.Errorf(
"failed retrieving state root at index %d: %w",
idx,
err,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM with minor suggestions for consistency and clarity.

The error handling improvements in StateRootAtIndex align well with the PR objectives. The use of errors.MapError likely handles the mapping to the new ErrNotFound type, and the error message now includes the index, providing more context.

For consistency with other error messages and to improve clarity, consider the following changes:

  1. Use "failed to retrieve" instead of "failed retrieving" for consistency.
  2. Use "index" instead of "idx" in the error message for clarity.

Apply this diff to implement these changes:

-			"failed retrieving state root at index %d: %w",
-			idx,
+			"failed to retrieve state root at index %d: %w",
+			index,

These changes will make the error messages more uniform and clear across the file.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
err = errors.MapError(err)
if err != nil {
return common.Root{}, err
return common.Root{}, fmt.Errorf(
"failed retrieving state root at index %d: %w",
idx,
err,
)
err = errors.MapError(err)
if err != nil {
return common.Root{}, fmt.Errorf(
"failed to retrieve state root at index %d: %w",
index,
err,
)

Comment on lines +77 to +85
h, err := kv.latestBlockHeader.Get(kv.ctx)
err = errors.MapError(err)
if err != nil {
return h, fmt.Errorf(
"failed retrieving latest block header: %w",
err,
)
}
return h, nil
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM with a minor suggestion for consistency.

The error handling improvements in GetLatestBlockHeader are well-aligned with the PR objectives. The use of errors.MapError likely handles the mapping to the new ErrNotFound type, and the error message is now more descriptive.

For consistency with the suggested changes in other methods, consider updating the error message:

-			"failed retrieving latest block header: %w",
+			"failed to retrieve latest block header: %w",

This minor change would make the error messages more uniform across the file.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
h, err := kv.latestBlockHeader.Get(kv.ctx)
err = errors.MapError(err)
if err != nil {
return h, fmt.Errorf(
"failed retrieving latest block header: %w",
err,
)
}
return h, nil
h, err := kv.latestBlockHeader.Get(kv.ctx)
err = errors.MapError(err)
if err != nil {
return h, fmt.Errorf(
"failed to retrieve latest block header: %w",
err,
)
}
return h, nil

Comment on lines 38 to 45
err = storageerr.MapError(err)
if err != nil {
return nil, err
return nil, fmt.Errorf(
"failed iterating slashings: %w",
err,
)
}

Copy link
Contributor

@coderabbitai coderabbitai bot Oct 15, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure the iterator is properly closed to prevent resource leaks

After obtaining the iterator from kv.slashings.Iterate, it should be closed after use to prevent potential resource leaks. It's recommended to add defer iter.Close() after checking for errors.

Apply this diff to close the iterator:

 func (kv *KVStore[
     BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT,
     ForkT, ValidatorT, ValidatorsT,
 ]) GetSlashings() ([]math.Gwei, error) {
     var slashings []math.Gwei
     iter, err := kv.slashings.Iterate(kv.ctx, nil)
     err = storageerr.MapError(err)
     if err != nil {
         return nil, fmt.Errorf(
             "failed iterating slashings: %w",
             err,
         )
     }
+    defer iter.Close()

     for iter.Valid() {
         var slashing uint64
         slashing, err = iter.Value()
         if err != nil {
             return nil, err
         }
         slashings = append(slashings, math.Gwei(slashing))
         iter.Next()
     }
     return slashings, nil
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
err = storageerr.MapError(err)
if err != nil {
return nil, err
return nil, fmt.Errorf(
"failed iterating slashings: %w",
err,
)
}
err = storageerr.MapError(err)
if err != nil {
return nil, fmt.Errorf(
"failed iterating slashings: %w",
err,
)
}
defer iter.Close()

🛠️ Refactor suggestion

Consider handling 'collections.ErrNotFound' to return an empty slice

In GetSlashings, if there are no slashing entries, kv.slashings.Iterate might return a collections.ErrNotFound error. To make the behavior consistent with GetSlashingAtIndex and GetTotalSlashing, consider checking for collections.ErrNotFound and returning an empty slice without an error.

Apply this diff:

 err = storageerr.MapError(err)
+if errors.Is(err, collections.ErrNotFound) {
+    return []math.Gwei{}, nil
+} else if err != nil {
     return nil, fmt.Errorf(
         "failed iterating slashings: %w",
         err,
     )
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
err = storageerr.MapError(err)
if err != nil {
return nil, err
return nil, fmt.Errorf(
"failed iterating slashings: %w",
err,
)
}
err = storageerr.MapError(err)
if errors.Is(err, collections.ErrNotFound) {
return []math.Gwei{}, nil
} else if err != nil {
return nil, fmt.Errorf(
"failed iterating slashings: %w",
err,
)
}

Copy link
Contributor

Choose a reason for hiding this comment

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

@abi87, great! Glad to hear that you'll address the iterator issue in PR #2077.

(^_^)


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Right! I will fix the iterator issue in #2077

Copy link
Contributor

Choose a reason for hiding this comment

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

@abi87, that's great! Looking forward to the fix in PR #2077.

(^_^)

Comment on lines +81 to +85
var (
ctx = kv.ctx
version = payloadHeader.Version()
)
if err := kv.latestExecutionPayloadVersion.Set(ctx, version); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify SetLatestExecutionPayloadHeader by removing unnecessary variable

The variable ctx is assigned kv.ctx but is used only once. You can simplify the code by using kv.ctx directly, eliminating the need for the extra variable.

Apply this diff to streamline the function:

 func (kv *KVStore[
     BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT,
     ForkT, ValidatorT, ValidatorsT,
 ]) SetLatestExecutionPayloadHeader(
     payloadHeader ExecutionPayloadHeaderT,
 ) error {
-    var (
-        ctx     = kv.ctx
-        version = payloadHeader.Version()
-    )
+    version := payloadHeader.Version()
-    if err := kv.latestExecutionPayloadVersion.Set(ctx, version); err != nil {
+    if err := kv.latestExecutionPayloadVersion.Set(kv.ctx, version); err != nil {
         return err
     }
     kv.latestExecutionPayloadCodec.SetActiveForkVersion(payloadHeader.Version())
     return kv.latestExecutionPayloadHeader.Set(kv.ctx, payloadHeader)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var (
ctx = kv.ctx
version = payloadHeader.Version()
)
if err := kv.latestExecutionPayloadVersion.Set(ctx, version); err != nil {
version := payloadHeader.Version()
if err := kv.latestExecutionPayloadVersion.Set(kv.ctx, version); err != nil {

Comment on lines +97 to +105
idx, err := kv.eth1DepositIndex.Get(kv.ctx)
err = errors.MapError(err)
if err != nil {
return 0, fmt.Errorf(
"failed retrieving eth1 deposit index %d, %w",
idx,
err,
)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid including uninitialized variables in error messages

In the GetEth1DepositIndex method, including idx in the error message before it's successfully retrieved could be misleading, as it may contain a default value (e.g., zero). For clarity, consider modifying the error message to exclude idx.

Apply this diff to adjust the error message:

     if err != nil {
-        return 0, fmt.Errorf(
-            "failed retrieving eth1 deposit index %d, %w",
-            idx,
-            err,
-        )
+        return 0, fmt.Errorf(
+            "failed retrieving eth1 deposit index: %w",
+            err,
+        )
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
idx, err := kv.eth1DepositIndex.Get(kv.ctx)
err = errors.MapError(err)
if err != nil {
return 0, fmt.Errorf(
"failed retrieving eth1 deposit index %d, %w",
idx,
err,
)
}
idx, err := kv.eth1DepositIndex.Get(kv.ctx)
err = errors.MapError(err)
if err != nil {
return 0, fmt.Errorf(
"failed retrieving eth1 deposit index: %w",
err,
)
}

)
}

kv.latestExecutionPayloadCodec.SetActiveForkVersion(v)
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

SetActiveForkVersion Does Not Validate Version Inputs

The SetActiveForkVersion method in mod/storage/pkg/encoding/ssz.go assigns the provided version directly without validating whether it is valid or supported. This lack of validation may lead to unexpected behavior if an invalid or unsupported version is set.

  • File: mod/storage/pkg/encoding/ssz.go
    • SetActiveForkVersion lacks error handling for invalid versions.
🔗 Analysis chain

Ensure SetActiveForkVersion handles invalid versions

When setting the active fork version with kv.latestExecutionPayloadCodec.SetActiveForkVersion(v), it's important to verify that invalid or unsupported versions are properly handled. Lack of validation may lead to unexpected behavior elsewhere in the code.

Run the following script to check the implementation of SetActiveForkVersion:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that SetActiveForkVersion handles invalid versions.

# Search for the SetActiveForkVersion method implementation and check for error handling.
rg --type go 'func\s+\([^)]+\)\s+SetActiveForkVersion\s*\(' -A 15

# Review the implementation to ensure it includes validation logic.

Length of output: 1081

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 comments (1)
mod/state-transition/pkg/core/state/statedb.go (1)

Line range hint 1-424: Consider reviewing other methods for error handling improvements

While the changes in UpdateSlashingAtIndex align with the PR objectives, it might be beneficial to review other methods in this file (e.g., IncreaseBalance, DecreaseBalance, ExpectedWithdrawals) for potential error handling improvements. This would ensure consistency across the entire StateDB struct and further enhance the robustness of the code.

For instance, methods that interact with storage (like GetBalance in IncreaseBalance and DecreaseBalance) might benefit from similar error handling patterns introduced in UpdateSlashingAtIndex.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between fbd9772 and 3e88d11.

⛔ Files ignored due to path filters (1)
  • mod/state-transition/go.sum is excluded by !**/*.sum
📒 Files selected for processing (3)
  • mod/state-transition/go.mod (4 hunks)
  • mod/state-transition/pkg/core/state/statedb.go (2 hunks)
  • mod/storage/pkg/beacondb/slashing.go (4 hunks)
🧰 Additional context used
🔇 Additional comments (9)
mod/state-transition/go.mod (3)

12-12: LGTM: Updated errors module version.

The update to github.com/berachain/beacon-kit/mod/errors aligns with the PR objectives of improving error handling. This change likely introduces the new beacondb.ErrNotFound error type mentioned in the PR summary.


22-23: LGTM: New indirect dependencies added.

The addition of new indirect dependencies, including cosmossdk.io/collections, cosmossdk.io/core, and github.com/google/go-cmp, appears to support the new error handling mechanisms and integration with Cosmos SDK. The specific versions used contribute to build stability.

Also applies to: 56-56


28-28: LGTM: Updated chain-spec module version.

The update to github.com/berachain/beacon-kit/mod/chain-spec is likely related to changes supporting the new error handling mechanisms. The minor version change suggests incremental improvements that align with the PR objectives.

mod/state-transition/pkg/core/state/statedb.go (1)

27-27: LGTM: New import for improved error handling

The addition of the storageerrors import aligns with the PR objective of improving error handling for storage-related operations. This change will allow for more specific error handling in the StateDB methods.

mod/storage/pkg/beacondb/slashing.go (5)

24-27: Appropriate import additions

The inclusion of "fmt" and "github.com/berachain/beacon-kit/mod/storage/pkg/errors" is necessary and appropriate for the enhanced error handling implemented in the code.


36-41: Ensure the iterator is properly closed to prevent resource leaks

As previously mentioned, after obtaining the iterator from kv.slashings.Iterate, it should be closed after use to prevent potential resource leaks. Consider adding defer iter.Close() after checking for errors.


36-41: Consider handling 'beacondb.ErrNotFound' to return an empty slice

If there are no slashing entries, kv.slashings.Iterate might return a beacondb.ErrNotFound error. To maintain consistency with other methods and enhance client experience, consider checking for this error and returning an empty slice without an error.


Line range hint 64-69: Proper error mapping and handling in GetSlashingAtIndex

The use of errors.MapError(err) followed by returning the error directly ensures that specific errors like beacondb.ErrNotFound are properly propagated to the clients. This aligns with the PR objectives to improve error uniformity and clarity.


Line range hint 88-93: Consistent error handling in GetTotalSlashing

The addition of errors.MapError(err) and the unified error handling approach enhance the method's reliability. Propagating mapped errors directly allows clients to receive more informative error messages, fulfilling the PR's intent.

github.com/berachain/beacon-kit/mod/primitives v0.0.0-20240911165923-82f71ec86570
github.com/berachain/beacon-kit/mod/storage v0.0.0-00010101000000-000000000000
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update the placeholder version for the storage module.

The github.com/berachain/beacon-kit/mod/storage module is added with a placeholder version (v0.0.0-00010101000000-000000000000). This is likely due to the local replacement directive. Before merging, ensure that this is replaced with a proper version or commit hash to maintain reproducible builds.

mod/state-transition/go.mod 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: 8

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 3e88d11 and db3bee6.

📒 Files selected for processing (4)
  • mod/storage/pkg/beacondb/registry.go (14 hunks)
  • mod/storage/pkg/beacondb/slashing.go (4 hunks)
  • mod/storage/pkg/block/store.go (4 hunks)
  • mod/storage/pkg/block/store_test.go (3 hunks)
🧰 Additional context used
🔇 Additional comments (8)
mod/storage/pkg/block/store.go (1)

30-30: LGTM: New import added for error handling.

The addition of the errors package import is necessary and aligns with the changes made in the file.

mod/storage/pkg/beacondb/slashing.go (2)

67-68: Consistent error handling in GetSlashingAtIndex

The error mapping using errors.MapError(err) and subsequent checks align with the updated error handling strategy.


91-92: Consistent error mapping in GetTotalSlashing

The use of errors.MapError(err) ensures uniform error processing across the codebase.

mod/storage/pkg/beacondb/registry.go (5)

42-45: Clarify error message in AddValidator

Consider rephrasing the error message for better clarity, as previously suggested.


66-68: Clarify error message in AddValidatorBartio

Consider rephrasing the error message for consistency and clarity, similar to prior feedback.


104-108: Proper formatting of pubkey in error messages

Good job updating the error message to use %x for pubkey, ensuring correct hexadecimal representation.


126-130: Proper formatting of cometBFTAddress in error messages

Well done on changing the format specifier to %x for cometBFTAddress, providing accurate hexadecimal output.


324-324: Clarify error message when retrieving slot

The previous suggestion to specify the failure in retrieving the slot value remains applicable.

@@ -39,15 +40,15 @@ func (m MockBeaconBlock) GetSlot() math.Slot {
}

func (m MockBeaconBlock) HashTreeRoot() common.Root {
return [32]byte{byte(m.slot)}
return common.Root{byte(m.slot)}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider full initialization of common.Root

While the change to common.Root improves type safety, consider initializing it with a full 32-byte array for completeness and to avoid potential issues with uninitialized bytes.

Consider updating the return statement as follows:

return common.Root{byte(m.slot), 0, 0, /* ... */ 0}

This ensures all 32 bytes of the common.Root are explicitly initialized.

}

func (m MockBeaconBlock) GetTimestamp() math.U64 {
return m.slot
}

func (m MockBeaconBlock) GetStateRoot() common.Root {
return [32]byte{byte(m.slot)}
return common.Root{byte(m.slot)}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider full initialization of common.Root

Similar to the HashTreeRoot method, consider initializing the common.Root with a full 32-byte array for completeness and to avoid potential issues with uninitialized bytes.

Consider updating the return statement as follows:

return common.Root{byte(m.slot), 0, 0, /* ... */ 0}

This ensures all 32 bytes of the common.Root are explicitly initialized.

@@ -27,6 +27,7 @@
"github.com/berachain/beacon-kit/mod/primitives/pkg/common"
"github.com/berachain/beacon-kit/mod/primitives/pkg/math"
"github.com/berachain/beacon-kit/mod/storage/pkg/block"
"github.com/berachain/beacon-kit/mod/storage/pkg/errors"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update import to use beacondb package

To align with the PR's objective of introducing beacondb.ErrNotFound, please update the import statement to use the beacondb package instead of the errors package.

Apply this diff to make the necessary change:

-	"github.com/berachain/beacon-kit/mod/storage/pkg/errors"
+	"github.com/berachain/beacon-kit/mod/storage/pkg/beacondb"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"github.com/berachain/beacon-kit/mod/storage/pkg/errors"
"github.com/berachain/beacon-kit/mod/storage/pkg/beacondb"

Comment on lines +85 to +90
_, err = blockStore.GetSlotByBlockRoot(common.Root{byte(8)})
require.ErrorIs(t, err, errors.ErrNotFound)
_, err = blockStore.GetParentSlotByTimestamp(2)
require.ErrorContains(t, err, "not found")
require.ErrorIs(t, err, errors.ErrNotFound)
_, err = blockStore.GetSlotByStateRoot(common.Root{byte(8)})
require.ErrorIs(t, err, errors.ErrNotFound)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use beacondb.ErrNotFound for consistency

To align with the PR's objective of introducing beacondb.ErrNotFound, please update the error checks to use beacondb.ErrNotFound instead of errors.ErrNotFound. This ensures consistent error handling across the codebase.

Apply this diff to make the necessary changes:

-	require.ErrorIs(t, err, errors.ErrNotFound)
+	require.ErrorIs(t, err, beacondb.ErrNotFound)
-	require.ErrorIs(t, err, errors.ErrNotFound)
+	require.ErrorIs(t, err, beacondb.ErrNotFound)
-	require.ErrorIs(t, err, errors.ErrNotFound)
+	require.ErrorIs(t, err, beacondb.ErrNotFound)

Remember to update the import statement as suggested in the previous comment.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
_, err = blockStore.GetSlotByBlockRoot(common.Root{byte(8)})
require.ErrorIs(t, err, errors.ErrNotFound)
_, err = blockStore.GetParentSlotByTimestamp(2)
require.ErrorContains(t, err, "not found")
require.ErrorIs(t, err, errors.ErrNotFound)
_, err = blockStore.GetSlotByStateRoot(common.Root{byte(8)})
require.ErrorIs(t, err, errors.ErrNotFound)
_, err = blockStore.GetSlotByBlockRoot(common.Root{byte(8)})
require.ErrorIs(t, err, beacondb.ErrNotFound)
_, err = blockStore.GetParentSlotByTimestamp(2)
require.ErrorIs(t, err, beacondb.ErrNotFound)
_, err = blockStore.GetSlotByStateRoot(common.Root{byte(8)})
require.ErrorIs(t, err, beacondb.ErrNotFound)

Comment on lines +94 to +98
return 0, fmt.Errorf(
"%w, block root: %s",
errors.ErrNotFound,
blockRoot,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM: Error handling improved with more context.

The changes align with the PR objective by using the new errors.ErrNotFound error type. The error message now includes the block root, providing more context for debugging.

Consider using a constant for the error message format to improve maintainability:

const errMsgBlockRootNotFound = "%w, block root: %s"

return 0, fmt.Errorf(errMsgBlockRootNotFound, errors.ErrNotFound, blockRoot)

Comment on lines +110 to +114
return 0, fmt.Errorf(
"%w, timestamp: %d",
errors.ErrNotFound,
timestamp,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM: Error handling improved with more context.

The changes align with the PR objective by using the new errors.ErrNotFound error type. The error message now includes the timestamp, providing more context for debugging. The use of stderrors.New for the genesis slot error is appropriate.

Consider using constants for the error message formats to improve maintainability:

const (
    errMsgTimestampNotFound = "%w, timestamp: %d"
    errMsgGenesisSlotParent = "parent slot not supported for genesis slot 0"
)

// In the first error case
return 0, fmt.Errorf(errMsgTimestampNotFound, errors.ErrNotFound, timestamp)

// In the genesis slot case
return slot, stderrors.New(errMsgGenesisSlotParent)

Also applies to: 117-117

Comment on lines +129 to +133
return 0, fmt.Errorf(
"%w, state root: %s",
errors.ErrNotFound,
stateRoot,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM: Error handling improved with more context.

The changes align with the PR objective by using the new errors.ErrNotFound error type. The error message now includes the state root, providing more context for debugging.

Consider using a constant for the error message format to improve maintainability:

const errMsgStateRootNotFound = "%w, state root: %s"

return 0, fmt.Errorf(errMsgStateRootNotFound, errors.ErrNotFound, stateRoot)

Comment on lines +37 to +45
err = errors.MapError(err)
if err != nil {
return nil, err
return nil, fmt.Errorf(
"failed iterating slashings: %w",
err,
)
}
defer func() {
err = errors.Join(err, iter.Close())
err = stderrors.Join(err, iter.Close())
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure err is a named return value to capture deferred errors properly

In the GetSlashings function, the deferred function modifies err to include any error from iter.Close(). However, since err is not a named return parameter, this modification will not affect the returned error value. To ensure that any error from iter.Close() is correctly returned, err should be a named return parameter.

Apply this diff to modify the function signature:

-func (kv *KVStore[
+func (kv *KVStore[
     BeaconBlockHeaderT, Eth1DataT, ExecutionPayloadHeaderT,
     ForkT, ValidatorT, ValidatorsT,
-]) GetSlashings() ([]math.Gwei, error) {
+]) GetSlashings() (slashings []math.Gwei, err error) {
     var slashings []math.Gwei
     iter, err := kv.slashings.Iterate(kv.ctx, nil)
     err = errors.MapError(err)
     if err != nil {
         return nil, fmt.Errorf(
             "failed iterating slashings: %w",
             err,
         )
     }
     defer func() {
         err = stderrors.Join(err, iter.Close())
     }()
     // rest of the code remains unchanged
 }

Committable suggestion was skipped due to low confidence.

@abi87 abi87 added DO NOT MERGE just don't merge it (just yet) and removed Ready for Review labels Nov 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DO NOT MERGE just don't merge it (just yet)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants