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

Remove explicit returns #8205

Merged
merged 4 commits into from
Nov 20, 2024
Merged

Remove explicit returns #8205

merged 4 commits into from
Nov 20, 2024

Conversation

frcroth
Copy link
Member

@frcroth frcroth commented Nov 18, 2024

URL of deployed dev instance (used for testing):

  • https://___.webknossos.xyz

I did not find a linting option in scalac to find return statements (-Xlint:nonlocal-return seems to be something different). https://docs.scala-lang.org/overviews/compiler-options/index.html

Steps to test:

  • Generate ad-hoc meshes
  • Use the findData route
  • For the cum sum thing I am not sure how to test it.

TODOs:

  • ...

Issues:


(Please delete unneeded items, merge only when none are left open)

Summary by CodeRabbit

  • New Features

    • Enhanced the logic for checking segment IDs and finding data offsets, improving performance and readability.
    • Improved JSON parsing logic to handle incorrect order of data elements more effectively.
    • Updated data retrieval functions to return a magnification vector instead of a resolution vector.
  • Bug Fixes

    • Streamlined error handling and logging for the JSON parsing process to ensure accurate timing and error reporting.
  • Refactor

    • Simplified methods for better readability and maintainability across multiple services.
    • Renamed variables to reflect updated data structures in the data retrieval process.

@frcroth frcroth requested a review from fm3 November 18, 2024 13:54
@frcroth frcroth self-assigned this Nov 18, 2024
Copy link
Contributor

coderabbitai bot commented Nov 18, 2024

Walkthrough

The pull request introduces several modifications across four files. The AdHocMeshService.scala file refactors the subVolumeContainsSegmentId method for improved readability by replacing a nested loop with the exists method. The DataFinder.scala file's getExactDataOffset method is refactored to utilize an Iterator for better performance and clarity. In CumsumParser.scala, the parseImpl method is adjusted to maintain the FileReader open during recursive calls, enhancing JSON parsing logic. Additionally, the admin_rest_api.ts and layer_settings_tab.tsx files update return types and variable names to reflect changes in data structure, focusing on mag instead of resolution.

Changes

File Path Change Summary
.../AdHocMeshService.scala Refactored subVolumeContainsSegmentId method to use exists for segment ID checks.
.../DataFinder.scala Refactored getExactDataOffset to use Iterator and collectFirst for finding non-zero elements.
.../CumsumParser.scala Updated parseImpl to keep FileReader open during recursion; modified logging and return structure.
Method signatures updated for parseImpl and parse without parameter changes.
frontend/javascripts/admin/admin_rest_api.ts Updated return types of findDataPositionForLayer and findDataPositionForVolumeTracing to include mag instead of resolution.
frontend/javascripts/oxalis/view/left-border-tabs/layer_settings_tab.tsx Renamed variable foundResolution to foundMag in handleFindData method to reflect new data structure.

Assessment against linked issues

Objective Addressed Explanation
Get rid of return statements in Scala (#6356)

Possibly related PRs

Suggested labels

bug, enhancement, backend

Suggested reviewers

  • daniel-wer
  • MichaelBuessemeyer

🐇 In the meadow, changes bloom bright,
Refactoring code, a joyful sight!
With exists and Iterator in play,
We hop through logic, clear as day.
Parsing JSON with grace and flair,
A cleaner path, we gladly share! 🌼

Warning

Rate limit exceeded

@frcroth has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 24 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 fa83ccd and 6e579fa.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fa83ccd and 6e579fa.

📒 Files selected for processing (1)
  • frontend/javascripts/oxalis/view/left-border-tabs/layer_settings_tab.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/javascripts/oxalis/view/left-border-tabs/layer_settings_tab.tsx

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
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

🧹 Outside diff range and nitpick comments (4)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/DataFinder.scala (2)

9-17: LGTM! Consider adding documentation for the voxel offset calculation.

The Iterator.tabulate implementation is clean and functional. However, the voxel offset calculation logic could benefit from a brief comment explaining the dimensional scaling.

 private def getExactDataOffset(data: Array[Byte], bytesPerElement: Int): Vec3Int = {
   val bucketLength = DataLayer.bucketLength

+  // Calculate voxel offsets in 3D space:
+  // x: scaled by bytesPerElement
+  // y: scaled by bytesPerElement * bucketLength (row stride)
+  // z: scaled by bytesPerElement * bucketLength^2 (slice stride)
   Iterator
     .tabulate(bucketLength, bucketLength, bucketLength) { (z, y, x) =>

18-24: Consider simplifying the nested flatten calls.

The current implementation works well but could be more concise by using flatten.flatten.

     }
-    .flatten
-    .flatten
+    .flatten.flatten
     .collectFirst {

Alternatively, you could use Iterator.tabulate's single-dimensional form with index division/modulo for a potentially more efficient approach:

Iterator
  .tabulate(bucketLength * bucketLength * bucketLength) { i =>
    val x = i % bucketLength
    val y = (i / bucketLength) % bucketLength
    val z = i / (bucketLength * bucketLength)
    val scaledX = x * bytesPerElement
    val scaledY = y * bytesPerElement * bucketLength
    val scaledZ = z * bytesPerElement * bucketLength * bucketLength
    (x, y, z, scaledX + scaledY + scaledZ)
  }
  .collectFirst {
    case (x, y, z, voxelOffset) if data.slice(voxelOffset, voxelOffset + bytesPerElement).exists(_ != 0) =>
      Vec3Int(x, y, z)
  }
  .getOrElse(Vec3Int.zeros)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/storage/CumsumParser.scala (1)

54-60: Consider extracting timing logic for better separation of concerns.

While the timing measurement is now correctly placed after parsing completion, consider extracting it to a separate wrapper method for better separation of concerns.

Here's a suggested refactoring:

  def parse(f: File, maxReaderRange: Long): BoundingBoxCache =
-   parseImpl(f, maxReaderRange, List(), System.currentTimeMillis())
+   withTiming("Cumsum parsing") {
+     parseImpl(f, maxReaderRange, List())
+   }

+ private def withTiming[T](operation: String)(block: => T): T = {
+   val start = System.currentTimeMillis()
+   val result = block
+   val end = System.currentTimeMillis()
+   logger.info(s"$operation took ${end - start} ms")
+   result
+ }

  def parseImpl(f: File,
                maxReaderRange: Long,
-               initialBoundingBoxList: List[(Long, Long, Long, Long, Long, Long)],
-               start: Long): BoundingBoxCache = {
+               initialBoundingBoxList: List[(Long, Long, Long, Long, Long, Long)]): BoundingBoxCache = {
    // ... existing implementation ...
-   val end = System.currentTimeMillis()
-   logger.info(s"Cumsum parsing took ${end - start} ms")
    new BoundingBoxCache(cache,
      BoundingBoxFinder(positionSets._1, positionSets._2, positionSets._3, minBoundingBox),
      maxReaderRange)

This change:

  1. Separates timing concerns from parsing logic
  2. Makes timing reusable across other operations
  3. Maintains functional style without explicit returns
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/AdHocMeshService.scala (1)

136-148: Consider improving readability with better formatting and documentation

While the implementation is correct, consider these readability improvements:

 def subVolumeContainsSegmentId[T](
     data: Array[T],
     dataDimensions: Vec3Int,
     boundingBox: BoundingBox,
     segmentId: T
 ): Boolean = {
+  // Check if the segment exists within the bounding box by calculating
+  // the linear voxel offset for each position in 3D space
   boundingBox.topLeft.x until boundingBox.bottomRight.x exists { x =>
     boundingBox.topLeft.y until boundingBox.bottomRight.y exists { y =>
       boundingBox.topLeft.z until boundingBox.bottomRight.z exists { z =>
+        // Convert 3D coordinates to linear array index
         val voxelOffset = x + y * dataDimensions.x + z * dataDimensions.x * dataDimensions.y
         data(voxelOffset) == segmentId
       }
     }
   }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ec3015f and d0f10fc.

📒 Files selected for processing (3)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/AdHocMeshService.scala (1 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/DataFinder.scala (1 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/storage/CumsumParser.scala (1 hunks)
🔇 Additional comments (2)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/storage/CumsumParser.scala (1)

51-52: LGTM! Successfully eliminated explicit return.

The changes effectively remove the explicit return statement while maintaining the correct control flow. This aligns well with Scala's best practices and fixes the NonLocalReturn concerns mentioned in issue #6356.

webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/AdHocMeshService.scala (1)

136-148: Successfully removed explicit returns using idiomatic Scala!

The refactoring of subVolumeContainsSegmentId effectively eliminates explicit returns by using exists, which aligns perfectly with the PR's objective. The implementation maintains the same functionality while being more idiomatic Scala.

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.

Very nice! Cumsum parsing and AdHoc meshing LGTM and appear to work :) Unfortunately, the findData route now always fails for me. I tested with the color layers of several datasets including l4_sample. Did it work for you? If so, maybe we can debug this together on my laptop 🤷

The CI rule is not that important IMO. Then let’s take care of this when doing reviews :)

@frcroth frcroth requested a review from fm3 November 20, 2024 12:23
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.

🎉

cc @dieknolle3333 note that this change renames resolution to mag in the scope of the “find data” functionality, just so you’re not confused about potential merge conflicts in #8168 .

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

🧹 Outside diff range and nitpick comments (1)
frontend/javascripts/oxalis/view/left-border-tabs/layer_settings_tab.tsx (1)

Line range hint 1054-1076: Bug: Incorrect variable reference in condition.

There's a potential bug in the error handling condition:

if ((!position || !resolution) && volume.fallbackLayer) {

The variable resolution is undefined as it was renamed to mag. This condition should be updated.

Apply this fix:

-if ((!position || !resolution) && volume.fallbackLayer) {
+if ((!position || !mag) && volume.fallbackLayer) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d0f10fc and fa83ccd.

📒 Files selected for processing (2)
  • frontend/javascripts/admin/admin_rest_api.ts (2 hunks)
  • frontend/javascripts/oxalis/view/left-border-tabs/layer_settings_tab.tsx (3 hunks)
🔇 Additional comments (4)
frontend/javascripts/oxalis/view/left-border-tabs/layer_settings_tab.tsx (2)

1029-1032: Variable rename from foundResolution to foundMag for better terminology consistency.

The change aligns with the PR's objective to use more accurate terminology. The term mag (magnification) is more precise than resolution in this context.


1043-1051: Verify the destructuring of mag property.

The code now expects a mag property from the API responses of both findDataPositionForVolumeTracing and findDataPositionForLayer. Ensure that these API endpoints have been updated to return the mag property instead of resolution.

frontend/javascripts/admin/admin_rest_api.ts (2)

1549-1558: Verify API consumers are updated for the resolution → mag change.

The change from resolution to mag in the return type and implementation looks good. Please ensure all consumers of this API are updated to handle the new property name.


1567-1574: LGTM! Consistent with findDataPositionForLayer changes.

The change from resolution to mag is consistently applied here, maintaining parallel structure with the findDataPositionForLayer function.

@frcroth frcroth merged commit 3c7700c into master Nov 20, 2024
3 checks passed
@frcroth frcroth deleted the remove-returns branch November 20, 2024 13:00
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.

Get rid of return statements in scala
2 participants