Merge remote-tracking branch 'origin/claude/r9-g1-inbound-456713' into claude/integration-r9-f1bc5c

충돌 하나와 텍스트 충돌 없는 컴파일 깨짐 하나를 정리했다.

- docs/upgrade/2026-11-maturity-review.md 머리 「커밋:」 줄: G3의 「실패한 동시
  인덱스 drop의 복구 절차」와 G1의 「r9-g1 GraphQL 판정 순서와 인자 변환 단계」를
  모두 남겼다. G1 항목은 G1이 둔 자리(r8-f1 뒤), G3 항목은 G3가 둔 자리(끝)다.
- PostgreSqlDistributedLockIntegrationTest: G3가 OutboxRunbookSql을 RunbookSql로
  바꿨는데 G1의 새 테스트 두 곳이 옛 이름을 부른다. 새 이름으로 바꿨다.
This commit is contained in:
DongHyeonka
2026-11-07 10:00:44 +09:00
22 changed files with 662 additions and 57 deletions
+37 -3
View File
@@ -14,7 +14,10 @@ status: stub
- HTTP 409 with `error.code=LOCK_ACQUISITION_TIMEOUT` and `Retry-After: 1`; GraphQL extension
`code=LOCK_ACQUISITION_TIMEOUT`, gRPC trailer `error-code: LOCK_ACQUISITION_TIMEOUT` (`ABORTED`), all
`retryable=true`. A 4xx answer, so no server ERROR line — look at the metric.
`retryable=true`.
- No server log line. A 4xx answer is not an incident, so no transport logs it, and the lock adapters
do not log a timeout either. The exception's message (lock key, wait time) reaches no log and no
client, so which lock timed out is recorded nowhere. Read the metric and the lock table below.
- Before 2026-11-07 the template answered this as 500 `INTERNAL_ERROR` with an "unhandled exception"
ERROR line (the exception was not an `ApiErrorCarrier`). A service on an older template sees that
instead.
@@ -22,8 +25,39 @@ status: stub
## Diagnosis
- Check `lock.acquisition` metric for lock name and duration
- Identify lock holders (check DB `integration_lock` table)
1. Contention rate. With `APP_MULTI_INSTANCE_ENABLED=true` the JDBC lock is metered: compare
`lock.acquisition{outcome="timeout"}` with `lock.acquisition{outcome="acquired"}`. The counter has
no lock name and no wait time — a key is never a metric tag (`docs/registries/metrics.yaml`). The
in-process lock (`APP_MULTI_INSTANCE_ENABLED=false`, the default) has no metric and keeps nothing in
the database; the steps below apply only to the JDBC lock.
2. Who holds locks now. `INT_LOCK` has one row per held lock. `CLIENT_ID` is the holding instance's
lock repository id, and the times are UTC. A row whose `EXPIRED_AFTER` has passed is a dead lease:
the next acquisition of that key takes it over. The oldest live rows are the long holders.
<!-- runbook-sql: lock-holders -->
```sql
SELECT lock_key, region, client_id, created_date, expired_after
FROM int_lock
ORDER BY created_date;
```
3. The holder of one lock whose key you know from the code (for example `orders/42`). `LOCK_KEY` is
not the key: Spring Integration stores the key's name-based UUID (`UUID.nameUUIDFromBytes` of the
key's UTF-8 bytes), so a key cannot be read back from the table. This computes the UUID from the
key and finds its row:
<!-- runbook-sql: lock-holder-of-key -->
```sql
SELECT region, client_id, created_date, expired_after
FROM int_lock
WHERE lock_key = (
SELECT overlay(overlay(h placing '3' from 13)
placing to_hex(8 | (('x' || substr(h, 17, 1))::bit(4)::int & 3)) from 17)::uuid::text
FROM md5('<lock_key>') AS h);
```
`:adapter:outbound:persistence-jpa:postgresqlDistributedLockIntegrationTest` runs both blocks, read
from this file, against real PostgreSQL while locks are held.
## Action
+3 -3
View File
@@ -4,7 +4,7 @@
- 커밋: `34565130` High·P1 19건 · `1400dc15` 남은 발견·매뉴얼·생성 명령 · `5786126c` 남은 항목과 합친 뒤 결함 ·
`7ef8d0b4` 재리뷰 기록 · `bbe944bd` 재리뷰 결함 · `ecc74b7d` 2차 재리뷰 기록·이 안내 · `1885bf8d` 2차 재리뷰 결함 ·
`339cf8fd` 3차 확인 리뷰 기록 · `f40c03c6` 3차 확인 리뷰 Minor · `c2e55510` 마지막 확인 리뷰 기록 ·
`2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) · `paths` 필터 trigger를 단계 실행으로 세지 않음(2026-11-06 소유자 결정, B-36) · r8-f1 전송 오류 처리(2026-11-07, B-45~B-48) · 태그 push·`release` workflow는 `releaseCheck`에만 셈(2026-11-07 소유자 결정, B-36) · 실패한 동시 인덱스 drop의 복구 절차(2026-11-07, 재리뷰 RR8-03-01, 5절) — `docs(...)` 커밋은 문서만 바꾼다
`2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) · `paths` 필터 trigger를 단계 실행으로 세지 않음(2026-11-06 소유자 결정, B-36) · r8-f1 전송 오류 처리(2026-11-07, B-45~B-48) · r9-g1 GraphQL 판정 순서와 인자 변환 단계(2026-11-07 소유자 결정, B-45·B-46) · 태그 push·`release` workflow는 `releaseCheck`에만 셈(2026-11-07 소유자 결정, B-36) · 실패한 동시 인덱스 drop의 복구 절차(2026-11-07, 재리뷰 RR8-03-01, 5절) — `docs(...)` 커밋은 문서만 바꾼다
- 근거 문서: `docs/reviews/2026-11-01-maturity-review/README.md` 13~16절, `docs/reviews/2026-11-03-rereview/README.md`
4·6·8~13절, 각 커밋의 `BREAKING CHANGE:` 꼬리말
- 아래 표의 각 줄은 위 범위의 diff와 코드로 확인했다. 확인하지 못한 것은 그 자리에 "확인 못 함"으로 적었고 9절에
@@ -100,8 +100,8 @@
| B-31 | 핸들러 밖 오류(`/error` 디스패치)를 `EnvelopeErrorController`가 실패 Envelope로 답한다. 전에는 Boot `/error` 맵이 `success:true`로 감싸져 요청 경로까지 실려 나갔다. 기본 JWT 체인에서 익명 400이 401로 바뀌지 않는다. 4xx·5xx 본문은 `success:true`로 감싸지 않는다. 보안 체인이 `DispatcherType.ERROR`를 허용한다 | 오류 본문 모양이 바뀐다. 자기 SecurityFilterChain이 ERROR 디스패치를 막으면 400이 401로 나간다 | 자기 체인에 `auth.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()`을 넣는다(템플릿 `SecurityConfig`와 같게) | `bbe944bd` · `src/adapter/inbound/web/.../error/EnvelopeErrorController.java`, `.../auth/SecurityConfig.java` |
| B-32 | 새·바뀐 오류 코드: 비동기 요청 timeout 500 `INTERNAL_ERROR` → 503 `REQUEST_TIMEOUT`(retryable). `IDEMPOTENCY_KEY_INVALID` 400(`details.reason`=`MISSING`·`MALFORMED`, `IdempotencyKeyHeader.parse`를 쓰는 엔드포인트, sample은 `BAD_PARAMETER`에서 바뀜). web-advanced 예외 10종이 모두 500 `INTERNAL_ERROR`였다가 각자 코드(`ADMISSION_REFUSED` 503 등) | 코드로 분기하던 클라이언트가 새 코드를 모른다 | 클라이언트 분기표에 더한다. web-advanced 표는 `src/adapter/inbound/web-advanced/README.md` 「오류 응답」 | `1400dc15` · `src/adapter/inbound/web/.../error/WebTransportError.java`, `HttpStatusErrorCodes.java`, `src/adapter/inbound/web-advanced/.../error/WebAdvancedError.java` |
| B-33 | DB 실패 분류: 낙관적 잠금 충돌 500 → 409 `DB_OPTIMISTIC_CONFLICT`. 커밋 단계 연결 끊김(08xxx, 40003 등)을 재시도 가능으로 답하던 것 → 500 `DB_COMPLETION_UNKNOWN`(retryable=false) | 응답 status·code가 바뀐다 | 409는 다시 읽고 재시도, `DB_COMPLETION_UNKNOWN`은 업무 데이터로 결과를 확인 | `34565130`, `1400dc15` · `src/adapter/outbound/persistence-jpa/.../failure/PersistenceExceptionTranslator.java` |
| B-45 | 분산 락 timeout(`LockAcquisitionTimeoutException`): 500 `INTERNAL_ERROR`(retryable=false) → 409 `LOCK_ACQUISITION_TIMEOUT`(retryable=true, `Retry-After: 1`). GraphQL extension `code`·`retryable`, gRPC `ABORTED` + trailer `error-code`도 같은 코드. 예외가 `ApiErrorCarrier`가 되어 레지스트리가 약속한 값으로 답한다. 4xx라 "unhandled exception" ERROR 줄이 사라진다 | 500을 "재시도 금지"로 읽던 클라이언트가 이제 409를 받는다. 이 예외에 자기 `@ExceptionHandler`를 둔 서비스는 그쪽 응답이 그대로 나간다 | `Retry-After` 뒤 같은 요청을 다시 보내게 한다. 자기 처리기를 두었다면 지워도 된다 | r8-f1(2026-11-07, 재리뷰 RR7-01-04) · `src/application-core/.../lock/LockAcquisitionTimeoutException.java`, `src/adapter/inbound/web/.../observability/RetryAfterAdvisor.java` |
| B-46 | 다른 예외로 감싼 carrier: web·GraphQL도 gRPC처럼 원인 사슬의 첫 carrier 코드로 답한다(전에는 500 `INTERNAL_ERROR`). `IllegalArgumentException`이 carrier를 감쌌으면 `BAD_PARAMETER` 대신 그 carrier 코드다. STOMP ERROR 프레임의 `error-code`도 `IllegalArgumentException` 뒤의 carrier를 그 코드로 낸다. gRPC는 `Status.INVALID_ARGUMENT.withCause(iae)`처럼 `IllegalArgumentException`을 원인으로 든 raw status를 던져도 `onError`로 넘긴 것과 같이 `INVALID_ARGUMENT`·`BAD_PARAMETER`다(전에는 던지면 `INTERNAL`) | 감싼 실패에 500·`INTERNAL`을 받던 클라이언트가 이제 그 carrier 코드(예: 503 `DB_UNAVAILABLE`)를 받는다 | 클라이언트 분기는 `error.code`로 한다(바꿀 것 없음). 감싼 실패를 일부러 500으로 보내려면 감싸지 말고 `IllegalStateException`을 던진다 | r8-f1(2026-11-07, 소유자 결정 2026-11-06, 재리뷰 RR7-01-05·RR7-01-03) · `src/shared-contract/.../error/ApiErrorCarrier.java` `firstIn`, 네 전송의 오류 처리기 |
| B-45 | 분산 락 timeout(`LockAcquisitionTimeoutException`): 500 `INTERNAL_ERROR`(retryable=false) → 409 `LOCK_ACQUISITION_TIMEOUT`(retryable=true, `Retry-After: 1`). GraphQL extension `code`·`retryable`, gRPC `ABORTED` + trailer `error-code`도 같은 코드. 예외가 `ApiErrorCarrier`가 되어 레지스트리가 약속한 값으로 답한다. 4xx라 "unhandled exception" ERROR 줄이 사라진다 | 500을 "재시도 금지"로 읽던 클라이언트가 이제 409를 받는다. 이 예외에 자기 `@ExceptionHandler`를 둔 서비스는 web에서 그쪽 응답이 그대로 나간다. GraphQL에서 이 예외를 `GraphQlExceptionResolver`에 등록한 매핑은 쓰이지 않는다: 실패 자신이 carrier라 그 코드가 등록 매핑보다 먼저다 | `Retry-After` 뒤 같은 요청을 다시 보내게 한다. 자기 처리기와 GraphQL 등록 매핑을 두었다면 지워도 된다 | r8-f1(2026-11-07, 재리뷰 RR7-01-04), r9-g1(2026-11-07, 재리뷰 RR8-01-01) · `src/application-core/.../lock/LockAcquisitionTimeoutException.java`, `src/adapter/inbound/web/.../observability/RetryAfterAdvisor.java` |
| B-46 | 다른 예외로 감싼 carrier: web·GraphQL도 gRPC처럼 원인 사슬의 첫 carrier 코드로 답한다(전에는 500 `INTERNAL_ERROR`). `IllegalArgumentException`이 carrier를 감쌌으면 `BAD_PARAMETER` 대신 그 carrier 코드다. STOMP ERROR 프레임의 `error-code`도 `IllegalArgumentException` 뒤의 carrier를 그 코드로 낸다. gRPC는 `Status.INVALID_ARGUMENT.withCause(iae)`처럼 `IllegalArgumentException`을 원인으로 든 raw status를 던져도 `onError`로 넘긴 것과 같이 `INVALID_ARGUMENT`·`BAD_PARAMETER`다(전에는 던지면 `INTERNAL`). 바뀌지 않는 것 둘(소유자 결정 2026-11-07): GraphQL에서 앱이 `GraphQlExceptionResolver`에 등록한 실패는 carrier를 원인으로 들어도 등록한 코드로 답한다(등록 매핑이 원인 사슬의 carrier보다 먼저, 실패 자신이 carrier면 그 코드가 먼저). 인자 변환 단계 — web `MethodArgumentTypeMismatchException`·`HttpMessageNotReadableException`, GraphQL `@Argument` binder — 는 원인에 carrier가 있어도 `BAD_PARAMETER`·`VALIDATION_FAILED`다. STOMP는 `@DestinationVariable`·`@Header`의 `ConversionFailedException`과 받은 메시지가 실린 `MessageConversionException`을 원인의 carrier와 상관없이 거부 WARN 한 줄로 남긴다 | 감싼 실패에 500·`INTERNAL`을 받던 클라이언트가 이제 그 carrier 코드(예: 503 `DB_UNAVAILABLE`)를 받는다. GraphQL 등록 매핑과 인자 변환 실패의 답은 그대로다 | 클라이언트 분기는 `error.code`로 한다(바꿀 것 없음). 감싼 실패를 일부러 500으로 보내려면 감싸지 말고 `IllegalStateException`을 던진다 | r8-f1(2026-11-07, 소유자 결정 2026-11-06, 재리뷰 RR7-01-05·RR7-01-03), r9-g1(2026-11-07, 재리뷰 RR8-01-01, README 19.4절 ①·④) · `src/shared-contract/.../error/ApiErrorCarrier.java` `firstIn`, 네 전송의 오류 처리기 |
| B-47 | `Retry-After`를 레지스트리 `retry_after_seconds`대로 붙인다. 새로 붙는 응답: 503 `DB_UNAVAILABLE` 5초, 409 `DB_SERIALIZATION_FAILURE`·`DB_DEADLOCK` 1초, 503 `DB_IDLE_IN_TX_TIMEOUT` 2초(나머지 `OUTBOX_PUBLISH_FAILED`·`JOB_*`는 HTTP로 나가지 않는 코드다). 전에는 web 표에서 빠져 헤더가 없었다. 표와 레지스트리를 `OperationalErrorRegistryContractTest`(document-contract, `mainCheck`)가 대조한다 | 이 응답에 `Retry-After`가 생긴다. 템플릿 `OperationalError` 행의 `retry_after_seconds`를 바꾼 서비스는 `RetryAfterAdvisor` 표도 같이 바꾸지 않으면 `mainCheck`가 실패한다(대조 대상은 `OperationalError` 코드뿐이다) | 헤더를 따르는 클라이언트는 그만큼 기다렸다 재시도한다. 자기 코드의 값은 그 코드가 `RetryAfterHint`로 말한다 | r8-f1(2026-11-07, 소유자 결정) · `src/adapter/inbound/web/.../observability/RetryAfterAdvisor.java`, `src/app-bootstrap/src/test/.../contract/OperationalErrorRegistryContractTest.java` |
| B-48 | GraphQL `@Argument` 값이 컨트롤러 파라미터 타입으로 바뀌지 않으면(Spring 인자 binder의 `BindException`) `INTERNAL_ERROR`(`INTERNAL`) 대신 `BAD_PARAMETER`(`REQUEST`, `BAD_REQUEST`)로 답한다. 로그는 ERROR + 예외(`rejected value [...]`가 실림) 대신 WARN 한 줄 `request refused as BAD_PARAMETER by org.springframework.validation.BindException (executionId=…)`이다 | 그 실패에 `INTERNAL_ERROR`를 받던 클라이언트가 `BAD_PARAMETER`를 받는다. ERROR 경보가 잘못된 인자에 울리지 않는다 | 클라이언트는 `extensions.code`로 가른다. `BindException`에 자기 `GraphQlExceptionResolver` 매핑을 둔 서비스는 그 매핑이 그대로 먼저다 | r8-f1(2026-11-07, 소유자 결정) · `src/adapter/inbound/graphql/.../error/GraphQlWireErrorMapper.java` |
+3 -1
View File
@@ -91,7 +91,9 @@
| Draft-12 offset 불일치 | problem 문서는 프로토콜 예외로 유지 | 소유자 | 결정 12 |
| 알림 category 생략 | 거부(400), 판정은 유스케이스 | 소유자 | 결정 13 |
| 오류 코드 로그 레벨 | `error-codes.yaml`에 `log_level` 칸을 두지 않는다. 레벨은 실패 종류·경로가 정한다(`ServerFailureLog`, 보안 필터 `AuthErrorResponseWriter`). 칸이 다시 생기면 `OperationalErrorRegistryContractTest`가 실패한다. 보안 필터는 5xx(`AUTH_JWKS_UNAVAILABLE`·`INTERNAL_AUTH_MISCONFIGURATION`)를 ERROR, 4xx를 WARN으로 남긴다. 401 서명·issuer·audience 불일치는 WARN | 소유자 | 2026-11-06, `docs/superpowers/specs/2026-11-06-error-code-log-level-design.md` 10절 |
| 감싼 carrier를 전송이 읽는 법 | web·GraphQL·STOMP·gRPC 네 전송 모두 원인 사슬의 첫 carrier를 본다. 감싼 carrier의 응답이 500 `INTERNAL_ERROR` 대신 그 carrier의 코드가 된다 | 소유자 | `1103` 18.4절(RR7-01-05), 2026-11-06 |
| 감싼 carrier를 전송이 읽는 법 | web·GraphQL·STOMP·gRPC 네 전송 모두 원인 사슬의 첫 carrier를 본다. 감싼 carrier의 응답이 500 `INTERNAL_ERROR` 대신 그 carrier의 코드가 된다. 그보다 먼저 답하는 것은 아래 「GraphQL 판정 순서」(등록 매핑)와 「인자 변환 단계의 감싼 carrier」 두 행이다 | 소유자 | `1103` 18.4절(RR7-01-05), 2026-11-06 |
| GraphQL 판정 순서 | 플랫폼 거부 → 실패 자신이 carrier → 등록된 application 매핑 → 원인 사슬의 첫 carrier → 거부된 인자(`IllegalArgumentException`, 인자 binder의 `BindException`) → 가림(`INTERNAL_ERROR`). 앱이 등록한 실패는 carrier를 원인으로 들어도 등록한 코드로 답한다(web에서 앱의 도메인 advice가 먼저 받는 것과 같다). 실패 자신이 carrier인 타입(예: `LockAcquisitionTimeoutException`)을 등록한 매핑은 쓰이지 않는다. 로그 줄은 어느 단계가 답하든 원인 사슬의 첫 carrier로 정한다 — 등록 매핑이 답해도 그 안의 서버 쪽 carrier 줄은 남는다 | 소유자(2026-11-07). 로그 줄은 기본값(2026-11-07) | `1103` 19.4절 ①(RR8-01-01), 2026-11-07 총괄 세션 전달 |
| 인자 변환 단계의 감싼 carrier | 「감싼 carrier를 전송이 읽는 법」은 인자 변환 단계를 덮지 않는다. web `MethodArgumentTypeMismatchException`·`HttpMessageNotReadableException`과 GraphQL `@Argument` binder 실패는 원인에 carrier가 있어도 `BAD_PARAMETER`·`VALIDATION_FAILED`다. STOMP는 `@DestinationVariable`·`@Header`의 `ConversionFailedException`과 받은 메시지가 실린 `MessageConversionException`을 원인 사슬의 carrier보다 먼저 거부로 보고 WARN 한 줄(타입만)을 남긴다. 요청 형식 오류의 코드는 전송이 정한다 | 소유자(2026-11-07) | `1103` 19.4절 ④(round8/01 「Declined to judge」), 2026-11-07 총괄 세션 전달 |
| `Retry-After` 값 | web `RetryAfterAdvisor` 표는 레지스트리 `retry_after_seconds` 칸과 코드마다 같다. 빠져 있던 7개(`DB_UNAVAILABLE` 5, `DB_SERIALIZATION_FAILURE` 1, `DB_DEADLOCK` 1, `DB_IDLE_IN_TX_TIMEOUT` 2, `OUTBOX_PUBLISH_FAILED` 30, `JOB_EXECUTOR_REJECTED` 5, `JOB_TIMEOUT` 10)를 채웠고, `OperationalErrorRegistryContractTest`가 둘을 대조한다 | 소유자 | 2026-11-07 총괄 세션 전달(소유자 원문 "권하는 안대로"), r8-f1 보고 「범위 밖」 1 |
| GraphQL 인자 변환 실패 | Spring GraphQL 인자 binder의 `BindException`(`@Argument` 값이 파라미터 타입으로 바뀌지 않음)은 `BAD_PARAMETER`(`REQUEST`)로 답하고, WARN 한 줄(예외 타입만, 입력값 없음)을 남긴다. web이 바뀌지 않는 경로 변수에 답하는 것과 같다 | 소유자 | 2026-11-07 같은 전달, r8-f1 보고 「범위 밖」 2 |
| 약속한 응답으로 맞추기 | 레지스트리·`docs/web/http-contract.md`·Javadoc이 이미 약속한 응답으로 코드를 맞추는 것은 결함 수정이다. 고치기 전에 묻지 않고, 응답이 바뀌니 업그레이드 안내 행은 적는다. 약속한 곳끼리 다르면 묻는다 | 기본값(2026-11-07) | `docs/work/improve.md` 7절, `docs/work/evidence.md` 11절 |
+4 -3
View File
@@ -121,9 +121,10 @@ application/platform namespace split.
모든 client 에러는 `error/GraphQlWireErrorMapper` 하나를 거친다 — 전송 interceptor, 실행 전
pipeline(instrumentation), data fetcher resolver 세 곳이 같은 bean 을 받는다. 순서는 플랫폼 거부
(예외가 구현한 `error/GraphQlPlatformRejection`) → `ApiErrorCarrier`(자기 또는 원인 사슬의 첫 carrier의
`ApiErrorCode`) → 등록된
application 매핑(`GraphQlExceptionResolver`) → `IllegalArgumentException`·인자 binder의 `BindException`=`BAD_PARAMETER`. 어디에도 안
(예외가 구현한 `error/GraphQlPlatformRejection`) → 실패 자신이 `ApiErrorCarrier`면 그 `ApiErrorCode` → 등록된
application 매핑(`GraphQlExceptionResolver`) → 원인 사슬의 첫 carrier → `IllegalArgumentException`·인자 binder의
`BindException`=`BAD_PARAMETER`(2026-11-07 소유자 결정). 등록 매핑이 원인 사슬의 carrier보다 먼저라, 앱이 등록한
실패는 하위 실패를 원인으로 들어도 등록한 코드로 답한다. 실패 자신이 carrier인 타입은 등록해도 쓰이지 않는다. 어디에도 안
걸린 예외는 `INTERNAL_ERROR` 로 가려지고, 같은 executionId 로 ERROR 로그 한 줄이 남는다. client 문구는
shared-contract `ClientErrorMessages`(Category 별 한국어 표), `retryable` 은 코드의 값이다. Category →
wire category/`ErrorType` 표는 mapper 의 `RENDERINGS` 하나뿐이고 [README.md](README.md)에 옮겨 둔다.
+16 -9
View File
@@ -66,19 +66,26 @@ instrumentation, data fetcher resolver 세 곳이 같은 bean 을 받는다).
1. **플랫폼 거부** — 플랫폼 예외가 `error/GraphQlPlatformRejection`(wire code·shared `Category`·
필요하면 wire category/constraint)을 구현한다. `instanceof` 사슬로 등록하던 두 번째 목록은 없다.
2. **`ApiErrorCarrier`** — 실패 자신이나 원인 사슬의 첫 carrier(`ApiErrorCarrier.firstIn`, web·gRPC·STOMP와
같은 함수)를 그 `ApiErrorCode` 로 매핑. 로그 줄도 감싼 예외가 아니라 그 carrier 로 정한다(재리뷰 RR7-01-05).
shared-contract 의 `MappingException`·
2. **실패 자신이 `ApiErrorCarrier`** — 그 `ApiErrorCode` 로 매핑. shared-contract 의 `MappingException`·
`AdapterDisabledException`·`PersistenceFailureException`(JPA 예외 포함)·`DependencyFailureException`,
application 의 멱등성 예외, DataLoader 키 실패(`GraphQlBatchLoadException`, **등록된 `ApiErrorCode`
만** — 소유자 결정 25)가 모두 여기로 온다.
3. **등록된 application 매핑**(`GraphQlExceptionResolver`).
4. **`IllegalArgumentException`과 인자 binder의 `BindException`** → `BAD_PARAMETER`(`REQUEST`, `BAD_REQUEST`) —
application 의 멱등성·락 예외, DataLoader 키 실패(`GraphQlBatchLoadException`, **등록된 `ApiErrorCode`
만** — 소유자 결정 25)가 모두 여기로 온다. 이런 타입을 `GraphQlExceptionResolver`에 등록해도 쓰이지 않는다.
3. **등록된 application 매핑**(`GraphQlExceptionResolver`). 앱이 그 실패 타입에 내린 결정이라 원인 사슬의
carrier보다 먼저다. 앱이 등록한 실패가 하위 실패(예: `PersistenceFailureException`)를 원인으로 들어도 등록한
코드로 답한다. web 에서 앱의 도메인 advice 가 먼저 받는 것과 같다(소유자 결정 2026-11-07, 재리뷰 RR8-01-01).
4. **원인 사슬의 첫 carrier**(`ApiErrorCarrier.firstIn`, web·gRPC·STOMP와 같은 함수) — 등록되지 않은 예외가
감싼 carrier 를 그 코드로 매핑(재리뷰 RR7-01-05).
5. **`IllegalArgumentException`과 인자 binder의 `BindException`** → `BAD_PARAMETER`(`REQUEST`, `BAD_REQUEST`) —
web·gRPC·STOMP 와 같다. `BindException`은 `@Argument` 값이 파라미터 타입으로 바뀌지 않을 때 Spring 이 컨트롤러
전에 던진다(web 의 경로 변수 변환 실패와 같은 답, 소유자 결정 2026-11-07). 로그도 같은 WARN 한 줄
전에 던진다(web 의 경로 변수 변환 실패와 같은 답, 소유자 결정 2026-11-07). 변환기가 던진 실패는 binding
result 에 남고 원인으로 실리지 않아, 변환기가 carrier 를 던져도 답은 `BAD_PARAMETER`다(인자 변환 단계는 carrier 를
보지 않는다, 소유자 결정 2026-11-07). 로그도 같은 WARN 한 줄
`request refused as BAD_PARAMETER by <예외 타입> (executionId=<id>)` 이고, 입력값이 들 수 있는 메시지
(`BindException`은 `rejected value [...]`)는 남기지 않는다.
5. 나머지는 `INTERNAL_ERROR` 로 가려지고 같은 executionId 로 ERROR 로그 한 줄이 남는다.
6. 나머지는 `INTERNAL_ERROR` 로 가려지고 같은 executionId 로 ERROR 로그 한 줄이 남는다.
로그 줄은 어느 단계가 답하든 원인 사슬의 첫 carrier 로 정한다. 등록 매핑이 답한 실패도 그 안의 서버 쪽 carrier
(예: DB 연결 실패)는 그 carrier 의 줄(persistence 는 분류만)을 남긴다. 4xx carrier 는 남기지 않는다.
- **client 문구**: shared-contract `ClientErrorMessages`(Category 별 한국어 문구 표 하나, 소유자
결정 11). 예외 메시지는 절대 나가지 않는다.
@@ -13,6 +13,11 @@ import org.slf4j.LoggerFactory;
* message. That default is the important half: a new exception type introduced anywhere in the
* stack is masked automatically instead of leaking until someone notices.
*
* <p>A registered mapping answers before a carrier in the failure's cause chain, so a failure the
* application models keeps its code when it keeps what it translated as its cause. A failure that
* is itself an {@code ApiErrorCarrier} answers with its own code before any mapping is consulted;
* registering such a type changes nothing ({@link GraphQlWireErrorMapper#map}).
*
* <p>Partial data is untouched here. This maps one failing field; sibling fields that resolved stay
* in the response.
*/
@@ -40,12 +40,13 @@ import org.springframework.validation.BindException;
* the detail goes to the log under that id ({@link GraphQlExceptionResolver}).
*
* <p>A carrier is logged here, with {@link ServerFailureLog}'s line — the one the web and gRPC
* adapters write — plus the execution id the client received. A server-side code therefore leaves
* its detail in the log, such as the scope digest of an {@code IDEMPOTENCY_RECOVERY_REQUIRED}
* (review 2026-11-04 RR4-03-03); a persistence failure leaves its classification only. An unmapped
* {@link IllegalArgumentException} leaves the WARN line every transport writes for it, naming its
* type and never its message (review 2026-11-05 RR6-01-06); so does an {@code @Argument} the
* argument binder refused, whose message quotes the rejected value.
* adapters write — plus the execution id the client received, also when a registered mapping
* answers the failure that wraps it. A server-side code therefore leaves its detail in the log,
* such as the scope digest of an {@code IDEMPOTENCY_RECOVERY_REQUIRED} (review 2026-11-04
* RR4-03-03); a persistence failure leaves its classification only. An unmapped {@link
* IllegalArgumentException} leaves the WARN line every transport writes for it, naming its type and
* never its message (review 2026-11-05 RR6-01-06); so does an {@code @Argument} the argument binder
* refused, whose message quotes the rejected value.
*/
public final class GraphQlWireErrorMapper {
@@ -106,44 +107,64 @@ public final class GraphQlWireErrorMapper {
/**
* Maps a failure from any stage.
*
* <p>Order: a platform rejection, then an {@link ApiErrorCarrier} — the failure itself or the
* first one in its cause chain, as on every transport (review 2026-11-06 RR7-01-05) — then the
* application's registered mappings, then a refused argument as {@code BAD_PARAMETER} (the same
* answer every transport gives), and finally the masked internal error. A refused argument is an
* {@link IllegalArgumentException} or the {@link BindException} Spring for GraphQL's argument
* binder raises when an {@code @Argument} the client sent does not convert to the parameter's
* type, as the web adapter answers a path variable that does not (owner decision 2026-11-07).
* Platform rejections come first: an authorization denial raised from inside a resolver means the
* same thing to a client as one raised before execution. A registered mapping outranks the
* argument rule so an application that models its own {@code IllegalArgumentException} subtype
* keeps its code.
* <p>Order (owner decision 2026-11-07, re-review RR8-01-01):
*
* <ol>
* <li>a platform rejection;
* <li>a failure that is itself an {@link ApiErrorCarrier}, by its code;
* <li>the application's registered mappings;
* <li>the first carrier in the failure's cause chain, as on every transport (review 2026-11-06
* RR7-01-05);
* <li>a refused argument as {@code BAD_PARAMETER}, the same answer every transport gives;
* <li>the masked internal error.
* </ol>
*
* <p>Platform rejections come first: an authorization denial raised from inside a resolver means
* the same thing to a client as one raised before execution. A registered mapping outranks a
* carrier in the cause chain because it is the application's decision about that failure type — a
* failure it models keeps its code when it keeps what it translated as its cause, as an
* application's own exception handler keeps it on the web transport. It does not outrank a
* failure that is itself a carrier: that failure already says its code. It outranks the argument
* rule so an application that models its own {@code IllegalArgumentException} subtype keeps its
* code. A refused argument is an {@link IllegalArgumentException} or the {@link BindException}
* Spring for GraphQL's argument binder raises when an {@code @Argument} the client sent does not
* convert to the parameter's type, as the web adapter answers a path variable that does not
* (owner decision 2026-11-07).
*
* <p>The binder keeps a converter's failure in the binding result, not as a cause, so a carrier a
* converter throws never answers in place of {@code BAD_PARAMETER}: the argument conversion stage
* does not read a carrier (owner decision 2026-11-07).
*/
public GraphQlWireError map(Throwable failure, GraphQlErrorContext context) {
if (failure instanceof GraphQlPlatformRejection rejection) {
return fromRejection(rejection, context);
}
ApiErrorCode shared = sharedCodeOf(failure);
logAnswer(failure, shared, context);
if (shared != null) {
logAnswer(failure, shared, context);
return fromApiError(shared, context);
}
return applicationMappings.resolve(failure, context);
}
/**
* Writes {@link ServerFailureLog}'s line for a failure answered with a shared code: the carrier's
* line at ERROR — the carrier's, not a wrapper's — or nothing for a client-side carrier; an
* unmapped refused argument the WARN line naming its type, as on every transport. A binding
* failure's message quotes the rejected value, so it is never logged.
* Writes {@link ServerFailureLog}'s line for a failure: the line of the first carrier in its
* cause chain at ERROR — the carrier's, not a wrapper's — or nothing for a client-side carrier,
* whichever stage answers, so a failure the application registered still leaves the server-side
* carrier it wraps in the log; an unmapped refused argument the WARN line naming its type, as on
* every transport. A binding failure's message quotes the rejected value, so it is never logged.
* Anything else is logged by the masking resolver, or not at all when a mapping answers it.
*
* @param shared the shared code the failure is answered with, or {@code null}
*/
private static void logAnswer(
Throwable failure, ApiErrorCode shared, GraphQlErrorContext context) {
String suffix = " (executionId={})";
Optional<Throwable> carrier = ApiErrorCarrier.firstIn(failure);
if (carrier.isPresent()) {
ServerFailureLog.of(carrier.get(), shared)
ServerFailureLog.of(carrier.get(), ((ApiErrorCarrier) carrier.get()).errorCode())
.ifPresent(line -> LOG.error(line.format(suffix), line.arguments(context.executionId())));
} else if (isRefusedArgument(failure)) {
} else if (shared != null && isRefusedArgument(failure)) {
ServerFailureLog line = ServerFailureLog.refused(OperationalError.BAD_PARAMETER, failure);
LOG.warn(line.format(suffix), line.arguments(context.executionId()));
}
@@ -201,18 +222,24 @@ public final class GraphQlWireErrorMapper {
}
/**
* The shared code a failure carries, or {@code null}: the code of the first carrier in its cause
* chain.
* The shared code a failure is answered with, or {@code null} when a registered mapping or the
* masking answers it — stages 2, 4 and 5 of {@link #map}'s order.
*
* <p>A refused argument the application did not register a mapping for is {@link
* OperationalError#BAD_PARAMETER}, as it is on the web, gRPC and STOMP transports.
*/
private ApiErrorCode sharedCodeOf(Throwable failure) {
if (failure instanceof ApiErrorCarrier carrier) {
return carrier.errorCode();
}
if (applicationMappings.maps(failure)) {
return null;
}
Optional<Throwable> carrier = ApiErrorCarrier.firstIn(failure);
if (carrier.isPresent()) {
return ((ApiErrorCarrier) carrier.get()).errorCode();
}
if (isRefusedArgument(failure) && !applicationMappings.maps(failure)) {
if (isRefusedArgument(failure)) {
return OperationalError.BAD_PARAMETER;
}
return null;
@@ -302,6 +302,75 @@ class GraphQlWireErrorMapperTest {
null);
}
@org.junit.jupiter.api.Test
void aRegisteredFailureThatKeepsACarrierAsItsCauseIsAnsweredWithItsRegisteredCode() {
// given
GraphQlWireErrorMapper mapper = new GraphQlWireErrorMapper(orderUnavailableRegistered());
RuntimeException failure = new OrderUnavailableException(persistenceFailureWithASqlCause());
// when
GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test());
// then
assertThat(error.extensions())
.extracting(extensions -> extensions.get("code"), extensions -> extensions.get("category"))
.containsExactly("ORDER_UNAVAILABLE", "BUSINESS");
}
@org.junit.jupiter.api.Test
void aRegisteredFailureThatKeepsACarrierAsItsCauseStillLeavesTheCarriersServerLine() {
// given
GraphQlWireErrorMapper mapper = new GraphQlWireErrorMapper(orderUnavailableRegistered());
RuntimeException failure = new OrderUnavailableException(persistenceFailureWithASqlCause());
// when
List<ILoggingEvent> logged =
loggedWhile(() -> mapper.map(failure, GraphQlErrorContext.of("exec-9")));
// then
assertThat(logged)
.singleElement()
.extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getThrowableProxy)
.containsExactly(
"persistence failure classified as DB_UNAVAILABLE (category=TRANSIENT_DEPENDENCY,"
+ " retryable=true) (executionId=exec-9)",
null);
}
@org.junit.jupiter.api.Test
void aCarrierTheApplicationAlsoRegisteredIsAnsweredWithItsOwnCode() {
// given
GraphQlWireErrorMapper mapper =
new GraphQlWireErrorMapper(
GraphQlExceptionResolver.builder()
.map(
LockAcquisitionTimeoutException.class,
GraphQlErrorCode.of("ORDER_BUSY"),
GraphQlErrorCategory.BUSINESS,
"주문을 처리하는 중입니다")
.build());
RuntimeException failure =
new LockAcquisitionTimeoutException("orders/42", Duration.ofSeconds(3));
// when
GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test());
// then
assertThat(error.extensions())
.extracting(extensions -> extensions.get("code"), extensions -> extensions.get("retryable"))
.containsExactly("LOCK_ACQUISITION_TIMEOUT", true);
}
private static GraphQlExceptionResolver orderUnavailableRegistered() {
return GraphQlExceptionResolver.builder()
.map(
OrderUnavailableException.class,
GraphQlErrorCode.of("ORDER_UNAVAILABLE"),
GraphQlErrorCategory.BUSINESS,
"주문을 지금 처리할 수 없습니다")
.build();
}
private static PersistenceFailureException persistenceFailureWithASqlCause() {
return new PersistenceFailureException(
OperationalError.DB_UNAVAILABLE,
@@ -309,6 +378,15 @@ class GraphQlWireErrorMapperTest {
new SQLException("jdbc:postgresql://db.internal/customer?password=secret", "08006"));
}
/** A failure the application models and registers; it keeps what it translated as its cause. */
private static final class OrderUnavailableException extends RuntimeException {
private static final long serialVersionUID = 1L;
OrderUnavailableException(Throwable cause) {
super("order unavailable", cause);
}
}
/**
* Every line this package writes while {@code action} runs: the mapper's own and the masking
* resolver's, so a failure that should have been classified but was masked shows up too.
@@ -7,10 +7,13 @@ import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.error.PersistenceFailureException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@@ -33,7 +36,8 @@ import org.springframework.stereotype.Controller;
*/
class GraphQlArgumentBindingFailureTest {
private static final String SCHEMA = "type Query { order(id: ID!): String }";
private static final String SCHEMA =
"type Query { order(id: ID!): String invoice(number: String!): String }";
private static final String QUERY = "{ order(id: \"alice@example.com\") }";
@@ -71,6 +75,21 @@ class GraphQlArgumentBindingFailureTest {
null);
}
@Test
@DisplayName("변환기가 carrier 를 던져도 인자 변환 실패는 BAD_PARAMETER 다(인자 변환 단계는 carrier 를 보지 않는다)")
void anArgumentWhoseConverterThrowsACarrierIsStillABadParameterRequestError() {
// when
List<ResponseError> errors = errorsOf("{ invoice(number: \"INV-1\") }");
// then
assertThat(errors)
.singleElement()
.extracting(
error -> error.getExtensions().get("code"),
error -> error.getExtensions().get("category"))
.containsExactly("BAD_PARAMETER", "REQUEST");
}
private static List<ResponseError> errorsOf(String document) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.registerBean(OrderController.class);
@@ -123,5 +142,25 @@ class GraphQlArgumentBindingFailureTest {
String order(@Argument UUID id) {
return id.toString();
}
@QueryMapping
String invoice(@Argument InvoiceNumber number) {
return "unreachable: the number never converts";
}
}
/** An argument type whose conversion fails with a server-side carrier, as a lookup could. */
public static final class InvoiceNumber {
private InvoiceNumber() {}
/** The conversion the binder finds; a lookup that fails with a carrier for any number. */
public static InvoiceNumber valueOf(String value) {
if (!value.isEmpty()) {
throw new PersistenceFailureException(
OperationalError.DB_UNAVAILABLE, "invoice lookup failed for " + value, null);
}
return new InvoiceNumber();
}
}
}
+12
View File
@@ -215,6 +215,11 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
원인 사슬의 첫 carrier(`ApiErrorCarrier.firstIn`)를 찾아 `handleCarrier` 로 넘긴다. 감싼
persistence 실패도 500 `INTERNAL_ERROR` 와 SQL 원인 대신 그 분류 코드와 분류 한 줄로 남는다. GraphQL·gRPC·STOMP
도 같은 함수를 쓴다(소유자 결정 2026-11-06, 재리뷰 RR7-01-05).
- 인자 변환 단계는 원인의 carrier 를 보지 않는다. 경로 변수·쿼리 파라미터가 바뀌지 않은
`MethodArgumentTypeMismatchException` 은 `BAD_PARAMETER`, 읽지 못한 본문의 `HttpMessageNotReadableException` 은
`VALIDATION_FAILED` 다. 사용자 `Converter` 나 Jackson creator 가 carrier 를 던져 그 원인에 있어도 같다. 요청
형식 오류이고 그 코드는 전송이 정한다(소유자 결정 2026-11-07, 재리뷰 README 19.4절 ④). STOMP 도 같은 실패를
거부로 남긴다. 단언은 `TransportErrorHandlingTest`.
- 개별 override 가 없는 Spring MVC 예외(필수 파라미터·헤더·part 누락, binding 실패 등)는
`handleExceptionInternal` override 가 상태 코드 → 코드로 바꿔 같은 Envelope 로 보낸다. 503(Spring 의
async 요청 시간 초과)은 `INTERNAL_ERROR` 가 아니라 `REQUEST_TIMEOUT`(503, retryable) 이다(리뷰 02-08).
@@ -306,6 +311,13 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
`success:true` 로 감쌌으며 `path` 는 요청 경로 원문이었다(재리뷰 RR-02-02). 이 컨트롤러가 그 자리를
대신해 status 를 `GlobalExceptionHandler` 와 같은 표(`HttpStatusErrorCodes`)로 코드에 매핑하고 실패
Envelope 를 `EnvelopeResponseWriter` 로 쓴다. 요청에서 가져온 값은 싣지 않는다.
- 필터가 던진 예외는 `GlobalExceptionHandler` 를 지나지 않으니 `ServerFailureLog` 의 줄(persistence 는 분류만)도
없다. 대신 컨테이너가 `/error` 로 넘기기 전에 그 예외를 원인 사슬째 ERROR 로 남긴다. Tomcat 은 logger
`org.apache.catalina.core.ContainerBase.[…].[dispatcherServlet]` 에 `Servlet.service() for servlet
[dispatcherServlet] … threw exception` 과 스택을 쓰고, persistence 실패의 SQL 원인(값·제약 이름·접속 문자열)도
`Caused by:` 로 그대로 실린다. 필터에서 저장소나 외부 의존을 부르면 실패를 필터에서 잡아 `EnvelopeResponseWriter`
로 답하고, 로그 줄은 `ServerFailureLog.of` 로 정한다. 단언은 실제 Tomcat 의 `FilterFailureContainerLogIT`
(systemTest, 2026-11-07). Jetty 는 확인하지 않았다.
- `WebMvcPlatformAutoConfiguration` 이 `ErrorMvcAutoConfiguration` 보다 먼저 `ErrorController` 가 없을 때만
등록한다. 어댑터가 자기 `ErrorController` 를 두면 물러난다.
- `SecurityConfig` 는 오류 **디스패치**만 허용한다(`DispatcherType.ERROR`). 예전에는 `/error` 가 공개 경로가
@@ -108,6 +108,12 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
return ErrorResponseFactory.envelope(OperationalError.VALIDATION_FAILED, violations);
}
/**
* A path variable, query parameter or header that does not convert to its parameter's type is
* {@code BAD_PARAMETER}, whatever the conversion threw: a carrier a user {@code Converter} threw
* is not searched for, because the argument conversion stage answers a malformed request with the
* transport's own code (owner decision 2026-11-07). STOMP logs the same failure as a refusal.
*/
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<Envelope<Void>> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
Class<?> requiredType = ex.getRequiredType();
@@ -224,6 +230,11 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
HttpStatusCode.valueOf(OperationalError.VALIDATION_FAILED.httpStatus()));
}
/**
* An unreadable body is {@code VALIDATION_FAILED}, or {@code PAYLOAD_TOO_LARGE} when the body
* ceiling cut the read. A carrier a Jackson creator threw is not searched for, for the same
* reason as {@link #handleTypeMismatch}.
*/
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(
HttpMessageNotReadableException ex,
@@ -0,0 +1,145 @@
package dev.caskeleton.adapter.inbound.web.testkit.mvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.error.PersistenceFailureException;
import dev.caskeleton.webtestkit.ContractFixtureApplication;
import jakarta.servlet.Filter;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.sql.SQLException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.test.context.ActiveProfiles;
/**
* What the server log gets when a servlet filter throws, over a real Tomcat.
*
* <p>A filter runs before the MVC handler, so its exception never reaches {@code
* GlobalExceptionHandler} and never gets {@code ServerFailureLog}'s line, which keeps a persistence
* failure to its classification. The container logs the exception itself, causes and all, before it
* forwards to {@code /error}. A real container rather than MockMvc, because the line under test is
* the container's.
*/
@SpringBootTest(
classes = {
ContractFixtureApplication.class,
FilterFailureContainerLogIT.ThrowingFilterConfig.class
},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("web-contract")
class FilterFailureContainerLogIT {
private static final String FAILING_PATH = "/filter-failure";
/** The SQL detail a persistence failure's cause can hold; it must be visible to the test only. */
private static final String SQL_DETAIL = "jdbc:postgresql://db.internal/customer?password=secret";
private final HttpClient client =
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
@LocalServerPort private int port;
@Test
@DisplayName(
"필터가 던진 예외는 GlobalExceptionHandler 를 거치지 않고, 컨테이너가 원인 사슬째(persistence 원인의 SQL 문구까지) ERROR 한 줄로 남긴다")
void aFailureThrownByAFilterIsLoggedByTheContainerWithItsWholeCauseChain() throws Exception {
// when
List<ILoggingEvent> logged = warningsAndErrorsWhileRequesting(FAILING_PATH);
// then
assertThat(logged)
.extracting(
event -> event.getLoggerName().startsWith("org.apache.catalina.core.ContainerBase"),
ILoggingEvent::getLevel,
event -> causeMessages(event.getThrowableProxy()).contains(SQL_DETAIL))
.as("every WARN or ERROR line: %s", describe(logged))
.containsExactly(tuple(true, Level.ERROR, true));
}
/** Every WARN or ERROR line written anywhere while one request for {@code path} is answered. */
private List<ILoggingEvent> warningsAndErrorsWhileRequesting(String path) throws Exception {
Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
root.addAppender(appender);
try {
client.send(
HttpRequest.newBuilder(URI.create("http://localhost:" + port + path))
.header("Accept", "application/json")
.GET()
.build(),
HttpResponse.BodyHandlers.discarding());
} finally {
root.detachAppender(appender);
appender.stop();
}
return appender.list.stream()
.filter(event -> event.getLevel().isGreaterOrEqual(Level.WARN))
.toList();
}
/** The messages of a logged exception and all its causes. */
private static List<String> causeMessages(IThrowableProxy throwable) {
List<String> messages = new ArrayList<>();
for (IThrowableProxy current = throwable; current != null; current = current.getCause()) {
messages.add(current.getMessage());
}
return messages;
}
private static List<String> describe(List<ILoggingEvent> logged) {
return logged.stream()
.map(
event ->
event.getLevel()
+ " "
+ event.getLoggerName()
+ ": "
+ event.getFormattedMessage()
+ " "
+ causeMessages(event.getThrowableProxy()))
.toList();
}
/** A filter in front of every handler that fails the way a filter calling a store can. */
@Configuration(proxyBeanMethods = false)
static class ThrowingFilterConfig {
@Bean
FilterRegistrationBean<Filter> throwingFilter() {
Filter filter =
(request, response, chain) -> {
throw new IllegalStateException(
"filter failed",
new PersistenceFailureException(
OperationalError.DB_UNAVAILABLE,
"08006",
new SQLException(SQL_DETAIL, "08006")));
};
FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>(filter);
registration.addUrlPatterns(FAILING_PATH);
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registration;
}
}
}
@@ -12,6 +12,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedException;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice;
import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.error.PersistenceFailureException;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import jakarta.validation.constraints.Max;
import java.util.List;
@@ -24,6 +26,7 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
@@ -150,9 +153,47 @@ class TransportErrorHandlingTest {
.andExpect(jsonPath("$.error.details[0].rejectedValue").doesNotExist());
}
@Test
@DisplayName("경로 변수 변환기가 던진 carrier 는 원인에 있어도 보지 않는다: 400 BAD_PARAMETER(인자 변환 단계)")
void aPathVariableWhoseConverterThrowsACarrierIsStillABadParameter() throws Exception {
// when
var result = mvc.perform(get("/t/invoices/INV-1"));
// then
result
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.error.code").value("BAD_PARAMETER"));
}
@Test
@DisplayName("본문 생성자가 던진 carrier 는 원인에 있어도 보지 않는다: 400 VALIDATION_FAILED(인자 변환 단계)")
void aBodyWhoseCreatorThrowsACarrierIsStillValidationFailed() throws Exception {
// when
var result =
mvc.perform(
post("/t/signup")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"email\": \"alice@example.com\"}"));
// then
result
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED"));
}
@RestController
static class Probe {
@GetMapping("/t/invoices/{number}")
Map<String, String> invoice(@PathVariable("number") InvoiceNumber number) {
return Map.of("ok", "unreachable: the number never converts");
}
@PostMapping(value = "/t/signup", consumes = MediaType.APPLICATION_JSON_VALUE)
Map<String, String> signup(@RequestBody Signup signup) {
return Map.of("ok", "unreachable: the body never reads");
}
@GetMapping("/t/async-timeout")
Map<String, String> asyncTimeout() {
throw new AsyncRequestTimeoutException();
@@ -203,4 +244,29 @@ class TransportErrorHandlingTest {
throw new PageValidationException("size", "SIZE_EXCEEDS_MAX", "size must be <= 100");
}
}
/** A path-variable type whose conversion fails with a server-side carrier, as a lookup could. */
public static final class InvoiceNumber {
private InvoiceNumber() {}
/** The conversion Spring finds; a lookup that fails with a carrier for any number. */
public static InvoiceNumber valueOf(String value) {
if (!value.isEmpty()) {
throw new PersistenceFailureException(
OperationalError.DB_UNAVAILABLE, "invoice lookup failed for " + value, null);
}
return new InvoiceNumber();
}
}
/** A request body whose creator fails with a server-side carrier for any address. */
record Signup(String email) {
Signup {
if (!email.isEmpty()) {
throw new PersistenceFailureException(
OperationalError.DB_UNAVAILABLE, "signup lookup failed", null);
}
}
}
}
+5
View File
@@ -48,6 +48,11 @@
이 예외들의 메시지는 받은 JSON 조각이나 값을 담는다. 그래서 타입만 남긴다. 응답을 JSON으로 쓰지 못한
`MessageConversionException`은 받은 메시지가 실리지 않는다. 서버 탓이라 ERROR로 남는다.
이 거부는 원인 사슬의 carrier보다 먼저 판정한다. payload creator나 destination 변수 타입의 변환이 carrier를
던져도(조회하다 DB 실패 등) 인자를 거부한 것이라 같은 WARN 한 줄이다. web이 읽지 못한 본문과 바뀌지 않는 경로
변수에 원인과 상관없이 `VALIDATION_FAILED`·`BAD_PARAMETER`로 답하는 것과 같다. 인자 변환 단계는 carrier를 보지
않는다(소유자 결정 2026-11-07, 재리뷰 README 19.4절 ④).
- 그 밖의 예외는 예외와 함께 ERROR. 전에는 Spring이 예외 전체(persistence 실패의 SQL 원인 포함)를 ERROR로 남겼다.
필수 header·destination 변수가 없을 때의 `MessageHandlingException`도 ERROR다. 메시지에 입력값이 없고, Spring이
같은 타입으로 서버 실패도 감싸서 타입만으로는 클라이언트 탓을 가를 수 없다(결정 색인 기본값 2026-11-07).
@@ -42,6 +42,12 @@ import org.springframework.web.bind.annotation.ControllerAdvice;
* BAD_PARAMETER}, like a path variable). Their messages quote the input, so they are not logged. A
* reply the converter could not write is the server's failure: Spring raises the same {@link
* MessageConversionException} for it, but without a failed message, and it stays an error.
*
* <p>Those refusals are judged before the cause chain is searched for a carrier. A converter that
* throws a carrier — a payload creator or a destination-variable type that looks something up —
* still made a refusal of the argument, as the web adapter answers an unreadable body or a path
* variable that does not convert whatever their cause: the argument conversion stage does not read
* a carrier (owner decision 2026-11-07).
*/
@ControllerAdvice
class StompHandlerFailureLog {
@@ -50,6 +56,12 @@ class StompHandlerFailureLog {
@MessageExceptionHandler
void logFailure(Exception failure) {
Optional<ApiErrorCode> refusal = clientRefusalOf(failure);
if (refusal.isPresent()) {
ServerFailureLog line = ServerFailureLog.refused(refusal.get(), failure);
log.warn(line.format(""), line.arguments());
return;
}
Optional<Throwable> carrier = ApiErrorCarrier.firstIn(failure);
if (carrier.isPresent()) {
ServerFailureLog.of(carrier.get(), ((ApiErrorCarrier) carrier.get()).errorCode())
@@ -61,12 +73,6 @@ class StompHandlerFailureLog {
log.warn(line.format(""), line.arguments());
return;
}
Optional<ApiErrorCode> refusal = clientRefusalOf(failure);
if (refusal.isPresent()) {
ServerFailureLog line = ServerFailureLog.refused(refusal.get(), failure);
log.warn(line.format(""), line.arguments());
return;
}
log.error("unhandled failure in a STOMP message handler", failure);
}
@@ -183,6 +183,39 @@ class StompHandlerFailureLogTest {
.containsExactly(Level.WARN, "request refused as " + code + " by " + failureType, null);
}
/** Arguments whose conversion threw a server-side carrier: the converter, not the use case. */
static Stream<Arguments> conversionRefusalsAroundACarrier() {
return Stream.of(
Arguments.of(
"/app/signup",
"{\"email\": \"alice@example.com\"}".getBytes(StandardCharsets.UTF_8),
"VALIDATION_FAILED",
"org.springframework.messaging.converter.MessageConversionException"),
Arguments.of(
"/app/invoices/INV-1",
new byte[0],
"BAD_PARAMETER",
"org.springframework.core.convert.ConversionFailedException"));
}
@ParameterizedTest
@MethodSource("conversionRefusalsAroundACarrier")
@DisplayName("변환기가 던진 carrier 를 원인으로 든 인자 변환 실패도 거부로 WARN 한 줄이다(인자 변환 단계는 carrier 를 보지 않는다)")
void aConversionRefusalAroundACarrierIsStillLoggedAsARefusal(
String destination, byte[] payload, String code, String failureType) {
// when
List<ILoggingEvent> logged = loggedWhileHandling(destination, payload, Map.of());
// then
assertThat(logged)
.singleElement()
.extracting(
ILoggingEvent::getLevel,
ILoggingEvent::getFormattedMessage,
ILoggingEvent::getThrowableProxy)
.containsExactly(Level.WARN, "request refused as " + code + " by " + failureType, null);
}
@Test
void aReplyTheConverterCannotWriteIsLoggedAtErrorWithTheFailure() {
// when
@@ -321,6 +354,12 @@ class StompHandlerFailureLogTest {
@MessageMapping("/count")
void count(@Header("count") int count) {}
@MessageMapping("/signup")
void signup(@Payload Signup signup) {}
@MessageMapping("/invoices/{number}")
void invoice(@DestinationVariable InvoiceNumber number) {}
@MessageMapping("/unwritable-reply")
UnwritableReply unwritableReply() {
return new UnwritableReply();
@@ -340,6 +379,31 @@ class StompHandlerFailureLogTest {
/** A payload a client sends as JSON. */
record Greeting(String name) {}
/** A payload whose creator fails with a server-side carrier for any address. */
record Signup(String email) {
Signup {
if (!email.isEmpty()) {
throw new PersistenceFailureException(
OperationalError.DB_UNAVAILABLE, "signup lookup failed", null);
}
}
}
/** A destination-variable type whose conversion fails with a server-side carrier. */
public static final class InvoiceNumber {
private InvoiceNumber() {}
/** The conversion Spring finds; a lookup that fails with a carrier for any number. */
public static InvoiceNumber valueOf(String value) {
if (!value.isEmpty()) {
throw new PersistenceFailureException(
OperationalError.DB_UNAVAILABLE, "invoice lookup failed for " + value, null);
}
return new InvoiceNumber();
}
}
/** A reply the JSON converter cannot write: its only property is itself. */
static final class UnwritableReply {
public UnwritableReply getSelf() {
@@ -273,6 +273,14 @@ tasks.named('postgresqlConcurrentIndexMigrationIntegrationTest', Test) {
systemProperty 'migration.failed.runbook', migrationFailedRunbook.absolutePath
}
// The lock-timeout runbook gives an operator SQL to find who holds a lock; the lock lane reads it out
// of the runbook the same way, so the query an operator runs is the one that ran against PostgreSQL.
tasks.named('postgresqlDistributedLockIntegrationTest', Test) {
def lockTimeoutRunbook = new File(rootProject.projectDir.parentFile, 'docs/runbooks/lock-acquisition-timeout.md')
inputs.file(lockTimeoutRunbook).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('lockTimeoutRunbook')
systemProperty 'lock.acquisition-timeout.runbook', lockTimeoutRunbook.absolutePath
}
tasks.named('postgresqlSecurityBaselineIntegrationTest') {
// Cross-leaf task edge: see the handoff. verifyCleanArchitectureDependencies inspects
// configurations, not the task graph, so this edge is invisible to it.
@@ -8,8 +8,12 @@ import dev.caskeleton.application.lock.DistributedLock;
import dev.caskeleton.application.lock.DistributedLockPort;
import dev.caskeleton.application.lock.LockAcquisitionTimeoutException;
import dev.caskeleton.application.lock.testkit.DistributedLockContract;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.AfterAll;
@@ -19,11 +23,18 @@ import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.integration.jdbc.lock.DefaultLockRepository;
import org.springframework.integration.jdbc.lock.JdbcLockRegistry;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
/** Real PostgreSQL contract for the Spring Integration JDBC distributed-lock adapter. */
/**
* Real PostgreSQL contract for the Spring Integration JDBC distributed-lock adapter, and the SQL
* the lock-timeout runbook gives an operator to find a lock's holder, read out of the runbook
* itself.
*/
class PostgreSqlDistributedLockIntegrationTest {
private static final String LOCK_TIMEOUT_RUNBOOK = "lock.acquisition-timeout.runbook";
private static PostgreSqlReadinessSupport postgres;
private static DataSource dataSource;
@@ -120,6 +131,65 @@ class PostgreSqlDistributedLockIntegrationTest {
}
}
@Test
void theRunbookListsAHeldLockWithTheInstanceHoldingIt() throws Exception {
// given
RunbookSql runbook = RunbookSql.fromSystemProperty(LOCK_TIMEOUT_RUNBOOK);
Duration ttl = Duration.ofSeconds(30);
String holder = UUID.randomUUID().toString();
DefaultLockRepository repository = repository(dataSource, holder);
String key = "orders/runbook-holders-" + System.nanoTime();
DistributedLock held = adapter(repository, ttl).tryAcquire(key, Duration.ofSeconds(1), ttl);
try {
// when
List<Map<String, Object>> rows =
new JdbcTemplate(dataSource).queryForList(runbook.block("lock-holders"));
// then
assertThat(rows)
.filteredOn(row -> holder.equals(row.get("client_id")))
.extracting(row -> row.get("lock_key"))
.containsExactly(nameBasedUuidOf(key));
} finally {
held.close();
repository.stop();
}
}
@Test
void theRunbookFindsTheInstanceHoldingTheLockOfAKeyItIsGiven() throws Exception {
// given
RunbookSql runbook = RunbookSql.fromSystemProperty(LOCK_TIMEOUT_RUNBOOK);
Duration ttl = Duration.ofSeconds(30);
String holder = UUID.randomUUID().toString();
DefaultLockRepository holderRepository = repository(dataSource, holder);
DefaultLockRepository neighbourRepository = repository(dataSource);
String key = "orders/runbook-key-" + System.nanoTime();
DistributedLock held =
adapter(holderRepository, ttl).tryAcquire(key, Duration.ofSeconds(1), ttl);
DistributedLock neighbour =
adapter(neighbourRepository, ttl).tryAcquire(key + "/next", Duration.ofSeconds(1), ttl);
try {
// when
List<Map<String, Object>> rows =
new JdbcTemplate(dataSource)
.queryForList(runbook.block("lock-holder-of-key", Map.of("lock_key", key)));
// then
assertThat(rows).extracting(row -> row.get("client_id")).containsExactly(holder);
} finally {
held.close();
neighbour.close();
holderRepository.stop();
neighbourRepository.stop();
}
}
/** What Spring Integration stores as {@code LOCK_KEY} for a key that is not itself a UUID. */
private static String nameBasedUuidOf(String key) {
return UUID.nameUUIDFromBytes(key.getBytes(StandardCharsets.UTF_8)).toString();
}
private static DistributedLock acquireWithin(
LockRegistryDistributedLock adapter, String key, Duration leaseTtl, Duration bound)
throws InterruptedException {
@@ -143,7 +213,11 @@ class PostgreSqlDistributedLockIntegrationTest {
}
private static DefaultLockRepository repository(DataSource dataSource) {
DefaultLockRepository repository = new DefaultLockRepository(dataSource);
return repository(dataSource, UUID.randomUUID().toString());
}
private static DefaultLockRepository repository(DataSource dataSource, String clientId) {
DefaultLockRepository repository = new DefaultLockRepository(dataSource, clientId);
repository.setCheckDatabaseOnStart(false);
repository.setTransactionManager(new DataSourceTransactionManager(dataSource));
repository.afterPropertiesSet();
+4 -1
View File
@@ -582,7 +582,10 @@ application 계층은 락 획득/해제 계약만 알고, 실제 구현은 adapt
- `ApiErrorCarrier` 를 구현한다. 그래서 전송이 따로 처리기를 두지 않아도 web 은 409 +
`Retry-After: 1`(레지스트리 값), GraphQL·gRPC 는 같은 코드로 답하고, 4xx 라 서버 로그를 남기지 않는다. 전에는
carrier 가 아니어서 모든 전송이 500 `INTERNAL_ERROR`(재시도 불가)와 "unhandled" ERROR 로 답했다(재리뷰
RR7-01-04). 진단용 `getMessage()`(key·waitTime 포함)는 서버 로그 전용이고 API 클라이언트에 전달하면 안 된다.
RR7-01-04). `getMessage()`(key·waitTime 포함)는 클라이언트에 보내지 않고, 로그에도 남지 않는다. 4xx carrier 라
어느 전송도 남기지 않고, 락 adapter 도 timeout 을 남기지 않는다. 어느 락이 막혔는지 기록이 필요하면 호출자가
`key()` 를 직접 남긴다(엔티티 id 는 빼고). 운영 절차는 `docs/runbooks/lock-acquisition-timeout.md`
(`lock.acquisition` metric, `INT_LOCK` 보유자 조회)다(재리뷰 RR8-01-02).
---
@@ -11,7 +11,12 @@ import java.time.Duration;
* through {@link ApiErrorCarrier}, the hook every inbound transport reads a code from: the web
* adapter answers 409 with {@code Retry-After}, GraphQL and gRPC the same code, and none of them
* logs it as an unhandled failure. Without the hook it was answered as a 500 {@code INTERNAL_ERROR}
* (review 2026-11-06 RR7-01-04). {@link #getMessage()} is server-log-only. See README.
* (review 2026-11-06 RR7-01-04).
*
* <p>{@link #getMessage()} names the key and the wait time. It is never sent to a client, and no
* transport logs it either: a 4xx carrier is an answer, not an incident, so this timeout leaves no
* server line, and the lock adapters do not log one. A caller that wants a record of which lock
* timed out logs {@link #key()} itself, keeping entity ids out of the line. See README.
*/
public final class LockAcquisitionTimeoutException extends RuntimeException
implements ApiErrorCarrier {
+6
View File
@@ -86,6 +86,12 @@ Spring/Lettuce 타입을 노출하지 않는다.
adapter가 carrier를 다른 예외로 감싸 던져도 네 전송 모두 그 carrier의 코드로 답한다. 전에는 gRPC만 사슬을
따라가고 web·GraphQL·STOMP는 500 `INTERNAL_ERROR`로 답했다(소유자 결정 2026-11-06, 재리뷰 RR7-01-05).
사슬이 자기 자신으로 돌아오면 거기서 멈춘다.
- 원인 사슬의 carrier 보다 먼저 답하는 것이 있다.
- GraphQL 에서 앱이 `GraphQlExceptionResolver` 에 등록한 실패 타입은 원인에 carrier 가 있어도 등록한 코드로
답한다. 실패 자신이 carrier 면 그 코드가 등록 매핑보다 먼저다(소유자 결정 2026-11-07, 재리뷰 README 19.4절 ①).
- 인자 변환 단계(web 경로 변수·본문, STOMP payload·destination 변수·header, GraphQL `@Argument` binder)의 실패는
원인에 carrier 가 있어도 거부(`BAD_PARAMETER`·`VALIDATION_FAILED`)다(소유자 결정 2026-11-07, 재리뷰 README
19.4절 ④).
### ServerFailureLog — 모든 전송이 같은 로그 줄로
- carrier로 답한 실패의 서버 로그 줄을 정한다. web·GraphQL·gRPC·STOMP 어댑터가 이 클래스 하나를 쓴다
@@ -34,6 +34,13 @@ public interface ApiErrorCarrier {
* alike, instead of {@code INTERNAL_ERROR} on some of them (review 2026-11-06 RR7-01-05). The
* search stops where a cause chain loops back on itself.
*
* <p>A mapping a GraphQL application registered for the failure's own type answers before a
* carrier found behind the failure (owner decision 2026-11-07).
*
* <p>An argument that did not convert is refused by each transport's argument conversion stage
* whatever the conversion threw; that stage does not search for a carrier (owner decision
* 2026-11-07).
*
* @param failure the failure a transport is answering; may be {@code null}
* @return the carrier as the throwable it is — hand that to {@link ServerFailureLog#of}, not the
* wrapper, so its type still decides what may be logged