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

refactor: remove defer in loop #20223

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

Conversation

tropicaldog
Copy link
Contributor

@tropicaldog tropicaldog commented Apr 30, 2024

Description

Remove all occurrences of defer in loop

In Go, defers are only invoked in a terminal statement such as a return or panic;
invoking them in a for-loop means that all those resources will not be released
and will build up until the entire function returns or panics

https://stackoverflow.com/questions/45617758/proper-way-to-release-resources-with-defer-in-a-loop


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced error handling by encapsulating resource closure operations within a closure to improve error reporting and resource management in the Load method of the Store struct.
    • Added error handling for gas consumption during voting on a proposal in the SubmitProposal function of the Keeper struct in msg_server.go.
    • Introduced error handling for the importer.Close() method call in store/v2/commitment/store.go.
    • Refactored the writeChangeset method in store/v2/migration/manager.go to ensure immediate defer execution on return for proper resource handling.

@tropicaldog tropicaldog requested a review from a team as a code owner April 30, 2024 17:18
Copy link
Contributor

coderabbitai bot commented Apr 30, 2024

Walkthrough

Walkthrough

The recent changes across the codebase focus on refining error handling and resource management practices. By utilizing closures and optimizing resource closure strategies, these updates enhance error reporting, streamline resource cleanup, and improve the overall code reliability. These adjustments aim to enhance control flow, aligning with best practices in software development.

Changes

File Path Change Summary
store/commitment/store.go Modified importer.Close() within loops for direct error handling, removed defer, and added explicit error checks.
store/migration/manager.go
store/snapshots/store.go
store/storage/storage_test_suite.go
Refactored resource closure by eliminating defer statements and incorporating explicit calls with improved error handling.
tests/integration/auth/client/cli/suite_test.go
x/group/keeper/invariants.go
Adjusted resource closure to occur before critical operations explicitly, ensuring effective error handling and resource management.

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

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

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

CodeRabbit Configration File (.coderabbit.yaml)

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

Documentation and Community

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

@tropicaldog tropicaldog changed the title perf: refactor defer in loop perf: remove defer in loop Apr 30, 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: 6

store/storage/storage_test_suite.go Outdated Show resolved Hide resolved
x/group/keeper/invariants.go Outdated Show resolved Hide resolved
Comment on lines 120 to 123
err = memIt.Close()
if err != nil {
return "", broken
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling when closing the memIt iterator.

-		err = memIt.Close()
-		if err != nil {
-			return "", broken
-		}
+		if err := memIt.Close(); err != nil {
+			return fmt.Sprintf("failed to close member iterator: %v", err), true
+		}

This change ensures that any error during the closing of the memIt iterator is properly handled and reported, which aligns with the PR's objective of improving error handling in resource management.


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.

Suggested change
err = memIt.Close()
if err != nil {
return "", broken
}
if err := memIt.Close(); err != nil {
return fmt.Sprintf("failed to close member iterator: %v", err), true
}

store/migration/manager.go Outdated Show resolved Hide resolved
store/commitment/store.go Outdated Show resolved Hide resolved
store/commitment/store.go Outdated Show resolved Hide resolved
tropicaldog and others added 5 commits May 1, 2024 00:26
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Member

@tac0turtle tac0turtle left a comment

Choose a reason for hiding this comment

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

Hey if things are viewed as performance it would be good to get a benchmark. Thank you for the many prs you are making.

@tropicaldog tropicaldog changed the title perf: remove defer in loop refactor: remove defer in loop May 1, 2024
@tropicaldog
Copy link
Contributor Author

Thanks for your review! @tac0turtle
This PR focuses on refactoring to ensure proper resource handling with defer in loops. Given the nature of the change, benchmarks may not show the benefits, it's more avoiding resource buildup.

I'll update the PR title from perf to refactor to better reflect the purpose.

Please let me know if you have any other suggestions or concerns. I appreciate your feedback and support!

Copy link
Collaborator

@odeke-em odeke-em left a comment

Choose a reason for hiding this comment

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

Thank you for these fixes @tropicaldog! I've added some suggestions for correctness by using anonymous closures because the current changes make the resource releases less likely due to the large number of branches.

Also you could please update the commit description to say

In Go, defers are only invoked in a terminal statement such as a return or panic;
invoking them in a for-loop means that all those resources will not be released
and will build up until the entire function returns or panics

Comment on lines 137 to 146
defer batch.Close()

if err := batch.Set(csKey, csBytes); err != nil {
return fmt.Errorf("failed to write changeset to db.Batch: %w", err)
}
if err := batch.Write(); err != nil {
return fmt.Errorf("failed to write changeset to db: %w", err)
}
if err := batch.Close(); err != nil {
return fmt.Errorf("failed to close batch: %w", err)
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

The problem with the current change is that if batch.Set or batch.Write fail, then batch.Close() will now not be invoked. I do understand the importance of removing defers in the loop to avoid lingering resources that won't be cleaned up until a panic or a return, but the better fix for this would be making an anonymous closure so

// Invoking this code in a closure so that defer is called immediately on return
// yet not in the for-loop which can leave resource lingering.
err := func() error {
     defer batch.Close()

     if err := batch.Set(csKey, csBytes); err != nil {
	return fmt.Errorf("failed to write changeset to db.Batch: %w", err)
     }
     if err := batch.Write(); err != nil {
	return fmt.Errorf("failed to write changeset to db: %w", err)
     }
}()

if err != nil {
    return err
}

store/snapshots/store.go Show resolved Hide resolved
@@ -76,7 +76,6 @@ func GroupTotalWeightInvariantHelper(ctx sdk.Context, storeService storetypes.KV
msg += fmt.Sprintf("error while returning group member iterator for group with ID %d\n%v\n", groupInfo.Id, err)
return msg, broken
}
defer memIt.Close()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Your change to move it down below creates an even less likely chance that memIt.Close() due to the large number of branches that could return before it is invoked. You could apply that anonymous closure trick that I showed up above.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Much appreciated @odeke-em for your insightful review. I have refactored the code, could you kindly take a look. Thank you!

@tropicaldog tropicaldog requested a review from odeke-em May 1, 2024 14:03
store/snapshots/store.go Show resolved Hide resolved
store/commitment/store.go Outdated Show resolved Hide resolved
store/commitment/store.go Outdated Show resolved Hide resolved
Copy link
Collaborator

@odeke-em odeke-em left a comment

Choose a reason for hiding this comment

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

Almost there, thank you @tropicaldog! Just ensure that you whenever you make a closure; that you hoist all the code within the control flow so as to keep it logically the same.

store/snapshots/store.go Outdated Show resolved Hide resolved
store/snapshots/store.go Outdated Show resolved Hide resolved
@tropicaldog tropicaldog requested a review from odeke-em May 1, 2024 15:42
store/snapshots/store.go Outdated Show resolved Hide resolved
@tropicaldog tropicaldog requested a review from odeke-em May 2, 2024 01:44
Copy link
Collaborator

@odeke-em odeke-em left a comment

Choose a reason for hiding this comment

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

LGTM now, thank you @tropicaldog!

@odeke-em odeke-em requested a review from tac0turtle May 2, 2024 01:47
Copy link
Contributor

@alpe alpe left a comment

Choose a reason for hiding this comment

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

Nice updates and good use of closures 💪

var groupMember group.GroupMember
_, err = memIt.LoadNext(&groupMember)
if errors.ErrORMIteratorDone.Is(err) {
break
Copy link
Contributor

Choose a reason for hiding this comment

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

personal preference: break is good and does the job but you can also do return nil here already to exit early. There is nothing going on after the loop and a return would make it slightly more readable.

@tac0turtle
Copy link
Member

@tropicaldog could you rebase, we added store/v1 back to main so the files changed

tropicaldog and others added 10 commits May 9, 2024 21:28
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between b6a63be and 8701127.
Files selected for processing (2)
  • store/snapshots/store.go (2 hunks)
  • store/v2/commitment/store.go (1 hunks)
Additional Context Used
Path-based Instructions (2)
store/snapshots/store.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

store/v2/commitment/store.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

Additional comments not posted (3)
store/snapshots/store.go (2)

143-143: Ensure proper error handling and resource management in the goroutine.


154-163: Refactoring to remove defer inside the loop is correctly implemented.

Verification successful

Refactoring to remove defer inside the loop in the Load function appears to be correctly integrated and functioning as expected based on the test cases provided in store/snapshots/store_test.go. The error handling is consistently checked, ensuring that no errors occur during the operations, which aligns with the intended behavior post-refactoring.

  • store/snapshots/store_test.go: Various test cases check for errors after calling Load, confirming that the function handles errors as expected.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the integration of the `Load` function with other parts of the system.

# Test: Search for usages of the `Load` function. Expect: Correct handling of the returned error and channel.
rg --type go $'Load\('

Length of output: 3061



Script:

#!/bin/bash
# Description: Verify the error handling and resource management in the refactored `Load` function.

# Test: Search for error handling patterns in the files where `Load` is used, focusing on the `store/snapshots/store.go` and related test files.
rg --type go -C 5 'if err := store.Load' store/snapshots/store.go store/snapshots/store_test.go

Length of output: 97



Script:

#!/bin/bash
# Description: Broaden the search for error handling and resource management patterns around the `Load` function.

# Test: Search for general patterns of error handling and resource management in the files where `Load` is used, focusing on the `store/snapshots/store.go` and related test files.
rg --type go -C 5 'err.*store.Load' store/snapshots/store.go store/snapshots/store_test.go

Length of output: 3089

store/v2/commitment/store.go (1)

402-404: Ensure proper resource management by directly handling the Close operation.

Verification successful

The review of the direct handling of the Close() operation in the store/v2/commitment/store.go file has been verified against the broader codebase. The findings confirm that both direct and deferred Close() operations are used throughout the codebase, depending on the context and specific requirements for resource management. The direct handling in the provided snippet is consistent with a deliberate approach to ensure timely resource release, which is crucial in scenarios where resource locks or file handles need to be explicitly controlled.

  • The direct Close() in store/v2/commitment/store.go is appropriate for the context and aligns with practices observed in other critical parts of the codebase.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify proper resource management by directly handling the `Close` operation.

# Test: Search for direct `Close` calls in the codebase. Expect: Proper resource management.
rg --type go $'Close\('

Length of output: 41062

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 8701127 and 0415482.
Files selected for processing (1)
  • store/snapshots/store.go (3 hunks)
Files skipped from review as they are similar to previous changes (1)
  • store/snapshots/store.go

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 0415482 and a737df0.
Files selected for processing (1)
  • x/group/keeper/msg_server.go (1 hunks)
Additional Context Used
Path-based Instructions (1)
x/group/keeper/msg_server.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

Comment on lines 634 to 637
err = k.GasService.GasMeter(ctx).Consume(gasCostPerIteration, "vote on proposal")
if err != nil {
return &group.MsgSubmitProposalResponse{ProposalId: id}, errorsmod.Wrap(err, "the proposal was created but failed on gas consumption for vote")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider optimizing gas consumption handling.

The current implementation consumes gas for each vote within the loop. This could lead to high gas costs if there are many proposers. Consider batching these operations or implementing a more efficient gas management strategy to optimize resource usage.

@tac0turtle tac0turtle enabled auto-merge May 15, 2024 10:38
auto-merge was automatically disabled May 17, 2024 15:35

Head branch was pushed to by a user without write access

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between a737df0 and 076a43f.
Files selected for processing (2)
  • store/v2/commitment/store.go (1 hunks)
  • store/v2/migration/manager.go (1 hunks)
Additional Context Used
Path-based Instructions (2)
store/v2/migration/manager.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

store/v2/commitment/store.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

Additional comments not posted (2)
store/v2/migration/manager.go (1)

184-198: Refactored writeChangeset to use a closure for defer ensures immediate resource release, aligning with best practices.

store/v2/commitment/store.go (1)

414-416: Properly handling the error on importer.Close() enhances robustness in resource management.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review Details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 076a43f and 101706b.
Files selected for processing (1)
  • x/group/keeper/invariants.go (2 hunks)
Files skipped from review due to trivial changes (1)
  • x/group/keeper/invariants.go

@tropicaldog
Copy link
Contributor Author

@tac0turtle Hi could you re-review, I've fixed the conflicts with main.

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

Successfully merging this pull request may close these issues.

None yet

4 participants