Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Async reading in FileSystemDataVault #8126

Merged
merged 7 commits into from
Nov 13, 2024
Merged

Async reading in FileSystemDataVault #8126

merged 7 commits into from
Nov 13, 2024

Conversation

frcroth
Copy link
Member

@frcroth frcroth commented Oct 16, 2024

Steps to test:

  • View datasets (local, zarr3 sharded as it range queries)

Issues:


  • Updated changelog
  • Needs datastore update after deployment

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added metadata support for annotations on Trees and Segments.
    • Introduced a summary row in the time tracking overview.
    • Enhanced slider functionality for easier value adjustments.
    • Improved search functionality for unnamed segments.
    • Increased loading speeds for precomputed meshes.
    • Added a button to select all matching non-group results in the search popover.
    • Unified terminology in the UI, replacing "Resolution" with "Magnification."
    • Support for remote OME-Zarr NGFF version 0.5 datasets.
    • Superusers can now delete workflow reports.
  • Bug Fixes

    • Resolved issues with dataset uploads, bbox export, and annotation saving.
    • Corrected scrolling functionality in the trees and segments tab.
  • Improvements

    • Migrated nightly screenshot tests to GitHub Actions.
    • Thumbnails for datasets now utilize selected mapping from view configuration.
    • Enhanced asynchronous reading of image files for better performance.

@frcroth frcroth changed the title Implement FileSystemDataVault using Async Channel Async reading in FileSystemDataVault Oct 16, 2024
@frcroth frcroth marked this pull request as ready for review October 16, 2024 13:33
@frcroth frcroth requested a review from fm3 October 16, 2024 13:33
@frcroth frcroth self-assigned this Oct 16, 2024
@fm3
Copy link
Member

fm3 commented Nov 11, 2024

I did some testing here with thread count set to 1 and a large file.

  val vaultPath = new VaultPath(new URI(f"file:///largeFile"), FileSystemDataVault.create)
  for {
    before <- Instant.nowFox
    bytes <- vaultPath.readBytes(Some(Range.Long(0, 1147483646, 1)))
    _ = Instant.logSince(before, "reading bytes")
  } yield Ok

I requested this route several times in parallel. This way I could confirm that the thread is indeed not blocked in this async variant, and can reply to each request after the respective reading operation is complete. On master, it can only reply after all previous reading operations are complete (meaning the thread is blocked).

However, I also noticed that reading the file was consistently faster on master. On average I measured 634 ms on master versus 1160 ms here.

So it could be argued that using the synchronous variant (with more threads that consume some memory) is worth the faster loading, compared to this change (that could work with fewer threads). Do you have any opinions on this @frcroth @normanrz ? Of course the testing conditions were pretty specific (ssd on my laptop, warm OS cache, always the same file) and differ somewhat from realistic datastore load conditions.

@normanrz
Copy link
Member

Async usually helps with throughput when dealing with a lot of requests. It doesn't necessarily yield improvements with just a few requests. However, it shouldn't be much slower, either. So, these results are a bit surprising.

Copy link

coderabbitai bot commented Nov 12, 2024

Walkthrough

The pull request introduces significant enhancements to the WEBKNOSSOS platform, including new features for metadata handling, improved search functionality, and asynchronous file reading capabilities in the FileSystemDataVault. Key updates include the ability to add metadata to annotations, a summary row in time tracking, and improved slider functionality. The changelog reflects various bug fixes and performance improvements, particularly in dataset handling and user interface terminology adjustments. The transition to asynchronous file operations aims to optimize resource usage and enhance overall system responsiveness.

Changes

File Path Change Summary
CHANGELOG.unreleased.md Updated to include new features, changes, fixes, and improvements such as metadata for annotations, improved search, and asynchronous file reading capabilities.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/datavault/FileSystemDataVault.scala Introduced readAsync method for asynchronous file reading, updated readBytesLocal to handle multiple cases, and improved error handling in asynchronous context.

Assessment against linked issues

Objective Addressed Explanation
Async file reading implementation (#8010)

Possibly related PRs

Suggested labels

bug, frontend

Suggested reviewers

  • normanrz

Poem

In the meadow where bytes do play,
Asynchronous reads brighten the day.
Metadata blooms on annotations bright,
With sliders that dance, oh what a sight!
WEBKNOSSOS leaps with joy anew,
A rabbit's cheer for changes true! 🐇✨

Warning

Rate limit exceeded

@frcroth has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 1 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between f8f12c0 and 1966dc5.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f8f12c0 and 1966dc5.

📒 Files selected for processing (1)
  • CHANGELOG.unreleased.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.unreleased.md

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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 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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8dec578 and 28ddb66.

📒 Files selected for processing (2)
  • CHANGELOG.unreleased.md (1 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/datavault/FileSystemDataVault.scala (2 hunks)
🧰 Additional context used
🪛 LanguageTool
CHANGELOG.unreleased.md

[duplication] ~32-~32: Possible typo: you repeated a word
Context: ...calableminds/webknossos/pull/8126) ### Fixed - Fixed a bug during dataset upload in case the...

(ENGLISH_WORD_REPEAT_RULE)

🔇 Additional comments (2)
CHANGELOG.unreleased.md (1)

30-30: LGTM! Clear and concise changelog entry.

The changelog entry accurately describes the implementation of asynchronous file reading in the datastore filesystem, which aligns with the PR objectives.

webknossos-datastore/app/com/scalableminds/webknossos/datastore/datavault/FileSystemDataVault.scala (1)

42-69: Re-evaluate the use of asynchronous file reading for local files

While asynchronous I/O can improve throughput when handling many concurrent operations, it may introduce overhead and potentially degrade performance when reading local files, especially if the read operations are infrequent or involve small files.

Consider conducting thorough performance benchmarks to determine whether the asynchronous approach provides tangible benefits in this context. If it does not offer a significant improvement, it might be preferable to retain synchronous reading to avoid added complexity.

Copy link
Member

@fm3 fm3 left a comment

Choose a reason for hiding this comment

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

Alright, I did some more measuring and it looks like my numbers from yesterday were a little unfair, since they used parallel reading in the async case, while on master, everything was sequential (due to single thread + blocking).
In my new measurements from today, both implementations come in at 600–650ms.
So I’d say we should go for the async variant :)

@frcroth how do you feel about the suggestions by our AI reviewer? I guess it might make sense to add some validations for too-large files / ranges. Not sure about the suggested try/catch, but it does seem plausible too. What do you think?

@frcroth frcroth requested a review from fm3 November 13, 2024 10:03
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: 2

🧹 Outside diff range and nitpick comments (2)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/datavault/FileSystemDataVault.scala (2)

45-45: Use val instead of var for channel

The channel variable is only assigned once in the try block. Use val instead of var and move the declaration inside the try block.

Apply this diff:

-   var channel: AsynchronousFileChannel = null
    try {
-     channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)
+     val channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)

63-67: Improve error handling in CompletionHandler

The failed method should handle specific exceptions differently. For example, IOException might indicate a temporary failure that could be retried.

Apply this diff:

    override def failed(exc: Throwable, buffer: ByteBuffer): Unit = {
-     promise.failure(exc)
+     exc match {
+       case e: java.io.IOException =>
+         logger.warn(s"IO error reading file: ${path}", e)
+         promise.failure(e)
+       case e: java.nio.file.NoSuchFileException =>
+         logger.error(s"File not found: ${path}", e)
+         promise.failure(e)
+       case e =>
+         logger.error(s"Unexpected error reading file: ${path}", e)
+         promise.failure(e)
+     }
      channel.close()
    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 28ddb66 and f8f12c0.

📒 Files selected for processing (1)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/datavault/FileSystemDataVault.scala (2 hunks)
🔇 Additional comments (1)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/datavault/FileSystemDataVault.scala (1)

42-76: Verify performance impact of async implementation

Based on the PR comments, the async implementation shows slower performance in single-threaded scenarios. This needs investigation:

  1. The direct ByteBuffer allocation could be a bottleneck
  2. The Promise creation adds overhead
  3. Thread pool configuration might need tuning

Let's analyze the codebase for similar patterns:

Comment on lines +44 to +45
val buffer = ByteBuffer.allocateDirect(length)
var channel: AsynchronousFileChannel = null
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider reusing DirectByteBuffer for performance

Creating a direct ByteBuffer for each read operation is expensive. Consider implementing a buffer pool or using a ThreadLocal buffer for better performance.

Would you like me to provide an implementation of a buffer pool?

Comment on lines +35 to +36
val fileSize = Files.size(localPath)
readAsync(localPath, fileSize - length, length)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add bounds checking for SuffixLength case

The calculation fileSize - length could result in a negative position if length is greater than fileSize. Add validation to prevent this scenario.

Apply this diff:

  case SuffixLength(length) =>
    val fileSize = Files.size(localPath)
+   val adjustedLength = Math.min(length, Math.toIntExact(fileSize))
+   val position = Math.max(0, fileSize - adjustedLength)
-   readAsync(localPath, fileSize - length, length)
+   readAsync(localPath, position, adjustedLength)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
val fileSize = Files.size(localPath)
readAsync(localPath, fileSize - length, length)
val fileSize = Files.size(localPath)
val adjustedLength = Math.min(length, Math.toIntExact(fileSize))
val position = Math.max(0, fileSize - adjustedLength)
readAsync(localPath, position, adjustedLength)

@frcroth frcroth merged commit 825b1f8 into master Nov 13, 2024
3 checks passed
@frcroth frcroth deleted the async-file-vault branch November 13, 2024 10:49
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.

Async IO in FileSystemDataVault
3 participants