Skip to content

Implement SIMD Optimization for Vector Classes #106#131

Open
Patti88 wants to merge 6 commits intomainfrom
Implement-SIMD-Optimization-for-Vector-Classes-106
Open

Implement SIMD Optimization for Vector Classes #106#131
Patti88 wants to merge 6 commits intomainfrom
Implement-SIMD-Optimization-for-Vector-Classes-106

Conversation

@Patti88
Copy link
Copy Markdown
Contributor

@Patti88 Patti88 commented Feb 22, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a resilient server communication component that automatically retries data requests when temporary busy conditions occur, ensuring a smoother experience.
    • Enhanced the retry logic with dynamic delay adjustments to better manage high-demand scenarios and improve overall reliability.
    • Added a configuration class for retry parameters, providing default settings for maximum attempts and delays.
    • Added a new exception class for better error handling during busy server conditions.
  • Bug Fixes

    • Implemented handling for server busy conditions through a dedicated exception.
  • Tests

    • Implemented comprehensive tests to validate the improved handling of transient busy periods and confirm successful recovery after retries.
    • Added tests for scenarios involving server busy conditions and successful retries.
    • Enhanced test coverage for the retry logic with various conditions and edge cases.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Feb 22, 2025

Walkthrough

This pull request introduces a new ServerClient class that implements a fetchData() method to retrieve data from a server while utilizing an enhanced retry mechanism. The retry logic incorporates exponential backoff with jitter, and a new exception class, ServerBusyException, signals when the server is busy. Additionally, new test cases have been added to verify behavior under retry exhaustion and successful retrieval after multiple attempts. The RetryExecutor class has been enhanced with a builder pattern for more flexible configuration.

Changes

Files Change Summary
src/main/java/org/fungover/breeze/client/ServerClient.java Added the ServerClient class with two constructors and a fetchData() method that utilizes the retry mechanism.
src/main/java/org/fungover/breeze/control/RetryExecutor.java Enhanced the retry mechanism with a builder pattern and added the executeWithRetry() method for predefined settings.
src/main/java/org/fungover/breeze/control/ServerBusyException.java Introduced the ServerBusyException class to handle busy server conditions.
src/main/java/org/fungover/breeze/control/RetryConfig.java Added RetryConfig class with constants for default retry settings.
src/test/java/org/fungover/breeze/control/RetryExecutorTest.java Added comprehensive tests for the RetryExecutor class to validate retry logic and exception handling.
src/test/java/org/fungover/breeze/client/ServerClientTest.java Introduced tests for the ServerClient class to verify successful and failed data fetch scenarios.
pom.xml Added maven-compiler-plugin and maven-surefire-plugin with configurations for Java 23 and module inclusion.
src/main/java/org/fungover/breeze/vector/Vector4.java Refactored Vector4 from a record to a final class, utilizing an array for internal representation and enhancing arithmetic operations.
src/test/java/org/fungover/breeze/vector/Vector4Test.java Enhanced documentation and error handling in tests for the Vector4 class.

Possibly related PRs

Suggested labels

feature, minor

Suggested reviewers

  • AntonGrubisic
  • Daymaare

Poem

I’m a rabbit in the code, hopping with delight,
Jitter and retry keep our calls light,
When the server is busy, I bounce with a cheer,
Data arrives fresh, now that retry is here,
My digital hops celebrate changes so bright! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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
Copy Markdown
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 (2)
src/test/java/org/fungover/breeze/control/RetryExecutorTest.java (2)

33-33: Translate Swedish comment to English for consistency.

The comment "Vi förväntar oss att ett undantag kastas eftersom alla retries misslyckas" should be in English.

-        // Vi förväntar oss att ett undantag kastas eftersom alla retries misslyckas
+        // We expect an exception to be thrown since all retries fail

73-79: Improve test state management.

Using a mutable array to track attempts is not a clean testing practice. Consider using an AtomicInteger for better thread safety and cleaner code.

-        final int[] attempts = {0};
+        final AtomicInteger attempts = new AtomicInteger(0);
         String result = RetryExecutor.executeWithRetry(() -> {
-            if (attempts[0]++ < 2) throw new ServerBusyException();
+            if (attempts.getAndIncrement() < 2) throw new ServerBusyException();
-            return "Success after " + attempts[0] + " tries";
+            return "Success after " + attempts.get() + " tries";
         });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a3cc1f5 and 63c9d4a.

📒 Files selected for processing (4)
  • src/main/java/org/fungover/breeze/client/ServerClient.java (1 hunks)
  • src/main/java/org/fungover/breeze/control/RetryExecutor.java (4 hunks)
  • src/main/java/org/fungover/breeze/control/ServerBusyException.java (1 hunks)
  • src/test/java/org/fungover/breeze/control/RetryExecutorTest.java (2 hunks)
🔇 Additional comments (3)
src/main/java/org/fungover/breeze/control/ServerBusyException.java (1)

4-12: LGTM! Well-structured exception class.

The class follows Java exception class conventions and provides clear, descriptive messages.

src/main/java/org/fungover/breeze/control/RetryExecutor.java (2)

83-83: LGTM! Good implementation of exponential backoff with jitter.

The jitter implementation helps prevent the "thundering herd" problem in distributed systems.


1-1: PR title does not match the implemented changes.

The PR title mentions "SIMD Optimization for Vector Classes" but the changes implement retry logic with exponential backoff. Please update the PR title to accurately reflect the changes.

Likely an incorrect or invalid review comment.

Comment on lines +7 to +15
public String fetchData() throws Exception {
return RetryExecutor.executeWithRetry(() -> {
// Add actual server call logic here
if (Math.random() < 0.7) {
throw new ServerBusyException();
}
return "Sample Data";
});
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve testability and configurability of the server busy simulation.

The current implementation has several areas for improvement:

  1. Using Math.random() makes testing unpredictable.
  2. The probability threshold (0.7) is hard-coded.

Consider this refactoring:

 public class ServerClient {
+    private final double busyProbability;
+    private final Random random;
+
+    public ServerClient(double busyProbability) {
+        this.busyProbability = busyProbability;
+        this.random = new Random();
+    }
+
     public String fetchData() throws Exception {
         return RetryExecutor.executeWithRetry(() -> {
             // Add actual server call logic here
-            if (Math.random() < 0.7) {
+            if (random.nextDouble() < busyProbability) {
                 throw new ServerBusyException();
             }
             return "Sample Data";
         });
     }
 }
📝 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
public String fetchData() throws Exception {
return RetryExecutor.executeWithRetry(() -> {
// Add actual server call logic here
if (Math.random() < 0.7) {
throw new ServerBusyException();
}
return "Sample Data";
});
}
public class ServerClient {
private final double busyProbability;
private final Random random;
public ServerClient(double busyProbability) {
this.busyProbability = busyProbability;
this.random = new Random();
}
public String fetchData() throws Exception {
return RetryExecutor.executeWithRetry(() -> {
// Add actual server call logic here
if (random.nextDouble() < busyProbability) {
throw new ServerBusyException();
}
return "Sample Data";
});
}
}

Comment on lines +202 to +213
public static <T> T executeWithRetry(RiskyOperation<T> operation) throws Exception {
return builder()
.maxAttempts(5)
.exponentialBackoff(1000, 16000) // 1s, 2s, 4s, 8s, 16s
.retryOn(ServerBusyException.class)
.onExhaustion(ex -> {
System.out.println("Final attempt failed after exponential backoff");
return true;
})
.build()
.execute(operation);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve configurability and logging in executeWithRetry.

The method has hard-coded values and uses System.out for logging.

+    private static final Logger logger = LoggerFactory.getLogger(RetryExecutor.class);
+
     public static <T> T executeWithRetry(RiskyOperation<T> operation) throws Exception {
         return builder()
-                .maxAttempts(5)
-                .exponentialBackoff(1000, 16000) // 1s, 2s, 4s, 8s, 16s
+                .maxAttempts(RetryConfig.DEFAULT_MAX_ATTEMPTS)
+                .exponentialBackoff(RetryConfig.DEFAULT_INITIAL_DELAY, RetryConfig.DEFAULT_MAX_DELAY)
                 .retryOn(ServerBusyException.class)
                 .onExhaustion(ex -> {
-                    System.out.println("Final attempt failed after exponential backoff");
+                    logger.warn("Final attempt failed after exponential backoff", ex);
                     return true;
                 })
                 .build()
                 .execute(operation);
     }
📝 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
public static <T> T executeWithRetry(RiskyOperation<T> operation) throws Exception {
return builder()
.maxAttempts(5)
.exponentialBackoff(1000, 16000) // 1s, 2s, 4s, 8s, 16s
.retryOn(ServerBusyException.class)
.onExhaustion(ex -> {
System.out.println("Final attempt failed after exponential backoff");
return true;
})
.build()
.execute(operation);
}
private static final Logger logger = LoggerFactory.getLogger(RetryExecutor.class);
public static <T> T executeWithRetry(RiskyOperation<T> operation) throws Exception {
return builder()
.maxAttempts(RetryConfig.DEFAULT_MAX_ATTEMPTS)
.exponentialBackoff(RetryConfig.DEFAULT_INITIAL_DELAY, RetryConfig.DEFAULT_MAX_DELAY)
.retryOn(ServerBusyException.class)
.onExhaustion(ex -> {
logger.warn("Final attempt failed after exponential backoff", ex);
return true;
})
.build()
.execute(operation);
}

Copy link
Copy Markdown
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)
src/main/java/org/fungover/breeze/control/RetryExecutor.java (3)

33-35: Avoid wrapping non-retryable exceptions with IllegalArgumentException.

Throwing an IllegalArgumentException for non-retryable exceptions can obscure their real cause. Consider either rethrowing the original exception or introducing a more descriptive custom exception explaining it’s not retryable.

- throw new IllegalArgumentException("Operation failed", ex);
+ throw ex; // or wrap with a custom NonRetryableOperationException

47-50: Ensure the final return statement is reachable or remove as dead code.

Because the loop always throws if retries are exhausted, the return null; statement at line 50 is effectively unreachable. Remove this statement or justify under which condition it should return null.


105-116: Allow external configuration for default retry parameters.

Hard-coded defaults (5 attempts, 1s to 16s delay range, ServerBusyException as the retry type) can be limiting for broader usage. Offer a method or builder config to override these so users can provide different defaults without duplicating code.

src/main/java/org/fungover/breeze/client/ServerClient.java (1)

25-30: Use realistic server call logic or make it configurable for testing.

The placeholder "Sample Data" return is fine for demonstrations. However, consider injecting a service or callback for actual data retrieval. This makes testing and production usage more flexible.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 63c9d4a and ef59548.

📒 Files selected for processing (4)
  • src/main/java/org/fungover/breeze/client/ServerClient.java (1 hunks)
  • src/main/java/org/fungover/breeze/control/RetryConfig.java (1 hunks)
  • src/main/java/org/fungover/breeze/control/RetryExecutor.java (1 hunks)
  • src/test/java/org/fungover/breeze/control/RetryExecutorTest.java (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/main/java/org/fungover/breeze/control/RetryConfig.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/test/java/org/fungover/breeze/control/RetryExecutorTest.java
🔇 Additional comments (2)
src/main/java/org/fungover/breeze/control/RetryExecutor.java (1)

30-45: Use a dedicated logging framework instead of System.out/err.

These lines repeatedly use System.out.println() and System.err.println(). Past review comments have already suggested replacing them with a dedicated logging framework (e.g., Logger). This approach centralizes log management, honors log levels, and avoids mixing application output with console output.

src/main/java/org/fungover/breeze/client/ServerClient.java (1)

16-19: Validate busyProbability range.

Currently, there is no check to ensure busyProbability is between 0 and 1. A busyProbability value outside [0, 1] could lead to unexpected behavior in attemptFetchData().

Signed-off-by: Patti88 <patricia.nilsson@iths.se>
Signed-off-by: Patti88 <patricia.nilsson@iths.se>
Copy link
Copy Markdown
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: 3

🧹 Nitpick comments (12)
src/main/java/org/fungover/breeze/client/ServerClient.java (2)

27-29: Catch narrower exceptions or rethrow for clarity.

Currently, fetchData() can throw any Exception, which may complicate error handling in higher-level code. Consider narrowing or rethrowing exceptions to indicate specific failure modes (e.g., IOException, ServerBusyException, etc.).


31-36: Use descriptive return values or domain objects.

Returning a generic "Sample Data" string might be fine for testing, but in production code, returning a domain-specific object or a well-defined result type can improve clarity and maintainability.

src/test/java/org/fungover/breeze/client/ServerClientTest.java (1)

9-12: Expand coverage for different probabilities.

Current test covers only busyProbability=0.0. Add tests for a mid-range probability (e.g. 0.5) to confirm partial server-busy scenarios and the retry mechanism’s behavior.

Do you want me to generate stubs for additional test coverage?

src/main/java/org/fungover/breeze/control/RetryExecutor.java (4)

45-47: Replace standard output with a structured logger.

Using System.out.printf for logging can become unwieldy in production. A logging framework offers better configurability, severity levels, and message formatting.


49-60: Consistent error handling strategy.

Exceptions that are not assignable to retryOn escalate as IllegalArgumentException. This can be confusing if the real exception type is not closely related. Consider a more descriptive exception or a separate path for non-retryable errors.


71-73: Make backoff parameters configurable.

The 1.5 multiplier and 500 jitter are hard-coded. Exposing them as configurable parameters (e.g., via the Builder) can improve flexibility and help tune retry behavior.


128-139: Promote reuse of the builder for custom scenarios.

executeWithRetry provides a convenient default but might encourage usage without deeper configuration. Encourage advanced users to leverage the builder for more nuanced backoff settings and custom exceptions.

src/test/java/org/fungover/breeze/control/RetryExecutorTest.java (5)

43-60: Consider enhancing exhaustion handler verification.

While the test verifies that the handler is called, it could be improved by also verifying the exception details passed to the handler.

 @Test
 void executeShouldCallOnExhaustionHandler() {
     AtomicBoolean handlerCalled = new AtomicBoolean(false);
+    AtomicReference<Throwable> caughtException = new AtomicReference<>();
     RetryExecutor executor = RetryExecutor.builder()
             .maxAttempts(1)
             .onExhaustion(ex -> {
                 handlerCalled.set(true);
+                caughtException.set(ex);
                 return true;
             })
             .build();

     assertThrows(RetryExecutor.RetryExhaustedException.class, () ->
             executor.execute(() -> {
                 throw new ServerBusyException();
             })
     );
     assertTrue(handlerCalled.get());
+    assertNotNull(caughtException.get());
+    assertTrue(caughtException.get() instanceof ServerBusyException);
 }

62-64: Consider adding edge cases to parameterized test.

The test could be more comprehensive by including edge cases such as 0 (immediate success) and values greater than TEST_MAX_ATTEMPTS.

 @ParameterizedTest
-@ValueSource(ints = {1, 2, 3})
+@ValueSource(ints = {0, 1, 2, 3, 4})
 void executeShouldRetryCorrectNumberOfTimes(int failedAttempts) throws Exception {

98-105: Consider verifying specific default configuration values.

The test could be more thorough by verifying that specific default values (max attempts, delays, etc.) are being used.


107-115: Make the assertion more precise.

Using contains for string comparison is less precise than an exact match.

-        assertTrue(result.contains("Success after 3"));
+        assertEquals("Success after 3 tries", result);

117-134: Consider making the timing test more robust.

Time-based tests can be flaky. Consider:

  1. Using a clock abstraction for more reliable testing
  2. Adding some margin of error in the assertion
  3. Mocking the delay mechanism
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5dea4f8 and 7b7693f.

📒 Files selected for processing (4)
  • src/main/java/org/fungover/breeze/client/ServerClient.java (1 hunks)
  • src/main/java/org/fungover/breeze/control/RetryExecutor.java (1 hunks)
  • src/test/java/org/fungover/breeze/client/ServerClientTest.java (1 hunks)
  • src/test/java/org/fungover/breeze/control/RetryExecutorTest.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: builds
🔇 Additional comments (6)
src/main/java/org/fungover/breeze/client/ServerClient.java (3)

10-14: Consider thread-safety if multiple threads call this class.

Storing a single Random field in a multi-threaded environment can lead to concurrency issues, especially with non-thread-safe random number generators. If you anticipate multi-thread use, consider ThreadLocalRandom or synchronizing access to the Random instance.


15-17: Good use of constructor chaining.

Neatly delegates to the parameterized constructor, ensuring consistent initialization.


19-25: Validate random usage outside test contexts.

Using SecureRandom by default can be more costly than standard Random; verify that the cryptographic strength is actually needed for production. If not, consider Random or ThreadLocalRandom for performance.

src/test/java/org/fungover/breeze/control/RetryExecutorTest.java (3)

13-24: LGTM! Well-structured test class setup.

The helper method and constants are well-designed, making the tests more maintainable and readable.


26-31: LGTM! Clear and focused test case.

The test effectively verifies the basic success case without retries.


1-135: PR title does not match the changes.

The PR title mentions "SIMD Optimization for Vector Classes" but the changes implement retry logic. Please update the PR title to accurately reflect the changes.

Comment on lines +14 to +18
@Test
void testFailedFetch() {
ServerClient client = new ServerClient(1.0, new SecureRandom());
assertThrows(Exception.class, client::fetchData);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Test for exact exception type.

Rather than assertThrows(Exception.class), consider using assertThrows(ServerBusyException.class). This ensures the test checks the correct exception precisely, improving clarity.

-assertThrows(Exception.class, client::fetchData);
+assertThrows(ServerBusyException.class, client::fetchData);
📝 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
@Test
void testFailedFetch() {
ServerClient client = new ServerClient(1.0, new SecureRandom());
assertThrows(Exception.class, client::fetchData);
}
@Test
void testFailedFetch() {
ServerClient client = new ServerClient(1.0, new SecureRandom());
assertThrows(ServerBusyException.class, client::fetchData);
}

Comment on lines +31 to +41
while (attemptCount < maxAttempts) {
try {
logAttempt(attemptCount + 1);
return operation.run();
} catch (Exception ex) {
handleOperationError(ex, attemptCount, currentDelay);
attemptCount++;
currentDelay = calculateNextDelay(currentDelay);
Thread.sleep(currentDelay);
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Handle thread interruption gracefully.

When using Thread.sleep(currentDelay) in a loop, consider catching InterruptedException specifically and either restore the interrupted state or decide whether to break out of retries to avoid unwanted infinite retries in interrupted threads.

try {
    Thread.sleep(currentDelay);
} catch (InterruptedException ie) {
+    Thread.currentThread().interrupt();
    throw ie; 
}
📝 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
while (attemptCount < maxAttempts) {
try {
logAttempt(attemptCount + 1);
return operation.run();
} catch (Exception ex) {
handleOperationError(ex, attemptCount, currentDelay);
attemptCount++;
currentDelay = calculateNextDelay(currentDelay);
Thread.sleep(currentDelay);
}
}
while (attemptCount < maxAttempts) {
try {
logAttempt(attemptCount + 1);
return operation.run();
} catch (Exception ex) {
handleOperationError(ex, attemptCount, currentDelay);
attemptCount++;
currentDelay = calculateNextDelay(currentDelay);
try {
Thread.sleep(currentDelay);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw ie;
}
}
}

Comment on lines +88 to +96
@Test
void executeShouldNotRetryNonRetryableExceptions() {
RetryExecutor executor = createDefaultExecutor(ServerBusyException.class);
assertThrows(IllegalArgumentException.class, () ->
executor.execute(() -> {
throw new IOException("Non-retryable error");
})
);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect exception type in test.

The test is configured to retry on ServerBusyException but throws IOException while asserting IllegalArgumentException. This appears to be incorrect.

 @Test
 void executeShouldNotRetryNonRetryableExceptions() {
     RetryExecutor executor = createDefaultExecutor(ServerBusyException.class);
     assertThrows(IllegalArgumentException.class, () ->
             executor.execute(() -> {
-                throw new IOException("Non-retryable error");
+                throw new IllegalArgumentException("Non-retryable error");
             })
     );
 }
📝 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
@Test
void executeShouldNotRetryNonRetryableExceptions() {
RetryExecutor executor = createDefaultExecutor(ServerBusyException.class);
assertThrows(IllegalArgumentException.class, () ->
executor.execute(() -> {
throw new IOException("Non-retryable error");
})
);
}
@Test
void executeShouldNotRetryNonRetryableExceptions() {
RetryExecutor executor = createDefaultExecutor(ServerBusyException.class);
assertThrows(IllegalArgumentException.class, () ->
executor.execute(() -> {
throw new IllegalArgumentException("Non-retryable error");
})
);
}

Stelle83
Stelle83 previously approved these changes Feb 24, 2025
Copy link
Copy Markdown
Contributor

@Stelle83 Stelle83 left a comment

Choose a reason for hiding this comment

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

Consider adding more descriptive documentation/comments for better understanding of the methods and their purposes.

Overall, the changes improve code robustness, readability, and maintainability.

import java.util.function.Function;

public class RetryExecutor {
private static final SecureRandom JITTER = new SecureRandom();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Good use of SecureRandom for cryptographic randomness!

Copy link
Copy Markdown
Contributor

@kappsegla kappsegla left a comment

Choose a reason for hiding this comment

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

@Patti88 It looks like there are 2 deleted files in this PR? They should probably not be deleted? Also the title of the pull request doesn't seem to have anything to do with the actual implementation?

@sonarqubecloud
Copy link
Copy Markdown

Copy link
Copy Markdown
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 (3)
pom.xml (1)

68-78: Ensure compatibility with incubator modules and Java 23.

While specifying <maven.compiler.release>23</maven.compiler.release> and adding --add-modules=jdk.incubator.vector is valid for the latest JDK preview or incubator features, it may introduce compatibility issues or require a specific JDK build. Please confirm your build environment supports Java 23 and the incubator module.

Would you like a script to verify the installed JDK version and confirm that incubator modules are supported in your CI environment?

src/test/java/org/fungover/breeze/vector/Vector4Test.java (1)

49-59: Consider parameterizing repeated test patterns.

Several tests (e.g., verifying components after arithmetic, checking null inputs) follow the same structure, differing primarily by operation type. Parameterized tests or a shared helper method could reduce duplication and streamline additions of future vector operations.

Also applies to: 72-86

src/main/java/org/fungover/breeze/vector/Vector4.java (1)

68-73: Eliminate repeated vector species initialization.

You repeatedly retrieve FloatVector.SPECIES_128 across several methods. Consider extracting it into a private static final field, e.g.:

+ private static final VectorSpecies<Float> SPECIES = FloatVector.SPECIES_128;

This reduces duplication and clarifies the chosen vector species.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b7693f and f129d90.

📒 Files selected for processing (3)
  • pom.xml (1 hunks)
  • src/main/java/org/fungover/breeze/vector/Vector4.java (1 hunks)
  • src/test/java/org/fungover/breeze/vector/Vector4Test.java (10 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: builds
🔇 Additional comments (3)
pom.xml (1)

79-88: Validate test builds with the new module.

Including the same incubator module argument in the Surefire plugin is correct to ensure tests can compile and run. Double-check that your test coverage or other testing frameworks (e.g., Failsafe if you have integration tests) include the same module arguments for consistency throughout your build.

src/test/java/org/fungover/breeze/vector/Vector4Test.java (1)

16-18: Good documentation on the 'add' tests and accurate assertions.

These Javadoc comments concisely explain the test intention, and the assertThat(...).isCloseTo(...) checks are correctly tuned for floating-point comparisons. This clarity is commendable.

Also applies to: 26-29

src/main/java/org/fungover/breeze/vector/Vector4.java (1)

123-124: Reassess floating-point threshold for zero check.

Using Math.abs(d) < 1e-6f may classify very small but non-zero values as zero. If small divisors are legitimate, this threshold could unintentionally raise an exception. Consider making the epsilon configurable or using an exact check when that better aligns with your requirements.

@Patti88 Patti88 requested a review from kappsegla February 24, 2025 14:59
Copy link
Copy Markdown

@AfagMamedova AfagMamedova left a comment

Choose a reason for hiding this comment

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

Hej!
Jag tycker det här ser bra ut och det är kul att du försöker göra koden snabbare med SIMD.
Tydlig och snygg kod, lätt att följa. Bra idé att försöka göra beräkningar snabbare.
Kanske lägga till en alternativ lösning för datorer som inte kan köra SIMD?
Några tester vore bra, så man ser att allt fungerar som det ska.

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.

4 participants