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

handle badger iterator panics on app stop #1355

Merged

Conversation

requilence
Copy link
Contributor

No description provided.

Copy link

coderabbitai bot commented Jul 1, 2024

Walkthrough

The recent changes improve error handling in the BadgerDB usage within the localstore and persistentqueue packages. Specifically, the modifications ensure that any panics during database iterations are caught, logged, and turned into errors. This enhances the robustness and reliability of the code by preventing crashes and providing more informative error messages.

Changes

Files Change Summary
pkg/.../badger_helpers.go Added defer and recover to handle panics in iterateKeysByPrefixBatchedTx and iterateKeysByPrefixTx functions.
pkg/.../queries.go Added panic handling via defer and recover in queryRaw method of dsObjectStore.
pkg/.../stores.go Added panic handling with defer and log in GetKeys function.
util/persistentqueue/storage.go Enhanced List method of badgerStorage to handle panics with defer and recover.

In fields of code, where bytes do dance,
A bug or panic took its chance.
With deft new lines and cautious care,
We caught those errors in our snare.
Now our store stands strong and true,
Through errors, we resiliently grew.
🐇💻✨


Tip

Early access features: enabled

We are currently testing the following features in early access:

  • OpenAI gpt-4o model for code reviews and chat: OpenAI claims that this model is better at understanding and generating code than the previous models. We seek your feedback over the next few weeks before making it generally available.

Note:

  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.
  • Please join our Discord Community to provide feedback and report issues.
  • OSS projects are currently opted into early access features by default.

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

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (invoked as PR comments)

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

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

CodeRabbit Configration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

github-actions bot commented Jul 1, 2024

New Coverage 46.5% of statements
Patch Coverage 62.2% of changed statements (23/37)

Coverage provided by https://github.com/seriousben/go-patch-cover-action

Copy link

@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 UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2ec25c7 and be310e8.

Files selected for processing (4)
  • pkg/lib/localstore/objectstore/badger_helpers.go (6 hunks)
  • pkg/lib/localstore/objectstore/queries.go (1 hunks)
  • pkg/lib/localstore/stores.go (1 hunks)
  • util/persistentqueue/storage.go (1 hunks)
Additional context used
golangci-lint
pkg/lib/localstore/objectstore/queries.go

[error] 39-39: composites: github.com/anyproto/anytype-heart/pkg/lib/database.FilterAllIn struct literal uses unkeyed fields

(govet)

Additional comments not posted (5)
util/persistentqueue/storage.go (1)

37-42: LGTM!

The deferred function to handle panics during iteration is correctly placed and will help in catching and reporting panics.

pkg/lib/localstore/objectstore/badger_helpers.go (2)

40-45: LGTM!

The deferred function to handle panics during iteration is correctly placed and will help in catching and reporting panics.


81-86: LGTM!

The deferred function to handle panics during iteration is correctly placed and will help in catching and reporting panics.

pkg/lib/localstore/stores.go (1)

241-245: LGTM!

The deferred function to handle panics during iteration is correctly placed and will help in catching and reporting panics.

pkg/lib/localstore/objectstore/queries.go (1)

96-104: LGTM!

The deferred function to handle panics during iteration is correctly placed and will help in catching and reporting panics.

)

err := s.db.View(func(txn *badger.Txn) error {
defer func() {
Copy link

Choose a reason for hiding this comment

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

Use keyed fields in struct literals.

The github.com/anyproto/anytype-heart/pkg/lib/database.FilterAllIn struct literal uses unkeyed fields. This can lead to maintainability issues.

- optionFilter := database.FilterAllIn{relationKey, listValue.GetListValue()}
+ optionFilter := database.FilterAllIn{
+	Key: relationKey,
+	Value: listValue.GetListValue(),
+}
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
defer func() {
defer func() {
optionFilter := database.FilterAllIn{
Key: relationKey,
Value: listValue.GetListValue(),
}

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2ec25c7 and be310e8.

Files selected for processing (4)
  • pkg/lib/localstore/objectstore/badger_helpers.go (6 hunks)
  • pkg/lib/localstore/objectstore/queries.go (1 hunks)
  • pkg/lib/localstore/stores.go (1 hunks)
  • util/persistentqueue/storage.go (1 hunks)
Additional context used
golangci-lint
pkg/lib/localstore/objectstore/queries.go

[error] 39-39: composites: github.com/anyproto/anytype-heart/pkg/lib/database.FilterAllIn struct literal uses unkeyed fields

(govet)

Additional comments not posted (5)
util/persistentqueue/storage.go (1)

37-42: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all calls to List handle the potential error correctly.

pkg/lib/localstore/objectstore/badger_helpers.go (2)

40-45: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all calls to iterateKeysByPrefixBatchedTx handle the potential error correctly.

Verification successful

Proper Error Handling Verified

The runFullTextIndexer function correctly handles the error returned by BatchProcessFullTextQueue by logging the error and returning early if an error occurs. This ensures that any issues encountered during the batch processing of full-text queues are appropriately managed.

  • Location: core/indexer/fulltext.go, lines 102-105
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `iterateKeysByPrefixBatchedTx` handle the potential error correctly.

# Test: Search for the function usage. Expect: Proper error handling in all occurrences.
rg --type go $'iterateKeysByPrefixBatchedTx'

Length of output: 249



Script:

#!/bin/bash
# Description: Inspect error handling at the call site of `iterateKeysByPrefixBatchedTx` within `pkg/lib/localstore/objectstore/badger_helpers.go`.

# Extract the lines around the call to `iterateKeysByPrefixBatchedTx` to inspect error handling.
rg --type go -C 5 'iterateKeysByPrefixBatchedTx' pkg/lib/localstore/objectstore/badger_helpers.go

Length of output: 440



Script:

#!/bin/bash
# Description: Search for the function that calls the outer function which calls `iterateKeysByPrefixBatchedTx` and inspect how its error is handled.

# Search for the function that calls the outer function within the same file.
rg --type go -C 5 'db.View' pkg/lib/localstore/objectstore/badger_helpers.go

Length of output: 602



Script:

#!/bin/bash
# Description: Search for the function that calls `iterateKeysByPrefixBatched` and inspect how its error is handled.

# Search for the function that calls `iterateKeysByPrefixBatched` within the codebase.
rg --type go -C 5 'iterateKeysByPrefixBatched' 

Length of output: 2603



Script:

#!/bin/bash
# Description: Search for the function that calls `BatchProcessFullTextQueue` and inspect how its error is handled.

# Search for the function that calls `BatchProcessFullTextQueue` within the codebase.
rg --type go -C 5 'BatchProcessFullTextQueue' 

Length of output: 11162



Script:

#!/bin/bash
# Description: Extract the lines around the call to `BatchProcessFullTextQueue` in `core/indexer/fulltext.go` to inspect how the error `err` is handled.

# Extract the lines around the call to `BatchProcessFullTextQueue`.
rg --type go -C 10 'BatchProcessFullTextQueue' core/indexer/fulltext.go

Length of output: 768



Script:

#!/bin/bash
# Description: Extract the complete `runFullTextIndexer` function from `core/indexer/fulltext.go` to inspect how the error `err` is handled.

# Extract the complete `runFullTextIndexer` function.
ast-grep --lang go --pattern $'func (i *indexer) runFullTextIndexer(ctx context.Context) {
  $$$
}' core/indexer/fulltext.go

Length of output: 2437


81-86: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all calls to iterateKeysByPrefixTx handle the potential error correctly.

Verification successful

Function usage verified and no issues found.

The calls to iterateKeysByPrefixTx in the codebase handle the potential error correctly.

  • pkg/lib/localstore/objectstore/objects.go: The error is returned directly after the function call.
  • pkg/lib/localstore/objectstore/delete.go: The error is checked immediately after the function call and handled within an if statement.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `iterateKeysByPrefixTx` handle the potential error correctly.

# Test: Search for the function usage. Expect: Proper error handling in all occurrences.
rg --type go $'iterateKeysByPrefixTx'

Length of output: 505



Script:

#!/bin/bash
# Description: Inspect the code surrounding the calls to `iterateKeysByPrefixTx` in objects.go and delete.go

# Check the surrounding code in objects.go
echo "Checking objects.go:"
rg --context 5 'iterateKeysByPrefixTx' pkg/lib/localstore/objectstore/objects.go

# Check the surrounding code in delete.go
echo "Checking delete.go:"
rg --context 5 'iterateKeysByPrefixTx' pkg/lib/localstore/objectstore/delete.go

Length of output: 954

pkg/lib/localstore/stores.go (1)

241-245: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all calls to GetKeys handle the potential error correctly.

pkg/lib/localstore/objectstore/queries.go (1)

96-104: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all calls to queryRaw handle the potential error correctly.

Verification successful

Verification successful.

The errors from queryRaw are correctly handled in all instances.

  • getObjectsWithObjectInRelation error is logged.
  • QueryRaw errors are wrapped and returned in all instances.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `queryRaw` handle the potential error correctly.

# Test: Search for the function usage. Expect: Proper error handling in all occurrences.
rg --type go $'queryRaw'

Length of output: 420



Script:

#!/bin/bash
# Extract context around the lines where `queryRaw` is called to verify error handling.

# Extract 5 lines before and after the return statements involving `queryRaw`.
rg --type go -C 5 $'return s.queryRaw' pkg/lib/localstore/objectstore/queries.go

Length of output: 1203



Script:

#!/bin/bash
# Search for the usage of `getObjectsWithObjectInRelation` and `QueryRaw` to verify error handling.

# Search for `getObjectsWithObjectInRelation` usage
rg --type go $'getObjectsWithObjectInRelation'

# Search for `QueryRaw` usage
rg --type go $'QueryRaw'

Length of output: 6218



Script:

#!/bin/bash
# Extract context around the lines where `getObjectsWithObjectInRelation` and `QueryRaw` are called to verify error handling.

# Extract 5 lines before and after the `getObjectsWithObjectInRelation` call.
rg --type go -C 5 $'getObjectsWithObjectInRelation' pkg/lib/localstore/objectstore/queries.go

# Extract 5 lines before and after the `QueryRaw` calls in various files.
rg --type go -C 5 $'QueryRaw' pkg/lib/database/filter.go
rg --type go -C 5 $'QueryRaw' core/subscription/service.go
rg --type go -C 5 $'QueryRaw' core/kanban/group_tag.go

Length of output: 2413

Copy link

@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: 5

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2ec25c7 and be310e8.

Files selected for processing (4)
  • pkg/lib/localstore/objectstore/badger_helpers.go (6 hunks)
  • pkg/lib/localstore/objectstore/queries.go (1 hunks)
  • pkg/lib/localstore/stores.go (1 hunks)
  • util/persistentqueue/storage.go (1 hunks)

Comment on lines +37 to +42
var err error
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("badger iterator panic: %v", r)
}
}()
Copy link

Choose a reason for hiding this comment

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

Ensure err is returned if a panic occurs.

The defer function correctly captures and wraps the panic in an error message, but the err variable should be returned if a panic is detected.

	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("badger iterator panic: %v", r)
+			return
		}
	}()

Committable suggestion was skipped due to low confidence.

Comment on lines +40 to +45
var err error
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("badger iterator panic: %v", r)
}
}()
Copy link

Choose a reason for hiding this comment

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

Ensure err is returned if a panic occurs in iterateKeysByPrefixBatchedTx.

The defer function correctly captures and wraps the panic in an error message, but the err variable should be returned if a panic is detected.

	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("badger iterator panic: %v", r)
+			return
		}
	}()
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 err error
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("badger iterator panic: %v", r)
}
}()
var err error
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("badger iterator panic: %v", r)
return
}
}()

Comment on lines +81 to +86
var err error
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("badger iterator panic: %v", r)
}
}()
Copy link

Choose a reason for hiding this comment

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

Ensure err is returned if a panic occurs in iterateKeysByPrefixTx.

The defer function correctly captures and wraps the panic in an error message, but the err variable should be returned if a panic is detected.

	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("badger iterator panic: %v", r)
+			return
		}
	}()

Committable suggestion was skipped due to low confidence.

Comment on lines +241 to +245
defer func() {
if r := recover(); r != nil {
log.Errorf("badger iterator panic: %v", r)
}
}()
Copy link

Choose a reason for hiding this comment

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

Ensure the panic handling is effective in GetKeys.

The defer function correctly captures and logs the panic, but it would be better to also return an error if a panic is detected.

	defer func() {
		if r := recover(); r != nil {
			log.Errorf("badger iterator panic: %v", r)
+			err = fmt.Errorf("badger iterator panic: %v", r)
+			return
		}
	}()
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
defer func() {
if r := recover(); r != nil {
log.Errorf("badger iterator panic: %v", r)
}
}()
defer func() {
if r := recover(); r != nil {
log.Errorf("badger iterator panic: %v", r)
err = fmt.Errorf("badger iterator panic: %v", r)
return
}
}()

Comment on lines +96 to +104
err error
)

err := s.db.View(func(txn *badger.Txn) error {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("badger iterator panic: %v", r)
}
}()

Copy link

Choose a reason for hiding this comment

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

Ensure err is returned if a panic occurs in queryRaw.

The defer function correctly captures and wraps the panic in an error message, but the err variable should be returned if a panic is detected.

	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("badger iterator panic: %v", r)
+			return
		}
	}()
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 error
)
err := s.db.View(func(txn *badger.Txn) error {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("badger iterator panic: %v", r)
}
}()
err error
)
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("badger iterator panic: %v", r)
return
}
}()

@requilence requilence merged commit 2d08469 into main Jul 1, 2024
5 checks passed
@requilence requilence deleted the go-3454-badger-do-not-panic-when-calling-closed-badger branch July 1, 2024 11:33
@github-actions github-actions bot locked and limited conversation to collaborators Jul 1, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants