fix: 3차 확인 리뷰의 Minor 19건을 고친다

문제: 3차 수정의 확인 리뷰가 새 Important 없이 Minor 19건을 남겼다.
동작에 닿는 것이 셋이다. JDK read-idle watchdog이 공용 ForkJoinPool에서
돌아 그 풀이 바쁘면 300ms timeout이 6초 가까이 늦었다. 붙여 쓴
-x<task>를 verifyStrictLaneStages가 읽지 않아 lane을 뺀 workflow가
통과했다. 사용자 전송이 중간 클래스를 거쳐 @SystemCaller bean을 부르면
ArchUnit 규칙을 지났다. 잠금 대기 검사기는 FK·trigger·REINDEX와
lock_timeout = 0을 못 봤고, 쿼터 보정 SQL은 코드와 다른 모양의 행을
넣었다.

방법: 영역별 4묶음이 맡은 Minor만 test-driven-development 절차로
고쳤다(재리뷰 README 12절).
- watchdog은 전용 데몬 스레드 하나에서 돌고 스트림을 닫으면 작업을
  취소한다. read당 비용은 그대로다(21–24ns).
- 사용자 전송 → @SystemCaller는 직접·간접 의존 모두 거부한다. 리뷰가
  권한 직접 의존 검사는 중간 클래스 하나로 다시 열려서 버렸다.
- 검사기를 보강하면서 새로 걸린 이미 배포된 마이그레이션 5개는 내용을
  바꾸지 않고 동결 목록에 더했다(main과 blob이 같다).
- 비밀 목록 bean은 규칙보다 먼저 만들어 실제 클래스로 검사한다.

위험·한계: 회복 필요 예외 메시지 끝에 scope digest가 붙고 기동 실패
문구가 바뀌어, 문구 전체에 맞추던 로그 매처는 고쳐야 한다. 코드가 든
Redis 계정 참조의 fixture- 검사는 문서로만 막았다(코드로 막으려면 새
의존 edge가 필요하다). failure-retention ≥ replay-ttl 기동 검사는 넣지
않았다. -mx 같은 짧은 플래그 묶음과 graphql 전송 fixture는 남았다.
spotbugsTestFixtures(게이트 밖)의 정규식 경고가 15건으로 늘었다.

검증: ci, 두 빌드의 verifyStrictLaneStages --dry-run, mainCheck,
:integrationCheck, -p optional-platforms ci integrationCheck
performanceCheck, :performanceCheck, :releaseCheck(-PgitRevision),
verify-compose-profile-contracts(18 lane) 첫 실행 통과. watchdog은
공용 풀을 채운 상태에서 300ms 설정이 300ms에 끝나는 것을 쟀다.

Refs: docs/reviews/2026-11-03-rereview/README.md 11·12절, round3/
This commit is contained in:
DongHyeonka
2026-11-04 03:00:21 +09:00
parent 339cf8fdbf
commit f40c03c6d3
77 changed files with 1876 additions and 410 deletions
+1
View File
@@ -128,6 +128,7 @@ APP_IDEMPOTENCY_TTL=24h
APP_IDEMPOTENCY_PROVIDER=disabled
APP_IDEMPOTENCY_REDIS_NAMESPACE_ENVIRONMENT=local
APP_IDEMPOTENCY_PROCESSING_LEASE=30s
# Failure retention: at most 30d. Not checked against APP_IDEMPOTENCY_TTL; keep it at least that long.
APP_IDEMPOTENCY_FAILURE_RETENTION=24h
APP_LEASE_PROVIDER=disabled
APP_LEASE_REDIS_NAMESPACE_ENVIRONMENT=local
+4 -2
View File
@@ -11,8 +11,10 @@
- Boundaries: no business rule in a handler (HARD-STOP 4); no persistence entity or repository; no
broker SDK type. Allowed edges come only from the registry entry.
- A handler that calls a write use case is `@SystemCaller(reason = ...)` and constructs the
`@SystemInvoked` use case itself; the use case is never a bean (manual 09 「소비」 step 4,
`ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`).
`@SystemInvoked` use case itself; the use case is never a bean, and no user transport calls the
handler (manual 09 「소비」 step 4, manual 07 「시스템이 부르는 쓰기」,
`ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`,
`USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`).
- Tests: focused auto-configuration and inbox behavior tests; `./gradlew :adapter:inbound:messaging:check`.
The real Kafka + PostgreSQL redelivery lane is `messagingInboxRedeliveryIntegrationTest`
(`:integrationCheck`).
+7 -3
View File
@@ -103,8 +103,10 @@ PostgreSQL에서 같은 모양은 `InboxRedeliveryIntegrationTest`의 `Projectio
`messaging-core-api`만 보는 anti-corruption 경계이고, 소비는 inbound 방향이다.
- 고름(RR-01-12): handler가 `@SystemCaller`를 달고 `@SystemInvoked` use case를 직접 `new`로 만든다. 사용자
요청이 들어오는 전송(web·GraphQL·gRPC·WebSocket)만 그 use case에 닿지 못하고, 표시는 ArchUnit이 검사한다
(`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`: messaging·scheduler inbound 패키지에만, 사용자 전송
타입에 의존하지 않음). 기동 가드는 바꾸지 않는다: `@SystemInvoked` bean은 예외 없이 실패다.
(`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`: 표시한 클래스와 그 안에 중첩된 클래스는 messaging·
scheduler inbound 패키지에만, 사용자 전송 타입에 의존하지 않음). 사용자 전송이 handler bean을 주입받아
부르는 길은 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`가 막는다(RR3-01-01). 기동 가드는 바꾸지 않는다:
`@SystemInvoked` bean은 예외 없이 실패다. 규칙 전체는 매뉴얼 07장 「시스템이 부르는 쓰기」.
- 버림: use case를 bean으로 두고 가드에 "handler만 주입받으면 허용" 예외 — 누가 주입받는지는 기동 때
확정되지 않는다(`ObjectProvider`, `getBean`, 나중에 추가된 bean). 예외 조건이 곧 우회 경로가 된다.
- 버림: handler는 `CommandUseCase` 인터페이스만 받고 조립 모듈이 `new`로 넣기 — 소비자마다 composition
@@ -113,7 +115,9 @@ PostgreSQL에서 같은 모양은 `InboxRedeliveryIntegrationTest`의 `Projectio
- 버림: ArchUnit 대상에서 messaging 패키지를 통째로 빼기 — 클래스에 표시가 없어 의도가 안 보이고, 그
패키지의 아무 클래스(HTTP endpoint 포함)나 닿는다.
- 버림: 사용자 전송 패키지만 나열해 금지 — 나중에 새 전송이 생기면 조용히 열린다. 규칙은 "닿아도 되는
쪽"을 적는다.
쪽"을 적는다. 이 성질은 패키지 쪽에만 있다: 시스템 패키지 안에 놓인 endpoint를 알아보는 사용자 전송
**타입**은 나열 목록이다(`ARE_USER_TRANSPORT_TYPES`, JAX-RS·graphql-java 포함). 새 전송 라이브러리를
들이면 그 목록에 더한다(RR3-01-02).
- 버림: application-core에 소비 포트를 새로 만들어 platform `MessageHandler`로 감싸는 범용 bridge —
payload 타입 매핑과 결과 매핑 규칙을 먼저 정해야 해서 이번 범위보다 크다. 지금은 handler가 직접
use case를 부른다.
@@ -243,7 +243,14 @@ public final class IdempotencyScripts {
return {'APPLIED', attempt, rev, owner, '', ''}
""";
/** Inspect: read the record without touching it. */
/**
* Inspect: read the record without touching it.
*
* <p>The detail is {@code ownership|key PTTL|leaseUntil}. A completed record's replay deadline is
* its key's TTL; an in-progress record's lease is not, because its key lives for the lease plus
* {@code afterLease} — reading the lease off the TTL reported it a replay TTL too late (re-review
* 2026-11-04 RR3-03-05).
*/
private static final String INSPECT =
"""
local state = redis.call('HGET', KEYS[1], 'state')
@@ -268,7 +275,8 @@ public final class IdempotencyScripts {
end
return {state, attempt, rev, owner,
redis.call('HGET', KEYS[1], 'resp') or '',
mine .. '|' .. tostring(redis.call('PTTL', KEYS[1]))}
mine .. '|' .. tostring(redis.call('PTTL', KEYS[1])) .. '|'
.. (redis.call('HGET', KEYS[1], 'leaseUntil') or '')}
""";
private final RegisteredLuaScript claim = new RegisteredLuaScript(CLAIM);
@@ -361,9 +361,16 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort
if (reply.status() == ScriptStatus.FINGERPRINT_MISMATCH) {
return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.FINGERPRINT_MISMATCH);
}
String[] detail = reply.detail().split("\\|", 2);
String[] detail = reply.detail().split("\\|", 3);
String ownership = detail[0];
long ttlMillis = detail.length > 1 ? parseLong(detail[1]) : 0;
// The lease the record carries, in server time as the claim reported it — not the key's TTL,
// which runs a replay TTL past the lease (RR3-03-05).
long leaseUntilMillis = detail.length > 2 ? parseLong(detail[2]) : 0;
Optional<Instant> leaseUntil =
leaseUntilMillis > 0
? Optional.of(Instant.ofEpochMilli(leaseUntilMillis))
: Optional.empty();
if ("OPERATION_CONFLICT".equals(ownership)) {
return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.OPERATION_CONFLICT);
}
@@ -390,7 +397,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort
? new IdempotencyInspection(
IdempotencyInspectionOutcome.CLAIMED_SAME_OPERATION,
Optional.of(handle),
Optional.of(now.plusMillis(Math.max(1, ttlMillis))),
leaseUntil,
Optional.empty(),
Optional.empty())
: IdempotencyInspection.outcome(IdempotencyInspectionOutcome.IN_PROGRESS_OTHER);
@@ -399,7 +406,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort
? new IdempotencyInspection(
IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION,
Optional.of(handle),
Optional.of(now.plusMillis(Math.max(1, ttlMillis))),
leaseUntil,
Optional.empty(),
Optional.empty())
: IdempotencyInspection.outcome(IdempotencyInspectionOutcome.IN_PROGRESS_OTHER);
+6 -5
View File
@@ -42,11 +42,12 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d
left, the experimental Jetty HTTP/3 transport aborts the request, and the caller gets
`HttpDeadlineExceededException`. A streaming download's setup (up to the response headers) runs
inside the same deadline; after hand-over each body gap is bounded by `read-idle` and nothing else,
on both transports — the JDK transport arms its own per-read timer for this, because the JDK client
has no socket read timeout. A body that fails after hand-over throws `HttpBodyReadException`, an
`IOException` as `InputStream.read` promises, whose `failure()` is the same stable exception a
buffered call throws (`HttpResponseTimeoutException` for a stalled body,
`HttpResponseTruncatedException` for a cut one).
on both transports — on the JDK transport, which has no socket read timeout, a per-stream watchdog
on its own daemon thread (`httpclient-jdk-read-idle`) bounds each read's wait. A body that fails
after hand-over throws `HttpBodyReadException`, an `IOException` as `InputStream.read` promises,
whose `failure()` is the same stable exception a buffered call throws
(`HttpResponseTimeoutException` for a stalled body, `HttpResponseTruncatedException` for a cut
one).
- **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or
`PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it.
- **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline,
@@ -6,7 +6,9 @@ import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -31,6 +33,20 @@ import java.util.concurrent.atomic.AtomicBoolean;
* it moves the queue off the shared scheduler but keeps a queue insertion and removal on every
* read.
*
* <p>The watchdog wakes on a thread of its own: one daemon thread, {@code
* httpclient-jdk-read-idle}, shared by every JDK stream and started with the first (re-review
* 2026-11-04 RR3-03-01). It used to wake through {@code CompletableFuture.delayedExecutor}, whose
* task runs on the common {@code ForkJoinPool}; a service that filled that pool with blocking work
* — {@code supplyAsync(blockingCall)} without an executor — held every timeout until a pool thread
* came free, and a 300 ms {@code read-idle} ended after 2.7 s. The wake is O(1), and the close it
* may do waits on no I/O — the JDK body marks itself closed, cancels its subscription and wakes the
* read — so both run on this thread, as the per-read timer before RR-03-13 closed on the JDK's
* delay thread. Rejected: {@code delayedExecutor(delay, unit, Runnable::run)}, which judges on the
* JDK's own delay thread — that thread fires every {@code CompletableFuture} timeout in the
* process, so a slow close there would delay them all, and it returns no handle to take a closed
* stream's wake off the queue. Closing the stream cancels its pending wake, so a closed stream is
* not kept reachable until its {@code read-idle} passes.
*
* <p>{@link #skip} reads through this stream rather than delegating: the JDK body does not override
* {@code skip}, so {@code InputStream.skip} ran many reads inside one guarded call and a long skip
* over a steady body timed out as one long wait (re-review 2026-11-04 RR-03-12).
@@ -53,10 +69,35 @@ final class ReadIdleInputStream extends FilterInputStream {
private final AtomicBoolean idled = new AtomicBoolean();
private volatile long readStartedAt = NOT_READING;
private volatile boolean closed;
private volatile ScheduledFuture<?> pendingWake;
private final ScheduledExecutorService watchdogs;
ReadIdleInputStream(InputStream delegate, Duration readIdle) {
this(delegate, readIdle, SharedWatchdogs.INSTANCE);
}
/** The scheduler is a parameter so a test can see what a stream leaves queued on it. */
ReadIdleInputStream(InputStream delegate, Duration readIdle, ScheduledExecutorService watchdogs) {
super(Objects.requireNonNull(delegate, "body stream"));
this.readIdleNanos = Objects.requireNonNull(readIdle, "read idle timeout").toNanos();
this.watchdogs = Objects.requireNonNull(watchdogs, "watchdog scheduler");
}
/**
* A watchdog scheduler as every stream gets it: one daemon thread, and a cancelled wake leaves
* the queue at once instead of when it would have fired.
*/
static ScheduledThreadPoolExecutor newWatchdogs() {
ScheduledThreadPoolExecutor scheduler =
new ScheduledThreadPoolExecutor(
1,
runnable -> {
Thread thread = new Thread(runnable, "httpclient-jdk-read-idle");
thread.setDaemon(true);
return thread;
});
scheduler.setRemoveOnCancelPolicy(true);
return scheduler;
}
@Override
@@ -89,6 +130,7 @@ final class ReadIdleInputStream extends FilterInputStream {
@Override
public void close() throws IOException {
closed = true;
cancelPendingWake();
super.close();
}
@@ -113,7 +155,19 @@ final class ReadIdleInputStream extends FilterInputStream {
/** Wakes the watchdog when a read that started at {@code started} reaches read-idle. */
private void watchFrom(long started) {
long left = Math.max(0, readIdleNanos - (System.nanoTime() - started));
CompletableFuture.delayedExecutor(left, TimeUnit.NANOSECONDS).execute(this::watch);
pendingWake = watchdogs.schedule(this::watch, left, TimeUnit.NANOSECONDS);
// A close between the watchdog's check and this schedule did not see the new wake; take it
// off here. Both sides write their own volatile before reading the other's.
if (closed) {
cancelPendingWake();
}
}
private void cancelPendingWake() {
ScheduledFuture<?> wake = pendingWake;
if (wake != null) {
wake.cancel(false);
}
}
private void watch() {
@@ -158,4 +212,12 @@ final class ReadIdleInputStream extends FilterInputStream {
throw new SocketTimeoutException("no response body bytes within the read-idle timeout");
}
}
/** The scheduler every stream shares, started with the first stream that is read. */
private static final class SharedWatchdogs {
static final ScheduledExecutorService INSTANCE = newWatchdogs();
private SharedWatchdogs() {}
}
}
@@ -8,6 +8,8 @@ import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@@ -15,12 +17,14 @@ import org.junit.jupiter.api.Test;
/**
* What the JDK transport's read-idle bound promises: each read that waits longer than {@code
* read-idle} for the server ends the body, and nothing else does (re-review 2026-11-04 RR-03-12,
* RR-03-13).
* RR-03-13); the watchdog keeps that time whatever the common pool is doing, and leaves nothing
* scheduled for a stream that is closed or timed out (RR3-03-01).
*/
class ReadIdleInputStreamTest {
private static final Duration READ_IDLE = Duration.ofMillis(300);
private static final Duration GAP = Duration.ofMillis(20);
private static final Duration COMMON_POOL_HOLD = Duration.ofSeconds(3);
@Test
@DisplayName("데이터가 read-idle보다 짧은 간격으로 오면 read-idle보다 오래 걸리는 skip도 끝까지 건너뛴다")
@@ -67,6 +71,79 @@ class ReadIdleInputStreamTest {
assertThat(waited).isGreaterThanOrEqualTo(READ_IDLE).isLessThan(READ_IDLE.multipliedBy(3));
}
@Test
@DisplayName("공용 ForkJoinPool이 블로킹 작업으로 차 있어도 멈춘 read는 read-idle 무렵에 끝난다")
void aStalledReadTimesOutOnTimeWhileTheCommonPoolIsBlocked() throws Exception {
// given
// Every common-pool worker parks on a latch, which does not make the pool add a spare thread —
// what a service's supplyAsync(blockingCall) without an executor does. The hold is bounded so
// a watchdog that needs a pool worker still ends the read, late (re-review 2026-11-04
// RR3-03-01: 300 ms read-idle timed out after 2,699 ms).
int workers = Math.max(1, ForkJoinPool.getCommonPoolParallelism());
CountDownLatch occupied = new CountDownLatch(workers);
CountDownLatch release = new CountDownLatch(1);
for (int task = 0; task < workers * 2; task++) {
ForkJoinPool.commonPool()
.execute(
() -> {
occupied.countDown();
awaitQuietly(release, COMMON_POOL_HOLD);
});
}
assertThat(occupied.await(5, TimeUnit.SECONDS)).as("every common-pool worker is held").isTrue();
InputStream body = new ReadIdleInputStream(new StalledStream(), READ_IDLE);
long started = System.nanoTime();
try {
// when
Throwable failure = catchThrowable(body::read);
// then
Duration waited = Duration.ofNanos(System.nanoTime() - started);
assertThat(failure).isInstanceOf(SocketTimeoutException.class);
assertThat(waited).isGreaterThanOrEqualTo(READ_IDLE).isLessThan(READ_IDLE.multipliedBy(3));
} finally {
release.countDown();
}
}
@Test
@DisplayName("스트림을 닫으면 그 스트림의 watchdog 예약이 스케줄러에서 바로 빠진다")
void closingTheStreamTakesItsWatchdogOffTheScheduler() throws IOException {
// given
ScheduledThreadPoolExecutor watchdogs = ReadIdleInputStream.newWatchdogs();
try {
InputStream body = new ReadIdleInputStream(new DrippingStream(1, GAP), READ_IDLE, watchdogs);
body.read();
// when
body.close();
// then
assertThat(watchdogs.getQueue()).isEmpty();
} finally {
watchdogs.shutdownNow();
}
}
@Test
@DisplayName("read-idle로 끝난 스트림은 닫지 않아도 watchdog을 더 예약하지 않는다")
void aStreamThatTimedOutLeavesNoWatchdogBehind() {
// given
ScheduledThreadPoolExecutor watchdogs = ReadIdleInputStream.newWatchdogs();
try {
InputStream body = new ReadIdleInputStream(new StalledStream(), READ_IDLE, watchdogs);
// when
Throwable failure = catchThrowable(body::read);
// then
assertThat(failure).isInstanceOf(SocketTimeoutException.class);
assertThat(watchdogs.getQueue()).isEmpty();
} finally {
watchdogs.shutdownNow();
}
}
@Test
@DisplayName("호출자가 read 사이에 오래 머문 시간은 read-idle로 세지 않는다")
void timeTheCallerSpendsBetweenReadsIsNotIdle() throws Exception {
@@ -83,6 +160,14 @@ class ReadIdleInputStreamTest {
}
}
private static void awaitQuietly(CountDownLatch latch, Duration atMost) {
try {
latch.await(atMost.toNanos(), TimeUnit.NANOSECONDS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
}
}
/** Gives one byte per read, each after {@code gap}. */
private static final class DrippingStream extends InputStream {
@@ -95,7 +95,8 @@ not grow by wiring accident.
- OSIV is false in every runtime profile; Flyway owns schema change and Hibernate only validates.
- A migration that locks a table already in use starts with `SET LOCAL lock_timeout = '5s';`
(`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest` refuses one
without it; its list of migrations released before the rule only ever shrinks.
without it. Its list of migrations released before the rule never takes a new migration; it
grows only when the inspector learns a statement and finds it in a file already on `main`.
- Metric tags, exception messages, and logs carry no SQL parameters, entity ids, tenant ids, or PII.
- Contracts run against real PostgreSQL. H2 never satisfies one.
@@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.LockWaitMigrationInspector;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
@@ -26,21 +25,30 @@ class MigrationLockWaitTest {
* Migrations released before the rule, which wait without a bound and stay that way: they are
* applied (on {@code main} when the rule came in), and an applied migration is never edited
* ({@link AppliedMigrationImmutabilityTest}). Their waits are behind every database that ran
* them. Nothing is added here — a new migration bounds its wait.
* them. A new migration is never added here — it bounds its wait. The list grows only when the
* inspector learns a statement it did not know and finds it in a file released before the rule:
* {@code REFERENCES} on an existing table, and a {@code CREATE TABLE IF NOT EXISTS} that no
* longer exempts the statements after it (re-review 2026-11-03 round 3, RR3-02-01), added {@code
* jpa/idempotency/V1}, notification {@code V3}, {@code messaging/V1003} and {@code
* postgresql/V11} and {@code V12} — all five on {@code main} ({@code 01a8a2a7}), unchanged since.
*/
private static final Set<String> RELEASED_BEFORE_THE_RULE =
Set.of(
"jpa/core/V2__widen_capability_schema_stream.sql",
"jpa/idempotency/V1__expand_owner_safe_v2.sql",
"jpa/idempotency/V2__request_hash_varchar.sql",
"postgresql/V5__int_lock_expired_after.sql",
"postgresql/V9__widen_capability_schema_stream.sql",
"postgresql/V10__idempotency_request_hash_varchar.sql",
"postgresql/V11__durable_operation.sql",
"postgresql/V12__live_event_log.sql",
"postgresql/V13__outbox_canonical_transport_compatibility.sql",
"postgresql/V14__validate_outbox_canonical_constraints.sql",
"postgresql/V16__outbox_canonical_hash_columns_varchar.sql",
"postgresql/V17__outbox_event_lease_fencing.sql",
"postgresql/V18__outbox_event_unpublished_aggregate_order.sql",
"postgresql/V19__outbox_event_canonical_only.sql",
"jpa/notification-platform/V3__notification_platform_inbox_admin.sql",
"jpa/notification-platform/V4__notification_platform_alignment_and_activation.sql",
"jpa/notification-platform/V5__notification_recipient_expiry.sql",
"jpa/notification-platform/V6__notification_projection_facts.sql",
@@ -52,6 +60,7 @@ class MigrationLockWaitTest {
"jpa/fileserver/V4__fileserver_upload_terminal_state.sql",
"jpa/fileserver/V5__fileserver_file_owner.sql",
"messaging/V1002__messaging_outbox_lease_fencing.sql",
"messaging/V1003__messaging_admin_operation_journal.sql",
"messaging/V1004__messaging_outbox_canonical_metadata.sql",
"messaging/V1005__messaging_outbox_ordering_key_index.sql");
@@ -94,8 +103,7 @@ class MigrationLockWaitTest {
throws IOException {
Map<String, List<String>> unbounded = new TreeMap<>();
for (Map.Entry<String, Path> migration : migrations.entrySet()) {
List<String> statements =
inspector.unboundedLockingStatements(Files.readString(migration.getValue()));
List<String> statements = inspector.unboundedLockingStatements(migration.getValue());
if (!statements.isEmpty()) {
unbounded.put(migration.getKey(), statements);
}
@@ -1,12 +1,11 @@
package dev.caskeleton.adapter.outbound.persistence.migration;
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.VersionedMigrationFiles;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Stream;
/**
* The migration trees that run against the database this leaf owns, read the one way every
@@ -46,22 +45,18 @@ final class MigrationTrees {
private MigrationTrees() {}
/**
* Every versioned migration, keyed by its path below its tree ({@code postgresql/V22__...sql}),
* the key {@code applied-migrations.sha256} uses.
* Every versioned migration ({@link VersionedMigrationFiles}, the definition the sample's check
* uses too), keyed by its path below its tree ({@code postgresql/V22__...sql}), the key {@code
* applied-migrations.sha256} uses.
*/
static Map<String, Path> versionedMigrations() throws IOException {
Map<String, Path> migrations = new TreeMap<>();
for (Path root : ROOTS) {
try (Stream<Path> files = Files.walk(root)) {
for (Path file :
files
.filter(path -> path.getFileName().toString().matches("V\\d+__.+\\.sql"))
.toList()) {
String key = root.relativize(file).toString().replace('\\', '/');
if (migrations.put(key, file) != null) {
throw new IllegalStateException(
key + " exists in two migration trees; the classpath would load one at random");
}
for (Map.Entry<String, Path> migration : VersionedMigrationFiles.under(root).entrySet()) {
if (migrations.put(migration.getKey(), migration.getValue()) != null) {
throw new IllegalStateException(
migration.getKey()
+ " exists in two migration trees; the classpath would load one at random");
}
}
}
@@ -12,6 +12,8 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseMa
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseOneToOneEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnChildEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnParentEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinTableChildEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinTableParentEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.MutualForeignKeyInvoiceEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.MutualForeignKeyOrderEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.NoDefaultConstructorEntity;
@@ -19,6 +21,8 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OrderEnti
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningChildEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningManyToManyEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningOneToOneEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.TwoOwnerCourseEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.TwoOwnerStudentEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.UnidirectionalCollectionEntity;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.BadOrderController;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.GoodOrderController;
@@ -230,6 +234,51 @@ class JpaArchitectureRulesTest {
.hasMessageNotContaining("two fields map one link");
}
@Test
@DisplayName("mappedBy를 잊어 컬렉션은 조인 테이블에, 반대쪽은 자기 외래 키 열에 링크를 두면 한 링크가 아니라 따로 저장된 두 사본으로 거부된다")
void aCollectionInAJoinTableAndAToOneInItsOwnColumnAreRefusedAsTwoStoredCopies() {
// given
var classes =
new ClassFileImporter()
.importClasses(JoinTableParentEntity.class, JoinTableChildEntity.class);
// when
Throwable failure =
catchThrowable(
() -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes));
// then
assertThat(failure)
.isInstanceOf(AssertionError.class)
.hasMessageContaining("JoinTableParentEntity.children")
.hasMessageContaining("JoinTableChildEntity.parent")
.hasMessageContaining("the link is stored twice")
.hasMessageContaining("column parent_id")
.hasMessageNotContaining("two fields map one link");
}
@Test
@DisplayName("mappedBy 없는 두 @ManyToMany는 한 링크가 아니라 양쪽이 따로 저장하는 두 사본으로 거부된다")
void twoManyToManyCollectionsWithoutMappedByAreRefusedAsTwoStoredCopies() {
// given
var classes =
new ClassFileImporter()
.importClasses(TwoOwnerStudentEntity.class, TwoOwnerCourseEntity.class);
// when
Throwable failure =
catchThrowable(
() -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes));
// then
assertThat(failure)
.isInstanceOf(AssertionError.class)
.hasMessageContaining("TwoOwnerStudentEntity.courses")
.hasMessageContaining("TwoOwnerCourseEntity.students")
.hasMessageContaining("the link is stored twice")
.hasMessageNotContaining("two fields map one link");
}
@Test
@DisplayName("단방향 연관관계는 통과한다")
void unidirectionalAssociationsPass() {
@@ -0,0 +1,30 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
/** Refused by the association rule: the other half of {@link JoinTableParentEntity}'s pair. */
@Entity
public class JoinTableChildEntity {
@Id private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private JoinTableParentEntity parent;
protected JoinTableChildEntity() {}
/** The identifier. */
public Long id() {
return id;
}
/** The reference kept in this table's own column. */
public JoinTableParentEntity parent() {
return parent;
}
}
@@ -0,0 +1,35 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
/**
* Refused by the association rule: a pair without {@code mappedBy} that stores the link twice.
*
* <p>A {@code @OneToMany} without {@code @JoinColumn} keeps its links in a join table, and {@link
* JoinTableChildEntity#parent} keeps the same link in its own {@code parent_id} column — the shape
* forgetting {@code mappedBy} produces. Two copies stored apart, not one mapped twice (re-review
* round 3, RR3-02-05).
*/
@Entity
public class JoinTableParentEntity {
@Id private Long id;
@OneToMany private List<JoinTableChildEntity> children = new ArrayList<>();
protected JoinTableParentEntity() {}
/** The identifier. */
public Long id() {
return id;
}
/** The collection kept in the join table. */
public List<JoinTableChildEntity> children() {
return List.copyOf(children);
}
}
@@ -0,0 +1,28 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import java.util.HashSet;
import java.util.Set;
/** Refused by the association rule: the other half of {@link TwoOwnerStudentEntity}'s pair. */
@Entity
public class TwoOwnerCourseEntity {
@Id private Long id;
@ManyToMany private Set<TwoOwnerStudentEntity> students = new HashSet<>();
protected TwoOwnerCourseEntity() {}
/** The identifier. */
public Long id() {
return id;
}
/** The students, kept in this side's join table. */
public Set<TwoOwnerStudentEntity> students() {
return Set.copyOf(students);
}
}
@@ -0,0 +1,34 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import java.util.HashSet;
import java.util.Set;
/**
* Refused by the association rule: two {@code @ManyToMany} collections without {@code mappedBy}.
*
* <p>Both this collection and {@link TwoOwnerCourseEntity#students} own the link, each in its own
* join table by default. Two copies stored apart, not one mapped twice (re-review round 3,
* RR3-02-05).
*/
@Entity
public class TwoOwnerStudentEntity {
@Id private Long id;
@ManyToMany private Set<TwoOwnerCourseEntity> courses = new HashSet<>();
protected TwoOwnerStudentEntity() {}
/** The identifier. */
public Long id() {
return id;
}
/** The courses, kept in this side's join table. */
public Set<TwoOwnerCourseEntity> courses() {
return Set.copyOf(courses);
}
}
@@ -2,9 +2,15 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.migration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.InstanceOfAssertFactories.STRING;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -14,6 +20,9 @@ import org.junit.jupiter.params.provider.ValueSource;
*/
class LockWaitMigrationInspectorTest {
private static final String BOUNDED_ALTER =
"SET LOCAL lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;";
private final LockWaitMigrationInspector inspector = new LockWaitMigrationInspector();
@ParameterizedTest
@@ -26,7 +35,20 @@ class LockWaitMigrationInspectorTest {
"UPDATE outbox_event SET status = 'FAILED';",
"LOCK TABLE outbox_event IN SHARE MODE;",
"ALTER TABLE outbox_event ADD COLUMN c INT;\nSET LOCAL lock_timeout = '5s';",
"SET lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;"
"SET lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;",
"CREATE TABLE outbox_note (id BIGINT, event_id UUID REFERENCES outbox_event (event_id));",
"CREATE TABLE poster_note (id BIGINT);\n"
+ "ALTER TABLE poster_note ADD CONSTRAINT fk FOREIGN KEY (id) REFERENCES poster (id);",
"CREATE TRIGGER trg_outbox BEFORE UPDATE ON outbox_event FOR EACH ROW EXECUTE FUNCTION f();",
"CREATE OR REPLACE TRIGGER trg_outbox AFTER INSERT ON public.outbox_event"
+ " FOR EACH ROW EXECUTE FUNCTION f();",
"DROP TRIGGER IF EXISTS trg_outbox ON outbox_event;",
"REINDEX TABLE outbox_event;",
"REINDEX INDEX ux_outbox_event_aggregate_order;",
"REFRESH MATERIALIZED VIEW outbox_summary;",
"CLUSTER outbox_event USING ix_outbox_event_status;",
"VACUUM FULL outbox_event;",
"CREATE TABLE IF NOT EXISTS ledger (id BIGINT);\nALTER TABLE ledger ADD c INT;"
})
@DisplayName("이미 있는 테이블에 잠금을 거는 문장 앞에 SET LOCAL lock_timeout이 없으면 거부된다")
void aLockOnAnExistingTableWithoutABoundBeforeItIsRefused(String sql) {
@@ -50,8 +72,12 @@ class LockWaitMigrationInspectorTest {
"-- bound first\nset local lock_timeout = '5s';\ndelete from notification_suppression;",
"CREATE TABLE ledger (id BIGINT);\nCREATE INDEX ix_ledger ON ledger (id);\n"
+ "ALTER TABLE ledger ADD COLUMN c INT;",
"CREATE TABLE IF NOT EXISTS public.ledger (id BIGINT);\nALTER TABLE ledger ADD c INT;",
"CREATE INDEX CONCURRENTLY ix_outbox ON outbox_event (status);",
"REINDEX TABLE CONCURRENTLY outbox_event;",
"CREATE TABLE parent (id BIGINT PRIMARY KEY);\n"
+ "CREATE TABLE child (id BIGINT, parent_id BIGINT REFERENCES parent (id));",
"CREATE TABLE node (id BIGINT PRIMARY KEY, parent_id BIGINT REFERENCES node (id));",
"SET LOCAL lock_timeout TO 5000;\nDROP TRIGGER trg_outbox ON outbox_event;",
"-- ALTER TABLE outbox_event ADD COLUMN c INT;\n/* DELETE FROM outbox_event; */\n"
+ "COMMENT ON TABLE outbox_event IS 'update outbox_event set status';",
"CREATE TABLE poster_copy AS SELECT * FROM poster;"
@@ -68,6 +94,62 @@ class LockWaitMigrationInspectorTest {
assertThat(refused).isNull();
}
@ParameterizedTest
@ValueSource(
strings = {
"SET LOCAL lock_timeout = 0;\nALTER TABLE outbox_event ADD COLUMN c INT;",
"SET LOCAL lock_timeout = '0s';\nALTER TABLE outbox_event ADD COLUMN c INT;",
"SET LOCAL lock_timeout TO DEFAULT;\nALTER TABLE outbox_event ADD COLUMN c INT;",
"SET LOCAL lock_timeout = '5s';\nSET LOCAL lock_timeout = 0;\n"
+ "ALTER TABLE outbox_event ADD COLUMN c INT;",
"SET LOCAL lock_timeout = '5s';\nRESET lock_timeout;\n"
+ "ALTER TABLE outbox_event ADD COLUMN c INT;"
})
@DisplayName("lock_timeout을 0이나 기본값으로 두거나 되돌린 뒤의 잠금은 상한이 없는 것으로 거부된다")
void aLockAfterATimeoutOfZeroOrALiftedBoundIsRefused(String sql) {
// given
MigrationResource migration = new MigrationResource("V99__change.sql", sql);
// when
Throwable refused = catchThrowable(() -> inspector.requireBoundedLockWait(migration));
// then
assertThat(refused)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("alter table outbox_event");
}
@Test
@DisplayName("executeInTransaction=false인 마이그레이션의 SET LOCAL lock_timeout은 상한으로 세지 않는다")
void setLocalInANonTransactionalMigrationIsNotABound(@TempDir Path stream) throws IOException {
// given
Path script = Files.writeString(stream.resolve("V99__change.sql"), BOUNDED_ALTER);
Files.writeString(stream.resolve("V99__change.sql.conf"), "executeInTransaction=false\n");
// when
List<String> unbounded = inspector.unboundedLockingStatements(script);
// then
assertThat(unbounded)
.singleElement(STRING)
.contains("alter table outbox_event")
.contains("executeInTransaction=false");
}
@Test
@DisplayName("설정 파일이 없는 마이그레이션 파일은 트랜잭션 안에서 돌아 SET LOCAL lock_timeout이 상한이 된다")
void setLocalInAMigrationFileWithoutConfigurationIsABound(@TempDir Path stream)
throws IOException {
// given
Path script = Files.writeString(stream.resolve("V99__change.sql"), BOUNDED_ALTER);
// when
List<String> unbounded = inspector.unboundedLockingStatements(script);
// then
assertThat(unbounded).isEmpty();
}
@Test
@DisplayName("거부 메시지는 상한 없이 잠금을 기다리는 문장과 대상 테이블을 모두 말한다")
void theRefusalNamesEveryUnboundedStatementAndItsTable() {
@@ -0,0 +1,48 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.migration;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* One definition of a versioned migration for every check that walks a tree (re-review 2026-11-03
* round 3, RR3-02-03): the operating trees' checks once skipped {@code V22_1__} while the sample's
* counted it.
*/
class VersionedMigrationFilesTest {
@Test
@DisplayName("소수 버전을 포함한 버전 마이그레이션만 하위 디렉터리까지 찾고 다른 파일은 뺀다")
void everyVersionedMigrationIncludingADecimalVersionIsFoundAndNothingElse(@TempDir Path tree)
throws IOException {
// given
Files.createDirectories(tree.resolve("postgresql"));
for (String file :
Set.of(
"postgresql/V22__outbox.sql",
"postgresql/V22_1__outbox_fix.sql",
"postgresql/V22.2__outbox_index.sql",
"postgresql/V22__outbox.sql.conf",
"postgresql/R__view.sql",
"postgresql/U22__undo.sql",
"README.md")) {
Files.writeString(tree.resolve(file), "SELECT 1;");
}
// when
Set<String> found = VersionedMigrationFiles.under(tree).keySet();
// then
assertThat(found)
.containsExactlyInAnyOrder(
"postgresql/V22__outbox.sql",
"postgresql/V22_1__outbox_fix.sql",
"postgresql/V22.2__outbox_index.sql");
}
}
@@ -10,6 +10,8 @@ import com.tngtech.archunit.core.domain.JavaType;
import com.tngtech.archunit.lang.ArchCondition;
import com.tngtech.archunit.lang.ConditionEvents;
import com.tngtech.archunit.lang.SimpleConditionEvent;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
@@ -30,10 +32,12 @@ import java.util.stream.Stream;
* <ul>
* <li>With {@code mappedBy}: the inverse half says so. Only that half is reported, because the
* foreign key belongs to the owning {@code @ManyToOne} either way.
* <li>Without it: both halves map the same join column, one of them usually {@code insertable =
* false, updatable = false} (Hibernate's {@code @JoinColumn} form). Neither half says it is
* the copy, so both are reported (review RR-03-04). Reading the attribute alone let this form
* pass.
* <li>Without it: neither half says it is the copy, so both are reported (review RR-03-04).
* Reading the attribute alone let this form pass. Either both halves map the same join
* column, one of them usually {@code insertable = false, updatable = false} (Hibernate's
* {@code @JoinColumn} form), or each stores the link on its own — a {@code @OneToMany}
* without {@code @JoinColumn} in a join table beside the to-one's column, two
* {@code @ManyToMany} in a join table each — and the report says which (RR3-02-05).
* </ul>
*
* <p>Two to-one links the other way round — {@code Order.@OneToOne latestInvoice} and {@code
@@ -116,25 +120,48 @@ public final class SingleSidedAssociationCondition extends ArchCondition<JavaCla
+ " (@"
+ back.get().annotation()
+ ") point at each other without mappedBy: "
+ why(own.annotation(), back.get().annotation())
+ why(mappedType, member, own, target, counterpart, back.get())
+ ALTERNATIVE));
return;
}
}
/**
* Why a pair without {@code mappedBy} is refused. A collection and the to-one that points back,
* or two many-to-many collections, map one link from both ends; two to-one links are two foreign
* keys that reference each other's table.
* Why a pair without {@code mappedBy} is refused, from where each half keeps the link.
*
* <ul>
* <li>Two to-one links are two foreign keys that reference each other's table.
* <li>A collection with {@code @JoinColumn} and a to-one on that same column (or one that does
* not name its column) map one link from both ends — Hibernate's {@code @JoinColumn} form.
* <li>Anything else stores the link twice: a {@code @OneToMany} without {@code @JoinColumn}
* keeps it in a join table while the to-one keeps it in its own column (the shape a
* forgotten {@code mappedBy} produces), two {@code @ManyToMany} each own a join table, and
* two differently named columns are two columns (re-review 2026-11-03 round 3, RR3-02-05).
* </ul>
*/
private static String why(String own, String back) {
if (own.equals(inverseOf(back)) && !own.equals("OneToOne")) {
private static String why(
JavaClass ownType,
JavaMember ownMember,
Association own,
JavaClass backType,
JavaMember backMember,
Association back) {
if (!own.toMany() && !back.toMany()) {
return "each holds a foreign key to the other, so the two tables reference each other: neither"
+ " row can be inserted or deleted first, and one key has to be nullable and written by a"
+ " second UPDATE.";
}
Storage ownStorage = Storage.of(ownType, ownMember, own);
Storage backStorage = Storage.of(backType, backMember, back);
if (ownStorage.sameColumnAs(backStorage)) {
return "two fields map one link, and the read-only one does not follow a change made through"
+ " the other.";
}
return "each holds a foreign key to the other, so the two tables reference each other: neither"
+ " row can be inserted or deleted first, and one key has to be nullable and written by a"
+ " second UPDATE.";
return "the link is stored twice — in "
+ ownStorage.where()
+ " and in "
+ backStorage.where()
+ " — and each copy is written on its own, so the two drift apart.";
}
/** The annotation the other half of a pair carries. */
@@ -154,9 +181,48 @@ public final class SingleSidedAssociationCondition extends ArchCondition<JavaCla
return owner.getSimpleName() + "." + member.getName();
}
/**
* Where one half keeps the link: a foreign-key column ({@code column} is its name, empty when the
* mapping leaves it to the default) or a join table.
*
* @param where how the message names it
*/
private record Storage(boolean joinTable, String column, String where) {
static Storage of(JavaClass owner, JavaMember member, Association association) {
Optional<String> joinColumn =
member
.tryGetAnnotationOfType(JoinColumn.class.getName())
.map(annotation -> String.valueOf(annotation.get("name").orElse("")));
boolean joinTable =
association.annotation().equals("ManyToMany")
|| member.isAnnotatedWith(JoinTable.class)
|| (association.annotation().equals("OneToMany") && joinColumn.isEmpty());
if (joinTable) {
return new Storage(true, "", name(owner, member) + "'s join table");
}
String column = joinColumn.orElse("");
return new Storage(
false,
column,
column.isEmpty() ? name(owner, member) + "'s foreign-key column" : "column " + column);
}
/** Whether both halves name, or may default to, one foreign-key column. */
boolean sameColumnAs(Storage other) {
return !joinTable
&& !other.joinTable
&& (column.isEmpty() || other.column.isEmpty() || column.equalsIgnoreCase(other.column));
}
}
/** One association member: its annotation, its {@code mappedBy}, and the entity it points at. */
private record Association(String annotation, String mappedBy, JavaClass target) {
boolean toMany() {
return annotation.equals("OneToMany") || annotation.equals("ManyToMany");
}
static Optional<Association> of(JavaMember member) {
for (Class<? extends Annotation> type : ASSOCIATIONS) {
if (!member.isAnnotatedWith(type)) {
@@ -1,11 +1,16 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.migration;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -22,21 +27,44 @@ import java.util.regex.Pattern;
* version before it — a failed deploy, not an outage. {@code LOCAL}, because a plain {@code SET}
* outlives the migration on the pooled connection Flyway borrowed.
*
* <p>What counts as waiting for a lock: {@code ALTER TABLE}, {@code CREATE [UNIQUE] INDEX} and
* {@code DROP INDEX} without {@code CONCURRENTLY}, {@code LOCK TABLE}, {@code TRUNCATE}, {@code
* DROP TABLE}, and {@code UPDATE}/{@code DELETE} (they wait on the rows other transactions hold). A
* statement on a table this same migration created earlier waits for nothing and is left out.
* Comments and quoted literals are not read as statements. The check reads text, not a parse tree:
* it is a guard against the forgotten line, not a proof.
* <p>The statements it looks for, each on the table named in it:
*
* <ul>
* <li>{@code ALTER TABLE}, {@code LOCK TABLE}, {@code TRUNCATE}, {@code DROP TABLE};
* <li>{@code CREATE [UNIQUE] INDEX}, {@code DROP INDEX} and {@code REINDEX} without {@code
* CONCURRENTLY}, {@code REFRESH MATERIALIZED VIEW} without it, {@code CLUSTER}, {@code VACUUM
* FULL};
* <li>{@code REFERENCES} — in a new table as much as in an {@code ALTER TABLE} — on the table it
* references: a foreign key locks its parent against writes while it is added;
* <li>{@code CREATE TRIGGER} and {@code DROP TRIGGER} on the table the trigger is on;
* <li>{@code UPDATE} and {@code DELETE}, which wait on the rows other transactions hold.
* </ul>
*
* <p>A statement on a table this same migration created earlier waits for nothing and is left out;
* {@code CREATE TABLE IF NOT EXISTS} does not count as creating it, because the table may already
* be there. The bound in force at a statement is the last {@code lock_timeout} setting before it,
* and it counts only as {@code SET LOCAL} with a value that is not zero: {@code 0}, {@code DEFAULT}
* and {@code RESET} wait without end, a plain {@code SET} outlives the migration. A migration
* Flyway runs outside a transaction ({@code executeInTransaction=false} in its {@code .sql.conf},
* read by {@link #unboundedLockingStatements(Path)}) has no bound at all: {@code SET LOCAL} there
* only warns. Comments and quoted literals are not read as statements. The check reads text, not a
* parse tree: it is a guard against the forgotten line for the statements above, not a proof that
* no other statement waits (re-review 2026-11-03 round 3, RR3-02-01).
*/
public final class LockWaitMigrationInspector {
private static final String NAME =
"((?:\"[^\"]+\"|[a-z_][a-z0-9_$]*)(?:\\.(?:\"[^\"]+\"|[a-z_][a-z0-9_$]*))?)";
private static final String IDENTIFIER = "(?:\"[^\"]+\"|[a-z_][a-z0-9_$]*)";
/** A possibly qualified name the pattern does not capture: a trigger's own name. */
private static final String OTHER_NAME = IDENTIFIER + "(?:\\." + IDENTIFIER + ")?";
/** A possibly qualified name, captured as group 1: the table the statement locks. */
private static final String NAME = "(" + OTHER_NAME + ")";
private static final Pattern CREATED_TABLE =
Pattern.compile(
"\\bcreate\\s+(?:(?:temp|temporary|unlogged)\\s+)?table\\s+(?:if\\s+not\\s+exists\\s+)?"
"\\bcreate\\s+(?:(?:temp|temporary|unlogged)\\s+)?(?:table|materialized\\s+view)\\s+"
+ "(?!if\\s+not\\s+exists\\b)"
+ NAME);
/** Each pattern's group 1, when it has one, is the table the statement locks. */
@@ -48,6 +76,28 @@ public final class LockWaitMigrationInspector {
+ "(?:[a-z0-9_$\"]+\\s+)??on\\s+(?:only\\s+)?"
+ NAME),
Pattern.compile("\\bdrop\\s+index\\s+(?!concurrently\\b)"),
Pattern.compile(
"\\breindex\\s+(?:\\([^)]*\\)\\s+)?(?:(?:index|table)\\s+(?!concurrently\\b)"
+ NAME
+ "|(?:schema|database|system)\\b(?!\\s+concurrently\\b))"),
Pattern.compile("\\brefresh\\s+materialized\\s+view\\s+(?!concurrently\\b)" + NAME),
Pattern.compile(
"(?<!without )\\bcluster(?:\\s+verbose)?(?:\\s+(?!using\\b|on\\b)"
+ NAME
+ ")?(?=\\s*(?:;|$|using\\b))"),
Pattern.compile(
"\\bvacuum\\s+(?:\\([^)]*\\bfull\\b[^)]*\\)|full\\b)"
+ "(?:\\s+(?:freeze|verbose|analyze)\\b)*(?:\\s+"
+ NAME
+ ")?"),
Pattern.compile("\\breferences\\s+" + NAME),
Pattern.compile(
"\\bcreate\\s+(?:or\\s+replace\\s+)?(?:constraint\\s+)?trigger\\s+"
+ OTHER_NAME
+ "\\s+(?:before|after|instead\\s+of)\\s+[^;]*?\\bon\\s+(?:only\\s+)?"
+ NAME),
Pattern.compile(
"\\bdrop\\s+trigger\\s+(?:if\\s+exists\\s+)?" + OTHER_NAME + "\\s+on\\s+" + NAME),
Pattern.compile("\\block\\s+(?:table\\s+)?(?:only\\s+)?" + NAME),
Pattern.compile("\\btruncate\\s+(?:table\\s+)?(?:only\\s+)?" + NAME),
Pattern.compile("\\bdrop\\s+table\\s+(?:if\\s+exists\\s+)?" + NAME),
@@ -55,7 +105,22 @@ public final class LockWaitMigrationInspector {
Pattern.compile(
"\\bupdate\\s+(?:only\\s+)?" + NAME + "(?:\\s+(?:as\\s+)?[a-z_]\\w*)?\\s+set\\b"));
private static final Pattern BOUND = Pattern.compile("\\bset\\s+local\\s+lock_timeout\\b");
/**
* A {@code lock_timeout} setting: group 1 is {@code local} for {@code SET LOCAL}, group 2 the
* value. {@code RESET lock_timeout} matches with neither.
*/
private static final Pattern LOCK_TIMEOUT_SETTING =
Pattern.compile(
"\\bset\\s+(?:(local)\\s+|session\\s+)?lock_timeout(?:\\s*=\\s*|\\s+to\\s+)"
+ "('[^']*'|[^\\s;]+)|\\breset\\s+lock_timeout\\b");
/** A literal kept as written so a setting's value can be read: a number and an optional unit. */
private static final Pattern DURATION =
Pattern.compile("[0-9.]+\\s*[a-z]*", Pattern.CASE_INSENSITIVE);
/** The line in a migration's {@code .sql.conf} that makes Flyway run it outside a transaction. */
private static final Pattern OUTSIDE_A_TRANSACTION =
Pattern.compile("(?m)^\\s*executeInTransaction\\s*=\\s*false\\s*$");
/**
* Fails when the migration locks a table it did not create before it bounds the wait.
@@ -78,10 +143,27 @@ public final class LockWaitMigrationInspector {
}
/**
* The statements that wait for a lock on an existing table before any {@code SET LOCAL
* lock_timeout}, each as its leading words and table; empty when there are none.
* The statements that wait for a lock on an existing table without a {@code SET LOCAL
* lock_timeout} in force, each as its leading words and table; empty when there are none. The
* script is taken to run in a transaction, as Flyway runs a migration by default.
*/
public List<String> unboundedLockingStatements(String sql) {
return unboundedLockingStatements(sql, true);
}
/**
* The same, for a migration file on disk: a {@code <script>.conf} beside it that sets {@code
* executeInTransaction=false} makes every statement found unbounded, each named with the reason.
*/
public List<String> unboundedLockingStatements(Path script) throws IOException {
Path configuration = script.resolveSibling(script.getFileName() + ".conf");
boolean inTransaction =
!Files.exists(configuration)
|| !OUTSIDE_A_TRANSACTION.matcher(Files.readString(configuration)).find();
return unboundedLockingStatements(Files.readString(script), inTransaction);
}
private List<String> unboundedLockingStatements(String sql, boolean inTransaction) {
if (sql == null) {
return List.of();
}
@@ -91,14 +173,23 @@ public final class LockWaitMigrationInspector {
while (created.find()) {
createdAt.putIfAbsent(table(created.group(1)), created.start());
}
Matcher bound = BOUND.matcher(text);
int boundAt = bound.find() ? bound.start() : Integer.MAX_VALUE;
NavigableMap<Integer, Boolean> bounds = inTransaction ? bounds(text) : new TreeMap<>();
List<Located> found = new ArrayList<>();
for (Pattern pattern : LOCKING) {
Matcher statement = pattern.matcher(text);
while (statement.find()) {
if (statement.start() < boundAt && !createdEarlier(statement, createdAt)) {
found.add(new Located(statement.start(), statement.group().trim()));
Map.Entry<Integer, Boolean> setting = bounds.lowerEntry(statement.start());
boolean bounded = setting != null && setting.getValue();
if (!bounded && !createdEarlier(statement, createdAt)) {
String named = statement.group().trim();
found.add(
new Located(
statement.start(),
inTransaction
? named
: named
+ " (executeInTransaction=false: SET LOCAL does nothing outside a"
+ " transaction; move it to a migration that runs in one)"));
}
}
}
@@ -108,6 +199,18 @@ public final class LockWaitMigrationInspector {
.toList();
}
/** Each {@code lock_timeout} setting by position: whether it bounds the statements after it. */
private static NavigableMap<Integer, Boolean> bounds(String text) {
NavigableMap<Integer, Boolean> bounds = new TreeMap<>();
Matcher setting = LOCK_TIMEOUT_SETTING.matcher(text);
while (setting.find()) {
boolean local = setting.group(1) != null;
String value = setting.group(2) == null ? "" : setting.group(2);
bounds.put(setting.start(), local && value.matches(".*[1-9].*"));
}
return bounds;
}
private static boolean createdEarlier(Matcher statement, Map<String, Integer> createdAt) {
if (statement.groupCount() < 1 || statement.group(1) == null) {
return false;
@@ -124,7 +227,9 @@ public final class LockWaitMigrationInspector {
/**
* Blanks out comments and single-quoted literals, keeping every other character in place, so a
* word in a {@code COMMENT ON ... IS '...'} or a {@code -- } line is not read as a statement.
* word in a {@code COMMENT ON ... IS '...'} or a {@code -- } line is not read as a statement. A
* literal that is a number with an optional unit ({@code '5s'}) is kept: it holds no statement,
* and the {@code lock_timeout} value is read from it.
*/
private static String withoutCommentsAndLiterals(String sql) {
StringBuilder kept = new StringBuilder(sql.length());
@@ -140,6 +245,7 @@ public final class LockWaitMigrationInspector {
i = end < 0 ? sql.length() : end + 2;
kept.append(' ');
} else if (c == '\'') {
int start = i;
i++;
while (i < sql.length()) {
if (sql.charAt(i) == '\'' && i + 1 < sql.length() && sql.charAt(i + 1) == '\'') {
@@ -151,7 +257,12 @@ public final class LockWaitMigrationInspector {
i++;
}
}
kept.append("''");
String literal = sql.substring(start, i);
boolean duration =
literal.length() >= 2
&& literal.endsWith("'")
&& DURATION.matcher(literal.substring(1, literal.length() - 1)).matches();
kept.append(duration ? literal : "''");
} else {
kept.append(c);
i++;
@@ -0,0 +1,47 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.migration;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* The versioned migrations of one tree, found the way Flyway finds them: {@code V}, a version whose
* parts are separated by {@code _} or {@code .} ({@code V22}, {@code V22_1}, {@code V22.1}), two
* underscores, a description, {@code .sql}. Repeatable ({@code R__}) and undo ({@code U}) scripts
* and {@code .sql.conf} files are not versioned migrations.
*
* <p>One definition for every check that walks a tree — the operating trees' lock-wait and checksum
* checks and the sample stream's. Two copies had drifted: the operating trees' skipped {@code
* V22_1__} while the sample's counted it, so a decimal version in an operating tree was neither
* pinned nor held to the lock-wait rule (re-review 2026-11-03 round 3, RR3-02-03).
*/
public final class VersionedMigrationFiles {
private static final Pattern VERSIONED = Pattern.compile("V\\d+(?:[._]\\d+)*__.+\\.sql");
private VersionedMigrationFiles() {}
/**
* Every versioned migration below {@code root}, keyed by its path relative to {@code root} with
* {@code /} separators ({@code postgresql/V22__...sql}).
*/
public static SortedMap<String, Path> under(Path root) throws IOException {
Objects.requireNonNull(root, "root");
SortedMap<String, Path> migrations = new TreeMap<>();
try (Stream<Path> files = Files.walk(root)) {
for (Path file : files.filter(VersionedMigrationFiles::isVersioned).toList()) {
migrations.put(root.relativize(file).toString().replace('\\', '/'), file);
}
}
return migrations;
}
private static boolean isVersioned(Path file) {
return VERSIONED.matcher(file.getFileName().toString()).matches();
}
}
@@ -371,7 +371,14 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
mine = operationId.equals(field(rendered, "op")) ? "MINE" : "OPERATION_CONFLICT";
}
String stored = field(rendered, "resp");
return reply(state, attempt, rev, owner, stored == null ? "" : stored, mine + "|60000");
String leaseUntil = field(rendered, "leaseUntil");
return reply(
state,
attempt,
rev,
owner,
stored == null ? "" : stored,
mine + "|60000|" + (leaseUntil == null ? "" : leaseUntil));
}
private static List<Object> reply(
+12 -1
View File
@@ -38,9 +38,20 @@ service contributes them to the runtime as beans, one per lane it uses, through
@Bean RedisAccountContribution redisAdminAccount() {
return RedisSdkComposition.adminAccount("secret://ca-skeleton-admin-readonly@environment/APP_REDIS_ADMIN");
}
// The admin reference is code, not an environment value, so the prod secret guard only sees the
// variable it names when the composer names it too (adapter:outbound:support).
@Bean static RequiredProductionSecrets redisAdminSecret() {
return environment -> List.of("APP_REDIS_ADMIN");
}
```
— and builds `LettuceRedisCommandGateway.over(lease.driver())` over a borrowed lease. The service's
— and builds `LettuceRedisCommandGateway.over(lease.driver())` over a borrowed lease. The last bean
matters only with an admin account: under `prod`, `SecretSourceValidator` refuses a secret that holds
a lane fixture password (`fixture-admin` is in `infra/redis-sdk/acl`), but it learns which variables
are secrets from the registry, from `secret://` references in the environment and from
`RequiredProductionSecrets` beans — not from a reference held in code. Without the bean the admin
account could run in production on the public lane password (review 2026-11-04 RR3-04-03). The SDK
cannot contribute it itself: it depends on `redis-runtime` and `shared-contract` only. The service's
adapter composes the SDK objects it uses on top of that; `LiveRedisOperationsFixture` in this leaf's
tests is a complete worked composition (catalog, permit verifier, guard, executor, operations).
@@ -17,10 +17,22 @@ import dev.caskeleton.adapter.outbound.cache.redis.runtime.connection.RedisAccou
* @Bean RedisLaneContribution redisTransactionLane() { return RedisSdkComposition.transactionLane(16); }
* @Bean RedisLaneContribution redisAdminLane() { return RedisSdkComposition.adminLane(); }
* @Bean RedisAccountContribution redisAdminAccount() {
* return RedisSdkComposition.adminAccount("secret://ca-skeleton-admin@environment/APP_REDIS_ADMIN");
* return RedisSdkComposition.adminAccount(
* "secret://ca-skeleton-admin-readonly@environment/APP_REDIS_ADMIN");
* }
* @Bean static RequiredProductionSecrets redisAdminSecret() {
* return environment -> List.of("APP_REDIS_ADMIN");
* }
* }</pre>
*
* <p>The last bean names the admin account's variable to the {@code prod} secret guard, which
* refuses a secret holding a lane fixture password. The guard finds secrets in the registry, in
* {@code secret://} references among the environment's values, and in {@code
* RequiredProductionSecrets} beans; a reference held in code is none of those, so without it the
* admin account could run in production on the public {@code fixture-admin} password (review
* 2026-11-04 RR3-04-03). The SDK cannot declare it: it does not depend on {@code
* adapter:outbound:support}.
*
* <p>Like the SDK's other knobs (operation limits, enabled policies, raw approvals) these are code,
* not {@code app.redis.*} settings: the runtime's settings describe the runtime, and a lane nobody
* composed has no setting to be wrong about. An admin lane without an admin account runs on the
@@ -10,6 +10,11 @@ import org.springframework.core.env.Environment;
* secret-source guard, which checks each named secret resolves under the {@code prod} profile. The
* guard does not know which roles a module has or which secret each one needs; before this it
* spelled out every Redis role's selector and secret prefix itself.
*
* <p>Declare it with a {@code static} {@code @Bean} method without parameters. The guard reads it
* before any bean post-processor exists, so {@link StartupRuleRunner} creates every one in every
* profile before any rule runs, and fails the boot when one pulls another bean forward or its
* runtime class needs a post-processor — not only on the first {@code prod} boot.
*/
@FunctionalInterface
public interface RequiredProductionSecrets {
@@ -60,8 +60,11 @@ import org.springframework.util.ReflectionUtils;
* binding on the class or its {@code @Bean} method. Each of those stays unset or uncalled for the
* whole run, silently: a rule then reads {@code null} and its check is off, and a settings class
* that doubles as a secret list keeps its defaults in {@code prod}, where the secret guard reads it
* early, and only there (review 2026-11-04 RR2-04-03). The runner refuses such a bean by name
* before any rule runs, in every profile, and again by its runtime class when it is created.
* early, and only there (review 2026-11-04 RR2-04-03). The runner refuses such a bean before any
* rule runs, in every profile: first by the type its definition declares, then by its runtime
* class, because it creates every rule and every secret list then — the declared type of a {@code
* static} method that returns an interface hides the class behind it (RR3-04-01). A secret list
* that pulls another bean forward fails the same way in every profile, not only in {@code prod}.
*
* <p>Checked by what the bean needs rather than by how it is declared. Requiring a {@code static}
* factory method was the other way, and it checks the wrong thing: it refuses a rule registered
@@ -109,6 +112,16 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere
refuseUnprocessedMembers(beanFactory, name, beanFactory.getType(name, false));
}
}
// The declared type of a @Bean method can hide the class it returns (an interface-typed static
// method returning a class with an @Value field), and only creating the bean shows it. Rules
// are created below in every profile; secret lists are created here, so their runtime class is
// checked in every profile too, not only when prod's secret guard reads them (RR3-04-01).
for (String name :
beanFactory.getBeanNamesForType(RequiredProductionSecrets.class, true, false)) {
Set<String> before = singletons(beanFactory);
beanFactory.getBean(name, RequiredProductionSecrets.class);
refusePulledForward(beanFactory, name, "creating it", before);
}
IdentityHashMap<StartupRule, String> names = new IdentityHashMap<>();
List<StartupRule> rules = new ArrayList<>();
for (String name : beanFactory.getBeanNamesForType(StartupRule.class, true, false)) {
@@ -139,11 +152,11 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere
}
/**
* Fails when creating or running the rule {@code ruleName} brought a singleton into existence
* other than a rule or a {@link RequiredProductionSecrets}: that bean was built before the bean
* post-processors, so its settings are unbound and it is not proxied, for the rest of the run. A
* rule or secret list it created is held to {@link #refuseUnprocessedMembers} by its runtime
* class, which a {@code @Bean} method's declared return type may hide.
* Fails when creating or running the rule or secret list {@code ruleName} brought a singleton
* into existence other than a rule or a {@link RequiredProductionSecrets}: that bean was built
* before the bean post-processors, so its settings are unbound and it is not proxied, for the
* rest of the run. A rule or secret list it created is held to {@link #refuseUnprocessedMembers}
* by its runtime class, which a {@code @Bean} method's declared return type may hide.
*/
private static void refusePulledForward(
ConfigurableListableBeanFactory beanFactory,
@@ -170,7 +183,7 @@ public final class StartupRuleRunner implements BeanFactoryPostProcessor, Ordere
// A configuration error of the composition, so the configuration exit code (78): no
// environment fixes it, but neither does a retry, and it must not look like a crash.
throw StartupFailures.envValidation(
"startup rule '"
"startup rule or secret list '"
+ ruleName
+ "' created "
+ pulled
@@ -133,8 +133,11 @@ class StartupRuleRunnerTest {
}
@Test
@DisplayName("규칙이 실행 중에 꺼내는 RequiredProductionSecrets가 다른 bean을 앞당기면 기동이 실패한다")
@DisplayName("규칙이 읽는 RequiredProductionSecrets가 다른 bean을 앞당기면 규칙이 돌기 전에 기동이 실패한다")
void aProductionSecretsBeanThatPullsItsConfigurationForwardFailsTheBoot() {
// given
SecretReadingRuleConfig.SEEN.clear();
// when
runner
.withUserConfiguration(SecretReadingRuleConfig.class, NonStaticSecretsConfig.class)
@@ -143,8 +146,9 @@ class StartupRuleRunnerTest {
// then
assertThat(context.getStartupFailure())
.isInstanceOf(StartupFailureException.class)
.hasMessageContaining("secretReadingRule")
.hasMessageContaining("probeSecrets")
.hasMessageContaining("NonStaticSecretsConfig");
assertThat(SecretReadingRuleConfig.SEEN).isEmpty();
});
}
@@ -240,6 +244,43 @@ class StartupRuleRunnerTest {
});
}
@Test
@DisplayName("인터페이스 타입 static @Bean이 돌려준 비밀 목록의 @Value 필드는 그것을 읽는 규칙이 없는 프로필에서도 기동을 실패시킨다")
void aSecretsListHiddenBehindAnInterfaceTypedBeanFailsTheBootWithoutAReadingRule() {
// given
ValueFieldSecrets.SEEN.clear();
// when
runner
.withPropertyValues("probe4.secret=bound")
.withUserConfiguration(InterfaceTypedSecretsConfig.class)
.run(
context -> {
// then
assertThat(context.getStartupFailure())
.isInstanceOf(StartupFailureException.class)
.hasMessageContaining("hiddenSecrets")
.hasMessageContaining("secret (@Value)");
assertThat(ValueFieldSecrets.SEEN).isEmpty();
});
}
@Test
@DisplayName("다른 bean을 앞당기는 RequiredProductionSecrets는 그것을 읽는 규칙이 없는 프로필에서도 기동을 실패시킨다")
void aProductionSecretsBeanThatPullsItsConfigurationForwardFailsTheBootWithoutAReadingRule() {
// when
runner
.withUserConfiguration(NonStaticSecretsConfig.class)
.run(
context -> {
// then
assertThat(context.getStartupFailure())
.isInstanceOf(StartupFailureException.class)
.hasMessageContaining("probeSecrets")
.hasMessageContaining("NonStaticSecretsConfig");
});
}
private static StartupRule rule(StartupPhase phase, String summary, List<String> violations) {
return new StartupRule() {
@Override
@@ -395,6 +436,28 @@ class StartupRuleRunnerTest {
}
}
/** RR3-04-01: a secret list whose @Value field the declared interface return type hides. */
public static class ValueFieldSecrets implements RequiredProductionSecrets {
static final List<String> SEEN = new ArrayList<>();
@Value("${probe4.secret}")
private String secret;
@Override
public List<String> requiredSecrets(Environment environment) {
SEEN.add(secret);
return List.of();
}
}
@Configuration(proxyBeanMethods = false)
static class InterfaceTypedSecretsConfig {
@Bean
static RequiredProductionSecrets hiddenSecrets() {
return new ValueFieldSecrets();
}
}
@Configuration(proxyBeanMethods = false)
static class NonStaticSecretsConfig {
@Bean
+3 -2
View File
@@ -88,8 +88,9 @@ configurations, Redis as one 376-line class.
- **An environment-only guard is a `StartupRule` bean** (`support.startup`): it returns violations,
and the one `StartupRuleRunner` raises them before any other singleton exists (declare it with a
`static` `@Bean` method that takes only the `Environment`, the bean factory or an `ObjectProvider`
of static `RequiredProductionSecrets`; the runner fails the boot naming any other bean a rule
creates, and naming any rule or `RequiredProductionSecrets` that has an `@Value`/`@Autowired`/
of static `RequiredProductionSecrets`; in every profile the runner creates each rule and each
`RequiredProductionSecrets` before any rule runs, and fails the boot naming any other bean one of
them creates, and naming any whose runtime class has an `@Value`/`@Autowired`/
`@Inject`/`@Resource` member, a `@PostConstruct`/`@PreDestroy` callback or a
`@ConfigurationProperties` binding — those are created before the post-processors and would stay
unset). A guard that needs another bean stays a bean. A
+4 -2
View File
@@ -133,8 +133,10 @@ README의 "startup" 절에 있다.
lane용으로 적어 둔 공개 비밀번호(`infra/redis-sdk/acl`의 Redis ACL fixture, compose lane의
`REDIS_LANE_*`)라서, lane 환경이나 lane ACL 파일을 베낀 배포가 그대로 운영에 뜨는 것을 막는다
(review 2026-11-03 RR-07-04). 이 검사는 비밀값만 본다 — 레지스트리의 `secret` 행
(`CLASSIFIED_SECRETS`), 모듈이 기여한 비밀, `secret://…/<VAR>` 참조가 가리키는 변수
(review 2026-11-04 RR2-04-01). `fixture-`는 평범한 단어라서 `fixture-api` Deployment의 pod 이름
(`CLASSIFIED_SECRETS`), 모듈이 기여한 비밀, 환경 값에 든 `secret://…/<VAR>` 참조가 가리키는 변수
(review 2026-11-04 RR2-04-01). 코드에 든 참조(Redis SDK admin 계정의 `RedisAccountContribution`)는 보지
못하므로, 그 계정을 조립하는 쪽이 변수를 `RequiredProductionSecrets` bean으로도 낸다(RR3-04-03,
`src/adapter/outbound/redis-sdk/README.md`). `fixture-`는 평범한 단어라서 `fixture-api` Deployment의 pod 이름
(`HOSTNAME`)이나 앱 이름까지 거부하면 운영에서만 기동이 막혔다. `__LOCAL_DEV_` 표시는 정당한 값이 가질
일이 없으니 모든 값을 본다. 실패 메시지는 변수 이름만 적고 값은 적지 않는다. (2) 레지스트리에서 `secret` +
`prod_default: null`로 분류된 모든 키는 prod 에서 비어 있지 않게 주입돼야 한다 — 빈 시크릿으로
@@ -462,6 +462,10 @@ class ApplicationBoundaryArchitectureTest {
* framework types an endpoint is built from. {@code org.springframework.messaging} is named only
* for STOMP ({@code simp}, {@code @MessageMapping}): a broker listener's {@code @Payload} and
* {@code @Header} live beside them and are a system consumer's, not a user's.
*
* <p>The framework half is a list, unlike the package allowlist above: a transport library
* missing from it is not recognised as one. A service that brings in a new transport library adds
* its packages here (review 2026-11-04 RR3-01-02).
*/
private static final DescribedPredicate<JavaClass> ARE_USER_TRANSPORT_TYPES =
JavaClass.Predicates.resideInAnyPackage(
@@ -474,14 +478,33 @@ class ApplicationBoundaryArchitectureTest {
"org.springframework.messaging.simp..",
"io.grpc..",
"jakarta.servlet..",
"jakarta.websocket..")
"jakarta.websocket..",
"jakarta.ws.rs..",
"graphql..")
.or(
com.tngtech.archunit.core.domain.properties.HasName.Predicates.name(
"org.springframework.stereotype.Controller"))
.or(
com.tngtech.archunit.core.domain.properties.HasName.Predicates.name(
"org.springframework.messaging.handler.annotation.MessageMapping"))
.as("user-transport types (web, GraphQL, gRPC, WebSocket/STOMP endpoints)");
.as("user-transport types (web, JAX-RS, GraphQL, gRPC, WebSocket/STOMP endpoints)");
/**
* A class a user request comes in through: it lives in a user-transport package or is built from
* a user-transport type. A configuration that only registers a system caller is neither, which is
* why the rule below names these rather than every inbound class.
*/
private static final DescribedPredicate<JavaClass> ARE_USER_TRANSPORTS =
new DescribedPredicate<>(
"are user transports (in a user-transport package or built from one)") {
@Override
public boolean test(JavaClass candidate) {
return ARE_USER_TRANSPORT_TYPES.test(candidate)
|| candidate.getDirectDependenciesFromSelf().stream()
.anyMatch(
dependency -> ARE_USER_TRANSPORT_TYPES.test(dependency.getTargetClass()));
}
};
/**
* A class marked {@link SystemCaller}, or nested in one: a handler's anonymous or inner helper
@@ -533,13 +556,14 @@ class ApplicationBoundaryArchitectureTest {
* {@link SystemCaller} is a claim, so it is checked: the marked class lives in a system-driven
* inbound package and is no endpoint a user can call — a controller, a GraphQL or STOMP mapping,
* a gRPC service. Without this the mark would be the next way to silence the rule above (review
* 2026-11-03 RR-01-12).
* 2026-11-03 RR-01-12). The claim covers the classes nested in the marked one, because the rule
* above exempts exactly those: an endpoint nested in a job is checked as the job is (review
* 2026-11-04 RR3-01-01).
*/
@ArchTest
static final ArchRule SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS =
classes()
.that()
.areAnnotatedWith(SystemCaller.class)
.that(ARE_SYSTEM_CALLERS)
.should()
.resideInAnyPackage(SYSTEM_DRIVEN_INBOUND_PACKAGES)
.andShould(
@@ -547,10 +571,36 @@ class ApplicationBoundaryArchitectureTest {
com.tngtech.archunit.lang.conditions.ArchConditions.dependOnClassesThat(
ARE_USER_TRANSPORT_TYPES)))
.as(
"SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS: a @SystemCaller lives in a "
+ "system-driven inbound package (..adapter.inbound.messaging.., "
+ "..adapter.inbound.scheduler..) and depends on no user-transport type — the mark "
+ "says no user request reaches the class, so a user transport cannot carry it")
"SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS: a @SystemCaller, and every class "
+ "nested in one, lives in a system-driven inbound package "
+ "(..adapter.inbound.messaging.., ..adapter.inbound.scheduler..) and depends on "
+ "no user-transport type — the mark says no user request reaches the class, so a "
+ "user transport cannot carry it")
.allowEmptyShould(true);
/**
* The other way round: a user transport does not reach a {@link SystemCaller}, directly or
* through classes in between. A "run now" endpoint handed the job bean never names the {@link
* SystemInvoked} use case, so the rules above do not see it, yet a user request then runs a write
* no permission guards (review 2026-11-04 RR3-01-01). The configuration that registers the
* handler is no transport and may depend on it.
*
* <p>Like every rule here it reads class dependencies. A lookup at run time ({@code getBean},
* {@code ObjectProvider}) is not a dependency and is not seen.
*/
@ArchTest
static final ArchRule USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS =
noClasses()
.that(ARE_USER_TRANSPORTS)
.should()
.transitivelyDependOnClassesThat(ARE_SYSTEM_CALLERS)
.as(
"USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS: a class a user request comes in "
+ "through (a user-transport package, or built from a web, JAX-RS, GraphQL, gRPC "
+ "or WebSocket type) does not reach a @SystemCaller, directly or through other "
+ "classes — the system caller runs a @SystemInvoked write with no permission "
+ "check. A user-triggered run of the same work is its own use case with "
+ "@RequiresPermission (manual 07 「시스템이 부르는 쓰기」)")
.allowEmptyShould(true);
/**
@@ -168,6 +168,7 @@ class ArchRuleDiscoveryContractTest {
"SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION",
"TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES",
"THROWABLES_ARE_NAMED_EXCEPTION",
"USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS",
"USE_CASE_CAPABILITY_MATCHES_TRANSACTION_PORT_BOUNDARY",
"USE_CASE_PORTS_CARRY_ONE_OPERATION",
"VALIDATION_CONSTRAINTS_STAY_AT_WEB_BOUNDARY",
@@ -7,11 +7,16 @@ import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.lang.EvaluationResult;
import dev.caskeleton.application.architecture.violations.ApplicationDiagnosticFrameworkViolation;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerRegistrationFixture;
import dev.caskeleton.bootstrap.architecture.allowed.application.CleanProjectionQueryPort;
import dev.caskeleton.bootstrap.architecture.fixtures.application.RootWriteTransactionBoundaryUseCase;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.SystemCallerRestControllerFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.UnmarkedSystemInvokedHandlerFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemCallerWithNestedEndpointFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemJobLauncherFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerControllerFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerInvokingControllerFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemCallerRelayingControllerFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller.SystemInvokedCallingControllerFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.RawExternalResponseFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.outbound.messaging.GenericTypeLeakingAdapterFixture;
@@ -188,6 +193,47 @@ class ArchitectureViolationFixtureTest {
private static final JavaClasses SYSTEM_CALLER_THAT_IS_AN_HTTP_ENDPOINT_FIXTURE_ONLY =
new ClassFileImporter().importClasses(SystemCallerRestControllerFixture.class);
// Review 2026-11-04 RR3-01-01: a user transport that never names the use case but calls the
// system caller holding it — directly, and through one unmarked class in between.
private static final JavaClasses CONTROLLER_CALLING_A_SYSTEM_CALLER_FIXTURE_ONLY =
new ClassFileImporter()
.importClasses(
SystemCallerInvokingControllerFixture.class,
SystemCallerHandlerFixture.class,
SystemInvokedFixtureUseCase.class);
private static final JavaClasses CONTROLLER_RELAYING_TO_A_SYSTEM_CALLER_FIXTURE_ONLY =
new ClassFileImporter()
.importClasses(
SystemCallerRelayingControllerFixture.class,
SystemJobLauncherFixture.class,
SystemCallerHandlerFixture.class,
SystemInvokedFixtureUseCase.class);
// The configuration that registers the handler: it depends on a system caller and is no
// transport, so the rule above must leave it alone.
private static final JavaClasses SYSTEM_CALLER_REGISTRATION_FIXTURE_ONLY =
new ClassFileImporter()
.importClasses(
SystemCallerHandlerRegistrationFixture.class,
SystemCallerHandlerFixture.class,
SystemInvokedFixtureUseCase.class);
// An endpoint nested in a marked job: the mark exempts nested classes, so they carry its claim.
private static final JavaClasses ENDPOINT_NESTED_IN_A_SYSTEM_CALLER_FIXTURE_ONLY =
new ClassFileImporter()
.importClasses(
SystemCallerWithNestedEndpointFixture.class,
SystemCallerWithNestedEndpointFixture.RunNowEndpoint.class,
SystemInvokedFixtureUseCase.class);
// RR3-01-02: a JAX-RS endpoint carrying the mark. importPackages, so the compile-only
// jakarta.ws.rs types are read from bytecode and never linked.
private static final JavaClasses JAXRS_SYSTEM_CALLER_FIXTURE_ONLY =
new ClassFileImporter()
.importPackages(
"dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.jaxrs");
// Review 2026-11-03 RR-01-03: one class that builds the draft by hand.
private static final JavaClasses HAND_BUILT_DRAFT_FIXTURE_ONLY =
new ClassFileImporter().importClasses(HandBuiltIntegrationEventDraftFixture.class);
@@ -246,6 +292,51 @@ class ArchitectureViolationFixtureTest {
assertThat(result.hasViolation()).isTrue();
}
@Test
void aControllerThatCallsASystemCallerBeanIsCaught() {
EvaluationResult result =
ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate(
CONTROLLER_CALLING_A_SYSTEM_CALLER_FIXTURE_ONLY);
assertThat(result.hasViolation()).isTrue();
}
@Test
void aControllerThatReachesASystemCallerThroughAnotherClassIsCaught() {
EvaluationResult result =
ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate(
CONTROLLER_RELAYING_TO_A_SYSTEM_CALLER_FIXTURE_ONLY);
assertThat(result.hasViolation()).isTrue();
}
@Test
void aConfigurationThatRegistersASystemCallerMayDependOnIt() {
EvaluationResult result =
ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate(
SYSTEM_CALLER_REGISTRATION_FIXTURE_ONLY);
assertThat(result.getFailureReport().getDetails()).isEmpty();
}
@Test
void anEndpointNestedInASystemCallerIsCaught() {
EvaluationResult result =
ApplicationBoundaryArchitectureTest.SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS
.evaluate(ENDPOINT_NESTED_IN_A_SYSTEM_CALLER_FIXTURE_ONLY);
assertThat(result.hasViolation()).isTrue();
}
@Test
void aJaxRsEndpointMarkedAsASystemCallerIsCaught() {
EvaluationResult result =
ApplicationBoundaryArchitectureTest.SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS
.evaluate(JAXRS_SYSTEM_CALLER_FIXTURE_ONLY);
assertThat(result.hasViolation()).isTrue();
}
@Test
void aFeatureThatBuildsAnIntegrationEventDraftByHandIsCaught() {
EvaluationResult result =
@@ -0,0 +1,18 @@
package dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* The configuration that registers a system caller as a bean. It depends on the handler and is no
* user transport, so {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} must not flag it — that is
* why the rule names user transports rather than every inbound class (review 2026-11-04 RR3-01-01).
*/
@Configuration(proxyBeanMethods = false)
public class SystemCallerHandlerRegistrationFixture {
@Bean
SystemCallerHandlerFixture systemCallerHandler() {
return new SystemCallerHandlerFixture();
}
}
@@ -4,6 +4,8 @@
* {@code @SystemInvoked} use case it constructed itself. {@code
* ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} and {@code
* SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS} must NOT flag it — it is the one legitimate
* way a consumer reaches a system write (manual 09 「소비」 step 4).
* way a consumer reaches a system write (manual 09 「소비」 step 4). The configuration that registers
* that handler as a bean is here too: {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} must not
* flag it either (review 2026-11-04 RR3-01-01).
*/
package dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging;
@@ -0,0 +1,24 @@
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.jaxrs;
import dev.caskeleton.application.security.SystemCaller;
import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
/**
* Negative fixture for {@code SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS}: a JAX-RS endpoint
* in a system-driven package carrying the mark. The transport-type half of the rule is a list, so a
* transport missing from it passes (review 2026-11-04 RR3-01-02). Loaded with {@code
* importPackages}: {@code jakarta.ws.rs-api} is compile-only here, so JUnit must never link it.
*/
@SystemCaller(reason = "fixture: a JAX-RS endpoint hiding in the messaging package")
@Path("/fixture/jaxrs-system-write")
public class JaxRsSystemCallerFixture {
private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase();
@POST
public void trigger() {
useCase.handle();
}
}
@@ -0,0 +1,34 @@
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler;
import dev.caskeleton.application.security.SystemCaller;
import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Negative fixture for {@code SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS}: a scheduled job
* that carries the mark, with an HTTP endpoint nested inside it. The mark exempts nested classes
* from {@code ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES}, so the claim has to be checked
* on them too (review 2026-11-04 RR3-01-01).
*/
@SystemCaller(reason = "fixture: the scheduler ticks it")
public final class SystemCallerWithNestedEndpointFixture {
private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase();
public void run() {
useCase.handle();
}
/** A user transport living under the job's mark. */
@RestController
public static class RunNowEndpoint {
private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase();
@PostMapping("/fixture/nested-run-now")
public void runNow() {
useCase.handle();
}
}
}
@@ -0,0 +1,20 @@
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
/**
* The class in between for {@code SystemCallerRelayingControllerFixture}: unmarked, no transport
* type, and it calls the system caller it is given.
*/
public class SystemJobLauncherFixture {
private final SystemCallerHandlerFixture handler;
public SystemJobLauncherFixture(SystemCallerHandlerFixture handler) {
this.handler = handler;
}
public void launch() {
handler.handle();
}
}
@@ -0,0 +1,26 @@
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a "run now" endpoint
* that is handed the system caller bean and calls it. It never names the {@code @SystemInvoked} use
* case, so the rule on that dependency does not see it, yet a user request now runs a write no
* permission guards (review 2026-11-04 RR3-01-01).
*/
@RestController
public class SystemCallerInvokingControllerFixture {
private final SystemCallerHandlerFixture handler;
public SystemCallerInvokingControllerFixture(SystemCallerHandlerFixture handler) {
this.handler = handler;
}
@PostMapping("/fixture/run-now")
public void runNow() {
handler.handle();
}
}
@@ -0,0 +1,26 @@
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.web.controller;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemJobLauncherFixture;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: the same "run now"
* endpoint with one more class in between. The launcher is neither a transport nor a system caller,
* so only a rule that follows the chain sees that a user request still reaches the system write
* (review 2026-11-04 RR3-01-01).
*/
@RestController
public class SystemCallerRelayingControllerFixture {
private final SystemJobLauncherFixture launcher;
public SystemCallerRelayingControllerFixture(SystemJobLauncherFixture launcher) {
this.launcher = launcher;
}
@PostMapping("/fixture/run-now-via-launcher")
public void runNow() {
launcher.launch();
}
}
@@ -163,9 +163,14 @@ public final class SecretSourceValidator implements StartupRule {
/**
* Names every secret that holds a lane fixture password: the keys the registry classifies {@code
* secret}, the ones a module contributed, and every variable a credential reference names. Read
* through the same backend the application resolves them with. The value is never put in the
* message.
* secret}, the ones a module contributed, and every variable a credential reference among the
* environment's values names. Read through the same backend the application resolves them with.
* The value is never put in the message.
*
* <p>A reference held in code is not seen — the typed Redis SDK's admin account is a {@code
* RedisAccountContribution} bean, which this rule cannot read without creating it early. Its
* composer names the variable in a {@link RequiredProductionSecrets} bean as well (review
* 2026-11-04 RR3-04-03, {@code RedisSdkComposition}).
*/
private static void collectFixturePasswordViolations(
Environment environment,
+12 -8
View File
@@ -202,12 +202,15 @@ subclass a final class (`RequiresPermissionProxyabilityTest`). It is registered
same reason — a use case built with `new` is never checked. A use case only the system calls (a
scheduler, a relay, a message consumer) carries `@SystemInvoked(reason = ...)` instead of a
permission and is not a bean: it is a write with no permission check, so no user request may reach
it. Its system caller constructs it — a composition module for a scheduler, or a
`@SystemCaller(reason = ...)` message handler in `..adapter.inbound.messaging..` (manual 09
「소비」 step 4). Both halves are enforced — a `@SystemInvoked` bean fails startup, and an inbound
adapter that depends on one without being a `@SystemCaller` fails
`ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES` (`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`
keeps the mark off user transports). A composition with `@RequiresPermission`
it. Its system caller constructs it — a composition module for a scheduler, a
`@SystemCaller(reason = ...)` message handler in `..adapter.inbound.messaging..`, or a
`@SystemCaller` scheduled job in the service's own `..adapter.inbound.scheduler..` package. Manual
07 「시스템이 부르는 쓰기」 is the canonical list of the three and where each lives. All of it is
enforced — a `@SystemInvoked` bean fails startup, an inbound adapter that depends on one without
being a `@SystemCaller` fails `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`,
`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS` keeps the mark (and classes nested in a marked
one) off user transports, and `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS` keeps a user transport
from calling a system caller. A composition with `@RequiresPermission`
beans but no enforcing advisor fails startup too (`composition:service-runtime`
`PermissionEnforcementGuard`, both checks).
@@ -268,8 +271,9 @@ generation; the V1 `IdempotencyScope`/`tryBegin` API is gone.
could not prove the outcome, so do not blindly retry.
- Every store answers an execution whose processing lease ran out with `RecoveryRequired` and never
takes it over; only a claim that never started or a retryable failure is taken over. A record lives
for the lease plus the replay TTL. `IdempotencyStoreContract` holds the fake, Redis and PostgreSQL
to both on real servers (re-review 2026-11-04 RR-01-11, RR-03-11).
for the lease plus the replay TTL. `IdempotencyStoreContract` holds Redis and PostgreSQL to both on
real servers; the in-memory fake models no time, so it runs only the contract's time-free cases
(re-review 2026-11-04 RR-01-11, RR-03-11, RR3-03-04).
The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency`
and its fixture were removed when this branch merged.
+2 -1
View File
@@ -458,7 +458,8 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장.
`PermissionEnforcementGuard`가 기동을 실패시키고, `@SystemCaller`가 아닌 inbound adapter가 그 클래스에
의존하면 `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`가 빌드를 실패시킨다(review 2026-11-03
RR-01-02, RR-01-12). 메시지 소비자는 `@SystemCaller` handler가 use case를 직접 만든다(매뉴얼 09장
「소비」 4단계).
「소비」 4단계). 시스템 호출자 세 가지(조립 모듈의 스케줄러, `@SystemCaller` 메시지 handler,
`@SystemCaller` 예약 작업)와 각각 두는 곳은 매뉴얼 07장 「시스템이 부르는 쓰기」가 정본이다.
### OutboxBackoffPolicy
@@ -121,9 +121,9 @@ public final class IdempotencyExecutor {
case IdempotencyClaimOutcome.InProgress ignored ->
throw IdempotencyInFlightException.forScopeDigest(diagnostic(scope));
case IdempotencyClaimOutcome.RecoveryRequired ignored ->
throw recovery("claim requires reconciliation");
throw recovery(scope, "claim requires reconciliation");
case IdempotencyClaimOutcome.OwnerOperationConflict ignored ->
throw recovery("claim requires reconciliation");
throw recovery(scope, "claim requires reconciliation");
case IdempotencyClaimOutcome.Unavailable ignored ->
throw new IdempotencyUnavailableException();
// The response was lost, not the attempt. The retained attempt is what makes the record
@@ -148,9 +148,11 @@ public final class IdempotencyExecutor {
IdempotencyInspection inspection = inspect(request);
return switch (inspection.outcome()) {
case CLAIMED_SAME_OPERATION ->
startAndRun(request, requireOwner(inspection), action, codec, false);
case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec);
case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload());
startAndRun(request, requireOwner(request.scope(), inspection), action, codec, false);
case EXECUTING_SAME_OPERATION ->
runStarted(request, requireOwner(request.scope(), inspection), action, codec);
case COMPLETED_REPLAY ->
codec.deserialize(requireResponse(request.scope(), inspection).payload());
case FINGERPRINT_MISMATCH ->
throw IdempotencyRequestMismatchException.forScopeDigest(diagnostic(request.scope()));
case IN_PROGRESS_OTHER ->
@@ -159,7 +161,8 @@ public final class IdempotencyExecutor {
// ABSENT, FAILED_RETRYABLE, ABANDONED and OPERATION_CONFLICT all mean the same thing here:
// this caller cannot prove what happened to its own attempt, and guessing is the one thing an
// owner-safe store exists to prevent.
default -> throw recovery("an indeterminate claim could not be resumed safely");
default ->
throw recovery(request.scope(), "an indeterminate claim could not be resumed safely");
};
}
@@ -179,11 +182,14 @@ public final class IdempotencyExecutor {
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
case INDETERMINATE -> {
if (alreadyRetried) {
throw recovery("execution start stayed indeterminate after reconciliation");
throw recovery(
request.scope(), "execution start stayed indeterminate after reconciliation");
}
yield resumeAfterIndeterminateStart(request, action, codec);
}
default -> throw recovery("execution start was not confirmed for this exact operation");
default ->
throw recovery(
request.scope(), "execution start was not confirmed for this exact operation");
};
}
@@ -194,11 +200,13 @@ public final class IdempotencyExecutor {
IdempotencyInspection inspection = inspect(request);
return switch (inspection.outcome()) {
case CLAIMED_SAME_OPERATION ->
startAndRun(request, requireOwner(inspection), action, codec, true);
case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec);
case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload());
startAndRun(request, requireOwner(request.scope(), inspection), action, codec, true);
case EXECUTING_SAME_OPERATION ->
runStarted(request, requireOwner(request.scope(), inspection), action, codec);
case COMPLETED_REPLAY ->
codec.deserialize(requireResponse(request.scope(), inspection).payload());
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
default -> throw recovery("execution start is indeterminate");
default -> throw recovery(request.scope(), "execution start is indeterminate");
};
}
@@ -253,7 +261,7 @@ public final class IdempotencyExecutor {
// The action has run. Reporting "unavailable" here would tell the client it did not.
case UNAVAILABLE -> throw new IdempotencyCompletionUnknownException();
case INDETERMINATE -> reconcileCompletion(request, result, codec, alreadyRetried);
default -> throw recovery("completion was not confirmed");
default -> throw recovery(request.scope(), "completion was not confirmed");
};
}
@@ -272,22 +280,25 @@ public final class IdempotencyExecutor {
IdempotencyInspection inspection = inspect(request);
return switch (inspection.outcome()) {
case COMPLETED_REPLAY -> {
StoredResponse stored = requireResponse(inspection);
StoredResponse stored = requireResponse(request.scope(), inspection);
if (stored.payload().equals(codec.serialize(result))) {
yield result;
}
// The stored response is somebody else's answer to this scope. Returning either one would
// be asserting a fact this caller cannot establish.
throw recovery("the completed response conflicts with the one this caller produced");
throw recovery(
request.scope(), "the completed response conflicts with the one this caller produced");
}
case EXECUTING_SAME_OPERATION -> {
if (alreadyRetried) {
throw recovery("completion stayed indeterminate after reconciliation");
throw recovery(request.scope(), "completion stayed indeterminate after reconciliation");
}
yield complete(request, requireOwner(inspection), result, codec, true);
yield complete(request, requireOwner(request.scope(), inspection), result, codec, true);
}
case UNAVAILABLE -> throw new IdempotencyCompletionUnknownException();
default -> throw recovery("the completion response is indeterminate and was not reconciled");
default ->
throw recovery(
request.scope(), "the completion response is indeterminate and was not reconciled");
};
}
@@ -320,20 +331,24 @@ public final class IdempotencyExecutor {
return transition.owner().orElse(fallback);
}
private static IdempotencyOwner requireOwner(IdempotencyInspection inspection) {
private static IdempotencyOwner requireOwner(
IdempotencyScopeDigest scope, IdempotencyInspection inspection) {
Optional<IdempotencyOwner> owner = inspection.owner();
return owner.orElseThrow(
() ->
recovery(
scope,
"the store reported "
+ inspection.outcome()
+ " without the owner handle it needs"));
}
private static StoredResponse requireResponse(IdempotencyInspection inspection) {
private static StoredResponse requireResponse(
IdempotencyScopeDigest scope, IdempotencyInspection inspection) {
return inspection
.response()
.orElseThrow(() -> recovery("the store reported a completed replay with no response"));
.orElseThrow(
() -> recovery(scope, "the store reported a completed replay with no response"));
}
/**
@@ -345,7 +360,13 @@ public final class IdempotencyExecutor {
return scope.operationCode() + "::v" + scope.keyDigestVersion() + "::" + scope.digest();
}
private static IdempotencyRecoveryRequiredException recovery(String message) {
return new IdempotencyRecoveryRequiredException(message);
/**
* A recovery-required failure that names its scope, as the in-flight and mismatch failures do:
* the runbook's first step is to find this record, and the scope digest is the only identity this
* lifecycle holds (re-review 2026-11-04 RR3-03-03).
*/
private static IdempotencyRecoveryRequiredException recovery(
IdempotencyScopeDigest scope, String message) {
return new IdempotencyRecoveryRequiredException(message + ": " + diagnostic(scope));
}
}
@@ -4,7 +4,11 @@ import dev.caskeleton.shared.error.ApiErrorCarrier;
import dev.caskeleton.shared.error.ApiErrorCode;
import dev.caskeleton.shared.error.OperationalError;
/** Raised when request replay cannot safely decide whether an external effect already occurred. */
/**
* Raised when request replay cannot safely decide whether an external effect already occurred. The
* executor's message ends with the opaque scope digest, for logs only — the record an operator
* looks up (re-review 2026-11-04 RR3-03-03); transports answer with the code's fixed message.
*/
public final class IdempotencyRecoveryRequiredException extends RuntimeException
implements ApiErrorCarrier {
@@ -15,14 +15,18 @@ import java.lang.annotation.Target;
* system reaches it through a delivery or a tick. This marker is how an inbound adapter of the
* second kind says so, in code, next to the reason. Without it an inbound adapter that depends on a
* {@code @SystemInvoked} use case fails {@code ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES};
* with it, {@code SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS} checks the claim: the class
* lives in a system-driven inbound package ({@code ..adapter.inbound.messaging..}, {@code
* ..adapter.inbound.scheduler..}) and depends on no user-transport type. A controller cannot carry
* it.
* with it, {@code SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS} checks the claim on the class
* and on every class nested in it: they live in a system-driven inbound package ({@code
* ..adapter.inbound.messaging..}, {@code ..adapter.inbound.scheduler..}) and depend on no
* user-transport type. A controller cannot carry it.
*
* <p>The marked adapter constructs the use case it calls with {@code new} from the ports it is
* given and keeps it to itself: the use case is never a bean ({@code PermissionEnforcementGuard}
* refuses one), so nothing but this adapter holds it. Review 2026-11-03 RR-01-12, decision 9.1.
* refuses one), and no user transport depends on the adapter, directly or through other classes
* ({@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}). The rules read class dependencies; a bean
* looked up at run time ({@code getBean}, {@code ObjectProvider}) is not seen. The three system
* callers and where each lives are listed in manual 07 「시스템이 부르는 쓰기」. Review 2026-11-03 RR-01-12,
* decision 9.1; review 2026-11-04 RR3-01-01.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@@ -19,13 +19,15 @@ import java.lang.annotation.Target;
* <p>A use case marked this way is a write with no permission check, so no user request may reach
* it. Its system caller constructs it directly and keeps it: a composition module hands it to a
* scheduler (the outbox relay), or a {@link SystemCaller} inbound adapter — a message handler, a
* scheduled job — constructs it from the ports its bean method receives (manual 09 「소비」 step 4).
* Both ways a user could reach it are refused: a bean of it fails startup ({@code
* composition:service-runtime} {@code PermissionEnforcementGuard}), and an inbound adapter that
* depends on it without being a {@link SystemCaller} fails the architecture rule {@code
* ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} (review 2026-11-03 RR-01-02, RR-01-12). It is
* not a way to silence the rule that a mutating use case declares a permission: a write a user
* triggers declares one, and a write both a user and the system trigger is two use cases.
* scheduled job — constructs it from the ports its bean method receives (manual 07 「시스템이 부르는 쓰기」
* lists the three). The ways a user could reach it are refused: a bean of it fails startup ({@code
* composition:service-runtime} {@code PermissionEnforcementGuard}), an inbound adapter that depends
* on it without being a {@link SystemCaller} fails the architecture rule {@code
* ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES}, and a user transport that depends on the
* system caller fails {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} (review 2026-11-03
* RR-01-02, RR-01-12; review 2026-11-04 RR3-01-01). It is not a way to silence the rule that a
* mutating use case declares a permission: a write a user triggers declares one, and a write both a
* user and the system trigger is two use cases.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@@ -185,6 +185,56 @@ class IdempotencyExecutorTest {
assertThat(ran).isFalse();
}
/**
* The runbook's first step for a recovery-required answer is to find the record, and the scope
* digest is the only identity the lifecycle holds; the ERROR line of a 5xx carrier prints the
* message (re-review 2026-11-04 RR3-03-03).
*/
@ParameterizedTest(name = "{0}")
@MethodSource("recoveryRequiredStores")
@DisplayName("회복 필요로 끝나면 운영자가 기록을 찾도록 예외 메시지에 scope digest를 남긴다")
void aRecoveryRequiredFailureNamesTheScopeDigest(String path, FakeStore store) {
// when
Throwable thrown =
catchThrowable(
() ->
executor(store)
.execute(
SCOPE,
FINGERPRINT,
ATTEMPT,
() -> new IdempotentAction.Outcome.Success<>("created"),
codec()));
// then
assertThat(thrown)
.isInstanceOf(IdempotencyRecoveryRequiredException.class)
.hasMessageContaining(SCOPE.operationCode())
.hasMessageContaining(SCOPE.digest());
}
static Stream<Arguments> recoveryRequiredStores() {
FakeStore expiredExecution = new FakeStore();
expiredExecution.claim = new IdempotencyClaimOutcome.RecoveryRequired(1);
FakeStore abandonedAfterLostClaim = new FakeStore();
abandonedAfterLostClaim.claim = new IdempotencyClaimOutcome.Indeterminate(OPERATION);
abandonedAfterLostClaim.inspection =
IdempotencyInspection.outcome(IdempotencyInspectionOutcome.ABANDONED);
FakeStore conflictingReplay = startedStore();
conflictingReplay.complete = IdempotencyCompleteOutcome.INDETERMINATE;
conflictingReplay.inspectionAfterComplete =
new IdempotencyInspection(
IdempotencyInspectionOutcome.COMPLETED_REPLAY,
Optional.empty(),
Optional.empty(),
Optional.of(new StoredResponse("somebody-elses-answer")),
Optional.of(Instant.parse("2026-07-29T13:00:00Z")));
return Stream.of(
Arguments.of("claim answered recovery required", expiredExecution),
Arguments.of("lost claim found abandoned", abandonedAfterLostClaim),
Arguments.of("lost completion found someone else's", conflictingReplay));
}
/**
* The action already ran when completion fails, so "refused before the action" would be false.
* Effects in the action's own transaction roll back with the exception; anything else it did has
@@ -9,6 +9,7 @@ import dev.caskeleton.application.idempotency.IdempotencyCompleteOutcome;
import dev.caskeleton.application.idempotency.IdempotencyFailOutcome;
import dev.caskeleton.application.idempotency.IdempotencyFailureDisposition;
import dev.caskeleton.application.idempotency.IdempotencyInspection;
import dev.caskeleton.application.idempotency.IdempotencyInspectionOutcome;
import dev.caskeleton.application.idempotency.IdempotencyInspectionRequest;
import dev.caskeleton.application.idempotency.IdempotencyMutationResult;
import dev.caskeleton.application.idempotency.IdempotencyOwner;
@@ -378,6 +379,28 @@ public abstract class IdempotencyStoreContract {
.isGreaterThan(claimed.stateRevision());
}
@Test
@DisplayName("실행 중인 자기 기록을 inspect하면 기록 수명이 아니라 claim이 받은 처리 lease 만료 시각이 나온다")
void inspectingAnOwnExecutionReportsItsProcessingLeaseNotTheRecordLifetime() {
// given
// A record now outlives its lease by the replay TTL, so a store that reports when the record
// goes away reports a lease hours past the real one (re-review 2026-11-04 RR3-03-05).
IdempotencyStorePort store = subject();
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
IdempotencyClaimOutcome.Acquired acquired =
(IdempotencyClaimOutcome.Acquired) store.claim(claim(attempt, FINGERPRINT));
store.markExecutionStarted(acquired.owner(), OPERATION);
// when
IdempotencyInspection inspection =
store.inspect(new IdempotencyInspectionRequest(SCOPE, FINGERPRINT, attempt));
// then
assertThat(inspection.outcome())
.isEqualTo(IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION);
assertThat(inspection.processingLeaseUntil()).contains(acquired.processingLeaseUntil());
}
@Test
@DisplayName("renew한 처리 lease는 처음 만료 시각이 지나도 다른 요청에 넘어가지 않는다")
void aRenewedLeaseOutlivesItsFirstExpiry() {
@@ -14,9 +14,6 @@ import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
/** Repository policy for the operator-facing environment contract. No Gradle API. */
public final class EnvContractVerifier {
@@ -59,28 +56,9 @@ public final class EnvContractVerifier {
* manifest test and strict binder), not as a row here.
*/
private static final Pattern INDEXED_KEY = Pattern.compile(".*_[0-9]+(_.*)?");
private static final ObjectMapper JSON =
JsonMapper.builder().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build();
private EnvContractVerifier() {}
public static EnvContractResult verify(
File envFile,
Collection<File> configurationFiles,
File registryFile,
Collection<File> productionSources,
Collection<MetadataScope> metadataScopes,
Collection<String> enforcedPrefixes) {
return verify(
envFile,
configurationFiles,
registryFile,
productionSources,
metadataScopes,
enforcedPrefixes,
List.of());
}
/**
* Verifies the contract, and also every {@code APP_*} name the operator-facing files set.
*
@@ -93,38 +71,6 @@ public final class EnvContractVerifier {
* in a Compose file that nothing reads is a setting the operator believes is in force and is not
* ({@code APP_LOG_JSON_ENABLED} in the prod-smoke file, 07-10).
*
* @param operatorFiles the operator-facing files whose {@code APP_*} names are checked
*/
public static EnvContractResult verify(
File envFile,
Collection<File> configurationFiles,
File registryFile,
Collection<File> productionSources,
Collection<MetadataScope> metadataScopes,
Collection<String> enforcedPrefixes,
Collection<File> operatorFiles) {
Set<String> declared = new TreeSet<>();
for (MetadataScope scope : metadataScopes) {
if (scope.metadataFile().exists()) {
parseMetadata(scope.metadataFile()).properties().stream()
.map(SpringConfigurationProperty::name)
.forEach(declared::add);
}
}
return verify(
envFile,
configurationFiles,
registryFile,
productionSources,
metadataScopes,
enforcedPrefixes,
operatorFiles,
declared);
}
/**
* Verifies the contract, with every configuration property the composition declares.
*
* <p>An operator-file key whose registry row names a {@code property:} counts as read only when
* that property is declared — a registry row alone is what the operator file was already trusted
* for (review 2026-11-04 RR2-04-05). A non-{@code APP_} key of a JSON object counts as read only
@@ -132,17 +78,26 @@ public final class EnvContractVerifier {
* the {@code CASKELETON_GRPC_ENABLED} switch that started RR-06-07 was neither, and nothing read
* it.
*
* @param declaredProperties every property name the composition's configuration metadata declares
* <p>The typed properties under {@code typedPrefixes} and the declared properties an operator key
* may name are read once, from the same classpath, by {@link ConfigurationMetadataClasspath}. They
* used to be two computations — the task read the classpath, the tests a scope file — so the unit
* tests did not see the path the build runs (review 2026-11-04 RR3-04-04).
*
* @param metadataClasspath the composition's classpath with every capability a service can
* select, whose configuration metadata declares the properties
* @param typedPrefixes the property trees whose every typed property needs a registry row
* @param enforcedPrefixes the {@code APP_*} prefixes whose every registered key must be read
* @param operatorFiles the operator-facing files whose {@code APP_*} names are checked
*/
public static EnvContractResult verify(
File envFile,
Collection<File> configurationFiles,
File registryFile,
Collection<File> productionSources,
Collection<MetadataScope> metadataScopes,
Collection<File> metadataClasspath,
Collection<String> typedPrefixes,
Collection<String> enforcedPrefixes,
Collection<File> operatorFiles,
Collection<String> declaredProperties) {
Collection<File> operatorFiles) {
requireFile(
envFile,
"missing "
@@ -218,25 +173,23 @@ public final class EnvContractVerifier {
"shipped configuration references APP_ keys absent from docs/registries/env-keys.yaml "
+ "(optional defaults and environment secret references are included): ");
Set<String> declared = ConfigurationMetadataClasspath.propertiesUnder(metadataClasspath, "");
Set<String> typedProperties = new TreeSet<>();
Set<String> missingMetadata = new TreeSet<>();
for (MetadataScope scope : metadataScopes) {
if (!scope.metadataFile().exists()) {
missingMetadata.add(scope.propertyPrefix() + " (" + scope.metadataFile() + ")");
continue;
Set<String> undeclaredPrefixes = new TreeSet<>();
for (String prefix : typedPrefixes) {
List<String> underPrefix = declared.stream().filter(name -> name.startsWith(prefix)).toList();
if (underPrefix.isEmpty()) {
undeclaredPrefixes.add(prefix);
}
SpringConfigurationMetadata metadata = parseMetadata(scope.metadataFile());
metadata.properties().stream()
.map(SpringConfigurationProperty::name)
.filter(name -> name.startsWith(scope.propertyPrefix()))
.forEach(typedProperties::add);
typedProperties.addAll(underPrefix);
}
if (!missingMetadata.isEmpty()) {
if (!undeclaredPrefixes.isEmpty()) {
throw new IllegalStateException(
"verifyEnvKeys: configuration metadata is missing for "
+ missingMetadata
+ " — run the owning module's compileJava first (the annotation processor writes it), "
+ "or the typed-property check silently covers nothing.");
"verifyEnvKeys: no configuration metadata on the classpath declares a property under "
+ undeclaredPrefixes
+ " — put the owning module on the metadata classpath and run its compileJava (the"
+ " annotation processor writes the metadata), or the typed-property check silently"
+ " covers nothing.");
}
failUnlessEmpty(
@@ -247,7 +200,7 @@ public final class EnvContractVerifier {
Set<String> scopedRegistryProperties = new TreeSet<>();
for (String property : registryProperties) {
if (metadataScopes.stream().anyMatch(scope -> property.startsWith(scope.propertyPrefix()))) {
if (typedPrefixes.stream().anyMatch(property::startsWith)) {
scopedRegistryProperties.add(property);
}
}
@@ -279,7 +232,6 @@ public final class EnvContractVerifier {
"operator files (Compose, logback-spring.xml, the Compose lane contract, the smoke wrapper)"
+ " set APP_ keys absent from docs/registries/env-keys.yaml: ");
Set<String> typedRows = new TreeSet<>();
Set<String> declared = new HashSet<>(declaredProperties);
registryRows.stream()
.filter(row -> row.property().filter(declared::contains).isPresent())
.forEach(row -> typedRows.add(row.name()));
@@ -374,14 +326,6 @@ public final class EnvContractVerifier {
return COMPOSE_ENVIRONMENT_KEY;
}
private static SpringConfigurationMetadata parseMetadata(File file) {
SpringConfigurationMetadata metadata =
JSON.readValue(file, SpringConfigurationMetadata.class);
return metadata.properties() == null
? new SpringConfigurationMetadata(List.of())
: metadata;
}
private static List<EnvRegistryRow> parseRegistryRows(File registryFile) {
List<EnvRegistryRow> rows = new ArrayList<>();
RowBuilder current = null;
@@ -469,10 +413,6 @@ public final class EnvContractVerifier {
}
}
private record SpringConfigurationMetadata(List<SpringConfigurationProperty> properties) {}
private record SpringConfigurationProperty(String name) {}
private static final class RowBuilder {
private final String name;
private String property;
@@ -1,11 +0,0 @@
package dev.caskeleton.buildlogic.config;
import java.io.File;
import java.util.Objects;
public record MetadataScope(String propertyPrefix, File metadataFile) {
public MetadataScope {
Objects.requireNonNull(propertyPrefix, "propertyPrefix");
Objects.requireNonNull(metadataFile, "metadataFile");
}
}
@@ -1,13 +1,6 @@
package dev.caskeleton.buildlogic.config;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.ConfigurableFileCollection;
@@ -71,20 +64,16 @@ public abstract class VerifyEnvKeysTask extends DefaultTask {
}
EnvContractResult result;
try {
List<MetadataScope> scopes = new ArrayList<>();
for (String prefix : TYPED_PREFIXES) {
scopes.add(new MetadataScope(prefix, metadataOf(prefix)));
}
result =
EnvContractVerifier.verify(
getEnvFile().get().getAsFile(),
getConfigurationFiles().getFiles(),
getRegistryFile().get().getAsFile(),
getProductionSources().getFiles(),
scopes,
getMetadataClasspath().getFiles(),
TYPED_PREFIXES,
ENFORCED_PREFIXES,
getOperatorFiles().getFiles(),
ConfigurationMetadataClasspath.propertiesUnder(getMetadataClasspath().getFiles(), ""));
getOperatorFiles().getFiles());
} catch (IllegalStateException invalidContract) {
throw new GradleException(invalidContract.getMessage(), invalidContract);
}
@@ -99,24 +88,4 @@ public abstract class VerifyEnvKeysTask extends DefaultTask {
result.typedPropertyCount(),
result.consumedOrDeprecatedRegistryRowCount());
}
/** The typed properties under {@code prefix}, as one metadata file the verifier reads. */
private File metadataOf(String prefix) {
Set<String> properties =
ConfigurationMetadataClasspath.propertiesUnder(getMetadataClasspath().getFiles(), prefix);
StringBuilder json = new StringBuilder("{\"properties\":[");
String separator = "";
for (String property : properties) {
json.append(separator).append("{\"name\":\"").append(property).append("\"}");
separator = ",";
}
json.append("]}");
File file = new File(getTemporaryDir(), prefix + "metadata.json");
try {
Files.writeString(file.toPath(), json, StandardCharsets.UTF_8);
} catch (IOException failure) {
throw new UncheckedIOException("failed to write " + file, failure);
}
return file;
}
}
@@ -20,16 +20,18 @@ import java.util.regex.Pattern;
* dropped before anything is matched, so a task named only in a comment is not "run".
*
* <p>A command is read with what decides whether it gates anything (review 2026-11-03 RR-06-04):
* its {@code -x} exclusions, and the {@code continue-on-error} and {@code if:} of its step and its
* job. A command whose failure cannot fail the run, or that runs only under a condition other than
* a status function, is still returned, with the reason it does not count. So is a command of a
* workflow that starts only on {@code workflow_dispatch}: nothing runs it unless someone asks, the
* same reason an {@code if:} on the event name does not count (review 2026-11-04 RR2-04-04).
* its {@code -x} exclusions (spelled {@code -x task}, {@code -xtask}, {@code --exclude-task task}
* or {@code --exclude-task=task}, as Gradle reads them), and the {@code continue-on-error} and
* {@code if:} of its step and its job. A command whose failure cannot fail the run, or that runs
* only under a condition other than a status function, is still returned, with the reason it does
* not count. So is a command of a workflow that starts only on {@code workflow_dispatch}: nothing
* runs it unless someone asks, the same reason an {@code if:} on the event name does not count
* (review 2026-11-04 RR2-04-04).
*
* <p>Which build a command starts is where it starts: the step's {@code working-directory} (or the
* job's or the workflow's {@code defaults.run.working-directory}) joined with its {@code -p}, as a
* path from the repository root. A {@code run:} that is an input of a {@code uses:} step ({@code
* with: run:}) is not a shell command and is not read.
* job's or the workflow's {@code defaults.run.working-directory}) joined with its {@code -p} (also
* {@code -pdir} and {@code --project-dir}), as a path from the repository root. A {@code run:} that
* is an input of a {@code uses:} step ({@code with: run:}) is not a shell command and is not read.
*/
public final class WorkflowGradleInvocations {
private static final Pattern RUN_KEY = Pattern.compile("^(\\s*)(?:-\\s+)?run:(.*)$");
@@ -614,6 +616,12 @@ public final class WorkflowGradleInvocations {
index++;
} else if (token.startsWith("--exclude-task=")) {
excluded.add(token.substring("--exclude-task=".length()));
} else if (token.startsWith("-x") && token.length() > 2) {
// Gradle takes a short option's value attached, the way it takes -Dkey=value:
// -xgrpcPerformanceTest excludes that task (review 2026-11-04 RR3-04-02).
excluded.add(token.substring(2));
} else if (token.startsWith("-p") && token.length() > 2) {
projectDir = token.substring(2);
} else if (OPTIONS_WITH_VALUE.contains(token)) {
index++;
} else if (!token.startsWith("-")) {
@@ -4,8 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@@ -23,8 +25,10 @@ class EnvContractVerifierTest {
List.of(fixture.applicationYaml().toFile()),
fixture.registry().toFile(),
List.of(),
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
List.of("APP_REDIS_"));
fixture.metadataClasspath(),
List.of("app.redis."),
List.of("APP_REDIS_"),
List.of());
assertEquals(2, result.envKeyCount());
assertEquals(1, result.requiredPlaceholderCount());
@@ -50,13 +54,43 @@ class EnvContractVerifierTest {
List.of(fixture.applicationYaml().toFile()),
fixture.registry().toFile(),
List.of(),
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
List.of("APP_REDIS_")));
fixture.metadataClasspath(),
List.of("app.redis."),
List.of("APP_REDIS_"),
List.of()));
assertTrue(failure.getMessage().contains("typed configuration properties absent"));
assertTrue(failure.getMessage().contains("app.redis.port"));
}
@Test
@DisplayName("typed prefix 아래 property를 선언한 metadata가 classpath에 없으면 검사가 빈 채로 통과하지 않고 실패한다")
void aTypedPrefixNothingOnTheClasspathDeclaresFails(@TempDir Path temp) throws Exception {
// given
Fixture fixture = fixture(temp);
Path unrelatedClasses = fixture.repositoryRoot().resolve("adapter/other/build/classes/java/main");
Files.createDirectories(unrelatedClasses);
// when
IllegalStateException failure =
assertThrows(
IllegalStateException.class,
() ->
EnvContractVerifier.verify(
fixture.envFile().toFile(),
List.of(fixture.applicationYaml().toFile()),
fixture.registry().toFile(),
List.of(),
List.of(unrelatedClasses.toFile()),
List.of("app.redis."),
List.of("APP_REDIS_"),
List.of()));
// then
assertTrue(failure.getMessage().contains("no configuration metadata"), failure.getMessage());
assertTrue(failure.getMessage().contains("app.redis."), failure.getMessage());
}
@Test
void envExamplePresenceDoesNotCountAsRuntimeConsumption(@TempDir Path temp) throws Exception {
Fixture fixture = fixture(temp);
@@ -79,8 +113,10 @@ class EnvContractVerifierTest {
List.of(fixture.applicationYaml().toFile()),
fixture.registry().toFile(),
List.of(),
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
List.of("APP_REDIS_")));
fixture.metadataClasspath(),
List.of("app.redis."),
List.of("APP_REDIS_"),
List.of()));
assertTrue(failure.getMessage().contains("registered Redis keys that nothing reads"));
assertTrue(failure.getMessage().contains("APP_REDIS_UNUSED"));
@@ -101,8 +137,10 @@ class EnvContractVerifierTest {
List.of(fixture.applicationYaml().toFile(), secondary.toFile()),
fixture.registry().toFile(),
List.of(),
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
List.of("APP_REDIS_")));
fixture.metadataClasspath(),
List.of("app.redis."),
List.of("APP_REDIS_"),
List.of()));
assertTrue(failure.getMessage().contains("shipped configuration references APP_ keys"));
assertTrue(failure.getMessage().contains("APP_SECONDARY_ONLY"));
@@ -124,8 +162,10 @@ class EnvContractVerifierTest {
List.of(fixture.applicationYaml().toFile(), secondary.toFile()),
fixture.registry().toFile(),
List.of(),
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
List.of("APP_REDIS_")));
fixture.metadataClasspath(),
List.of("app.redis."),
List.of("APP_REDIS_"),
List.of()));
assertTrue(failure.getMessage().contains("required env absent from src/.env.example"));
assertTrue(failure.getMessage().contains("APP_REQUIRED_SECONDARY"));
@@ -145,8 +185,10 @@ class EnvContractVerifierTest {
List.of(fixture.applicationYaml().toFile()),
fixture.registry().toFile(),
List.of(),
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
List.of("APP_REDIS_")));
fixture.metadataClasspath(),
List.of("app.redis."),
List.of("APP_REDIS_"),
List.of()));
assertTrue(failure.getMessage().contains("required env absent from src/.env.example"));
assertTrue(failure.getMessage().contains("APP_REQUIRED"));
@@ -175,7 +217,8 @@ class EnvContractVerifierTest {
List.of(fixture.applicationYaml().toFile()),
fixture.registry().toFile(),
List.of(),
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
fixture.metadataClasspath(),
List.of("app.redis."),
List.of("APP_REDIS_"),
List.of(compose.toFile())));
@@ -201,7 +244,8 @@ class EnvContractVerifierTest {
List.of(fixture.applicationYaml().toFile()),
fixture.registry().toFile(),
List.of(),
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
fixture.metadataClasspath(),
List.of("app.redis."),
List.of("APP_REDIS_"),
List.of(compose.toFile())));
@@ -223,7 +267,8 @@ class EnvContractVerifierTest {
List.of(fixture.applicationYaml().toFile()),
fixture.registry().toFile(),
List.of(),
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
fixture.metadataClasspath(),
List.of("app.redis."),
List.of("APP_REDIS_"),
List.of(compose.toFile()));
@@ -325,13 +370,47 @@ class EnvContractVerifierTest {
assertTrue(failure.getMessage().contains("APP_GHOST_ENABLED"), failure.getMessage());
}
private static EnvContractResult verifyWithOperatorFiles(Fixture fixture, Path operatorFile) {
@Test
@DisplayName("레지스트리 행의 property를 classpath의 다른 모듈 metadata가 선언하면 그 키는 읽히는 것으로 친다")
void anOperatorKeyWhoseRegisteredPropertyAnotherModuleDeclaresPasses(@TempDir Path temp)
throws Exception {
// given
Fixture fixture = fixture(temp);
Files.writeString(
fixture.envFile(), Files.readString(fixture.envFile()) + "APP_GHOST_ENABLED=true\n");
Files.writeString(
fixture.registry(),
Files.readString(fixture.registry())
+ "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n");
Path ghostClasses = fixture.repositoryRoot().resolve("adapter/ghost/build/classes/java/main");
Files.createDirectories(ghostClasses.resolve("META-INF"));
Files.writeString(
ghostClasses.resolve(ConfigurationMetadataClasspath.METADATA),
"{\"properties\":[{\"name\":\"app.ghost.enabled\"}]}");
Path compose = fixture.repositoryRoot().resolve("docker-compose.yml");
Files.writeString(
compose, "services:\n app:\n environment:\n APP_GHOST_ENABLED: \"true\"\n");
// when
EnvContractResult result = verifyWithOperatorFiles(fixture, compose, ghostClasses);
// then
assertEquals(3, result.envKeyCount());
}
private static EnvContractResult verifyWithOperatorFiles(
Fixture fixture, Path operatorFile, Path... otherModuleClasses) {
List<File> classpath = new ArrayList<>(fixture.metadataClasspath());
for (Path classes : otherModuleClasses) {
classpath.add(classes.toFile());
}
return EnvContractVerifier.verify(
fixture.envFile().toFile(),
List.of(fixture.applicationYaml().toFile()),
fixture.registry().toFile(),
List.of(),
List.of(new MetadataScope("app.redis.", fixture.redisMetadata().toFile())),
classpath,
List.of("app.redis."),
List.of("APP_REDIS_"),
List.of(operatorFile.toFile()));
}
@@ -347,9 +426,9 @@ class EnvContractVerifierTest {
Path envFile = repositoryRoot.resolve(".env.example");
Path applicationYaml = repositoryRoot.resolve("app-bootstrap/src/main/resources/application.yml");
Path registry = docsRoot.resolve("env-keys.yaml");
Path metadata =
repositoryRoot.resolve(
"adapter/outbound/redis-runtime/build/classes/java/main/META-INF/spring-configuration-metadata.json");
Path redisClasses =
repositoryRoot.resolve("adapter/outbound/redis-runtime/build/classes/java/main");
Path metadata = redisClasses.resolve(ConfigurationMetadataClasspath.METADATA);
Files.writeString(envFile, "APP_REQUIRED=required\nAPP_REDIS_HOST=localhost\n");
Files.writeString(
@@ -359,7 +438,7 @@ class EnvContractVerifierTest {
"- name: APP_REQUIRED\n type: string\n default: none\n"
+ "- name: APP_REDIS_HOST\n property: app.redis.host\n type: string\n default: localhost\n");
Files.writeString(metadata, "{\"properties\":[{\"name\":\"app.redis.host\"}]}");
return new Fixture(repositoryRoot, envFile, applicationYaml, registry, metadata);
return new Fixture(repositoryRoot, envFile, applicationYaml, registry, redisClasses, metadata);
}
private record Fixture(
@@ -367,5 +446,12 @@ class EnvContractVerifierTest {
Path envFile,
Path applicationYaml,
Path registry,
Path redisMetadata) {}
Path redisClasses,
Path redisMetadata) {
/** The redis-runtime classes directory, as the composition's metadata classpath holds it. */
List<File> metadataClasspath() {
return List.of(redisClasses.toFile());
}
}
}
@@ -226,6 +226,40 @@ class WorkflowGradleInvocationsTest {
assertThat(invocation.executes(":integrationCheck", ".")).isTrue();
}
@Test
@DisplayName("-x에 태스크를 붙여 쓴 토큰은 Gradle처럼 그 태스크를 뺀 것으로 읽는다")
void anExcludedTaskAttachedToDashXIsReadAsAnExclusion() {
// given
String workflow =
"""
- run: ./gradlew performanceCheck -xgrpcPerformanceTest --exclude-task=:leaf:test
""";
// when
Invocation invocation = WorkflowGradleInvocations.read(workflow).get(0);
// then
assertThat(invocation.excludedTasks()).containsExactly("grpcPerformanceTest", ":leaf:test");
}
@Test
@DisplayName("-p에 디렉터리를 붙여 쓴 명령은 Gradle처럼 그 디렉터리의 빌드를 실행한다")
void aProjectDirectoryAttachedToDashPIsTheBuildTheCommandStarts() {
// given
String workflow =
"""
- run: ./gradlew -poptional-platforms integrationCheck --stacktrace
""";
// when
Invocation invocation = WorkflowGradleInvocations.read(workflow).get(0);
// then
assertThat(invocation.projectDir()).isEqualTo("optional-platforms");
assertThat(invocation.executes(":integrationCheck", ".")).isFalse();
assertThat(invocation.executes(":integrationCheck", "optional-platforms")).isTrue();
}
@Test
@DisplayName("job의 continue-on-error와 단계의 if 조건은 명령을 실행으로 세지 않는 이유로 남는다")
void jobAndStepGatingIsKeptAsTheReasonACommandDoesNotCount() {
+6 -2
View File
@@ -45,7 +45,7 @@ executor, 설정 기본값이 함께 빠진다(그때 KEYED use case는 executor
| 언제 | 키 |
| --- | --- |
| 켤 때 | `APP_IDEMPOTENCY_PROVIDER` (`redis` 또는 `postgresql`), 그리고 그 provider 모듈의 줄과 env |
| 조정할 때 | `APP_IDEMPOTENCY_PROCESSING_LEASE`(≤1h), `APP_IDEMPOTENCY_TTL`(≤72h, processing lease 이상), `APP_IDEMPOTENCY_FAILURE_RETENTION`(≤30d) |
| 조정할 때 | `APP_IDEMPOTENCY_PROCESSING_LEASE`(≤1h), `APP_IDEMPOTENCY_TTL`(≤72h, processing lease 이상), `APP_IDEMPOTENCY_FAILURE_RETENTION`(≤30d, `APP_IDEMPOTENCY_TTL` 이상으로 — 기동 검사는 없다) |
## 설계 결정 참조 (app-bootstrap에서 옮김)
@@ -74,7 +74,7 @@ executor, 설정 기본값이 함께 빠진다(그때 KEYED use case는 executor
| `provider` | `APP_IDEMPOTENCY_PROVIDER` | `disabled` | `disabled` \| `redis` \| `postgresql` |
| `processing-lease` | `APP_IDEMPOTENCY_PROCESSING_LEASE` | 30s | 1h |
| `replay-ttl` | `APP_IDEMPOTENCY_TTL` | 24h | 72h, 그리고 `processing-lease` 이상 |
| `failure-retention` | `APP_IDEMPOTENCY_FAILURE_RETENTION` | 24h | 30d |
| `failure-retention` | `APP_IDEMPOTENCY_FAILURE_RETENTION` | 24h | 30d. `replay-ttl`과 비교하지 않는다(아래) |
| `response-codec-id` | — | `json-v2` | 1–64자 |
| `policy-revision` | — | 2 | 양수 |
| `reaper-interval` | — | 10m | 양수 |
@@ -87,6 +87,10 @@ executor, 설정 기본값이 함께 빠진다(그때 KEYED use case는 executor
둔다 — 이 검사는 store 를 지키는 것이 아니라 재생을 무력하게 만드는 정책을 막는다.
`IdempotencyClaimRequest` 에는 두지 않았다: 포트는 어떤 값 쌍으로도 쓸 수 있고, store 가 모든 쌍에서
안전한지는 공유 계약이 본다.
- **`failure-retention` 은 `replay-ttl` 과 비교하지 않는다.** 실패로 표시된 기록(포기·재시도 가능)은 표시부터
이 기간만 남는다. `replay-ttl` 보다 짧으면 효과 불명으로 포기한 기록이 먼저 사라져 같은 키 재전송이 작업을
다시 돌리므로 운영 값은 `replay-ttl` 이상으로 둔다. 기동 검사로 막지 않은 이유: 지금 기동하는 설정을 이
라운드에서 실패로 바꾸지 않는다 — 검사 추가는 소유자 결정으로 남겼다(재리뷰 2026-11-04 RR3-03-02).
- **상한 검사는 컴팩트 생성자에서 fail-fast 로 던진다.** `Duration`의 상한은 JSR-303(`@Valid`)
애너테이션으로 표현할 수 없어 생성자에서 직접 검증한다. 검증을 느슨하게 두면 과도하게 긴 TTL 이
저장소를 조용히 부풀리고 멱등성 키 추측 공격의 유효 시간 창을 넓히기 때문에, 부팅 시점에 즉시
+2 -1
View File
@@ -32,7 +32,8 @@ composition:service-runtime
유스케이스가 빈으로 등록돼 있으면 같은 가드가 기동을 멈춘다 — 권한 검사가 없는 쓰기를 전송 계층이
닿는 곳에 두는 조립이기 때문이다(review 2026-11-03 RR-01-02). 가드가 허용하는 경우는 하나다: 시스템
호출자의 bean이 자기가 `new`로 만든 use case를 필드로 든다(스케줄러에 넘기는 조립 모듈, 또는
`@SystemCaller` 메시지 handler — RR-01-12). 가드는 bean 타입만 보므로 둘 다 기동한다.
`@SystemCaller` 메시지 handler·예약 작업 — RR-01-12, 목록의 정본은 매뉴얼 07장 「시스템이 부르는 쓰기」).
가드는 bean 타입만 보므로 모두 기동한다.
- 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(설정 브리지와 tracing 스위치는
`spring.factories`의 `EnvironmentPostProcessor`·`AutoConfigurationImportFilter`). 구성 루트의
@@ -32,12 +32,13 @@ import org.springframework.util.ClassUtils;
* reach with no check, whatever advisor the context holds, so its presence fails startup (review
* 2026-11-03 RR-01-02), with no exception. The system caller that runs it holds it instead, and
* that is the one condition this guard allows: the use case is a field of a bean, never a bean.
* There are two such callers (decision 9.1, RR-01-12): a scheduler, to which a composition module
* hands the use case it constructed (the outbox relay), and a {@code @SystemCaller} message
* handler, which constructs the use case from the ports its own bean method receives. The guard
* looks at bean types only, so both start. {@code
* ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} closes the static path, a user transport that
* constructs one itself.
* There are two shapes of such a caller (decision 9.1, RR-01-12): a scheduler, to which a
* composition module hands the use case it constructed (the outbox relay), and a
* {@code @SystemCaller} message handler or scheduled job, which constructs the use case from the
* ports its own bean method receives (manual 07 「시스템이 부르는 쓰기」 lists them). The guard looks at bean
* types only, so all of them start. The static paths are the architecture rules': {@code
* ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES} refuses a user transport that constructs one
* itself, and {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} one that calls the system caller.
*/
final class PermissionEnforcementGuard implements SmartInitializingSingleton, BeanFactoryAware {
@@ -71,7 +72,7 @@ final class PermissionEnforcementGuard implements SmartInitializingSingleton, Be
"@SystemInvoked use cases are registered as beans, where a transport can reach a write"
+ " that has no permission check — a system-invoked use case is constructed by the"
+ " system caller that runs it (a scheduler's composition, a @SystemCaller message"
+ " handler) and never registered as a bean: "
+ " handler or scheduled job) and never registered as a bean: "
+ String.join(", ", systemInvoked));
}
if (!unenforced.isEmpty()) {
@@ -3,6 +3,7 @@ package dev.caskeleton.grpc.ledger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
@@ -13,9 +14,10 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.postgresql.ds.PGSimpleDataSource;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
@@ -31,6 +33,13 @@ import org.testcontainers.postgresql.PostgreSQLContainer;
* Flyway runs it, in one transaction. Unbounded it waits until the writer leaves, with every claim
* queued behind it, and then applies; bounded it fails with {@code lock_not_available} first and
* its rollback leaves the ledger as it was.
*
* <p>Every migration after V001 is held to this, read from the tree itself ({@link
* GrpcOperationLedgerMigrations#inOrder()}), so a V004 is checked without anyone naming it here.
* This is the ledger tree's lock-wait rule: the optional build cannot reach the persistence-jpa
* testkit whose text check the other trees run, and a copy of that check would drift (re-review
* 2026-11-03 round 3, RR3-02-04). A later migration that does not touch the ledger at all fails
* here too, on purpose: say so in this test rather than let the rule pass it unseen.
*/
@Testcontainers(disabledWithoutDocker = true)
class GrpcOperationLedgerMigrationLockWaitIT {
@@ -47,12 +56,13 @@ class GrpcOperationLedgerMigrationLockWaitIT {
.withUsername("grpc")
.withPassword("grpc");
/** Every ledger migration after V001, the one that creates the ledger. */
static Stream<String> migrationsAfterTheFirst() throws IOException {
return GrpcOperationLedgerMigrations.inOrder().stream().skip(1);
}
@ParameterizedTest
@ValueSource(
strings = {
"V002__index_grpc_operation_ledger_finished_rows.sql",
"V003__add_grpc_operation_ledger_claim_attempt.sql"
})
@MethodSource("migrationsAfterTheFirst")
@DisplayName("ledger에 쓴 트랜잭션이 열려 있으면 ledger를 잠그는 마이그레이션은 상한 안에 실패하고 아무것도 바꾸지 않는다")
void aLedgerMigrationGivesUpOnAnOpenWriterAndChangesNothing(String migration) throws Exception {
PGSimpleDataSource dataSource = dataSource();
@@ -73,6 +83,10 @@ class GrpcOperationLedgerMigrationLockWaitIT {
String.valueOf(attempt.sqlState()),
attempt.took().compareTo(GIVES_UP_WITHIN) < 0,
schema(statement)))
.as(
"%s must put SET LOCAL lock_timeout = '5s'; before it locks the ledger"
+ " (docs/jpa/migration-guide.md, \"Bound the lock wait\")",
migration)
.containsExactly(LOCK_NOT_AVAILABLE, true, schemaBefore);
}
}
@@ -3,24 +3,44 @@ package dev.caskeleton.grpc.ledger;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;
/**
* The ledger's Flyway scripts in version order, as one SQL text for a test database.
*
* <p>One list for every PostgreSQL lane, so a new migration is applied by all of them or by none;
* two copies of the list drift the first time someone adds a V003 to one of them.
* <p>One list for every PostgreSQL lane, so a new migration is applied by all of them or by none.
* The list is the tree on disk, not a copy of it: a hand-kept list let a V004 that nobody added to
* it go unapplied and unchecked by every lane (re-review 2026-11-03 round 3, RR3-02-04).
*/
final class GrpcOperationLedgerMigrations {
private static final List<String> IN_ORDER =
List.of(
"db/migration/grpc/V001__create_grpc_operation_ledger.sql",
"db/migration/grpc/V002__index_grpc_operation_ledger_finished_rows.sql",
"db/migration/grpc/V003__add_grpc_operation_ledger_claim_attempt.sql");
/** The ledger's tree from this leaf's directory, where the lanes run. */
private static final Path TREE = Path.of("src/main/resources/db/migration/grpc");
/** The same tree on the classpath, where the scripts are read from. */
private static final String LOCATION = "db/migration/grpc/";
private GrpcOperationLedgerMigrations() {}
/**
* The file name of every versioned migration in the tree ({@code V<version>__<name>.sql}), in
* Flyway's order: by version, its parts compared as numbers.
*/
static List<String> inOrder() throws IOException {
try (Stream<Path> files = Files.list(TREE)) {
return files
.map(file -> file.getFileName().toString())
.filter(name -> name.matches("V\\d+(?:[._]\\d+)*__.+\\.sql"))
.sorted(Comparator.comparing(GrpcOperationLedgerMigrations::version, Arrays::compare))
.toList();
}
}
/** Every migration's SQL, concatenated in version order. */
static String all() throws IOException {
return before(null);
@@ -29,26 +49,31 @@ final class GrpcOperationLedgerMigrations {
/** The SQL of every migration before the one named, concatenated in version order. */
static String before(String fileName) throws IOException {
StringBuilder sql = new StringBuilder();
for (String path : IN_ORDER) {
if (path.endsWith("/" + fileName)) {
for (String name : inOrder()) {
if (name.equals(fileName)) {
break;
}
sql.append(read(path)).append('\n');
sql.append(read(name)).append('\n');
}
return sql.toString();
}
/** One migration's SQL, by its file name. */
static String named(String fileName) throws IOException {
for (String path : IN_ORDER) {
if (path.endsWith("/" + fileName)) {
return read(path);
}
if (!inOrder().contains(fileName)) {
throw new IOException("no gRPC operation-ledger migration is named " + fileName);
}
throw new IOException("no gRPC operation-ledger migration is named " + fileName);
return read(fileName);
}
private static String read(String path) throws IOException {
private static int[] version(String fileName) {
return Arrays.stream(fileName.substring(1, fileName.indexOf("__")).split("[._]"))
.mapToInt(Integer::parseInt)
.toArray();
}
private static String read(String fileName) throws IOException {
String path = LOCATION + fileName;
try (InputStream stream =
GrpcOperationLedgerMigrations.class.getClassLoader().getResourceAsStream(path)) {
if (stream == null) {
@@ -217,7 +217,9 @@ app:
# profile the guard lets the sample start under must also start it. This document used to name
# `local` alone, so `test` and `demo` were allowed and stopped on an object-storage binding with no
# destination (review 2026-11-04 RR2-04-02). SampleDemoProfilesStartupSystemTest starts the sample
# under each listed profile with nothing but this file and a database address.
# under each listed profile, given a database address and free ports: `demo` and `local` with the
# shipped configuration alone, `test` with the system-test source set's application-test.yml loaded
# as well.
spring:
config:
activate:
@@ -3,14 +3,13 @@ package dev.caskeleton.sample.portfolio.bootstrap.persistence;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.LockWaitMigrationInspector;
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.VersionedMigrationFiles;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@@ -33,13 +32,12 @@ class SampleMigrationLockWaitTest {
@DisplayName("샘플 스트림의 규칙 이후 마이그레이션은 기존 테이블 잠금 앞에 SET LOCAL lock_timeout을 둔다")
void everySampleMigrationAfterTheRuleBoundsItsLockWait() throws IOException {
// given
Map<String, Path> migrations = versionedMigrations();
Map<String, Path> migrations = VersionedMigrationFiles.under(STREAM);
// when
Map<String, List<String>> unbounded = new TreeMap<>();
for (Map.Entry<String, Path> migration : migrations.entrySet()) {
List<String> statements =
inspector.unboundedLockingStatements(Files.readString(migration.getValue()));
List<String> statements = inspector.unboundedLockingStatements(migration.getValue());
if (!statements.isEmpty()) {
unbounded.put(migration.getKey(), statements);
}
@@ -50,14 +48,4 @@ class SampleMigrationLockWaitTest {
.as("these wait for a table lock without a bound: %s", unbounded)
.isEqualTo(RELEASED_BEFORE_THE_RULE);
}
private static Map<String, Path> versionedMigrations() throws IOException {
Map<String, Path> migrations = new TreeMap<>();
try (Stream<Path> files = Files.list(STREAM)) {
files
.filter(path -> path.getFileName().toString().matches("V[0-9_]+__.+\\.sql"))
.forEach(path -> migrations.put(path.getFileName().toString(), path));
}
return migrations;
}
}
@@ -47,7 +47,8 @@ public enum OperationalError implements ApiErrorCode {
IDEMPOTENT_IN_FLIGHT(Category.CONFLICT, 409, true),
IDEMPOTENT_REQUEST_MISMATCH(Category.VALIDATION, 422, false),
IDEMPOTENCY_UNAVAILABLE(Category.TRANSIENT_DEPENDENCY, 503, true),
// the action ran and recording its result failed; a resend with the same key never runs it again
// the action ran and recording its result failed; while the server still holds the record, a
// resend with the same key never runs it again (docs/web/http-contract.md, "서버가 기억하는 기간")
IDEMPOTENCY_COMPLETION_UNKNOWN(Category.TRANSIENT_DEPENDENCY, 503, true),
IDEMPOTENCY_RECOVERY_REQUIRED(Category.DATA_INTEGRITY, 500, false),
// adapter runtime lifecycle