Skip to content

Migrate WAL mutex from parking lot to tokio#6307

Merged
timvisee merged 3 commits intodevfrom
wal-tokio-mutex
Apr 4, 2025
Merged

Migrate WAL mutex from parking lot to tokio#6307
timvisee merged 3 commits intodevfrom
wal-tokio-mutex

Conversation

@timvisee
Copy link
Member

@timvisee timvisee commented Apr 2, 2025

Migrates the WAL lock from a sync parking lot mutex to an async tokio mutex.

The mutex is almost exclusively used in async context. I therefore suggest to make it an async mutex, so that we don't run into the constant issue of trying to hold this lock across await points.

This is the first step in a bigger attempt to more clearly define the boundary between our sync (segments) and async (the rest) code. Currently, this boundary is very vague because we constantly mix up the two flavors, which creates constant problems. I'd like to clean up this technical dept a bit.

Contains no logic changes. Purely mechanical to change the mutex type.

All Submissions:

  • Contributions should target the dev branch. Did you create your branch from dev?
  • Have you followed the guidelines in our Contributing document?
  • Have you checked to ensure there aren't other open Pull Requests for the same update/change?

New Feature Submissions:

  1. Does your submission pass tests?
  2. Have you formatted your code locally using cargo +nightly fmt --all command prior to submission?
  3. Have you checked your code using cargo clippy --all --all-features command?

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 2, 2025

📝 Walkthrough

Walkthrough

The pull request introduces several changes aimed at transitioning from synchronous to asynchronous operations across the codebase. Key modifications include updating locking mechanisms for the Write-Ahead Log (WAL) by switching from ParkingMutex to Tokio’s asynchronous Mutex, and altering method implementations to use .await where necessary. This affects methods related to WAL operations, snapshots, local shard loading, and update handling. Function signatures in multiple modules, such as LocalShard, QueueProxyShard, ShardReplicaSet, Shard, and the update handler, have been updated to include the async keyword. Additionally, some functions now document that they will panic if called in an asynchronous context. These changes ensure that operations which were previously blocking are now handled in a non-blocking, asynchronous manner.

Suggested Reviewers

  • generall
  • ffuugoo
✨ 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 (4)
lib/collection/src/shards/shard.rs (1)

234-234: Consider releasing lock before logging
You're holding the WAL mutex lock while creating and logging this debug message. If the logging operation becomes slow for any reason, it might block other tasks. Consider reading last_index() into a local variable and then releasing the lock before calling log::debug!.

lib/collection/src/update_handler.rs (2)

695-695: Potential blocking flush in wait logic
Calling wal.lock().await.flush() in the path where wait is true may stall other tasks if flush is time-consuming. Consider whether you need a more fine-grained approach, such as performing the flush outside the main lock if feasible.


820-820: Avoid extended lock during acknowledgement
You're locking the WAL to call ack(ack). In heavily loaded environments, consider reading the necessary state under lock, releasing it, then acknowledging to minimize time spent holding the mutex.

lib/collection/src/shards/queue_proxy_shard.rs (1)

468-468: Potential concurrency bottleneck while reading WAL
Locking the WAL here to retrieve items is correct, but if transferring large batches, you might consider partial reads or using separate read structures to reduce lock contention.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ec544ff and 07b1878.

📒 Files selected for processing (6)
  • lib/collection/src/shards/local_shard/mod.rs (5 hunks)
  • lib/collection/src/shards/queue_proxy_shard.rs (5 hunks)
  • lib/collection/src/shards/replica_set/shard_transfer.rs (2 hunks)
  • lib/collection/src/shards/shard.rs (2 hunks)
  • lib/collection/src/update_handler.rs (5 hunks)
  • lib/collection/src/wal_delta.rs (26 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
lib/collection/src/shards/shard.rs (2)
lib/collection/src/wal_delta.rs (2)
  • wal (1615-1627)
  • wal_version (121-128)
lib/collection/src/shards/replica_set/shard_transfer.rs (1)
  • wal_version (492-501)
lib/collection/src/wal_delta.rs (4)
lib/collection/src/shards/replica_set/shard_transfer.rs (1)
  • wal_version (492-501)
lib/collection/src/shards/shard.rs (1)
  • wal_version (250-266)
lib/collection/src/update_handler.rs (1)
  • new (132-169)
lib/collection/src/shards/local_shard/mod.rs (2)
  • new (161-239)
  • new (1272-1277)
⏰ 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: test-consensus
  • GitHub Check: test (macos-latest)
  • GitHub Check: test-consensus-compose
  • GitHub Check: test (windows-latest)
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test (ubuntu-latest)
  • GitHub Check: test
🔇 Additional comments (41)
lib/collection/src/shards/shard.rs (1)

250-252:

Details

✅ Verification successful

Verify async signature usage
The wal_version function is now asynchronous. Double-check that all consumers of wal_version() call it with .await and handle potential concurrency or error scenarios from the future properly.


🏁 Script executed:

#!/bin/bash
# Check for all usage of wal_version in the repo to ensure calls are awaited.
rg -A 3 "wal_version\("

Length of output: 1933


Async Signature Verified:
The asynchronous implementation of wal_version appears to be correctly integrated across the codebase. All consumers—such as in lib/collection/src/shards/shard.rs, lib/collection/src/wal_delta.rs, lib/collection/src/shards/replica_set/shard_transfer.rs, and lib/collection/src/shards/transfer/wal_delta.rs—are properly using .await and handling errors as expected. No further action is required.

lib/collection/src/update_handler.rs (3)

246-252: Ensure asynchronous error handling in try_recover
This function has been changed to async. Confirm that any errors, especially those arising from wal.lock().await, are properly handled or bubbled up. Also verify that external callers are updated to use .await and are prepared to handle partial recoveries mid-await.


628-630: Double-check logic after async recovery
Here, try_recover is being awaited. If recovery fails, the code aborts further processing. Ensure that this is the intended flow and that no critical cleanup steps are missed after a failed recovery.


779-779: Confirm concurrency of async flush
Invoking flush_async() here is appropriate for non-blocking behavior. Verify downstream code to ensure it safely handles any partial flush states that might occur if tasks race to read from the WAL while this flush is ongoing.

lib/collection/src/shards/queue_proxy_shard.rs (3)

69-75: Async constructor pattern
Defining pub async fn new and immediately calling Inner::new(...).await ensures the shard setup can await WAL locks or remote checks. This is appropriate if shard construction necessarily depends on async I/O. Confirm that any failures are properly handled or propagated as errors.


91-100: Async creation from existing WAL version
Similarly, making pub async fn new_from_version ensures that verifying the version within the WAL is fully asynchronous. Verify that the calling sites either handle or propagate potential concurrency errors when multiple tasks attempt creation from different versions.


389-394: Check nested WAL locking in new
Calling wrapped_shard.wal.wal.lock().await.last_index() inline is straightforward; just confirm that no other operation in this constructor accidentally re-locks the same WAL in nested code paths, which might risk deadlocks.

lib/collection/src/shards/local_shard/mod.rs (7)

176-176: Adoption of tokio::sync::Mutex matches the new async design

Using tokio::sync::Mutex here is congruent with the PR objective of migrating to async locking, reducing potential blocking.


619-619: Asynchronous lock acquisition

Transitioning to .lock().await is correct for async contexts and aligns with the new async Mutex usage.


628-630: Improved logging granularity

This updated log message clarifies the WAL recovery start point. Looks good.


929-932: Documentation clarifies blocking lock usage

Explicitly stating the function will panic in async contexts helps avoid misuse. Consider elaborating any multi-threaded constraints if relevant.


939-939: Blocking lock is valid for synchronous usage

blocking_lock() is appropriate if strictly invoked from non-async code. Ensure external callers never await this function, as warned in the docstring.


968-972: Reinforcing the panic condition in documentation

Reiterating the risk of calling this function asynchronously helps steer correct usage patterns.


974-974: Second blocking lock usage

Same caution applies; ensure a strictly synchronous calling context to prevent runtime deadlocks.

lib/collection/src/shards/replica_set/shard_transfer.rs (2)

180-193: Async queue-proxy initialization

Awaiting either QueueProxyShard::new or ::new_from_version is correctly handled for both from_version scenarios.


500-500: Async wal_version retrieval

Using .await for the WAL version lookup ensures consistent async handling of I/O-bound operations.

lib/collection/src/wal_delta.rs (25)

5-5: Use of tokio::sync is correct
Migration from parking_lot to tokio's Mutex is well-implemented.


11-11: Refined visibility
Changing the type alias to pub(crate) properly restricts scope. No issues found.


50-53: Refined function signature
Returning an OwnedMutexGuard in an async context avoids lifetime complications and looks clean.


68-68: Owned lock acquisition
lock_owned(self.wal.clone()).await is correctly used to yield an OwnedMutexGuard.


112-112: Awaiting WAL lock
Replacing synchronous locking with .await aligns with the asynchronous migration.


121-122: Asynchronous wal_version
Switching to an async function and awaiting the lock is consistent with the new locking model.


136-136: Await lock before read
Ensuring the lock is awaited prevents blocking in an async context.


292-292: Arc<Mutex<...>> initialization
Wrapping the WAL in Arc<Mutex<...>> correctly adopts asynchronous locking patterns.


377-377: Verify single operation
Awaiting b_wal.wal.lock() before counting ensures proper synchronization.


389-390: Zipping multiple reads
Locking each WAL asynchronously then zipping results maintains consistency across WALs.


487-487: Count check
Locking and reading the WAL ensures the correct number of points is counted.


496-499: Multiple WAL comparison
Acquiring locks and chaining .read(0) calls for each WAL is a clear approach in test code.


583-583: Test assertion
Confirming the correct number of missed operations after an async lock is reliable.


593-596: Concurrent WAL checks
Awaiting each lock and zipping across multiple WALs is consistent with async usage.


689-689: Delta read check
Async lock usage matches the rest of the code and ensures consistency.


699-701: Chained locking
Locking and reading each WAL before zipping them together is a standard test pattern.


794-795: Double assertion
Ensuring both nodes have two operations post-delta is correct under async locking.


805-807: Await lock
Guard acquisition is awaited before reading and zipping with the counterpart WAL’s read, minimizing race conditions.


815-817: Consistency check
Again, verifying equality after awaiting each lock is central to safe concurrency.


821-823: Ensuring 3 operations
Confirming the WAL operation count matches across all nodes after acquiring locks.


839-839: Awaited lock in testing
Continuing to ensure we don't block elsewhere by asynchronously locking the WAL.


846-846: Lock for read
Explicitly awaiting each lock promotes correctness in these test flows.


853-853: Consistent async usage
No issues with another awaited lock call here.


1214-1214: Operation count assertion
Verifies newly inserted deltas are detected properly via async locks.


1399-1408: Collecting locked WAL references
Temporarily holding each WAL lock for comparison is an acceptable pattern in tests. Blocking concurrency here is fine in a test context.

@agourlay
Copy link
Member

agourlay commented Apr 3, 2025

Can we please get a small performance test for a quick sanity check that this is not much slower?

@timvisee
Copy link
Member Author

timvisee commented Apr 3, 2025

Can we please get a small performance test for a quick sanity check that this is not much slower?

Here are some basic bfb benchmarks for this PR compared to the dev branch. The tests are quite arbitrary but do cover different connection counts, operation sizes and segment counts. Results seem to be within margin of error. Here are the commands, and the upsert times with a resolution of one second:

  • bfb -n 10000000 --indexing-threshold 0 --skip-wait-index

    • dev: 48s, 47s
    • PR: 47s, 47s
  • bfb -n 10000000 --indexing-threshold 0 --skip-wait-index --segments 10 --threads 10 --parallel 10

    • dev: 32s, 33s
    • PR: 31s, 31s
  • bfb -n 1000000 -d 1500 --on-disk-vectors true --on-disk-payload --text-payloads --text-payload-length 100 --int-payloads 100 --timestamp-payload --indexing-threshold 0 --skip-wait-index --segments 10 --threads 10 --parallel 10 --wait-on-upsert

    • dev: 49s, 52s
    • PR: 51s, 51s
  • bfb -n 1000000 -d 16 -b 1 --indexing-threshold 0 --segments 10 --threads 10 --parallel 10 --wait-on-upsert --skip-wait-index

    • dev: 49s, 45s
    • PR: 45s, 45s

@timvisee timvisee merged commit 289f9b5 into dev Apr 4, 2025
17 checks passed
@timvisee timvisee deleted the wal-tokio-mutex branch April 4, 2025 10:18
pull bot pushed a commit to kp-forks/qdrant that referenced this pull request Apr 21, 2025
* Migrate WAL from sync parking lot to async tokio mutex

* Improve logging

* Migrate tests
This was referenced Oct 14, 2025
@coderabbitai coderabbitai bot mentioned this pull request Dec 1, 2025
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