test(persistence-jpa): 동시 claim 시험이 둘째 claim을 상한 두고 따로 기다린다 #64

Merged
donghyeon.kang merged 1 commits from test/jpa-claim-wait-order into main 2026-11-20 12:35:48 +00:00
@@ -23,16 +23,21 @@ import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.sql.DataSource;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@@ -55,6 +60,20 @@ import org.springframework.transaction.PlatformTransactionManager;
@Tag("jpa-contract")
class JpaDurableOperationStoreContractTest extends DurableOperationStoreContract {
/** How long the main thread waits for one worker's step or claim before it calls it stuck. */
private static final Duration STEP = Duration.ofSeconds(30);
/**
* How long worker-b may queue behind worker-a's open claim before the main thread lets worker-a
* commit. A third of the transaction timeout both workers run under, so a queued worker-b's claim
* still has time to finish once worker-a commits instead of being cancelled.
*/
private static final Duration WORKER_B_QUEUES_AT_MOST =
Duration.ofSeconds(SpringTransaction.DEFAULT_TIMEOUT_SECONDS / 3);
/** Longer than worker-b may queue and inside the transaction timeout, so worker-a commits. */
private static final Duration WORKER_A_HOLDS_AT_MOST = WORKER_B_QUEUES_AT_MOST.multipliedBy(2);
private static JpaPlatformContractSupport support;
private static AnnotationConfigApplicationContext context;
@@ -85,57 +104,102 @@ class JpaDurableOperationStoreContractTest extends DurableOperationStoreContract
}
@Test
@DisplayName("worker-a의 claim이 커밋 전이어도 worker-b는 그 잠금을 기다리지 않고 다른 operation을 가져간다")
void twoWorkersClaimingAtOnceTakeDifferentOperations() throws Exception {
// given
Instant now = Instant.parse("2026-08-25T09:00:00Z");
inTransaction(() -> store().submit(submission("op-1", "a", now)));
inTransaction(() -> store().submit(submission("op-2", "b", now.plusSeconds(1))));
CountDownLatch firstClaimed = new CountDownLatch(1);
CountDownLatch secondDone = new CountDownLatch(1);
ExecutorService pool = Executors.newSingleThreadExecutor();
CountDownLatch firstMayCommit = new CountDownLatch(1);
ExecutorService workers = Executors.newFixedThreadPool(2);
// when
List<String> claimed;
List<String> outcome;
try {
// The first claim holds its row lock until the second has claimed. With plain FOR UPDATE the
// second would block behind it; with no lock at all both would take op-1.
CompletableFuture<DurableOperationClaim> first =
CompletableFuture.supplyAsync(
// worker-a keeps its row lock, uncommitted, while worker-b claims on a thread, connection and
// transaction of its own. With plain FOR UPDATE worker-b queues behind that lock and takes
// op-2 once worker-a commits; with no lock clause it queues the same way and then takes op-1
// as well.
Future<DurableOperationClaim> first =
workers.submit(
() ->
inTransaction(
() -> {
DurableOperationClaim claim = claimNow("worker-a", now);
firstClaimed.countDown();
awaitOrFail(secondDone);
DurableOperationClaim claim;
try {
claim = claimNow("worker-a", now);
} finally {
// A failed claim surfaces through its future below, not as a wait.
firstClaimed.countDown();
}
// Longer than the main thread waits for worker-b below, so a worker-b
// stuck behind this lock is what the test sees; the main thread's finally
// releases this wait either way.
awaitOrFail(firstMayCommit, WORKER_A_HOLDS_AT_MOST);
return claim;
}),
pool);
awaitOrFail(firstClaimed);
DurableOperationClaim second = inTransaction(() -> claimNow("worker-b", now));
secondDone.countDown();
claimed =
}));
awaitOrFail(firstClaimed, STEP);
Future<DurableOperationClaim> second =
workers.submit(() -> inTransaction(() -> claimNow("worker-b", now)));
boolean secondClaimedWhileFirstHeld = isDoneWithin(second, WORKER_B_QUEUES_AT_MOST);
firstMayCommit.countDown();
outcome =
List.of(
first.get(30, TimeUnit.SECONDS).operationId().value(), second.operationId().value());
Stream.of(
resultOf(first, "worker-a's claim did not commit"),
resultOf(second, "worker-b's claim did not end once worker-a committed"))
.map(claim -> claim.operationId().value())
.sorted()
.collect(Collectors.joining(",")),
secondClaimedWhileFirstHeld
? "worker-b did not wait"
: "worker-b waited for worker-a's open claim");
} finally {
pool.shutdownNow();
firstMayCommit.countDown();
workers.shutdownNow();
}
// then
assertThat(claimed).containsExactlyInAnyOrder("op-1", "op-2");
assertThat(outcome)
.as("the operations the two workers took, and whether worker-b waited for worker-a")
.containsExactly("op-1,op-2", "worker-b did not wait");
}
private DurableOperationClaim claimNow(String workerId, Instant now) {
return store().claimNext(workerId, Duration.ofMinutes(2), now).orElseThrow();
}
private static void awaitOrFail(CountDownLatch latch) {
/** Whether the claim ends within {@code limit}; a claim that fails ends too. */
private static boolean isDoneWithin(Future<?> claim, Duration limit) throws InterruptedException {
try {
if (!latch.await(30, TimeUnit.SECONDS)) {
throw new IllegalStateException("the other claim did not arrive within 30 seconds");
claim.get(limit.toMillis(), TimeUnit.MILLISECONDS);
return true;
} catch (ExecutionException failed) {
return true;
} catch (TimeoutException stillWaiting) {
return false;
}
}
/** A worker's claim, or a failure that says what it was stuck on, after {@link #STEP}. */
private static <T> T resultOf(Future<T> claim, String stuck) throws Exception {
try {
return claim.get(STEP.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException timeout) {
throw new AssertionError(stuck, timeout);
}
}
/** Waits for the other worker's step; a step that never comes fails the test, not hangs it. */
private static void awaitOrFail(CountDownLatch latch, Duration limit) {
try {
if (!latch.await(limit.toMillis(), TimeUnit.MILLISECONDS)) {
throw new IllegalStateException("the other worker did not arrive within " + limit);
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted while waiting for the other claim", interrupted);
throw new IllegalStateException("interrupted waiting for the other worker", interrupted);
}
}