Skip to content

Conversation

coszio
Copy link
Contributor

@coszio coszio commented Apr 25, 2025

This PR fixes one thing we overlooked in gridstore.

Pending updates only stored the last place where a value is. So, when flushing, we would only free the previous stored value. If multiple updates happened in between flushes, we'd end up with storage that is never marked as free.

With these changes, now we keep track of all the places that values have been written in between flushes, so that we only keep the latest one, and are able to mark all the previous places as free.

Testing

For testing, I modified one test, so that it failed without the changes, and also did manual validation by making sure that

bfb -n 5000000 --max-id 10 -d 128 --float-payloads true --segments 1 --on-disk-payload --text-payloads --text-payload-length 100 --skip-field-indices

doesn't grow the size of payload storage forever. It now reduces in between flushes, and it is minimal after updates have finished.

@coszio coszio requested review from agourlay and generall April 25, 2025 16:51
Comment on lines 38 to 45
#[derive(Debug)]
enum PointerUpdate {
Set(ValuePointer),
Unset(ValuePointer),
#[derive(Debug, Default)]
struct PointerUpdates {
/// Whether the latest pointer is set (true) or unset (false)
latest_is_set: bool,
/// List of pointers where the value was written
history: SmallVec<[ValuePointer; 1]>,
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is the main change of the PR

Copy link
Contributor

coderabbitai bot commented Apr 25, 2025

📝 Walkthrough

Walkthrough

The changes introduce and standardize the use of the smallvec crate across multiple Rust project components. Initially, smallvec version "1.15.0" is added as a dependency in the root Cargo.toml. Subsequently, in the lib/collection, lib/gridstore, and lib/segment crates, the dependency specification for smallvec is updated to use the workspace version rather than a fixed version. In the lib/gridstore/src/tracker.rs file, the PointerUpdate enum is replaced by a new PointerUpdates struct that maintains a history of pointer updates using a SmallVec, allowing tracking of multiple successive updates per point offset and improved management of outdated pointers. The Tracker struct's pending_updates field and related methods are updated accordingly. Additionally, the test test_update_single_payload in lib/gridstore/src/gridstore.rs is refactored to remove repeated code by introducing a closure that encapsulates payload insertion and verification logic. No changes are made to the declarations of exported or public entities outside of these internal refactorings.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2014bbd and cda2f0f.

📒 Files selected for processing (1)
  • lib/gridstore/src/tracker.rs (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/gridstore/src/tracker.rs
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: test-snapshot-operations-s3-minio
  • GitHub Check: test-shard-snapshot-api-s3-minio
  • GitHub Check: test-low-resources
  • GitHub Check: test-consistency
  • GitHub Check: integration-tests
  • GitHub Check: integration-tests-consensus
  • GitHub Check: rust-tests (macos-latest)
  • GitHub Check: rust-tests (windows-latest)
  • GitHub Check: test-consensus-compose
  • GitHub Check: storage-compat-test
  • GitHub Check: rust-tests (ubuntu-latest)
  • GitHub Check: lint
  • GitHub Check: Basic TLS/HTTPS tests
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in 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
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

🧹 Nitpick comments (3)
lib/gridstore/src/tracker.rs (3)

39-45: Consider documenting the invariants of PointerUpdates
Because correctness of the clean-up logic relies on history never being empty once latest_is_set becomes true/false, a short doc-comment describing that assumption will help future maintainers.


172-190: Optionally deduplicate old_pointers before returning
With the fix above duplicates should be rare, but if external callers treat the returned vector as a set, it may be safer (and cheaper long-term) to weed out duplicates here:

old_pointers.sort_unstable();
old_pointers.dedup();

Not essential, but helps keep the freeing path idempotent.


291-293: Minor ergonomics—avoid double Option with and_then
Readability can be improved by replacing the map(..).or_else(..).flatten() dance with:

self.pending_updates
    .get(&point_offset)
    .and_then(PointerUpdates::latest)
    .or_else(|| self.get_raw(point_offset).copied())

Same behaviour, one fewer Option layer.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c8a9606 and 2351c95.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • Cargo.toml (1 hunks)
  • lib/collection/Cargo.toml (1 hunks)
  • lib/gridstore/Cargo.toml (1 hunks)
  • lib/gridstore/src/gridstore.rs (1 hunks)
  • lib/gridstore/src/tracker.rs (8 hunks)
  • lib/segment/Cargo.toml (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: test-snapshot-operations-s3-minio
  • GitHub Check: test-shard-snapshot-api-s3-minio
  • GitHub Check: Basic TLS/HTTPS tests
  • GitHub Check: test-low-resources
  • GitHub Check: test-consistency
  • GitHub Check: rust-tests (macos-latest)
  • GitHub Check: test-consensus-compose
  • GitHub Check: rust-tests (windows-latest)
  • GitHub Check: integration-tests-consensus
  • GitHub Check: rust-tests (ubuntu-latest)
  • GitHub Check: lint
  • GitHub Check: integration-tests
  • GitHub Check: storage-compat-test
🔇 Additional comments (8)
Cargo.toml (1)

208-208: Properly adding smallvec dependency.

Adding the smallvec crate as a workspace dependency aligns with the PR objective to improve space reuse in gridstore by tracking update history.

lib/gridstore/Cargo.toml (1)

20-20: LGTM - Adding smallvec as a workspace dependency.

This addition is consistent with the root Cargo.toml change and supports the implementation of pointer update history tracking in the tracker module.

lib/collection/Cargo.toml (1)

46-46: Good standardization of smallvec dependency.

Converting from a fixed version to a workspace dependency enhances consistency across the project.

lib/segment/Cargo.toml (1)

94-94: Good standardization of smallvec dependency.

Converting from a fixed version to a workspace dependency enhances consistency across the project.

lib/gridstore/src/gridstore.rs (1)

736-767: Good test refactoring with explicit block offset reuse test.

The refactored test with a closure nicely validates the PR objective of improved space reuse. The test now explicitly verifies that after flushing updates, the first block offset becomes available again for reuse.

The closure eliminates code duplication and makes the test more maintainable while clearly demonstrating the improved behavior.

lib/gridstore/src/tracker.rs (3)

9-9: Good call introducing SmallVec to avoid heap allocations in the common case
The import is correct and sits with the other extern-crate imports, keeping the module header tidy.


309-313: Looks good – offset tracking logic preserved
Ensures next_pointer_offset only grows.


321-324: Behaviourally sound, but double-check race conditions in the caller
unset relies on get returning the latest flushed/pending value. If Tracker is ever shared across threads, the caller must synchronise calls to set/unset/flush.

@coszio coszio requested a review from Copilot April 25, 2025 17:05
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR updates the gridstore implementation to more effectively manage and free outdated pointers during flushes by tracking the complete history of pointer updates. Key changes include:

  • Replacing the previous pointer update enum with a new PointerUpdates struct to record update history.
  • Adjusting the persistence logic to free all outdated pointer locations.
  • Updating tests and Cargo.toml dependency references for consistency.

Reviewed Changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated no comments.

Show a summary per file
File Description
lib/segment/Cargo.toml Changed smallvec to be workspace-managed.
lib/gridstore/src/tracker.rs Introduced PointerUpdates struct and updated flush logic to correctly free earlier pointer updates.
lib/gridstore/src/gridstore.rs Modified tests to verify block offset reuse after flush.
lib/gridstore/Cargo.toml Updated smallvec dependency to workspace.
lib/collection/Cargo.toml Updated smallvec dependency to workspace.
Cargo.toml Updated smallvec dependency version reference.

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

🧹 Nitpick comments (2)
lib/gridstore/src/tracker.rs (2)

78-88: Consider using a reference instead of consuming self.

The outdated_pointers method currently consumes self by taking ownership, which means the PointerUpdates instance can't be used after calling this method. Consider changing the signature to use a reference if you need to preserve the instance.

-    fn outdated_pointers(self) -> impl Iterator<Item = ValuePointer> {
+    fn outdated_pointers(&self) -> impl Iterator<Item = ValuePointer> + '_ {
-        let take = if self.latest_is_set {
+        let take = if self.latest_is_set {
             // all but the latest one
-            self.history.len().saturating_sub(1)
+            self.history.len().saturating_sub(1)
         } else {
             // all of them
-            self.history.len()
+            self.history.len()
         };

-        self.history.into_iter().take(take)
+        self.history.iter().take(take).copied()
     }

171-201: Consider handling errors more robustly.

If mmap.flush() fails, the method will return an error, but the pending updates have already been taken and will be lost. Consider handling this more robustly to preserve updates in case of errors.

     pub fn write_pending_and_flush(&mut self) -> std::io::Result<Vec<ValuePointer>> {
         // Write pending updates from memory
-        let mut pending_updates = std::mem::take(&mut self.pending_updates);
+        // Take a clone instead of ownership to preserve updates in case of errors
+        let mut pending_updates = self.pending_updates.clone();
+        self.pending_updates.clear();
         let mut old_pointers = Vec::new();
         for (point_offset, updates) in pending_updates.drain() {
             match updates.latest() {
                 // ... existing code ...
             }
             old_pointers.extend(updates.outdated_pointers());
         }
         // increment header count if necessary
         self.persist_pointer_count();

         // Flush the mmap
-        self.mmap.flush()?;
+        if let Err(e) = self.mmap.flush() {
+            // Restore the pending updates on error
+            self.pending_updates = pending_updates;
+            return Err(e);
+        }

         Ok(old_pointers)
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2351c95 and 2014bbd.

📒 Files selected for processing (1)
  • lib/gridstore/src/tracker.rs (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Basic TLS/HTTPS tests
  • GitHub Check: test-snapshot-operations-s3-minio
  • GitHub Check: test-shard-snapshot-api-s3-minio
  • GitHub Check: test-low-resources
  • GitHub Check: test-consistency
  • GitHub Check: integration-tests-consensus
  • GitHub Check: rust-tests (macos-latest)
  • GitHub Check: test-consensus-compose
  • GitHub Check: rust-tests (windows-latest)
  • GitHub Check: integration-tests
  • GitHub Check: storage-compat-test
  • GitHub Check: rust-tests (ubuntu-latest)
  • GitHub Check: lint
🔇 Additional comments (10)
lib/gridstore/src/tracker.rs (10)

9-9: Good addition of the SmallVec dependency.

The import of smallvec::SmallVec is appropriate for this use case, as it provides a vector-like container that's optimized for the common case where there are few elements, avoiding heap allocations.


39-45: Well-structured replacement for PointerUpdate.

This new PointerUpdates struct effectively implements the core of the PR's objective, tracking all locations where values have been written between flushes, not just the last one.


47-62: Implementation looks good with proper safeguards.

The implementation for set and unset is clear and includes the defensive check to prevent duplicate pointers in the history as suggested in previous review comments.


69-75: Clean implementation of latest pointer resolution.

The latest method correctly handles both set and unset states, returning the appropriate value based on the latest_is_set flag.


78-88: Good implementation with safeguard against underflow.

The outdated_pointers method correctly identifies which pointers should be freed based on the latest state, and includes the saturating_sub safeguard as suggested in a previous review.


107-107: Appropriate field type update.

The pending_updates field has been correctly updated to use the new PointerUpdates struct.


175-193: Core improvement for space reuse implemented correctly.

This is the main change of the PR, as noted in previous comments. The implementation now properly:

  1. Handles the latest pointer state (set/unset)
  2. Collects all outdated pointers from the update history
  3. Ensures they're properly freed

This directly addresses the PR's objective of improving space reuse by tracking all locations where values were written between flushes.


294-294: Appropriate method update.

The get method has been properly updated to use the new PointerUpdates.latest() method.


312-315: Clean implementation of set method.

The method now correctly creates or retrieves a PointerUpdates instance and delegates to its set method.


324-327: Well-implemented unset method.

The method correctly creates or retrieves a PointerUpdates instance and delegates to its unset method.

@coszio coszio merged commit 6be0c62 into dev Apr 25, 2025
17 checks passed
@coszio coszio deleted the reuse-more-in-gridstore branch April 25, 2025 22:03
/// If this is `true`, then history must have at least one element.
latest_is_set: bool,
/// List of pointers where the value has been written
history: SmallVec<[ValuePointer; 1]>,
Copy link
Member

Choose a reason for hiding this comment

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

Great! I like the use of SmallVec here.

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