From e5558f25e0e46a41c3c840b83bbf97275aae57c2 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 20 Nov 2026 19:21:41 +0900 Subject: [PATCH] =?UTF-8?q?test(persistence-jpa):=20=EB=8F=99=EC=8B=9C=20c?= =?UTF-8?q?laim=20=EC=8B=9C=ED=97=98=EC=9D=B4=20=EB=91=98=EC=A7=B8=20claim?= =?UTF-8?q?=EC=9D=84=20=EC=83=81=ED=95=9C=20=EB=91=90=EA=B3=A0=20=EB=94=B0?= =?UTF-8?q?=EB=A1=9C=20=EA=B8=B0=EB=8B=A4=EB=A6=B0=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JpaDurableOperationStoreContractTest의 twoWorkersClaimingAtOnce...는 둘째 claim을 메인 스레드에서 상한 없이 돌린다. 잠금 절을 plain FOR UPDATE로 바꾸면 둘째 claim이 첫째의 행 잠금 뒤에서 막힌다. 시험은 30초 뒤 트랜잭션 제한 시간(SpringTransaction 기본 30초)에 걸려 「persistence failure after the transaction deadline passed」로 끝난다. 잠금 절을 지워도 같은 메시지다. 실패 메시지가 원인(막힘, 같은 행)을 말하지 않는다. PostgreSqlRecipientLeaseFencingIntegrationTest의 동시 claim 시험과 같은 순서로 바꾼다. - worker-a는 자기 스레드·트랜잭션에서 claim하고 커밋 전에 최대 20초 기다린다. 메인은 worker-b의 claim을 다른 스레드에서 10초까지 기다린다. worker-a가 더 오래 기다리므로 막힌 쪽이 worker-b로 보인다. - 10초는 트랜잭션 제한 30초의 3분의 1이다(DEFAULT_TIMEOUT_SECONDS / 3). 막혔던 worker-b가 worker-a 커밋 뒤에도 claim을 끝낼 시간이 남는다. worker-b를 30초 기다리면 worker-b의 문장이 제한 시간에 취소되어, 변이가 단언 대신 같은 예외로 끝났다(아래 검증). - 그다음 worker-a를 커밋시키고 두 claim을 30초 상한으로 받는다. - then은 「두 worker가 가진 operation」과 「worker-b가 기다렸는가」를 한 번에 본다. plain FOR UPDATE면 op-1,op-2와 「waited」가, 잠금 절이 없으면 op-1,op-1과 「waited」가 나온다. - 고친 메서드에만 한국어 DisplayName을 단다(규칙 2). 버린 안: - worker-b가 기다렸는지만 보는 안. 잠금 절이 없을 때와 plain FOR UPDATE를 같은 메시지로 보여 줘 원인을 가르지 못한다. - 이 시험의 TransactionPort에 더 긴 제한 시간을 주는 안. 같은 클래스의 다른 시험까지 운영과 다른 제한 시간에서 돌게 된다. 위험: 정상 경로의 시간은 그대로다(claim 둘, 1초 미만). 변이에서는 worker-b를 10초 기다린 뒤에 끝난다. 부하로 정상 claim이 10초를 넘기면 「waited」로 실패한다. 잠금 절이 없을 때 op-1,op-1이 나오는 것은 PostgreSQL READ COMMITTED가 기다린 UPDATE를 같은 행에 다시 적용하기 때문이다. 검증(desktop, jpaPlatformContractTest lane, --rerun --no-build-cache, nice 19): - 고치기 전 시험(기준 0ecfb56f) + 잠금 절 없음 / plain FOR UPDATE: 둘 다 30.4초 뒤 PersistenceFailureException 「persistence failure after the transaction deadline passed」로 실패. - 첫 고침(worker-b 30초 대기, 트리 9b7eeda9): lane 전체 rc=0, 고친 시험 5회 통과. 두 변이는 30.4·30.5초 뒤 ExecutionException(같은 deadline 예외)으로 실패해 단언 메시지가 나오지 않았다. 리뷰가 짚은 대로다. - 고친 트리 1a1dcc5f(worker-b 10초 대기, 기준 0ecfb56f 위. 이 커밋과 persistence-jpa 파일이 같다): - 고친 시험 5회: 모두 통과(0.4~0.5초). - 잠금 절 없음: 10.4초 뒤 실패. 실제 [op-1,op-1, worker-b waited for worker-a's open claim]. - plain FOR UPDATE: 10.4초 뒤 실패. 실제 [op-1,op-2, worker-b waited for worker-a's open claim]. - 변이 뒤 worktree가 그 트리로 돌아온 것을 git write-tree로 봤다. - 클래스 전체(--tests JpaDurableOperationStoreContractTest) 10회: 모두 통과(34개, 실패·skip 0). - PR head 트리 dfdd428d(main 782e93ff 위): scripts/verify.sh leaf :adapter:outbound:persistence-jpa rc=0(683개, skip 0), pr --no-cache rc=0(7269개, skip 35), main rc=0(1980개, skip 19, jpaPlatformContractTest 실행). --- .../JpaDurableOperationStoreContractTest.java | 112 ++++++++++++++---- 1 file changed, 88 insertions(+), 24 deletions(-) diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java index 22fa4f0f..93ca166f 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java @@ -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 claimed; + List 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 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 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 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 resultOf(Future 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); } } -- 2.54.0