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

Fix race condition when loading the kryon subgraph parallelly just after VajramKryonGraph creation #330

Merged
merged 5 commits into from
Feb 12, 2025

Conversation

RamAnvesh
Copy link
Collaborator

@RamAnvesh RamAnvesh commented Feb 12, 2025

Closes #328

Summary by CodeRabbit

  • Chores

    • Updated project configuration to streamline the handling of build artifacts.
  • Refactor

    • Enhanced internal concurrency mechanisms and thread safety across key operations for improved performance and reliability.
  • Tests

    • Simplified test configurations by reducing unnecessary parameters.
    • Introduced benchmark tests and refined parallel execution checks to better assess overall performance.
    • Added parameterized tests for concurrent execution to identify race conditions.

Copy link

coderabbitai bot commented Feb 12, 2025

Warning

Rate limit exceeded

@RamAnvesh has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 12 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 c8ac5a7 and df002a2.

📒 Files selected for processing (1)
  • vajram/vajram-krystex/src/main/java/com/flipkart/krystal/vajramexecutor/krystex/VajramKryonGraph.java (5 hunks)

Walkthrough

This pull request primarily focuses on enhancing thread safety and streamlining executor configurations. The changes replace standard map implementations with concurrent variants in several registry classes, refactor method signatures and internal logic to support these concurrency improvements, and update test cases accordingly. Additionally, the PR updates the .gitignore file to exclude all bin directories recursively. Adjustments across test files further consolidate executor strategies and improve the structure for concurrent and performance benchmarking.

Changes

File(s) Change Summary
.gitignore Added rule **/bin/ to ignore any bin directories anywhere in the project.
krystex/.../LogicDefinitionRegistry.java
krystex/.../kryon/KryonDefinitionRegistry.java
Replaced HashMap and LinkedHashMap with ConcurrentHashMap to enhance thread safety for internal maps.
vajram/vajram-krystex/.../VajramKryonGraph.java Changed map implementations to ConcurrentHashMap; replaced _getVajramExecutionGraph with loadKryonSubgraph; updated dependency handling with additional method parameters.
vajram/vajram-krystex/.../KrystexVajramExecutorTest.java Removed KryonExecStrategy parameter from test method signatures and updated executor configurations to default to the BATCH strategy.
vajram/vajram-samples/.../FormulaTest.java Modified test lifecycle (replacing @AfterEach with @AfterAll and updating beforeAll and setUp); added new concurrency benchmark methods; refactored executor leasing.
vajram/vajram-samples/.../SplitAdderTest.java Added .singleThreadExecutor(executorLease.get()) configuration in benchmark tests to ensure dedicated execution.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant VajramKryonGraph
    participant DependencyManager

    Client->>VajramKryonGraph: getKryonId(vajramId)
    VajramKryonGraph->>VajramKryonGraph: loadKryonSubgraph(vajramId, loadingInProgress)
    VajramKryonGraph->>DependencyManager: Load dependencies for vajramId
    DependencyManager-->>VajramKryonGraph: Return kryon definitions
    VajramKryonGraph-->>Client: Return kryonId
Loading

Poem

I'm a bunny with a keen, quick hop,
In a world of threads, I never stop!
Maps now run concurrently with grace,
Tests streamlined—errors out of place.
Leaping through code changes with flair,
Celebrating improvements with a joyful air!
🐇💻 Happy coding!


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

@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 (9)
vajram/vajram-samples/src/test/java/com/flipkart/krystal/vajram/samples/calculator/adder/SplitAdderTest.java (1)

135-202: Consider adding warmup iterations to benchmark.

The benchmark configuration is well documented, but consider adding warmup iterations to ensure JVM optimizations are in place before measuring performance.

 @Test
 void vajram_benchmark() throws Exception {
+    // Warmup iterations
+    int warmupCount = 1000;
+    for (int i = 0; i < warmupCount; i++) {
+      splitAdd(i);
+      splitAddAsync(i).get();
+    }
+
     int loopCount = 50_000;
     long javaNativeTimeNs = javaMethodBenchmark(this::splitAdd, loopCount);
vajram/vajram-krystex/src/main/java/com/flipkart/krystal/vajramexecutor/krystex/VajramKryonGraph.java (2)

231-234: Inline call to loadKryonSubgraph.

This direct call forces a new subgraph load when kryonId is not found. The concurrency risk is mitigated by loadKryonSubgraph’s synchronization block, which is good. Confirm that re-entrant calls or repeated attempts do not cause performance bottlenecks.


244-279: Initialize and register subgraph logic.

This large block creates or retrieves several definitions (including input resolvers and dependencies). Given the complexity, consider splitting the logic into smaller, dedicated methods or at least adding more in-line documentation to clarify the flow. This helps with readability and testing.

vajram/vajram-samples/src/test/java/com/flipkart/krystal/vajram/samples/calculator/FormulaTest.java (6)

65-70: Pre-leasing executors in beforeAll().

Pre-leasing executor instances for tests can reduce overhead. Confirm that your test environment always has enough resources for the maximum lease requests. Or handle LeaseUnavailableException more insightfully if test concurrency scales up.


72-75: Release leases in afterAll().

Closing leases ensures tests do not hold resources indefinitely. Great practice. Consider adding a final null-check or a try/catch around the close for extra safety in the face of partial failures.


166-233: Parallel test to highlight race conditions in graph loading.

This parameterized test is a great approach for stress-testing concurrency. Check if multiple increments of Adder.CALL_COUNTER might occur out of order. Ensure that 1 second (succeedsWithin(ofSeconds(1))) is enough margin under heavy load or lower-end machines.


235-299: Benchmark test with up to a million executors.

The approach thoroughly tests concurrency, but it may be time-consuming. Confirm that it runs within acceptable time in your CI pipeline (or mark as a heavy test like you did with @Disabled). Also note that repeated executor creation can artificially inflate overhead times, so be sure it aligns with real-world usage patterns.


312-312: @Disabled("Long running benchmark (~9s)").

Clearly labeling problematic or time-consuming tests is a good practice. Consider a separate performance test profile rather than disabling if you want occasional performance checks.


568-568: Acquire executors from leased array.

Directly retrieving the executor from the lease array is straightforward. Just confirm that each index of EXECUTOR_LEASES is not null and properly closed if an error occurs. Another check for out-of-bounds usage might be prudent.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0a0f331 and 5050287.

📒 Files selected for processing (7)
  • .gitignore (1 hunks)
  • krystex/src/main/java/com/flipkart/krystal/krystex/LogicDefinitionRegistry.java (1 hunks)
  • krystex/src/main/java/com/flipkart/krystal/krystex/kryon/KryonDefinitionRegistry.java (1 hunks)
  • vajram/vajram-krystex/src/main/java/com/flipkart/krystal/vajramexecutor/krystex/VajramKryonGraph.java (5 hunks)
  • vajram/vajram-krystex/src/test/java/com/flipkart/krystal/vajramexecutor/krystex/KrystexVajramExecutorTest.java (25 hunks)
  • vajram/vajram-samples/src/test/java/com/flipkart/krystal/vajram/samples/calculator/FormulaTest.java (6 hunks)
  • vajram/vajram-samples/src/test/java/com/flipkart/krystal/vajram/samples/calculator/adder/SplitAdderTest.java (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🔇 Additional comments (16)
vajram/vajram-samples/src/test/java/com/flipkart/krystal/vajram/samples/calculator/adder/SplitAdderTest.java (2)

155-155: LGTM! The single-threaded executor configuration aligns with race condition fix.

The addition of .singleThreadExecutor(executorLease.get()) in both benchmark methods ensures consistent thread handling and helps prevent race conditions when loading the kryon subgraph.

Also applies to: 227-227


54-59: Verify executor pool configuration and resource cleanup.

The class properly manages thread executors through a shared pool with:

  • Fixed pool size of 4 threads
  • Proper leasing and releasing of executors
  • Cleanup in tearDown

However, let's verify if 4 threads are sufficient for the benchmark load:

Also applies to: 61-80

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Check for other benchmark configurations in the codebase
rg -A 5 "SingleThreadExecutorsPool.*Test" 

Length of output: 13360


Executor Pool Configuration Verified

  • The grep results show that many tests use a fixed 4-thread configuration via a call like new SingleThreadExecutorsPool("Test", 4), consistent with the implementation in SplitAdderTest.java.
  • In a few tests where heavier loads are anticipated (e.g., TooManyQualifiersTest, DoubleMinusOneTest, AddZeroTest), a dynamic thread count (using Runtime.getRuntime().availableProcessors()) is used. This indicates that the 4-thread setup in the benchmark tests is an intentional and context-specific choice.
  • Resource cleanup is managed via tearDown routines in these tests (as noted in similar test classes), ensuring that executors are properly released.

Based on the findings, the 4-thread configuration in SplitAdderTest is consistent with other tests for similar benchmark loads and there is no evidence of resource leaks or mismanagement.

vajram/vajram-krystex/src/main/java/com/flipkart/krystal/vajramexecutor/krystex/VajramKryonGraph.java (5)

84-85: Switch to ConcurrentHashMap for vajramDefinitions and vajramDataByClass.

Replacing these LinkedHashMap instances with ConcurrentHashMap improves thread safety. However, if your code relies on predictable iteration order (as LinkedHashMap guaranteed), be aware that ConcurrentHashMap does not preserve insertion order. Please verify that this change does not break any ordering assumptions in the code.


88-92: Adopting ConcurrentHashMap for vajramExecutables.

Similar to the above, this change enhances concurrency. Double-check if iteration order was previously significant for vajramExecutables. If so, consider adding a note or test to confirm correctness under the new map.


177-177: Confirm that concurrency concerns around computeDependantChain are handled.

Even though only one line was changed here, this method potentially interacts with concurrently modified data structures. Ensure that all relevant map and chain accesses remain thread-safe.


235-242: Introduce synchronization for loading subgraph.

The synchronized block on vajramExecutables helps avoid the race condition. Ensure the lock coverage is sufficient and that no other references to vajramExecutables can be mutated outside this synchronized context.


457-457: Switch to concurrent method for dependency definitions.

Using loadKryonSubgraph inside createKryonDefinitionsForDependencies is consistent with the new concurrency model. Re-check if subsequent calls (possibly from multiple threads) do not accidentally introduce cyclical dependencies or deadlocks. If needed, add tests verifying concurrency for multiple dependencies referencing each other.

Also applies to: 473-474

vajram/vajram-samples/src/test/java/com/flipkart/krystal/vajram/samples/calculator/FormulaTest.java (4)

12-12: Added imports for parallel execution and concurrency utilities.

The new imports (Arrays.stream, CompletableFuture.runAsync, IntStream.range, atomic.LongAdder, org.checkerframework.checker...) suggest an expanded focus on concurrency testing. No immediate issues spotted, but keep them consistent with any chosen concurrency model (synchronous vs async).

Also applies to: 15-15, 17-17, 48-48, 50-50


60-61: Added dynamic thread count and executor lease array.

Using Runtime.getRuntime().availableProcessors() to size the arrays is a good pragmatic approach. Make sure that code does not exceed these leased executors, especially if future concurrency expansions are planned.


84-85: Reusing a leased executor in setUp().

Instead of creating a new executor each time, you're using an existing lease. This is more resource-friendly. Just ensure that any test concurrency does not cause cross-test interference.


565-565: Refactored getExecutors(int count) method signature.

This method taps the pre-leased executors. If count > MAX_THREADS, be sure to handle the scenario gracefully or document the expectation that count won’t exceed the number of leases available.

krystex/src/main/java/com/flipkart/krystal/krystex/kryon/KryonDefinitionRegistry.java (1)

15-15: Switched from LinkedHashMap to ConcurrentHashMap in KryonDefinitionRegistry.

This change improves thread safety but removes guaranteed iteration order. Verify that any dependent code does not rely on insertion order, and consider a thread-safe test if you frequently modify kryonDefinitions.

Also applies to: 20-20

krystex/src/main/java/com/flipkart/krystal/krystex/LogicDefinitionRegistry.java (1)

11-16: LGTM! Thread-safe implementation using ConcurrentHashMap.

The change from standard HashMap to ConcurrentHashMap for all three maps (outputLogicDefinitions, resolverLogicDefinitions, multiResolverDefinitions) improves thread safety and addresses potential race conditions during parallel loading of the kryon subgraph.

vajram/vajram-krystex/src/test/java/com/flipkart/krystal/vajramexecutor/krystex/KrystexVajramExecutorTest.java (3)

138-138: LGTM! Test method signatures simplified.

The removal of KryonExecStrategy parameter from test methods and standardization to use BATCH strategy improves test maintainability while preserving test coverage.

Also applies to: 157-157, 177-177, 201-201, 230-230, 260-260, 292-292, 318-318, 355-355, 398-398


544-565: LGTM! Executor configuration enhanced with request level cache.

The changes improve thread safety by:

  1. Standardizing execution strategy to BATCH
  2. Adding request level cache with proper decorator configuration

873-875: LGTM! Test data provider simplified.

The executorConfigsToTest method has been appropriately simplified while maintaining test coverage for both DEPTH and BREADTH traversal strategies.

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

🧹 Nitpick comments (1)
vajram/vajram-krystex/src/main/java/com/flipkart/krystal/vajramexecutor/krystex/VajramKryonGraph.java (1)

235-281: Consider adding debug logging for better observability.

Adding debug logs for the loading states would help in troubleshooting any potential issues.

  private KryonId loadKryonSubgraph(VajramID vajramId, Map<VajramID, KryonId> loadingInProgress) {
    synchronized (vajramExecutables) {
+     log.debug("Loading kryon subgraph for vajramId: {}, loadingInProgress: {}", vajramId, loadingInProgress);
      KryonId kryonId;
      if ((kryonId = vajramExecutables.get(vajramId)) != null) {
+       log.debug("Found existing kryon: {} for vajramId: {}", kryonId, vajramId);
        return kryonId;
      } else if ((kryonId = loadingInProgress.get(vajramId)) != null) {
+       log.debug("Found kryon: {} in progress for vajramId: {}", kryonId, vajramId);
        return kryonId;
      }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5050287 and c8ac5a7.

📒 Files selected for processing (1)
  • vajram/vajram-krystex/src/main/java/com/flipkart/krystal/vajramexecutor/krystex/VajramKryonGraph.java (5 hunks)
🔇 Additional comments (4)
vajram/vajram-krystex/src/main/java/com/flipkart/krystal/vajramexecutor/krystex/VajramKryonGraph.java (4)

84-92: LGTM! Thread-safe map implementations.

The change from LinkedHashMap to ConcurrentHashMap for vajramDefinitions, vajramDataByClass, and vajramExecutables improves thread safety when accessing these maps concurrently.


226-233: LGTM! Improved thread safety in getKryonId.

The method now correctly handles concurrent access by using a new loadingInProgress map to track the loading state of kryons.


235-281: LGTM! Well-implemented synchronization for loading kryon subgraphs.

The new loadKryonSubgraph method effectively prevents race conditions by:

  1. Using synchronized block on vajramExecutables
  2. Checking both vajramExecutables and loadingInProgress maps
  3. Properly tracking loading state to prevent cycles

456-477: LGTM! Thread-safe dependency resolution.

The method now accepts a loadingInProgress map to track the loading state during recursive calls, ensuring thread safety when resolving dependencies.

@RamAnvesh RamAnvesh merged commit 95173dd into flipkart-incubator:main Feb 12, 2025
1 check passed
@RamAnvesh RamAnvesh deleted the issue328_copilotChat branch February 12, 2025 03:03
@RamAnvesh RamAnvesh changed the title Fix race condition when loading the kryon subgraph parallely just after VajramKryonGraph creation Fix race condition when loading the kryon subgraph parallelly just after VajramKryonGraph creation Feb 18, 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.

#KryonExecutorExecuteKryonRaceCondition
1 participant