From a42a59baedbb949d61412ec9f5d4d714f0b27e9f Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 09:13:41 +0900 Subject: [PATCH 1/3] =?UTF-8?q?test(lock):=20=ED=8F=AC=ED=8A=B8=20?= =?UTF-8?q?=EA=B3=84=EC=95=BD=20=EC=8B=9C=ED=97=98=EC=9D=98=20=EB=8C=80?= =?UTF-8?q?=EA=B8=B0=EC=97=90=20=EC=83=81=ED=95=9C=EC=9D=84=20=EB=91=90?= =?UTF-8?q?=EA=B3=A0=20=EC=8B=A4=ED=8C=A8=ED=95=A0=20=EC=88=98=20=EC=97=86?= =?UTF-8?q?=EB=8A=94=20=EC=88=9C=EC=84=9C=20=EC=8B=9C=ED=97=98=EC=9D=84=20?= =?UTF-8?q?=EC=A7=80=EC=9A=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DistributedLockPortContractTest의 tryFinallyReleaseAfterWorkDemonstratesD4Ordering은 시험 안의 리스트에 두 문자열을 넣고 그 순서만 단언한다. main 코드가 끼지 않아 어떤 구현에서도 실패할 수 없다. 같은 파일의 대기 두 곳도 결과를 보지 않는다. held.await()에는 상한이 없어 holder 스레드가 lock을 못 잡으면 시험이 CI timeout까지 멈춘다. holder.join(1_000)은 스레드가 끝났는지 보지 않는다. 순서 시험과 그 설명 주석을 지우고, 커밋 뒤 finally에서 release하는 예시는 DistributedLockPort.tryAcquire Javadoc에 코드 블록으로 옮긴다. 검증할 main 코드가 없는 약속이라 시험이 아니라 포트 문서가 정본이다. 두 대기는 HOLDER_WAIT(5초) 상한을 두고 held.await 반환값이 true인지, join 뒤 holder.isAlive()가 false인지 단언한다. 실패하면 .as(...) 문구가 어느 대기에서 멈췄는지 말한다. 앞의 단언이 실패해도 holder가 release.await()에 남지 않게 release.countDown()은 finally에서 부른다. 위험: 5초는 SHORT_WAIT(50ms)의 100배라 green 경로에서는 닿지 않는다. join 상한을 1초에서 5초로 늘렸지만 스레드가 끝나면 바로 돌아오므로 green 시간은 그대로다. main 코드는 Javadoc 말고 바꾸지 않았다. Refs: REV-BE-0042 --- .../application/lock/DistributedLockPort.java | 12 +++ .../lock/DistributedLockPortContractTest.java | 76 ++++++------------- 2 files changed, 37 insertions(+), 51 deletions(-) diff --git a/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java b/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java index 61b666d3..7efe5614 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java @@ -17,6 +17,18 @@ public interface DistributedLockPort { * waitTime}. Returns a {@link DistributedLock} whose {@code close()} releases the lock — call it * only after the protected transaction commits. See README for lease-expiry-on-release behaviour. * + *

Release in {@code finally} after the transaction call returns, never inside its callback — + * releasing before the commit lets the next holder read state that is not yet visible: + * + *

{@code
+   * DistributedLock lock = port.tryAcquire(key, waitTime, leaseTtl);
+   * try {
+   *   tx.inWrite(() -> work()); // commits before it returns
+   * } finally {
+   *   lock.close(); // released after the commit
+   * }
+   * }
+ * * @param key the lock identifier; must be non-null and non-blank * @param waitTime the maximum time to wait for the lock; must be finite and positive * @param leaseTtl the maximum duration the lock may be held before the adapter auto-expires it diff --git a/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java b/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java index b1c1f0ab..dff5fe3b 100644 --- a/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java +++ b/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java @@ -5,9 +5,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.application.lock.testkit.InMemoryDistributedLock; import java.time.Duration; -import java.util.ArrayList; -import java.util.List; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; /** @@ -20,8 +19,6 @@ import org.junit.jupiter.api.Test; *
    *
  1. {@code tryAcquire} returns a non-null handle. *
  2. {@code close()} releases the lock so a subsequent acquire on the same key succeeds. - *
  3. A try-finally release pattern demonstrates the D4 ordering (work inside try, release in - * finally after work completes). *
  4. A second attempt while the key is held times out and throws {@link * LockAcquisitionTimeoutException} carrying the right key. *
@@ -30,6 +27,9 @@ class DistributedLockPortContractTest { private static final Duration SHORT_WAIT = Duration.ofMillis(50); private static final Duration LEASE_TTL = Duration.ofSeconds(30); + // Bounds each wait on the holder thread: far above SHORT_WAIT, so only a holder that never + // acquires or never ends reaches it, and the test then fails instead of hanging. + private static final Duration HOLDER_WAIT = Duration.ofSeconds(5); // ----------------------------------------------------------------------- // Tests @@ -57,38 +57,6 @@ class DistributedLockPortContractTest { second.close(); } - /** - * Demonstrates the D4 ordering invariant: the lock handle is released AFTER the protected work - * completes (represented here by a side-effect list), not before. - * - *

Canonical pattern (from port Javadoc): - * - *

-   *   DistributedLock lock = port.tryAcquire(key, waitTime, leaseTtl);
-   *   try {
-   *       txPort.inWrite(() -> { ... protected work ... });  // commit returns here
-   *   } finally {
-   *       lock.close();                                       // release AFTER commit
-   *   }
-   * 
- */ - @Test - void tryFinallyReleaseAfterWorkDemonstratesD4Ordering() { - DistributedLockPort port = new InMemoryDistributedLock(); - List events = new ArrayList<>(); - - DistributedLock lock = port.tryAcquire("payment/99", SHORT_WAIT, LEASE_TTL); - try { - events.add("work-done"); // represents: tx.inWrite(() -> { ... }) - } finally { - lock.close(); // release AFTER work (D4 ordering) - events.add("lock-released"); - } - - // work must complete before release - assertThat(events).containsExactly("work-done", "lock-released"); - } - /** * While the lock is held, a second attempt on the same key must time out and throw {@link * LockAcquisitionTimeoutException} carrying the correct key. @@ -99,7 +67,7 @@ class DistributedLockPortContractTest { @Test void timeoutWhileKeyIsHeldThrowsLockAcquisitionTimeoutExceptionWithCorrectKey() throws InterruptedException { - + // given InMemoryDistributedLock port = new InMemoryDistributedLock(); String key = "inventory/sku-99"; @@ -122,21 +90,27 @@ class DistributedLockPortContractTest { }, "lock-holder"); holder.start(); + try { + assertThat(held.await(HOLDER_WAIT.toMillis(), TimeUnit.MILLISECONDS)) + .as("holder thread acquired the lock within %s", HOLDER_WAIT) + .isTrue(); - held.await(); // wait for the holder thread to acquire the lock - - // Now try to acquire from the main thread — must time out - assertThatThrownBy(() -> port.tryAcquire(key, SHORT_WAIT, LEASE_TTL)) - .isInstanceOf(LockAcquisitionTimeoutException.class) - .satisfies( - ex -> { - LockAcquisitionTimeoutException timeout = (LockAcquisitionTimeoutException) ex; - assertThat(timeout.key()).isEqualTo(key); - assertThat(timeout.waitTime()).isEqualTo(SHORT_WAIT); - }); - - release.countDown(); // unblock the holder thread - holder.join(1_000); // wait for holder to finish cleanly + // when & then: a second acquire from the main thread must time out + assertThatThrownBy(() -> port.tryAcquire(key, SHORT_WAIT, LEASE_TTL)) + .isInstanceOf(LockAcquisitionTimeoutException.class) + .satisfies( + ex -> { + LockAcquisitionTimeoutException timeout = (LockAcquisitionTimeoutException) ex; + assertThat(timeout.key()).isEqualTo(key); + assertThat(timeout.waitTime()).isEqualTo(SHORT_WAIT); + }); + } finally { + release.countDown(); // unblock the holder thread even when an assertion above fails + } + holder.join(HOLDER_WAIT.toMillis()); + assertThat(holder.isAlive()) + .as("holder thread released the lock and ended within %s", HOLDER_WAIT) + .isFalse(); } @Test -- 2.54.0 From 0790eceed29be784d5de15f6267474ba049bff97 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 12:33:51 +0900 Subject: [PATCH 2/3] =?UTF-8?q?fix(lock):=20=EB=9D=BD=20=ED=8F=AC=ED=8A=B8?= =?UTF-8?q?=20=EC=98=88=EC=8B=9C=EB=A5=BC=20=EB=A3=A8=ED=8A=B8=20=ED=8A=B8?= =?UTF-8?q?=EB=9E=9C=EC=9E=AD=EC=85=98=EC=9C=BC=EB=A1=9C=20=EB=B0=94?= =?UTF-8?q?=EA=BE=B8=EA=B3=A0=20=EC=8B=9C=ED=97=98=EC=9D=B4=20=ED=95=B4?= =?UTF-8?q?=EC=A0=9C=EB=A5=BC=20=EB=8B=A8=EC=96=B8=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 포트 Javadoc 예시와 README의 「올바른 패턴」은 inWrite가 돌아오면 커밋됐다고 말한다. inWrite는 REQUIRED라 바깥 트랜잭션(inbox handler 등)이 있으면 합류만 하고 돌아오고, finally가 커밋 전에 락을 푼다. finally는 실패·롤백·결과 불명 때도 돌므로 "released after the commit"도 거짓이다. 다음 보유자가 "아직 안 보이는 상태를 읽는다"는 설명은 뜻이 반대다. 또 계약 시험은 holder 스레드가 끝났는지만 봐서, close를 지우거나 close가 예외를 던져도 통과한다. 예시를 inRootWrite로 바꾼다. 바깥 트랜잭션을 거절하고 물리 커밋 뒤에만 정상 반환하는 포트 동작은 이것뿐이다. inNew로 우회하는 안은 버린다. outbox·감사·보상 전용이고 바깥 작업과 따로 커밋된다. 시험은 설명만 줄이는 안 대신 holder의 예외 없음과 같은 키의 재획득을 단언한다. 위험·한계: 동작 코드는 바뀌지 않는다. 이미 트랜잭션 안인 호출자가 새 예시를 따르면 NestedRootTransactionRejectedException으로 실패하므로 그 모양을 쓸 수 없다고 문서에 적는다. 검증: 이 트리의 실험과 verify 결과는 PR #95 본문 「리뷰 반영」에 적는다. Refs: REV-BE-0042 --- src/application/core/README.md | 4 +++- .../application/lock/DistributedLockPort.java | 19 +++++++++++-------- .../lock/DistributedLockPortContractTest.java | 12 +++++++++--- 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/src/application/core/README.md b/src/application/core/README.md index d6001379..791f2a32 100644 --- a/src/application/core/README.md +++ b/src/application/core/README.md @@ -554,7 +554,9 @@ application 계층은 락 획득/해제 계약만 알고, 실제 구현은 adapt - **트랜잭션 커밋 순서 불변식(D4)**: 반환된 핸들은 보호 작업의 DB 트랜잭션이 **커밋된 후에만** 해제해야 한다. 트랜잭션 안(커밋 전)에서 해제하면 lost-update 경합이 생긴다 — 두 번째 스레드가 락을 얻어, 첫 트랜잭션의 쓰기가 DB 에 보이기 전에 자신의 read-modify-write 를 시작한다. - - 올바른 패턴: `tryAcquire` → `try { txPort.inWrite(...) } finally { lock.close() }`(커밋 후 해제). + - 올바른 패턴: 트랜잭션 밖에서 `tryAcquire` → `try { txPort.inRootWrite(...) } finally { lock.close() }`. + 호출이 끝나면 커밋·롤백·결과 불명 어느 쪽이든 해제한다. `inWrite`는 바깥 트랜잭션에 합류해 커밋 전에 + 돌아올 수 있어 쓰지 않는다. 이미 트랜잭션 안이면(inbox handler 등) 이 패턴을 쓸 수 없다. - 금지된 역순: `inWrite` 콜백 안에서 `lock.close()`(커밋 전 해제 → 다른 스레드가 stale 상태를 본다). - **효율 락이지 정합성 락이 아니다(D6)**: 이 락은 경합·불필요한 재시도를 줄이는 *효율* 장치다. 정합성(중복·충돌 쓰기 방지)은 여전히 DB 제약(유니크 인덱스·낙관적 동시성)이 강제한다. 이 락 diff --git a/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java b/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java index 7efe5614..714019ec 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java @@ -6,26 +6,29 @@ import java.time.Duration; * Outbound port for acquiring a distributed lock — the only dependency the application layer may * use for coordinated mutual exclusion (no lock client / SQL imports in use cases). {@code * tryAcquire} is a try-lock with a finite {@code waitTime} and a crash-safety {@code leaseTtl}; the - * handle must be released only after the protected transaction commits. This is an efficiency lock, - * not a correctness lock (DB constraints still guard correctness). See README for the full - * rationale. + * handle must be released only after the protected transaction ends, so never before its commit. + * This is an efficiency lock, not a correctness lock (DB constraints still guard correctness). See + * README for the full rationale. */ public interface DistributedLockPort { /** * Attempts to acquire the distributed lock identified by {@code key}, blocking for at most {@code * waitTime}. Returns a {@link DistributedLock} whose {@code close()} releases the lock — call it - * only after the protected transaction commits. See README for lease-expiry-on-release behaviour. + * only after the protected transaction ends. See README for lease-expiry-on-release behaviour. * - *

Release in {@code finally} after the transaction call returns, never inside its callback — - * releasing before the commit lets the next holder read state that is not yet visible: + *

Acquire outside any transaction and release in {@code finally}, also when the transaction + * fails, but never inside its callback — releasing before the commit lets the next holder act on + * stale state, before this transaction's writes are visible. A caller already in a transaction, + * such as an inbox handler, cannot use this shape: {@code inWrite} would join that transaction + * and return before its commit. * *

{@code
    * DistributedLock lock = port.tryAcquire(key, waitTime, leaseTtl);
    * try {
-   *   tx.inWrite(() -> work()); // commits before it returns
+   *   tx.inRootWrite(() -> work()); // refuses an ambient transaction; returns after the commit
    * } finally {
-   *   lock.close(); // released after the commit
+   *   lock.close(); // the transaction call ended: committed, rolled back, or outcome unknown
    * }
    * }
* diff --git a/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java b/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java index dff5fe3b..b9d62e27 100644 --- a/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java +++ b/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java @@ -1,12 +1,14 @@ package dev.caskeleton.application.lock; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.application.lock.testkit.InMemoryDistributedLock; import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; /** @@ -74,6 +76,7 @@ class DistributedLockPortContractTest { // Hold the lock in a background thread until the main thread's test completes. CountDownLatch held = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); + AtomicReference holderError = new AtomicReference<>(); Thread holder = new Thread( @@ -89,6 +92,7 @@ class DistributedLockPortContractTest { } }, "lock-holder"); + holder.setUncaughtExceptionHandler((thread, error) -> holderError.set(error)); holder.start(); try { assertThat(held.await(HOLDER_WAIT.toMillis(), TimeUnit.MILLISECONDS)) @@ -108,9 +112,11 @@ class DistributedLockPortContractTest { release.countDown(); // unblock the holder thread even when an assertion above fails } holder.join(HOLDER_WAIT.toMillis()); - assertThat(holder.isAlive()) - .as("holder thread released the lock and ended within %s", HOLDER_WAIT) - .isFalse(); + assertThat(holder.isAlive()).as("holder thread ended within %s", HOLDER_WAIT).isFalse(); + assertThat(holderError.get()).as("holder thread ended without an error").isNull(); + assertThatCode(() -> port.tryAcquire(key, SHORT_WAIT, LEASE_TTL).close()) + .as("holder thread released the lock") + .doesNotThrowAnyException(); } @Test -- 2.54.0 From fde7423d8cd3e70d4d0ba3bff5a35439dcc0fc60 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 23:38:13 +0900 Subject: [PATCH 3/3] =?UTF-8?q?fix(lock):=20=EA=B2=B0=EA=B3=BC=20=EB=B6=88?= =?UTF-8?q?=EB=AA=85=20=EB=95=8C=EC=9D=98=20=EB=9D=BD=20=ED=95=B4=EC=A0=9C?= =?UTF-8?q?=EC=99=80=20holder=20=ED=9A=8D=EB=93=9D=20=EC=8B=A4=ED=8C=A8=20?= =?UTF-8?q?=EC=9B=90=EC=9D=B8=EC=9D=84=20=EB=B0=9D=ED=9E=8C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 포트 Javadoc은 해제가 커밋보다 앞서는 일이 없다고 말한다. COMMIT 응답을 잃으면 finally가 락을 푼 뒤에 커밋이 보일 수 있어 거짓이다. 또 「커밋 후에만」이라는 핸들 규칙과 실패 때도 해제하라는 포트 규칙이 부딪혀 읽힌다. 시험은 holder가 락을 못 잡으면 5초 뒤 시간 초과만 말하고 새 예외 handler 때문에 원인 예외를 잃는다. 해제 기준을 트랜잭션 호출의 끝으로 쓰고, 「커밋 후에만」은 성공 경로의 말이라고 밝힌다. 시험은 시간 초과 단언보다 holder의 예외를 먼저 단언한다. handler가 latch도 내리는 안은 버린다. 락을 잡았다는 신호의 뜻이 흐려진다. 위험·한계: 동작 코드는 바뀌지 않는다. DistributedLock Javadoc과 persistence-jpa README, 바꾸지 않은 README 줄의 「커밋 후에만」은 이 PR 범위 밖이라 남는다. 실제 PostgreSQL로 해제 뒤 커밋을 재현하지 않았다. 검증: 발견별 변이·탐침 8건을 돌린다. 결과와 verify는 PR #95 본문 「리뷰 반영」에 적는다. Refs: REV-BE-0042 --- src/application/core/README.md | 5 +++-- .../application/lock/DistributedLockPort.java | 18 +++++++++++------- .../lock/DistributedLockPortContractTest.java | 7 ++++--- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/application/core/README.md b/src/application/core/README.md index 791f2a32..c8bfc15d 100644 --- a/src/application/core/README.md +++ b/src/application/core/README.md @@ -555,8 +555,9 @@ application 계층은 락 획득/해제 계약만 알고, 실제 구현은 adapt 해제해야 한다. 트랜잭션 안(커밋 전)에서 해제하면 lost-update 경합이 생긴다 — 두 번째 스레드가 락을 얻어, 첫 트랜잭션의 쓰기가 DB 에 보이기 전에 자신의 read-modify-write 를 시작한다. - 올바른 패턴: 트랜잭션 밖에서 `tryAcquire` → `try { txPort.inRootWrite(...) } finally { lock.close() }`. - 호출이 끝나면 커밋·롤백·결과 불명 어느 쪽이든 해제한다. `inWrite`는 바깥 트랜잭션에 합류해 커밋 전에 - 돌아올 수 있어 쓰지 않는다. 이미 트랜잭션 안이면(inbox handler 등) 이 패턴을 쓸 수 없다. + 호출이 끝나면 커밋·롤백·결과 불명 어느 쪽이든 해제한다. 이 문서의 「커밋 후에만」은 성공 경로의 말이다. + 결과 불명이면 해제 뒤에 커밋이 보일 수 있고 그 틈은 DB 제약이 막는다(D6). `inWrite`는 바깥 트랜잭션에 + 합류해 커밋 전에 돌아올 수 있어 쓰지 않는다. 이미 트랜잭션 안이면(inbox handler 등) 이 패턴을 쓸 수 없다. - 금지된 역순: `inWrite` 콜백 안에서 `lock.close()`(커밋 전 해제 → 다른 스레드가 stale 상태를 본다). - **효율 락이지 정합성 락이 아니다(D6)**: 이 락은 경합·불필요한 재시도를 줄이는 *효율* 장치다. 정합성(중복·충돌 쓰기 방지)은 여전히 DB 제약(유니크 인덱스·낙관적 동시성)이 강제한다. 이 락 diff --git a/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java b/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java index 714019ec..d47be2e8 100644 --- a/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java +++ b/src/application/core/src/main/java/dev/caskeleton/application/lock/DistributedLockPort.java @@ -6,22 +6,26 @@ import java.time.Duration; * Outbound port for acquiring a distributed lock — the only dependency the application layer may * use for coordinated mutual exclusion (no lock client / SQL imports in use cases). {@code * tryAcquire} is a try-lock with a finite {@code waitTime} and a crash-safety {@code leaseTtl}; the - * handle must be released only after the protected transaction ends, so never before its commit. - * This is an efficiency lock, not a correctness lock (DB constraints still guard correctness). See - * README for the full rationale. + * handle must be released only after the protected transaction call ends, never inside its + * callback. This is an efficiency lock, not a correctness lock (DB constraints still guard + * correctness). See README for the full rationale. */ public interface DistributedLockPort { /** * Attempts to acquire the distributed lock identified by {@code key}, blocking for at most {@code * waitTime}. Returns a {@link DistributedLock} whose {@code close()} releases the lock — call it - * only after the protected transaction ends. See README for lease-expiry-on-release behaviour. + * only after the protected transaction call ends. See README for lease-expiry-on-release + * behaviour. * *

Acquire outside any transaction and release in {@code finally}, also when the transaction * fails, but never inside its callback — releasing before the commit lets the next holder act on - * stale state, before this transaction's writes are visible. A caller already in a transaction, - * such as an inbox handler, cannot use this shape: {@code inWrite} would join that transaction - * and return before its commit. + * stale state, before this transaction's writes are visible. The after-commit rule of {@link + * DistributedLock#close()} describes the success path: on rollback or an unknown outcome release + * anyway. After an unknown outcome the commit may become visible after the release, and only DB + * constraints guard that window. A caller already in a transaction, such as an inbox handler, + * cannot use this shape: {@code inWrite} would join that transaction and return before its + * commit. * *

{@code
    * DistributedLock lock = port.tryAcquire(key, waitTime, leaseTtl);
diff --git a/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java b/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java
index b9d62e27..47441cb0 100644
--- a/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java
+++ b/src/application/core/src/test/java/dev/caskeleton/application/lock/DistributedLockPortContractTest.java
@@ -95,9 +95,10 @@ class DistributedLockPortContractTest {
     holder.setUncaughtExceptionHandler((thread, error) -> holderError.set(error));
     holder.start();
     try {
-      assertThat(held.await(HOLDER_WAIT.toMillis(), TimeUnit.MILLISECONDS))
-          .as("holder thread acquired the lock within %s", HOLDER_WAIT)
-          .isTrue();
+      boolean acquired = held.await(HOLDER_WAIT.toMillis(), TimeUnit.MILLISECONDS);
+      // the handler swallows the holder's stack trace, so report its error before the timeout
+      assertThat(holderError.get()).as("holder thread acquired the lock without an error").isNull();
+      assertThat(acquired).as("holder thread acquired the lock within %s", HOLDER_WAIT).isTrue();
 
       // when & then: a second acquire from the main thread must time out
       assertThatThrownBy(() -> port.tryAcquire(key, SHORT_WAIT, LEASE_TTL))
-- 
2.54.0