Skip to content

Conversation

JojiiOfficial
Copy link
Contributor

@JojiiOfficial JojiiOfficial commented Mar 18, 2025

Depends on #6137

Introduces a new type that counts inside a usize and writes the results into a CounterCell on drop.
This reduces potential errors when manually counting inside a hotpath and applying measurements afterwards.

This PR can be reviewed on per commit basis.

@JojiiOfficial JojiiOfficial force-pushed the prepare_index_creation_hw_measurement branch from 0955c6e to 6550930 Compare March 19, 2025 09:44
@JojiiOfficial JojiiOfficial force-pushed the write_back_counter_cell branch from 160a859 to 6c99f68 Compare March 19, 2025 09:45
@JojiiOfficial JojiiOfficial force-pushed the prepare_index_creation_hw_measurement branch from 9e8650b to e354ec0 Compare March 24, 2025 08:40
@JojiiOfficial JojiiOfficial force-pushed the write_back_counter_cell branch from 6c99f68 to 05c03ce Compare March 24, 2025 08:46
@generall generall force-pushed the prepare_index_creation_hw_measurement branch from e354ec0 to dd7a5c4 Compare March 24, 2025 12:24
Base automatically changed from prepare_index_creation_hw_measurement to dev March 24, 2025 18:39
@JojiiOfficial JojiiOfficial force-pushed the write_back_counter_cell branch from 05c03ce to 0524ba5 Compare March 25, 2025 13:36
Copy link
Contributor

coderabbitai bot commented Mar 25, 2025

📝 Walkthrough

Walkthrough

The changes introduce a new mechanism for accumulating and updating hardware counters. A new structure, WritebackCounterCell, is added along with a method in the CounterCell that creates its instance. This structure accumulates increments locally and writes the total back to the original counter when dropped. Across various modules—ranging from inverted, geo, map, to numeric indexes—local accumulator variables have been replaced with direct invocations of the write-back counter’s methods (incr_delta). The tests have been updated to reflect these changes, ensuring that write-back increments are correctly registered in performance-critical sections. Overall, the modifications streamline counter operations by consolidating the logic into a direct hardware counter interface through the write-back approach.

✨ 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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: 0

🧹 Nitpick comments (1)
lib/common/common/src/counter/counter_cell.rs (1)

74-98: Well-documented performance optimization for hot-paths

The documentation thoroughly explains the purpose, benefits, and use cases for WritebackCounterCell. This is a valuable addition that provides clear guidance on when to use (and when not to use) this optimization.

One suggestion: consider adding examples in the documentation showing typical usage patterns to guide developers unfamiliar with this pattern.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9adf861 and 0524ba5.

📒 Files selected for processing (10)
  • lib/common/common/src/counter/counter_cell.rs (1 hunks)
  • lib/common/common/src/counter/hardware_counter.rs (2 hunks)
  • lib/segment/src/index/field_index/full_text_index/mutable_inverted_index.rs (2 hunks)
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index.rs (2 hunks)
  • lib/segment/src/index/field_index/map_index/mod.rs (1 hunks)
  • lib/segment/src/index/field_index/map_index/mutable_map_index.rs (2 hunks)
  • lib/segment/src/index/field_index/mmap_point_to_values.rs (2 hunks)
  • lib/segment/src/index/field_index/numeric_index/immutable_numeric_index.rs (2 hunks)
  • lib/segment/src/index/field_index/numeric_index/mmap_numeric_index.rs (2 hunks)
  • lib/segment/src/index/field_index/numeric_index/mutable_numeric_index.rs (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
lib/segment/src/index/field_index/numeric_index/immutable_numeric_index.rs (1)
src/common/metrics.rs (1)
  • counter (513-522)
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: test-shard-snapshot-api-s3-minio
  • GitHub Check: Basic TLS/HTTPS tests
  • GitHub Check: test-snapshot-operations-s3-minio
  • GitHub Check: test-low-resources
  • GitHub Check: test-consistency
  • GitHub Check: test-consensus-compose
  • GitHub Check: test (macos-latest)
  • GitHub Check: test
  • GitHub Check: test (windows-latest)
  • GitHub Check: test-consensus
  • GitHub Check: test
  • GitHub Check: test (ubuntu-latest)
  • GitHub Check: test
🔇 Additional comments (30)
lib/common/common/src/counter/hardware_counter.rs (3)

213-216: Good addition of write-back counter to tests

The write-back counter is now properly tested in the test_hw_counter_drain method. This ensures that when a write-back counter is used and dropped, its increments are properly accumulated in the original counter.


219-219: Correctly updated assertion for cumulative counter value

Good adjustment of the expected value from 1 to 2, accounting for both the direct increment (line 211) and the write-back counter increment (line 215).


237-240: Appropriate write-back counter usage in accumulator test

Effective demonstration of using write-back counters alongside direct counter increments. This change properly tests the accumulation of both increment methods to ensure they work together correctly.

lib/segment/src/index/field_index/numeric_index/mmap_numeric_index.rs (2)

6-6: Good addition of required import

Correctly added the import for HwMeasurementIteratorExt which provides the measure_hw_with_cell method used in the updated code.


258-260: Improved hardware counter measurement approach

Replaced the previous inspect-based counter incrementing pattern with a more efficient and cleaner measure_hw_with_cell approach. This change improves code readability and maintainability while following the new counter pattern.

lib/segment/src/index/field_index/mmap_point_to_values.rs (2)

287-295: Enhanced hardware counter handling with write-back pattern

Good update to use the write-back counter pattern. The parameter rename from hw_acc to hw_counter improves naming consistency, and using a write-back counter through write_back_counter() follows the new efficient counter pattern.


303-303: Correctly updated increment to use write-back counter

Updated the increment call to use the new write-back counter mechanism, ensuring hardware measurements are properly accumulated.

lib/segment/src/index/field_index/numeric_index/immutable_numeric_index.rs (2)

7-7: Added required HwMeasurementIteratorExt import

Correctly imported the trait that provides the measure_hw_with_cell method used in the updated code.


225-227: Improved hardware counter measurement in immutable index

Replaced the previous hardware counter incrementing approach with the cleaner measure_hw_with_cell pattern. This change provides a more consistent and efficient way to measure hardware usage across the codebase.

lib/segment/src/index/field_index/geo_index/mutable_geo_index.rs (3)

329-331: Good use of write-back counter pattern.

The implementation correctly obtains a write-back counter from the hardware counter cell, which will accumulate increments locally and write back to the original counter when dropped.


337-337: Properly measuring geo hash size with write-back counter.

The code now directly measures each geo hash's size with the write-back counter, which is more efficient than accumulating counts in a local variable.


351-351: Efficiently measuring total point offset size.

The implementation correctly calculates the total memory size for all point offsets at once, which is an efficient approach.

lib/segment/src/index/field_index/numeric_index/mutable_numeric_index.rs (2)

265-268: Good use of write-back counter pattern.

The implementation correctly obtains a write-back counter from the hardware counter cell, which accumulates increments locally and writes back to the original counter when dropped.


272-273: Correctly measuring key and index size in each iteration.

The code now directly increments the write-back counter with both the key and index sizes in each loop iteration, eliminating the need for a local counter variable.

lib/segment/src/index/field_index/full_text_index/mutable_inverted_index.rs (4)

86-88: Good use of write-back counter pattern.

The implementation correctly obtains a write-back counter from the hardware counter cell, which will accumulate increments locally and write back to the original counter when dropped.


94-95: Accurately measuring Document overhead.

The code now uses the write-back counter to track the memory overhead of expanding the point_to_docs vector, with a clear comment explaining that it's only measuring the Document's overhead.


105-106: Properly measuring postings expansion size.

The write-back counter correctly measures the size difference when the postings vector needs to be expanded.


118-118: Accurately tracking point ID size.

The implementation correctly measures the size of each point ID with the write-back counter.

lib/segment/src/index/field_index/map_index/mod.rs (3)

506-508: Good use of write-back counter pattern.

The implementation correctly obtains a write-back counter from the hardware counter cell, accumulating increments locally and writing back to the original counter when dropped.


515-515: Correctly measuring unique value size.

The write-back counter now tracks the size of each unique value added to the index, which is more direct than using a local counter variable.


518-518: Properly measuring point ID size.

The implementation correctly measures the size of each point ID with the write-back counter.

lib/common/common/src/counter/counter_cell.rs (4)

66-72: New method provides performance-optimized counting

The write_back_counter method creates a new WritebackCounterCell that accumulates increments and writes back to the original counter only when dropped. This is a good design for optimizing performance in hot-paths and loops.


100-105: Drop implementation ensures proper counter updates

The drop implementation correctly writes the accumulated count back to the original cell, which is the core mechanism that makes this optimization work without requiring manual reconciliation.


107-117: Simple and efficient WritebackCounterCell implementation

The implementation is clean and focused. The incr_delta method performs a simple addition without any cell access, which is exactly what's needed for the performance optimization.


119-134: Test validates core functionality but can be expanded

The test correctly verifies that the counter value is written back on drop. However, based on an earlier review comment, adding an additional assertion after incrementing but before dropping would better demonstrate the behavior.

Consider enhancing the test to include additional assertions and test cases:

 #[test]
 fn test_write_back_counter() {
     let cell = CounterCell::new();

     {
         let mut wb_counter = cell.write_back_counter();
         wb_counter.incr_delta(4);
         assert_eq!(cell.get(), 0);
+        // Multiple increments
+        wb_counter.incr_delta(2);
+        assert_eq!(cell.get(), 0);
     }

     assert_eq!(cell.get(), 6);
+    
+    // Test nested scopes
+    {
+        let mut wb_counter1 = cell.write_back_counter();
+        wb_counter1.incr_delta(10);
+        {
+            let mut wb_counter2 = cell.write_back_counter();
+            wb_counter2.incr_delta(4);
+            assert_eq!(cell.get(), 6);
+        }
+        assert_eq!(cell.get(), 10);
+    }
+    assert_eq!(cell.get(), 20);
 }
lib/segment/src/index/field_index/map_index/mutable_map_index.rs (5)

61-64: Adopting optimized counter for write operations

The change replaces direct counter increments with a write-back counter for better performance in this hot path. Good optimization for write-intensive operations.


71-71: Performance-optimized counter increment replaces direct call

The direct increment to the write-back counter eliminates cell access overhead during the loop, which is a good optimization for performance-critical code.


138-141: Adopting optimized counter for read operations

Using the write-back counter for read operations matches the pattern used in write operations, maintaining consistency and providing the same performance benefits.


142-143: Improved code documentation

The added comment clarifies the purpose of the overhead increment. This helps maintain code clarity while transitioning to the write-back counter pattern.


151-151: Consistent use of write-back counter

The counter increment inside the loop uses the write-back counter consistently with the rest of the changes, providing performance benefits for iterative operations.

@JojiiOfficial JojiiOfficial merged commit 2ef9612 into dev Apr 3, 2025
17 checks passed
@JojiiOfficial JojiiOfficial deleted the write_back_counter_cell branch April 3, 2025 18:09
pull bot pushed a commit to kp-forks/qdrant that referenced this pull request Apr 21, 2025
* Add WritebackCounterCell

* Replace custom counting with WritebackCounterCell

* Update lib/common/common/src/counter/counter_cell.rs

Co-authored-by: Tim Visée <tim+github@visee.me>

---------

Co-authored-by: Tim Visée <tim+github@visee.me>
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.

5 participants