Skip to content

Conversation

beer-1
Copy link
Contributor

@beer-1 beer-1 commented Feb 23, 2025

Here is context: cosmos/cosmos-sdk#23740

When we use statesync, it is using this IAVL importer but sometimes the IAVL store is empty even there is no notable errors. And after digging the issue, I found importer is not waiting the batch.Close().

This PR is to fix to importer to wait previous batch's WriteSync() and Close().

Additional context after writing the testcode

Hey @aljo242
I found (cosmos-db)Batch.Write() is already handling this issue, by calling batch.Commit() here at batch.Write().

So this was not the cause, but it is only happened in v1.2.x and v1.3.x.

This commit should be back ported to v1.2.x and v1.3.x.

in the meantime, I have changed this PR to add test case to cover data race between batch.Write() and importer.Commit(). If you run this test at v1.2.x or v1.3.x branch, then it will be failed.

Here is the PR for release/v1.2.x #1057.

@beer-1 beer-1 requested a review from a team February 23, 2025 13:53
Copy link

coderabbitai bot commented Feb 23, 2025

Walkthrough

This pull request introduces a new test function, TestImporterDataIntegrity, in the testing file. The function validates the integrity of data imported into a mutable tree structure by writing entries beyond the maximum batch size, exporting nodes from an immutable version of the tree, and then reimporting them into a new mutable tree backed by a LevelDB database. It confirms that the data remains consistent after closing and reopening the database. Additionally, new import statements for binary encoding and SHA3 hashing are added to support the test functionality.

Changes

File Change Summary
import_test.go - Added TestImporterDataIntegrity function to validate data import integrity in a mutable tree structure.
- Introduced new import statements for encoding/binary and golang.org/x/crypto/sha3.

Sequence Diagram(s)

sequenceDiagram
    participant T as TestImporterDataIntegrity
    participant M1 as Initial MutableTree
    participant I as ImmutableTree
    participant DB as Temporary DB (LevelDB)
    participant M2 as New MutableTree

    T->>M1: Initialize tree & write > max batch entries
    M1->>T: Save version and retrieve immutable tree
    T->>I: Export nodes from immutable tree
    T->>DB: Create temporary LevelDB instance
    T->>M2: Instantiate new mutable tree with DB
    M2->>T: Import version and add exported nodes
    T->>M2: Commit changes and save new version
    T->>DB: Reopen DB and verify data integrity
Loading

Suggested labels

backport/v1.x

Suggested reviewers

  • kocubinski
  • sontrinh16

Poem

I'm a nimble little rabbit, hopping through the code,
Keys and hashes in my burrow, where data integrity's bestowed.
With trees that sway in binary breeze and LevelDB on the trail,
I nibble tests and crunch the numbers without ever going stale.
Hoppy changes bloom in our code field—let's celebrate, not derail!
🐇🎉

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 generate docstrings to generate docstrings for this 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.

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
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0bce70d and 68bfc85.

📒 Files selected for processing (1)
  • import.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (go)
  • GitHub Check: Test
  • GitHub Check: Benchmarks
🔇 Additional comments (1)
import.go (1)

85-103: LGTM! Improved error handling and synchronous batch operations.

The changes enhance reliability by:

  1. Immediately checking and propagating errors from previous batch operations
  2. Using WriteSync() to ensure synchronous completion
  3. Properly handling errors from both WriteSync() and Close() operations

This aligns well with the PR objective of ensuring proper wait for batch operations.

Copy link

@aljo242 aljo242 left a comment

Choose a reason for hiding this comment

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

@beer-1 can we get a test for this case?

@beer-1
Copy link
Contributor Author

beer-1 commented Mar 6, 2025

Hey @aljo242
I found (goleveldb)Batch.Write() is already handling this issue, by calling .Commit() here.

so this was not the cause, but it only happened in v1.2.x and v1.3.x problem
This commit should be back ported to v1.2.x 34895bf

@beer-1 beer-1 force-pushed the fix/importer-close branch from 8fafe57 to 046ba12 Compare March 6, 2025 07:34
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
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 68bfc85 and 046ba12.

📒 Files selected for processing (1)
  • import_test.go (2 hunks)
🔇 Additional comments (5)
import_test.go (5)

3-10: Appropriate import additions for the new test case.

The added imports for encoding/binary and golang.org/x/crypto/sha3 are correctly included to support the new test function. These packages are used for generating deterministic keys in the test.


312-326: Good test design for database persistence.

Using a persistent LevelDB database instead of an in-memory database is the right approach for testing the issue described in the PR objectives. This effectively tests whether the importer correctly waits for batch operations to complete before proceeding.

Consider adding a comment explaining the specific issue being tested to make the purpose clearer:

+	// Use a persistent database to test that batch operations complete correctly
+	// This specifically tests that the importer waits for batch.Close() to complete
	tempDir := t.TempDir()
	db, err := dbm.NewGoLevelDB("importer-test", tempDir)

327-332: Properly closing resources in sequence.

The code correctly saves the version and explicitly closes both the tree and database in the proper sequence. This is good practice and essential for testing the described issue.


334-348: Comprehensive data verification after database reopening.

The test properly reopens the database and verifies that all imported data is present and correct. This is an effective way to ensure that the importer waited for all operations to complete before closing.


277-349: This test effectively addresses the PR's main objective.

This test function comprehensively tests the data integrity issue described in the PR objectives. By writing more than the maximum batch size, using a persistent database, and verifying data after database reopening, it correctly tests whether the importer waits for batch operations to complete.

The test aligns perfectly with the PR description: "fix: importer to wait db close" by ensuring database operations are properly completed before proceeding.

@beer-1 beer-1 changed the title fix: importer to wait db close fix: add test case to cover data race between batch.Write() and importer.Commit() Mar 6, 2025
@beer-1 beer-1 requested a review from aljo242 March 6, 2025 07:37
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

🧹 Nitpick comments (3)
import_test.go (3)

303-308: Inconsistent error handling pattern for ErrorExportDone.

The current error check uses direct equality comparison err == ErrorExportDone, whereas other tests in this file use errors.Is(err, ErrorExportDone). Consider using errors.Is() for consistency and better error handling with wrapped errors.

-		if err == ErrorExportDone {
+		if errors.Is(err, ErrorExportDone) {
 			break
 		}
-
-		require.NoError(t, err)
+		else if err != nil {
+			require.NoError(t, err)
+		}

311-331: Ensure proper resource management with defer statements.

While the test correctly closes resources, consider using defer for consistent resource cleanup, especially for the importer and database connections. This ensures resources are properly released even if the test fails partway through.

 	importer, err := newTree.Import(version)
 	require.NoError(t, err)
+	defer importer.Close()
 
 	for _, node := range exported {
 		err = importer.Add(node)
 		require.NoError(t, err)
 	}
 	err = importer.Commit()
 	require.NoError(t, err)
-	importer.Close()
 
 	_, version, err = newTree.SaveVersion()
 	require.NoError(t, err)
+	defer func() {
+		err = newTree.Close()
+		require.NoError(t, err)
+		err = db.Close()
+		require.NoError(t, err)
+	}()
-	err = newTree.Close()
-	require.NoError(t, err)
-	err = db.Close()
-	require.NoError(t, err)

284-286: Consider parameterizing the test data generation.

For better maintainability, consider extracting the key and value generation logic into a helper function, especially since this pattern is repeated later in the test for verification.

+	generateKeyValue := func(i int) ([]byte, []byte) {
+		key := sha3.Sum256(binary.BigEndian.AppendUint64([]byte{}, uint64(i)))
+		return key[:], []byte{byte(i)}
+	}
+
 	// write more than maxBatchSize
 	for i := 0; i < maxBatchSize+1; i++ {
-		bz := sha3.Sum256(binary.BigEndian.AppendUint64([]byte{}, uint64(i)))
-		_, err := tree.Set(bz[:], []byte{byte(i)})
+		key, value := generateKeyValue(i)
+		_, err := tree.Set(key, value)
 		require.NoError(t, err)
 	}

And then reuse it during verification:

 	for i := 0; i < maxBatchSize+1; i++ {
-		bz := sha3.Sum256(binary.BigEndian.AppendUint64([]byte{}, uint64(i)))
-		value, err := itree.Get(bz[:])
+		key, expectedValue := generateKeyValue(i)
+		value, err := itree.Get(key)
 		require.NoError(t, err)
-		require.Equal(t, []byte{byte(i)}, value)
+		require.Equal(t, expectedValue, value)
 	}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 046ba12 and 08ddf01.

📒 Files selected for processing (1)
  • import_test.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Benchmarks
  • GitHub Check: Test
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
import_test.go (2)

4-10: Import statements added appropriately for the new test.

The new imports for binary encoding and SHA3 hashing are correctly added to support the key generation mechanism in TestImporterDataIntegrity.


278-348: Well-structured test that effectively validates data integrity across batches.

This test effectively validates the fix for the data race between batch.Write() and importer.Commit() by:

  1. Creating a tree with entries exceeding maxBatchSize
  2. Exporting and then importing the data into a new LevelDB-backed tree
  3. Closing and reopening the database to verify persistence
  4. Checking that all values were correctly saved

The test properly uses temporary directories, handles resources with appropriate cleanup, and employs thorough error checking. This is an excellent test case that specifically targets the race condition mentioned in the PR objectives.

@aljo242
Copy link

aljo242 commented Apr 11, 2025

@beer-1 lgtm when we fix the lints (just can add //nolint comment)

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

Successfully merging this pull request may close these issues.

3 participants