-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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 racing condition in BaseQueryRewriteContext #17124
Open
mingshl
wants to merge
2
commits into
opensearch-project:main
Choose a base branch
from
mingshl:fix-racing
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+200
−9
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
182 changes: 182 additions & 0 deletions
182
server/src/test/java/org/opensearch/index/query/BaseQueryRewriteContextTests.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,182 @@ | ||
/* | ||
* SPDX-License-Identifier: Apache-2.0 | ||
* | ||
* The OpenSearch Contributors require contributions made to | ||
* this file be licensed under the Apache-2.0 license or a | ||
* compatible open source license. | ||
*/ | ||
|
||
package org.opensearch.index.query; | ||
|
||
import org.opensearch.client.Client; | ||
import org.opensearch.common.util.concurrent.CountDown; | ||
import org.opensearch.core.action.ActionListener; | ||
import org.opensearch.core.common.io.stream.NamedWriteableRegistry; | ||
import org.opensearch.core.xcontent.NamedXContentRegistry; | ||
import org.junit.Before; | ||
import org.junit.Test; | ||
|
||
import java.util.concurrent.ExecutorService; | ||
import java.util.concurrent.Executors; | ||
import java.util.concurrent.TimeUnit; | ||
import java.util.concurrent.atomic.AtomicInteger; | ||
|
||
import static org.junit.Assert.assertEquals; | ||
import static org.junit.Assert.assertFalse; | ||
import static org.junit.Assert.assertTrue; | ||
import static org.junit.Assert.fail; | ||
import static org.mockito.Mockito.mock; | ||
|
||
/** | ||
* Unit tests for the BaseQueryRewriteContext class to verify the fix for racing conditions | ||
* in async action registration and execution. | ||
*/ | ||
public class BaseQueryRewriteContextTests { | ||
private BaseQueryRewriteContext context; | ||
private Client mockClient; | ||
|
||
@Before | ||
public void setUp() { | ||
mockClient = mock(Client.class); | ||
context = new BaseQueryRewriteContext( | ||
mock(NamedXContentRegistry.class), | ||
mock(NamedWriteableRegistry.class), | ||
mockClient, | ||
() -> System.currentTimeMillis() | ||
); | ||
} | ||
|
||
/** | ||
* Tests concurrent registration and execution of async actions. | ||
* | ||
* This test simulates a scenario where multiple threads are simultaneously | ||
* registering a large number of async actions, followed by a single execution | ||
* of all registered actions. It verifies that: | ||
* 1. All registered actions are executed correctly. | ||
* 2. The total number of executed actions matches the expected count. | ||
* 3. There are no remaining async actions after execution. | ||
* 4. No exceptions occur during the process, indicating thread-safety. | ||
* | ||
* @throws InterruptedException if the test is interrupted while waiting for threads to complete | ||
*/ | ||
@Test | ||
public void testConcurrentRegistrationAndExecution() throws InterruptedException { | ||
int numThreads = 10; | ||
int actionsPerThread = 1000; | ||
mingshl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
ExecutorService executorService = Executors.newFixedThreadPool(numThreads); | ||
CountDown startCountDown = new CountDown(1); | ||
CountDown endCountDown = new CountDown(numThreads); | ||
AtomicInteger totalExecutedActions = new AtomicInteger(0); | ||
|
||
for (int i = 0; i < numThreads; i++) { | ||
executorService.submit(() -> { | ||
while (startCountDown.isCountedDown() == false) { | ||
Thread.yield(); | ||
} | ||
for (int j = 0; j < actionsPerThread; j++) { | ||
context.registerAsyncAction((client, listener) -> { | ||
totalExecutedActions.incrementAndGet(); | ||
listener.onResponse(null); | ||
}); | ||
} | ||
endCountDown.countDown(); | ||
}); | ||
} | ||
|
||
startCountDown.countDown(); | ||
while (endCountDown.isCountedDown() == false) { | ||
Thread.yield(); | ||
} | ||
|
||
CountDown executionCountDown = new CountDown(1); | ||
context.executeAsyncActions(new ActionListener<Void>() { | ||
@Override | ||
public void onResponse(Void aVoid) { | ||
executionCountDown.countDown(); | ||
} | ||
|
||
@Override | ||
public void onFailure(Exception e) { | ||
fail("Execution failed: " + e.getMessage()); | ||
} | ||
}); | ||
|
||
while (executionCountDown.isCountedDown() == false) { | ||
Thread.yield(); | ||
} | ||
ensureAllActionsExecuted(); | ||
assertEquals(numThreads * actionsPerThread, totalExecutedActions.get()); | ||
assertFalse(context.hasAsyncActions()); | ||
|
||
executorService.shutdown(); | ||
assertTrue(executorService.awaitTermination(10, TimeUnit.SECONDS)); | ||
} | ||
|
||
/** | ||
* Tests the fix for the racing condition by simulating concurrent registration and execution. | ||
* | ||
* This test creates a scenario where multiple threads are simultaneously: | ||
* 1. Registering async actions | ||
* 2. Periodically executing the registered actions | ||
* | ||
* It verifies that: | ||
* 1. No exceptions occur during the process, indicating thread-safety. | ||
* 2. All actions are eventually executed, leaving no remaining async actions. | ||
* 3. The fix prevents any race conditions that could occur in this situation. | ||
* | ||
* @throws InterruptedException if the test is interrupted while waiting for threads to complete | ||
*/ | ||
@Test | ||
public void testRacingConditionFixed() throws InterruptedException { | ||
int numThreads = 5; | ||
int actionsPerThread = 1000; | ||
ExecutorService executorService = Executors.newFixedThreadPool(numThreads); | ||
CountDown startCountDown = new CountDown(1); | ||
CountDown endCountDown = new CountDown(numThreads); | ||
AtomicInteger totalExecutedActions = new AtomicInteger(0); | ||
|
||
for (int i = 0; i < numThreads; i++) { | ||
executorService.submit(() -> { | ||
while (startCountDown.isCountedDown() == false) { | ||
Thread.yield(); | ||
} | ||
for (int j = 0; j < actionsPerThread; j++) { | ||
context.registerAsyncAction((client, listener) -> { | ||
totalExecutedActions.incrementAndGet(); | ||
listener.onResponse(null); | ||
}); | ||
if (j % 100 == 0) { | ||
context.executeAsyncActions(ActionListener.wrap(v -> {}, e -> fail("Execution failed: " + e.getMessage()))); | ||
} | ||
} | ||
endCountDown.countDown(); | ||
}); | ||
} | ||
|
||
startCountDown.countDown(); | ||
while (endCountDown.isCountedDown() == false) { | ||
Thread.yield(); | ||
} | ||
|
||
// Final execution to ensure all remaining actions are processed | ||
context.executeAsyncActions(ActionListener.wrap(v -> {}, e -> fail("Final execution failed: " + e.getMessage()))); | ||
|
||
executorService.shutdown(); | ||
assertTrue(executorService.awaitTermination(30, TimeUnit.SECONDS)); // Increased timeout | ||
ensureAllActionsExecuted(); | ||
assertEquals(numThreads * actionsPerThread, totalExecutedActions.get()); | ||
assertFalse(context.hasAsyncActions()); | ||
} | ||
|
||
private void ensureAllActionsExecuted() { | ||
int maxAttempts = 10; | ||
for (int i = 0; i < maxAttempts && context.hasAsyncActions(); i++) { | ||
context.executeAsyncActions(ActionListener.wrap(v -> {}, e -> fail("Execution failed: " + e.getMessage()))); | ||
try { | ||
Thread.sleep(100); // Give some time for actions to complete | ||
} catch (InterruptedException e) { | ||
Thread.currentThread().interrupt(); | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think we need to copy the list here; this gives us no value over a
CopyOnWriteArrayList
which we wouldn't need the atomic reference for. Can't we simply just update the list in-place but wrapped in the atomic reference for thread safety? (CC @msfroh to confirm this suggestion):There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I tried, if not returning new list, I am having test failure, so it still cause racing condition during registration.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm... if we need to copy the whole list anyway, I think I like @dbwiddis's suggestion of using
CopyOnWriteArrayList
over myAtomicReference
suggestion.