Conversation
Summary of ChangesHello @mrain, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly refactors the reward Merkle tree architecture by introducing a two-level, storage-backed design. This change improves the scalability and persistence of reward account balance management. The new structure allows for flexible storage solutions, with a file system-backed option now available, and ensures compatibility through necessary dependency updates and API adjustments across the codebase. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces a storage-backed, two-level Merkle tree for rewards, which is a significant feature for managing large state efficiently. The implementation includes a RewardMerkleTreeStorage trait with both in-memory and file-system backends. My review primarily focuses on the new storage implementations, highlighting several critical issues in error handling and cache management within the file-system storage that could lead to data loss or corruption. I've also pointed out some incomplete features in the forgettable tree implementation. The other changes, which are mostly refactoring and dependency updates related to this new feature, look good.
| } | ||
|
|
||
| // Flush the current cache if it exists | ||
| if let Err(e) = self.flush_cache() { |
There was a problem hiding this comment.
Ignoring the result of flush_cache() can lead to data loss. If flushing fails, the dirty cache entry is discarded, and a new tree is loaded. This function should panic if flushing fails to prevent data loss. A similar issue exists in clone() on line 136.
self.flush_cache().expect("Error flushing Reward Merkle tree cache");| let root = self | ||
| .load_from_disk(index) | ||
| .unwrap_or(InnerRewardMerkleTreeRoot::Empty); |
There was a problem hiding this comment.
The use of unwrap_or here can mask critical errors. load_from_disk returns an Err for I/O or deserialization issues (other than NotFound), and unwrap_or will replace this Err with an empty tree. This effectively hides the error and can lead to state corruption. It would be safer to panic on such errors, as they are likely unrecoverable.
load_from_disk already handles the NotFound case by returning an Ok(Empty), so using expect here would only trigger on actual errors.
let root = self
.load_from_disk(index)
.expect("Failed to load Merkle tree root from disk");| impl Drop for RewardMerkleTreeFSStorage { | ||
| fn drop(&mut self) { | ||
| // Ensure cache is flushed when storage is dropped | ||
| let _ = self.flush_cache(); |
There was a problem hiding this comment.
| impl Clone for CachedInMemoryStorage { | ||
| fn clone(&self) -> Self { | ||
| Self { | ||
| roots: RwLock::new(self.roots.read().unwrap().clone()), | ||
| cache: RwLock::new(self.cache.read().unwrap().clone()), | ||
| } | ||
| } |
There was a problem hiding this comment.
The current implementation of clone for CachedInMemoryStorage clones the cache, which can lead to inconsistencies. If both the original and the clone are used for modifications, they will have independent but initially identical dirty caches. A safer approach, as seen in RewardMerkleTreeFSStorage, is to flush the cache and provide the clone with a new, empty cache to ensure consistency.
| impl Clone for CachedInMemoryStorage { | |
| fn clone(&self) -> Self { | |
| Self { | |
| roots: RwLock::new(self.roots.read().unwrap().clone()), | |
| cache: RwLock::new(self.cache.read().unwrap().clone()), | |
| } | |
| } | |
| impl Clone for CachedInMemoryStorage { | |
| fn clone(&self) -> Self { | |
| // It is important to flush the cache before cloning to ensure the main `roots` map is up to date. | |
| self.flush_cache().expect("Failed to flush cache before cloning"); | |
| Self { | |
| roots: RwLock::new(self.roots.read().unwrap().clone()), | |
| cache: RwLock::new(None), | |
| } | |
| } | |
| } |
| let _ = self.flush_cache(); | ||
| let _ = other.flush_cache(); | ||
| *self.roots.read().unwrap() == *other.roots.read().unwrap() | ||
| } | ||
| } | ||
|
|
||
| impl Eq for CachedInMemoryStorage {} | ||
|
|
||
| impl CachedInMemoryStorage { | ||
| /// Create a new empty cached storage | ||
| pub fn new() -> Self { | ||
| Self { | ||
| roots: RwLock::new(HashMap::new()), | ||
| cache: RwLock::new(None), | ||
| } | ||
| } | ||
|
|
||
| /// Create storage with a pre-allocated capacity | ||
| pub fn with_capacity(capacity: usize) -> Self { | ||
| Self { | ||
| roots: RwLock::new(HashMap::with_capacity(capacity)), | ||
| cache: RwLock::new(None), | ||
| } | ||
| } | ||
|
|
||
| /// Get the number of stored roots (excluding cache) | ||
| pub fn len(&self) -> usize { | ||
| self.roots.read().unwrap().len() | ||
| } | ||
|
|
||
| /// Check if storage is empty (excluding cache) | ||
| pub fn is_empty(&self) -> bool { | ||
| self.roots.read().unwrap().is_empty() | ||
| } | ||
|
|
||
| /// Clear all stored roots and cache | ||
| pub fn clear(&self) { | ||
| self.roots.write().unwrap().clear(); | ||
| *self.cache.write().unwrap() = None; | ||
| } | ||
|
|
||
| /// Internal: Load an inner Merkle tree into the cache | ||
| fn load_into_cache(&self, index: OuterIndex) { | ||
| // Check if the requested tree is already cached | ||
| { | ||
| let cache = self.cache.read().unwrap(); | ||
| if let Some((cached_index, _)) = &*cache { | ||
| if *cached_index == index { | ||
| return; // Already cached | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Flush the current cache if it exists | ||
| let _ = self.flush_cache(); |
There was a problem hiding this comment.
|
|
||
| // Read all tree files from the storage directory | ||
| if let Ok(entries) = fs::read_dir(&self.storage_dir) { | ||
| for entry in entries.flatten() { |
There was a problem hiding this comment.
The use of flatten() on the ReadDir iterator might silently ignore I/O errors that can occur while iterating over directory entries. It's better practice to handle these errors explicitly, for example by logging a warning for any entry that cannot be read.
for entry_res in entries {
if let Ok(entry) = entry_res {| impl<S: RewardMerkleTreeStorage + Default> ForgetableMerkleTreeScheme | ||
| for RewardMerkleTreeV2Impl<S> | ||
| { | ||
| /// Reconstruct a sparse tree from a commitment with default storage | ||
| /// | ||
| /// Creates an empty tree with the given root. Accounts can be populated with remember. | ||
| fn from_commitment(commitment: impl Borrow<Self::Commitment>) -> Self { | ||
| let num_leaves = commitment.borrow().size(); | ||
| Self { | ||
| outer: OuterRewardMerkleTreeV2::from_commitment(commitment), | ||
| num_leaves, | ||
| storage: S::default(), | ||
| } | ||
| } | ||
|
|
||
| /// Remove an account from memory (not yet implemented, currently just performs lookup) | ||
| /// | ||
| /// Returns the account's balance and proof if it exists. | ||
| fn forget( | ||
| &mut self, | ||
| index: impl Borrow<Self::Index>, | ||
| ) -> LookupResult<Self::Element, Self::MembershipProof, ()> { | ||
| self.lookup(index) | ||
| // let outer_index = OuterIndex::new(index.borrow()); | ||
| // let outer_proof = match self.outer.lookup(outer_index) { | ||
| // LookupResult::Ok(_, proof) => proof, | ||
| // LookupResult::NotInMemory => { | ||
| // unreachable!("Outer reward merkle tree will never be forgetten.") | ||
| // }, | ||
| // LookupResult::NotFound(_) => return LookupResult::NotFound(()), | ||
| // }; | ||
| // match self.storage.forget(index) { | ||
| // LookupResult::Ok(value, mut proof) => { | ||
| // Self::patch_membership_proof(&mut proof, &outer_proof); | ||
| // LookupResult::Ok(value, proof) | ||
| // }, | ||
| // LookupResult::NotInMemory => LookupResult::NotInMemory, | ||
| // LookupResult::NotFound(_) => LookupResult::NotFound(()), | ||
| // } | ||
| } | ||
|
|
||
| /// Restore an account to memory using a proof (currently a no-op) | ||
| /// | ||
| /// Restores an account that was previously forgotten. Currently does nothing. | ||
| fn remember( | ||
| &mut self, | ||
| _pos: impl Borrow<Self::Index>, | ||
| _element: impl Borrow<Self::Element>, | ||
| _proof: impl Borrow<Self::MembershipProof>, | ||
| ) -> Result<(), MerkleTreeError> { | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| /// Forgetable universal operations: forget with non-membership proofs | ||
| impl<S: RewardMerkleTreeStorage + Default> ForgetableUniversalMerkleTreeScheme | ||
| for RewardMerkleTreeV2Impl<S> | ||
| { | ||
| /// Remove an account and generate proof (membership or non-membership) | ||
| /// | ||
| /// Currently just performs universal_lookup without actually removing from memory. | ||
| fn universal_forget( | ||
| &mut self, | ||
| pos: Self::Index, | ||
| ) -> LookupResult<Self::Element, Self::MembershipProof, Self::NonMembershipProof> { | ||
| self.universal_lookup(pos) | ||
| } | ||
|
|
||
| /// Restore non-membership information using a proof (currently a no-op) | ||
| /// | ||
| /// Restores non-membership information for an account. Currently does nothing. | ||
| fn non_membership_remember( | ||
| &mut self, | ||
| _pos: Self::Index, | ||
| _proof: impl Borrow<Self::NonMembershipProof>, | ||
| ) -> Result<(), MerkleTreeError> { | ||
| Ok(()) | ||
| } | ||
| } |
There was a problem hiding this comment.
The implementations for ForgetableMerkleTreeScheme and ForgetableUniversalMerkleTreeScheme appear to be incomplete. The methods forget, universal_forget, remember, and non_membership_remember are either stubbed out, are no-ops, or simply delegate to lookup methods without performing their intended 'forget' or 'remember' operations. This should be either fully implemented or clearly documented as a work in progress.
|
Created new PR to fix cargo audit. PR: #3924 Please merge that PR first to fix cargo-audit. |
Closes #<ISSUE_NUMBER>
This PR:
This PR does not:
Key places to review: