From f594b373b6530da0c266f5bd9c5aa6f1a4dec86e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 21 Nov 2026 08:41:15 +0900 Subject: [PATCH 1/3] =?UTF-8?q?fix(httpclient):=20=EB=91=90=20=EC=97=94?= =?UTF-8?q?=EC=A7=84=EC=9D=B4=20=EA=B3=B5=EC=9A=A9=20=EB=B6=84=EB=A5=98=20?= =?UTF-8?q?=EA=B7=9C=EC=B9=99=EC=9C=BC=EB=A1=9C=20=EB=B3=B8=EB=AC=B8=20?= =?UTF-8?q?=EC=A4=91=20=EB=81=8A=EA=B9=80=EC=9D=84=20RESPONSE=5FTRUNCATED?= =?UTF-8?q?=EB=A1=9C=20=EB=82=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ApacheFailureClassifier와 JdkFailureClassifier가 원인 사슬 걷기, JDK socket·TLS 예외 인식, stage만 보는 규칙(conservative·timeout·fallback)을 각자 복사해 두었고 이미 갈라졌다. 같은 SocketException("Connection reset")을 stage RESPONSE_BODY로 넣으면 Apache는 UNKNOWN(재시도 안 함), JDK는 RESPONSE_TRUNCATED(멱등이면 재시도)를 낸다. 설계 표(httpclient production capability 설계 1803행)는 본문이 덜 온 경우를 RESPONSE_TRUNCATED로 정한다. transport 패키지에 TransportFailureRules 하나를 두고 공용 규칙을 옮긴다. 분류기에는 엔진 전용 예외만 남는다(Apache: 풀 timeout 둘, ConnectTimeoutException·HttpHostConnectException, ConnectionClosedException / JDK: HttpConnectTimeoutException, HttpTimeoutException). 원인 하나마다 엔진 규칙을 먼저 본다. Apache 풀 timeout은 InterruptedIOException이고 connect timeout은 SocketTimeoutException이라 순서가 반대면 취소·stage timeout으로 읽힌다. 모르는 예외의 category는 stage가 RESPONSE_BODY이면 RESPONSE_TRUNCATED, 그 밖은 UNKNOWN이다. 새 계약 TransportFailureClassifierContractTest(계약 lane, 같은 transport 선택)가 같은 표 15줄을 고른 엔진마다 넣는다. 버린 안: 분류기마다 단위 시험 더하기 (두 값이 다르다는 것을 고정할 뿐 같아야 한다는 것을 막지 못한다), BlockingTransportProviderContract에 실제 socket 「본문 중 reset」 더하기 (Upstream·각본 fake에 본문 중 끊기를 새로 만들어야 하고, 각본 fake 분류기는 stage가 아니라 각본을 답해 같은 표를 통과할 수 없다). 위험: 의도한 동작 변경 넷이 계약 표에 고정된다. Apache RESPONSE_BODY의 모르는 예외 UNKNOWN→RESPONSE_TRUNCATED(buffered 멱등 요청이 재시도되고 streaming은 HttpResponseTruncatedException), JDK COMPLETE의 모르는 예외 RESPONSE_TRUNCATED→UNKNOWN, JDK RESPONSE_BODY InterruptedIOException의 evidence SENT_NO_RESPONSE→PARTIAL_RESPONSE(category CANCELLED라 재시도 판정 같음), JDK 보내기 전 stage timeout SENT_NO_RESPONSE→NOT_SENT/CONNECT (운영에서는 쓰기 신호가 없어 엔진 전에 stage가 REQUEST_BODY라 닿지 않음). 실험 HTTP/3 분류기는 이 규칙을 쓰지 않는다. virtual thread에서 Apache 본문 읽기 interrupt가 RESPONSE_TRUNCATED로 재시도되는지는 돌려 보지 않았다. 검증: 두 커밋을 합친 트리 46975fcf에서 확인했다. 고치기 전 분류기 두 개에 새 계약 표를 넣으면 32개 중 4개가 실패한다(Apache reset@RESPONSE_BODY가 기대 RESPONSE_TRUNCATED·실제 UNKNOWN, 나머지 셋은 위의 JDK 변경). 고친 뒤 통과한다. desktop scripts/verify.sh leaf :adapter:outbound:httpclient rc=0, scripts/verify.sh pr --no-cache rc=0 (tests=7302 failures=0), 노트북 scripts/verify.sh docs rc=0. Refs: REV-BE-0024 --- .../apache/ApacheFailureClassifier.java | 110 +--------- .../httpclient/jdk/JdkFailureClassifier.java | 106 ++------- .../transport/TransportFailureRules.java | 173 +++++++++++++++ ...ransportFailureClassifierContractTest.java | 203 ++++++++++++++++++ 4 files changed, 400 insertions(+), 192 deletions(-) create mode 100644 src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/TransportFailureRules.java create mode 100644 src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/TransportFailureClassifierContractTest.java diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheFailureClassifier.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheFailureClassifier.java index d08a53fa..f35d0490 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheFailureClassifier.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApacheFailureClassifier.java @@ -1,19 +1,10 @@ package dev.caskeleton.adapter.outbound.httpclient.apache; import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; -import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureClassifier; -import java.io.InterruptedIOException; -import java.net.ConnectException; -import java.net.NoRouteToHostException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.security.cert.CertificateException; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.SSLPeerUnverifiedException; +import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureRules; import org.apache.hc.client5.http.ConnectTimeoutException; import org.apache.hc.client5.http.HttpHostConnectException; import org.apache.hc.core5.http.ConnectionClosedException; @@ -21,28 +12,18 @@ import org.apache.hc.core5.http.ConnectionClosedException; /** * Maps Apache HttpClient 5 failures onto stable evidence (design §13.3, §13.4). * - *

The classifier is deliberately asymmetric: {@code NOT_SENT} is only produced for stages that - * prove nothing left the process. Once the request write has begun, an ambiguous I/O error stays - * {@code SENT_NO_RESPONSE}, because guessing "not sent" is what turns a timeout into a duplicate - * payment. + *

Only Apache's own exception types are recognised here. The cause chain, the JDK socket and TLS + * exceptions, and the stage rules are shared with the JDK engine in {@link TransportFailureRules}. */ public final class ApacheFailureClassifier implements TransportFailureClassifier { @Override public TransportFailure classify(Throwable failure, AttemptStage lastObservedStage) { - // The whole cause chain is inspected, not just the outermost throwable: Spring wraps engine - // exceptions, and a wrapped ConnectException still proves the request was never sent. Matching - // only the outer type would downgrade a provable NOT_SENT to an ambiguous SENT_NO_RESPONSE. - for (Throwable cause : chain(failure)) { - TransportFailure recognized = recognize(cause, lastObservedStage); - if (recognized != null) { - return recognized; - } - } - return conservative(lastObservedStage, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE"); + return TransportFailureRules.classify( + failure, lastObservedStage, ApacheFailureClassifier::recognize); } - private TransportFailure recognize(Throwable cause, AttemptStage lastObservedStage) { + private static TransportFailure recognize(Throwable cause, AttemptStage lastObservedStage) { if (cause instanceof org.apache.hc.core5.concurrent.CancellableDependency) { return TransportFailure.notSent( AttemptStage.POOL_ACQUIRE, FailureCategory.POOL_ACQUIRE_TIMEOUT, "POOL_ACQUIRE_TIMEOUT"); @@ -51,90 +32,21 @@ public final class ApacheFailureClassifier implements TransportFailureClassifier return TransportFailure.notSent( AttemptStage.POOL_ACQUIRE, FailureCategory.POOL_ACQUIRE_TIMEOUT, "POOL_ACQUIRE_TIMEOUT"); } - if (cause instanceof UnknownHostException) { - return TransportFailure.notSent( - AttemptStage.DNS, FailureCategory.DNS, "DNS_RESOLUTION_FAILED"); - } - if (cause instanceof ConnectTimeoutException - || cause instanceof HttpHostConnectException - || cause instanceof ConnectException - || cause instanceof NoRouteToHostException) { + // Both connect failures. ConnectTimeoutException is a SocketTimeoutException, so it is + // recognised here, before the shared timeout rule would classify it by the stage. + if (cause instanceof ConnectTimeoutException || cause instanceof HttpHostConnectException) { return TransportFailure.notSent( AttemptStage.CONNECT, FailureCategory.CONNECT, "CONNECT_FAILED"); } - if (cause instanceof SSLPeerUnverifiedException || cause instanceof CertificateException) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_TRUST_FAILED"); - } - if (cause instanceof SSLHandshakeException) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_HANDSHAKE_FAILED"); - } - if (cause instanceof SSLException - && !lastObservedStage.isAtLeast(AttemptStage.REQUEST_HEADERS)) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_TRANSIENT, "TLS_TRANSIENT_FAILURE"); - } - if (cause instanceof SocketTimeoutException) { - return timeout(lastObservedStage); - } - if (cause instanceof InterruptedIOException) { - // Not a timeout. A SocketTimeoutException means the peer went quiet; a bare - // InterruptedIOException usually means this thread was interrupted — a cancellation, from a - // caller or a shutdown. Treating the two alike classified a cancellation as a transient - // timeout, which the retry engine then retried, so cancelling a call could produce more - // requests than not cancelling it. The interrupt flag is restored because swallowing it - // leaves the thread unable to observe its own cancellation. - Thread.currentThread().interrupt(); - return conservative(lastObservedStage, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED"); - } if (cause instanceof ConnectionClosedException) { - return conservative( + return TransportFailureRules.conservative( lastObservedStage, FailureCategory.RESPONSE_TRUNCATED, "CONNECTION_CLOSED"); } return null; } - private java.util.List chain(Throwable failure) { - java.util.List chain = new java.util.ArrayList<>(); - Throwable current = failure; - while (current != null && !chain.contains(current)) { - chain.add(current); - current = current.getCause(); - } - return chain; - } - - private boolean isPoolAcquireTimeout(Throwable cause) { + private static boolean isPoolAcquireTimeout(Throwable cause) { String typeName = cause.getClass().getName(); return typeName.endsWith("ConnectionRequestTimeoutException"); } - - private TransportFailure timeout(AttemptStage lastObservedStage) { - if (lastObservedStage.provesNotSent()) { - return TransportFailure.notSent( - lastObservedStage, FailureCategory.CONNECT, "CONNECT_TIMEOUT"); - } - if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { - return new TransportFailure( - lastObservedStage, - ExecutionEvidence.PARTIAL_RESPONSE, - FailureCategory.RESPONSE_TIMEOUT, - "RESPONSE_BODY_TIMEOUT"); - } - return TransportFailure.sentNoResponse( - AttemptStage.RESPONSE_HEADERS, FailureCategory.RESPONSE_TIMEOUT, "RESPONSE_HEADER_TIMEOUT"); - } - - private TransportFailure conservative( - AttemptStage lastObservedStage, FailureCategory category, String reason) { - if (lastObservedStage.provesNotSent()) { - return TransportFailure.notSent(lastObservedStage, category, reason); - } - if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { - return new TransportFailure( - lastObservedStage, ExecutionEvidence.PARTIAL_RESPONSE, category, reason); - } - return TransportFailure.sentNoResponse(lastObservedStage, category, reason); - } } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java index 234b5919..994da83b 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/JdkFailureClassifier.java @@ -1,120 +1,40 @@ package dev.caskeleton.adapter.outbound.httpclient.jdk; import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; -import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureClassifier; -import java.io.InterruptedIOException; -import java.net.ConnectException; -import java.net.NoRouteToHostException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; +import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureRules; import java.net.http.HttpConnectTimeoutException; import java.net.http.HttpTimeoutException; -import java.security.cert.CertificateException; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.SSLPeerUnverifiedException; /** * Maps JDK HttpClient failures onto stable evidence (design §13.3, §13.5). * *

The JDK exposes fewer stage-specific exceptions than Apache, so anything other than a proven - * pre-send failure stays conservative. + * pre-send failure stays conservative. Only the client's own timeout types are recognised here; the + * cause chain, the socket and TLS exceptions, and the stage rules are shared with the Apache engine + * in {@link TransportFailureRules}. */ public final class JdkFailureClassifier implements TransportFailureClassifier { @Override public TransportFailure classify(Throwable failure, AttemptStage lastObservedStage) { - // Spring and the JDK both wrap engine exceptions; the chain is inspected so a wrapped - // ConnectException still classifies as provably NOT_SENT. - for (Throwable cause : chain(failure)) { - TransportFailure recognized = recognize(cause, lastObservedStage); - if (recognized != null) { - return recognized; - } - } - return fallback(lastObservedStage); + return TransportFailureRules.classify( + failure, lastObservedStage, JdkFailureClassifier::recognize); } - private TransportFailure recognize(Throwable cause, AttemptStage lastObservedStage) { - if (cause instanceof HttpConnectTimeoutException - || cause instanceof ConnectException - || cause instanceof NoRouteToHostException) { + private static TransportFailure recognize(Throwable cause, AttemptStage lastObservedStage) { + // HttpConnectTimeoutException extends HttpTimeoutException, so the connect case comes first. + if (cause instanceof HttpConnectTimeoutException) { return TransportFailure.notSent( AttemptStage.CONNECT, FailureCategory.CONNECT, "CONNECT_FAILED"); } - if (cause instanceof UnknownHostException) { - return TransportFailure.notSent( - AttemptStage.DNS, FailureCategory.DNS, "DNS_RESOLUTION_FAILED"); - } - if (cause instanceof SSLPeerUnverifiedException || cause instanceof CertificateException) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_TRUST_FAILED"); - } - if (cause instanceof SSLHandshakeException) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_HANDSHAKE_FAILED"); - } - if (cause instanceof SSLException - && !lastObservedStage.isAtLeast(AttemptStage.REQUEST_HEADERS)) { - return TransportFailure.notSent( - AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_TRANSIENT, "TLS_TRANSIENT_FAILURE"); - } - // HttpTimeoutException is an IOException, never an InterruptedIOException, so only the socket - // timeout needs excluding here; the JDK client's own timeouts are classified below. - if (cause instanceof InterruptedIOException && !(cause instanceof SocketTimeoutException)) { - // Cancellation, not a timeout. Classifying it as a timeout let the retry engine reissue a - // request the caller had just cancelled, and dropped the interrupt so the thread could not - // see its own cancellation either. - Thread.currentThread().interrupt(); - if (lastObservedStage.provesNotSent()) { - return TransportFailure.notSent( - lastObservedStage, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED"); - } - return TransportFailure.sentNoResponse( - lastObservedStage, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED"); - } - if (cause instanceof HttpTimeoutException || cause instanceof SocketTimeoutException) { - if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { - return new TransportFailure( - lastObservedStage, - ExecutionEvidence.PARTIAL_RESPONSE, - FailureCategory.RESPONSE_TIMEOUT, - "RESPONSE_BODY_TIMEOUT"); - } - return TransportFailure.sentNoResponse( - AttemptStage.RESPONSE_HEADERS, - FailureCategory.RESPONSE_TIMEOUT, - "RESPONSE_HEADER_TIMEOUT"); + // An IOException, never an InterruptedIOException, so the shared cancellation rule would not + // see it; it is the client's request timeout and reads like a socket timeout. + if (cause instanceof HttpTimeoutException) { + return TransportFailureRules.timeout(lastObservedStage); } return null; } - - private TransportFailure fallback(AttemptStage lastObservedStage) { - if (lastObservedStage.provesNotSent()) { - return TransportFailure.notSent( - lastObservedStage, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE"); - } - if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { - return new TransportFailure( - lastObservedStage, - ExecutionEvidence.PARTIAL_RESPONSE, - FailureCategory.RESPONSE_TRUNCATED, - "TRANSPORT_FAILURE"); - } - return TransportFailure.sentNoResponse( - lastObservedStage, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE"); - } - - private java.util.List chain(Throwable failure) { - java.util.List chain = new java.util.ArrayList<>(); - Throwable current = failure; - while (current != null && !chain.contains(current)) { - chain.add(current); - current = current.getCause(); - } - return chain; - } } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/TransportFailureRules.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/TransportFailureRules.java new file mode 100644 index 00000000..3566f686 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/TransportFailureRules.java @@ -0,0 +1,173 @@ +package dev.caskeleton.adapter.outbound.httpclient.transport; + +import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; +import java.io.InterruptedIOException; +import java.net.ConnectException; +import java.net.NoRouteToHostException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.List; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLPeerUnverifiedException; + +/** + * The classification rules the Stable engines, Apache and JDK, share (design §13.3). + * + *

An engine classifier contributes only what is particular to its engine: the exception types it + * alone throws. The rest lives here once — walking the cause chain, the JDK socket and TLS + * exceptions both engines surface, and the rules that turn a stage into evidence. Each engine used + * to carry its own copy of all of it, and the copies drifted: a failure nobody recognised while the + * response body was arriving was {@code UNKNOWN} on Apache and {@code RESPONSE_TRUNCATED} on JDK, + * so the same connection reset was a permanent failure on one engine and a retryable one on the + * other. {@code TransportFailureClassifierContractTest} holds both engines to one table. The + * experimental HTTP/3 classifier does not use these rules yet. + */ +public final class TransportFailureRules { + + private TransportFailureRules() {} + + /** + * One engine's recognition of its own exception types. + * + *

Answers {@code null} for a cause that is not one of them, so the shared rules try it next. + */ + @FunctionalInterface + public interface EngineRecognizer { + + TransportFailure recognize(Throwable cause, AttemptStage lastObservedStage); + } + + /** + * Classifies {@code failure} by the first cause in its chain that the engine or the shared rules + * recognise, outermost first, and by the stage alone when none is recognised. + * + *

The whole chain is read because Spring and the engines wrap their exceptions: a wrapped + * {@code ConnectException} still proves the request never left, and matching only the outer type + * would downgrade that to an ambiguous {@code SENT_NO_RESPONSE}. For each cause the engine's + * types are tried before the shared ones, so an engine exception that extends a JDK one is read + * as the engine meant it: Apache's pool timeout is an {@code InterruptedIOException} the shared + * rules would read as a cancellation, and its connect timeout a {@code SocketTimeoutException} + * they would read by the stage. + */ + public static TransportFailure classify( + Throwable failure, AttemptStage lastObservedStage, EngineRecognizer engine) { + for (Throwable cause : causeChain(failure)) { + TransportFailure recognized = engine.recognize(cause, lastObservedStage); + if (recognized == null) { + recognized = recognizeShared(cause, lastObservedStage); + } + if (recognized != null) { + return recognized; + } + } + return unrecognized(lastObservedStage); + } + + /** + * A timeout, read against the stage it happened in. + * + *

Before anything left it was the connect; while the body was arriving the response was partly + * received; anywhere between, the request may have been processed and no headers came back. + */ + public static TransportFailure timeout(AttemptStage lastObservedStage) { + if (lastObservedStage.provesNotSent()) { + return TransportFailure.notSent( + lastObservedStage, FailureCategory.CONNECT, "CONNECT_TIMEOUT"); + } + if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { + return new TransportFailure( + lastObservedStage, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.RESPONSE_TIMEOUT, + "RESPONSE_BODY_TIMEOUT"); + } + return TransportFailure.sentNoResponse( + AttemptStage.RESPONSE_HEADERS, FailureCategory.RESPONSE_TIMEOUT, "RESPONSE_HEADER_TIMEOUT"); + } + + /** + * A failure whose evidence only the stage can give. + * + *

Deliberately asymmetric: {@code NOT_SENT} is only produced for a stage that proves nothing + * left the process. Once the request write has begun the failure stays {@code SENT_NO_RESPONSE}, + * because guessing "not sent" is what turns a timeout into a duplicate payment; once the body was + * arriving, the response was partly received. + */ + public static TransportFailure conservative( + AttemptStage lastObservedStage, FailureCategory category, String reason) { + if (lastObservedStage.provesNotSent()) { + return TransportFailure.notSent(lastObservedStage, category, reason); + } + if (lastObservedStage.isAtLeast(AttemptStage.RESPONSE_BODY)) { + return new TransportFailure( + lastObservedStage, ExecutionEvidence.PARTIAL_RESPONSE, category, reason); + } + return TransportFailure.sentNoResponse(lastObservedStage, category, reason); + } + + private static TransportFailure recognizeShared(Throwable cause, AttemptStage lastObservedStage) { + if (cause instanceof UnknownHostException) { + return TransportFailure.notSent( + AttemptStage.DNS, FailureCategory.DNS, "DNS_RESOLUTION_FAILED"); + } + if (cause instanceof ConnectException || cause instanceof NoRouteToHostException) { + return TransportFailure.notSent( + AttemptStage.CONNECT, FailureCategory.CONNECT, "CONNECT_FAILED"); + } + if (cause instanceof SSLPeerUnverifiedException || cause instanceof CertificateException) { + return TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_TRUST_FAILED"); + } + if (cause instanceof SSLHandshakeException) { + return TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_HANDSHAKE_FAILED"); + } + if (cause instanceof SSLException + && !lastObservedStage.isAtLeast(AttemptStage.REQUEST_HEADERS)) { + return TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_TRANSIENT, "TLS_TRANSIENT_FAILURE"); + } + if (cause instanceof SocketTimeoutException) { + return timeout(lastObservedStage); + } + if (cause instanceof InterruptedIOException) { + // Not a timeout. A SocketTimeoutException means the peer went quiet; a bare + // InterruptedIOException usually means this thread was interrupted — a cancellation, from a + // caller or a shutdown. Treating the two alike classified a cancellation as a transient + // timeout, which the retry engine then retried, so cancelling a call could produce more + // requests than not cancelling it. The interrupt flag is restored because swallowing it + // leaves the thread unable to observe its own cancellation. + Thread.currentThread().interrupt(); + return conservative(lastObservedStage, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED"); + } + return null; + } + + private static TransportFailure unrecognized(AttemptStage lastObservedStage) { + // While the body was arriving, a failure nobody recognised is a response that stopped short — + // RESPONSE_TRUNCATED in the design's category table, and what Apache already reported for its + // own ConnectionClosedException. At any other stage, COMPLETE included, it proves nothing + // beyond + // what the stage proves: a read body did not stop short. + FailureCategory category = + lastObservedStage == AttemptStage.RESPONSE_BODY + ? FailureCategory.RESPONSE_TRUNCATED + : FailureCategory.UNKNOWN; + return conservative(lastObservedStage, category, "TRANSPORT_FAILURE"); + } + + private static List causeChain(Throwable failure) { + List chain = new ArrayList<>(); + Throwable current = failure; + while (current != null && !chain.contains(current)) { + chain.add(current); + current = current.getCause(); + } + return chain; + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/TransportFailureClassifierContractTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/TransportFailureClassifierContractTest.java new file mode 100644 index 00000000..9d997a11 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/TransportFailureClassifierContractTest.java @@ -0,0 +1,203 @@ +package dev.caskeleton.adapter.outbound.httpclient.contract; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.argumentSet; + +import dev.caskeleton.adapter.outbound.httpclient.apache.ApacheFailureClassifier; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; +import dev.caskeleton.adapter.outbound.httpclient.jdk.JdkFailureClassifier; +import dev.caskeleton.adapter.outbound.httpclient.testkit.HttpClientContract; +import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure; +import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailureClassifier; +import java.io.InterruptedIOException; +import java.net.ConnectException; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.util.List; +import java.util.stream.Stream; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLPeerUnverifiedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.web.client.ResourceAccessException; + +/** + * One classification table every selected Stable engine answers alike (design §13.3). + * + *

The table covers what the engines share: the cause chain, the JDK socket and TLS exceptions + * every engine surfaces, and the rules that turn a stage into evidence. An engine's own exception + * types are not in it. The engines used to keep a copy of these rules each, and the copies drifted + * with no test seeing it: a connection reset while the body was arriving was {@code UNKNOWN}, a + * permanent failure, on Apache and a retryable {@code RESPONSE_TRUNCATED} on JDK. A unit test per + * engine would only have pinned the two answers apart; one table for both pins them together. + * + *

Selection follows the transport contract lane ({@link HttpClientContract}). The scripted fake + * is not held to this table: its classifier answers a script rather than a stage, and the fake is + * held to the transport contract instead ({@code ScriptedTransportContractTest}). + */ +@Tag("httpclient-contract") +@ParameterizedClass +@MethodSource("transports") +class TransportFailureClassifierContractTest { + + private static final String RESET = "Connection reset"; + + @Parameter String transport; + + static List transports() { + return HttpClientContract.selectedTransports(); + } + + static Stream sharedClassifications() { + return Stream.of( + argumentSet( + "본문을 받다 연결이 reset되면 덜 온 응답이다", + new SocketException(RESET), + AttemptStage.RESPONSE_BODY, + new TransportFailure( + AttemptStage.RESPONSE_BODY, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.RESPONSE_TRUNCATED, + "TRANSPORT_FAILURE")), + argumentSet( + "쓰기를 시작한 뒤 reset은 보냈을 수 있는 모르는 실패다", + new SocketException(RESET), + AttemptStage.REQUEST_BODY, + TransportFailure.sentNoResponse( + AttemptStage.REQUEST_BODY, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE")), + argumentSet( + "본문을 다 읽은 뒤 모르는 실패는 덜 온 응답이 아니다", + new SocketException(RESET), + AttemptStage.COMPLETE, + new TransportFailure( + AttemptStage.COMPLETE, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.UNKNOWN, + "TRANSPORT_FAILURE")), + argumentSet( + "아무것도 나가기 전 모르는 실패는 안 보냄이다", + new SocketException(RESET), + AttemptStage.CONNECT, + TransportFailure.notSent( + AttemptStage.CONNECT, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE")), + argumentSet( + "감싼 연결 거부는 stage가 쓰기 뒤여도 안 보냄이다", + new ResourceAccessException("I/O error", new ConnectException("Connection refused")), + AttemptStage.REQUEST_BODY, + TransportFailure.notSent( + AttemptStage.CONNECT, FailureCategory.CONNECT, "CONNECT_FAILED")), + argumentSet( + "이름 풀이 실패는 DNS 단계의 안 보냄이다", + new UnknownHostException("users.internal"), + AttemptStage.POOL_ACQUIRE, + TransportFailure.notSent( + AttemptStage.DNS, FailureCategory.DNS, "DNS_RESOLUTION_FAILED")), + argumentSet( + "인증서를 믿지 못하면 영구 TLS 실패다", + new SSLPeerUnverifiedException("peer not authenticated"), + AttemptStage.TLS_HANDSHAKE, + TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_TRUST_FAILED")), + argumentSet( + "handshake 거절은 영구 TLS 실패다", + new SSLHandshakeException("handshake failure"), + AttemptStage.TLS_HANDSHAKE, + TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, FailureCategory.TLS_PERMANENT, "TLS_HANDSHAKE_FAILED")), + argumentSet( + "header 전 TLS 오류는 일시 TLS 실패다", + new SSLException("record overflow"), + AttemptStage.CONNECT, + TransportFailure.notSent( + AttemptStage.TLS_HANDSHAKE, + FailureCategory.TLS_TRANSIENT, + "TLS_TRANSIENT_FAILURE")), + argumentSet( + "쓰기를 시작한 뒤 TLS 오류는 모르는 실패다", + new SSLException("record overflow"), + AttemptStage.REQUEST_BODY, + TransportFailure.sentNoResponse( + AttemptStage.REQUEST_BODY, FailureCategory.UNKNOWN, "TRANSPORT_FAILURE")), + argumentSet( + "나가기 전 socket timeout은 connect timeout이다", + new SocketTimeoutException("connect timed out"), + AttemptStage.CONNECT, + TransportFailure.notSent( + AttemptStage.CONNECT, FailureCategory.CONNECT, "CONNECT_TIMEOUT")), + argumentSet( + "쓰기 뒤 socket timeout은 header 대기 timeout이다", + new SocketTimeoutException("read timed out"), + AttemptStage.REQUEST_BODY, + TransportFailure.sentNoResponse( + AttemptStage.RESPONSE_HEADERS, + FailureCategory.RESPONSE_TIMEOUT, + "RESPONSE_HEADER_TIMEOUT")), + argumentSet( + "본문 중 socket timeout은 본문 timeout이다", + new SocketTimeoutException("read timed out"), + AttemptStage.RESPONSE_BODY, + new TransportFailure( + AttemptStage.RESPONSE_BODY, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.RESPONSE_TIMEOUT, + "RESPONSE_BODY_TIMEOUT")), + argumentSet( + "쓰기 뒤 interrupt는 보냈을 수 있는 취소다", + new InterruptedIOException("interrupted"), + AttemptStage.REQUEST_BODY, + TransportFailure.sentNoResponse( + AttemptStage.REQUEST_BODY, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED")), + argumentSet( + "본문 중 interrupt는 덜 받은 응답의 취소다", + new InterruptedIOException("interrupted"), + AttemptStage.RESPONSE_BODY, + new TransportFailure( + AttemptStage.RESPONSE_BODY, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.CANCELLED, + "ATTEMPT_INTERRUPTED"))); + } + + @AfterEach + void clearTheInterruptACancellationRestores() { + Thread.interrupted(); + } + + @ParameterizedTest + @MethodSource("sharedClassifications") + void everyEngineClassifiesASharedFailureAlike( + Throwable failure, AttemptStage lastObservedStage, TransportFailure expected) { + // when + TransportFailure classified = classifier().classify(failure, lastObservedStage); + + // then + assertThat(classified).isEqualTo(expected); + } + + @Test + void aCancelledAttemptLeavesTheThreadInterrupted() { + // given + // An interrupt leaked from earlier work would make the flag below true without this call. + Thread.interrupted(); + + // when + classifier().classify(new InterruptedIOException("interrupted"), AttemptStage.REQUEST_BODY); + + // then + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + } + + private TransportFailureClassifier classifier() { + return "jdk".equals(transport) ? new JdkFailureClassifier() : new ApacheFailureClassifier(); + } +} -- 2.54.0 From befac7776cf31dc1e1914bbd32128c20bd43c008 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 21 Nov 2026 08:41:16 +0900 Subject: [PATCH 2/3] =?UTF-8?q?test(httpclient):=20=ED=92=80=20=EB=8C=80?= =?UTF-8?q?=EA=B8=B0=20timeout=20=EC=8B=9C=ED=97=98=EC=9D=B4=20stage?= =?UTF-8?q?=EA=B0=80=20=EC=95=84=EB=8B=88=EB=9D=BC=20=EC=98=88=EC=99=B8=20?= =?UTF-8?q?=EC=9D=B8=EC=8B=9D=EC=9C=BC=EB=A1=9C=20category=EA=B9=8C?= =?UTF-8?q?=EC=A7=80=20=EB=B3=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ApachePoolSaturationTest가 분류기에 stage POOL_ACQUIRE를 직접 넘기고 stage·evidence만 단언한다. 그 stage면 분류기가 풀 timeout을 못 알아봐도 NOT_SENT가 나와 시험이 초록이다. 못 알아보면 실제로는 CANCELLED, 재시도 안 함, 호출 스레드 interrupt가 된다. then을 extracting(stage, evidence, category, safeReason).containsExactly( POOL_ACQUIRE, NOT_SENT, POOL_ACQUIRE_TIMEOUT, "POOL_ACQUIRE_TIMEOUT") 한 번으로 하고, 넘기는 stage를 쓰기를 시작했을 수 있는 REQUEST_HEADERS로 바꾼다. 풀을 채우는 준비는 helper로 빼서 executor를 닫은 뒤 분류한다 (분기를 지운 변이에서 interrupt가 awaitTermination을 깨 단언 메시지를 가리지 않게). Thread.sleep(200)은 서버가 첫 요청을 받을 때까지의 takeRequest(상한 2초)로 바꾼다. 버린 안: gateway 수준 시험으로 올리기 (원인을 「분류기가 못 알아봄」으로 좁혀 주지 못한다). 위험: main 코드와 PoolSaturationPerformanceTest는 바꾸지 않는다. 검증: 트리 46975fcf에서 확인했다. 풀 timeout category를 UNKNOWN으로 바꾼 변이에서 새 시험은 기대 POOL_ACQUIRE_TIMEOUT·실제 UNKNOWN으로 실패하고 옛 시험은 통과한다. 풀 timeout 분기를 지운 변이에서 새 시험은 [REQUEST_HEADERS, SENT_NO_RESPONSE, CANCELLED, "ATTEMPT_INTERRUPTED"]로 실패한다(옛 시험은 3회 모두 InterruptedException). 고친 코드에서 통과한다. desktop scripts/verify.sh pr --no-cache rc=0. Refs: REV-BE-0022 --- .../apache/ApachePoolSaturationTest.java | 79 ++++++++++++------- 1 file changed, 51 insertions(+), 28 deletions(-) diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java index ccc2891a..7a9baf5b 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/apache/ApachePoolSaturationTest.java @@ -1,17 +1,19 @@ package dev.caskeleton.adapter.outbound.httpclient.apache; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.httpclient.api.operation.AttemptStage; import dev.caskeleton.adapter.outbound.httpclient.api.operation.ExecutionEvidence; +import dev.caskeleton.adapter.outbound.httpclient.api.operation.FailureCategory; import dev.caskeleton.adapter.outbound.httpclient.profile.ClientProfile; import dev.caskeleton.adapter.outbound.httpclient.profile.PoolSettings; +import dev.caskeleton.adapter.outbound.httpclient.profile.RuntimeGeneration; import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; import dev.caskeleton.adapter.outbound.httpclient.testkit.NoopLifecycleListener; import dev.caskeleton.adapter.outbound.httpclient.transport.TransportFailure; import java.time.Duration; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -20,56 +22,77 @@ import org.springframework.web.client.RestClient; class ApachePoolSaturationTest { + /** + * The stage handed to the classifier is one at which the request may already have left. A pool + * stage would make {@code NOT_SENT} come out whether or not the classifier recognised the + * timeout, and an unrecognised one is classified as a cancellation: not retried, and the calling + * thread left interrupted. Only recognising the exception gives this answer. + */ @Test - void poolAcquireTimeoutIsClassifiedAsNotSent() throws Exception { + void aPoolWaitTimeoutIsAPoolAcquireTimeoutProvenNotSentEvenWhenTheWriteMayHaveBegun() + throws Exception { + // given + Throwable saturated = failureOfACallThatFindsThePoolFull(); + + // when + TransportFailure failure = + new ApacheFailureClassifier().classify(saturated, AttemptStage.REQUEST_HEADERS); + + // then + assertThat(failure) + .extracting( + TransportFailure::stage, + TransportFailure::evidence, + TransportFailure::category, + TransportFailure::safeReason) + .containsExactly( + AttemptStage.POOL_ACQUIRE, + ExecutionEvidence.NOT_SENT, + FailureCategory.POOL_ACQUIRE_TIMEOUT, + "POOL_ACQUIRE_TIMEOUT"); + } + + /** + * One pooled connection, held by a call whose response body is late, and a second call that waits + * for it longer than the pool allows. Everything is shut down before the failure is returned, so + * classifying it is the only thing left to observe. + */ + private static Throwable failureOfACallThatFindsThePoolFull() throws Exception { ApacheBlockingTransportProvider provider = new ApacheBlockingTransportProvider(); - ExecutorService executor = Executors.newFixedThreadPool(2); + RuntimeGeneration generation = new RuntimeGeneration(1); + ExecutorService executor = Executors.newSingleThreadExecutor(); + Throwable saturated; try (MockHttpServer server = MockHttpServer.start()) { server.enqueueDelayedBody(200, "{\"slow\":true}", Duration.ofSeconds(2)); server.enqueueJson(200, "{\"fast\":true}"); - ClientProfile profile = singleConnectionProfile(server.uri("/")); RestClient client = RestClient.builder() - .requestFactory( - provider.create( - profile, - new dev.caskeleton.adapter.outbound.httpclient.profile.RuntimeGeneration(1), - NoopLifecycleListener.INSTANCE)) + .requestFactory(provider.create(profile, generation, NoopLifecycleListener.INSTANCE)) .build(); - - CountDownLatch firstStarted = new CountDownLatch(1); executor.execute( () -> { - firstStarted.countDown(); try { client.get().uri(server.uri("/slow")).retrieve().body(String.class); } catch (RuntimeException ignored) { // The holding request is only needed to occupy the single pooled connection. } }); - assertThat(firstStarted.await(2, TimeUnit.SECONDS)).isTrue(); - Thread.sleep(200); + // The server has the slow request once its connection is leased, so the next call waits. + server.takeRequest(Duration.ofSeconds(2)); - Throwable captured = null; - try { - client.get().uri(server.uri("/fast")).retrieve().body(String.class); - } catch (RuntimeException saturated) { - captured = saturated; - } + saturated = + catchThrowable(() -> client.get().uri(server.uri("/fast")).retrieve().body(String.class)); - assertThat(captured).isNotNull(); - TransportFailure failure = - new ApacheFailureClassifier().classify(captured, AttemptStage.POOL_ACQUIRE); - assertThat(failure.stage()).isEqualTo(AttemptStage.POOL_ACQUIRE); - assertThat(failure.evidence()).isEqualTo(ExecutionEvidence.NOT_SENT); - - provider.close( - profile, new dev.caskeleton.adapter.outbound.httpclient.profile.RuntimeGeneration(1)); + provider.close(profile, generation); } finally { executor.shutdownNow(); assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); } + if (saturated == null) { + throw new AssertionError("the second call was expected to time out waiting for the pool"); + } + return saturated; } private static ClientProfile singleConnectionProfile(java.net.URI baseUrl) { -- 2.54.0 From 5f6d76284139d3f749d16d4b27fe3b276e7f4d39 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 21 Nov 2026 09:04:47 +0900 Subject: [PATCH 3/3] =?UTF-8?q?fix(httpclient):=20interrupt=EB=90=9C=20thr?= =?UTF-8?q?ead=EC=9D=98=20=EB=AA=A8=EB=A5=B4=EB=8A=94=20=EC=8B=A4=ED=8C=A8?= =?UTF-8?q?=EB=A5=BC=20=EC=B7=A8=EC=86=8C=EB=A1=9C=20=EC=9D=BD=EB=8A=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit virtual thread가 socket을 읽다 interrupt되면 JDK가 socket을 닫고 SocketException("Closed by interrupt")을 던지며 interrupt 플래그는 선 채로 둔다. InterruptedIOException이 아니라 공용 규칙이 알아보지 못하고, stage RESPONSE_BODY의 모르는 예외라 RESPONSE_TRUNCATED가 된다. 재시도 엔진은 멱등 요청이면 재시도를 허가해 budget을 쓰고, backoff가 0보다 크면 Sleeper가 interrupt 플래그 때문에 IllegalStateException을 던진다. 공용 규칙 전의 Apache는 UNKNOWN이라 재시도하지 않았다(JDK는 전부터 TRUNCATED였다). 원인 사슬의 어느 원인도 알아보지 못했고 지금 thread의 interrupt 플래그가 서 있으면, stage만 보는 규칙 대신 취소(CANCELLED, ATTEMPT_INTERRUPTED)로 읽는다. 분류는 시도를 한 thread에서 돈다. ClosedByInterruptException도 플래그를 세우고 던지므로 같은 검사가 잡는다. 알아본 원인(timeout·DNS 등)은 플래그가 서 있어도 그대로 둔다. 버린 안: 원인 사슬에서 메시지 "Closed by interrupt"를 찾기(JDK 구현의 글자라 계약이 아니고, SocketException은 타입만 으로 interrupt를 말하지 않는다). 파생 서비스용 안내 docs/upgrade/2026-11-httpclient-failure-classification.md 에 공용 규칙으로 바뀐 동작 셋을 적는다. 문서가 이미 약속한 응답으로 맞춘 결함 수정이고 따라 고칠 코드가 없어 호환 깨짐 표시는 달지 않는다. #71 총괄 대조에서 찾음(앞 커밋이 만든 회귀). 위험: 앞서 새어 든 interrupt가 남은 thread에서는 모르는 실패가 취소로 읽혀 재시도되지 않는다(보수 쪽). 검증: 탐침은 주석만 다른 트리 ad2ff8cf에서 했다. 고치기 전 분류기에서 새 시험은 두 엔진 모두 실패한다(34개 중 6개 실패 = 새 시험 2개 + 앞 커밋 계약 표의 4개). interrupt 플래그 검사만 지운 변이에서는 34개 중 새 시험 두 엔진 2개만 실패한다. 고친 코드에서 0개 실패. 최종 트리 5c4210a0에서 desktop scripts/verify.sh leaf :adapter:outbound:httpclient rc=0 (tests=451), scripts/verify.sh pr --no-cache rc=0(tests=7304 failures=0), 노트북 scripts/verify.sh docs rc=0. Refs: REV-BE-0024 --- ...26-11-httpclient-failure-classification.md | 26 ++++++++++++++++++ .../transport/TransportFailureRules.java | 13 ++++++++- ...ransportFailureClassifierContractTest.java | 27 ++++++++++++++++++- 3 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 docs/upgrade/2026-11-httpclient-failure-classification.md diff --git a/docs/upgrade/2026-11-httpclient-failure-classification.md b/docs/upgrade/2026-11-httpclient-failure-classification.md new file mode 100644 index 00000000..6ba4065a --- /dev/null +++ b/docs/upgrade/2026-11-httpclient-failure-classification.md @@ -0,0 +1,26 @@ +# 업그레이드 안내 — 2026-11 HTTP client 전송 실패 분류 + +- 범위: Stable transport 두 개(Apache·JDK)의 전송 실패 분류를 공용 규칙 하나로 합친 변경. 설정 키와 공개 타입은 + 그대로다. 같은 실패에 두 transport가 같은 예외와 재시도 판정을 낸다. 따라 고칠 코드는 없다. +- 근거: 2026-11-21 리뷰 발견 REV-BE-0024(본문 중 끊김의 분류가 transport마다 달랐다). 본문 중 끊김이 + `HttpResponseTruncatedException`이라는 것은 `docs/httpclient/operations.md` 「예외」 표와 + `docs/httpclient/configuration-reference.md`가 이미 약속한 응답이다. + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 HTTP client를 Apache transport로 +쓰는 서비스, 호출 thread를 interrupt해서 호출을 취소하는 서비스다. + +## 2. 바뀐 동작 (따라 할 일 없음) + +| # | 바뀐 것 | 전에는 | 해당 서비스 | +| --- | --- | --- | --- | +| 1 | Apache transport에서 응답 본문을 받다가 엔진이 알아보지 못한 이유(`connection reset` 등)로 끊기면 `HttpResponseTruncatedException`이다. 문서가 약속한 타입이고 JDK transport와 같다. 버퍼 본문 호출은 안전하게 멱등이면 재시도 예산 안에서 다시 보낸다. 넘긴 뒤의 스트리밍 본문은 `HttpBodyReadException`의 `failure()`가 이 타입이다 | `HttpUnknownTransportException`이었고 재시도하지 않았다 | Apache transport를 쓰는 서비스 | +| 2 | JDK transport에서 본문을 다 읽은 뒤(단계 `COMPLETE`) 알아보지 못한 실패는 `HttpUnknownTransportException`이다. Apache와 같다 | `HttpResponseTruncatedException`이었다 | JDK transport를 쓰는 서비스 | +| 3 | 호출 thread의 interrupt 플래그가 선 채 알아보지 못한 실패로 끝난 시도는 취소(category `CANCELLED`, 사유 `ATTEMPT_INTERRUPTED`)다. 호출자는 `HttpUnknownTransportException`을 받고, 재시도하지 않는다. virtual thread가 socket을 읽다 interrupt되면 JDK가 socket을 닫고 `SocketException`을 던지는 경우가 이것이다 | JDK transport에서는 본문 중이면 `HttpResponseTruncatedException`이라 버퍼 본문의 멱등 호출을 다시 보냈다. Apache transport는 `HttpUnknownTransportException`이었다 | 호출 thread를 interrupt해 호출을 취소하는 서비스 | + +## 3. 바뀌지 않은 것 + +- 예외 타입 목록, 설정 키, `DefaultRetryEligibilityEngine`의 재시도 판정 규칙은 그대로다. 바뀐 것은 어떤 실패가 어느 + category가 되느냐다. +- 실험 transport인 Jetty HTTP/3의 분류는 이번에 바꾸지 않았다. diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/TransportFailureRules.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/TransportFailureRules.java index 3566f686..da27a0e9 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/TransportFailureRules.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/TransportFailureRules.java @@ -44,7 +44,8 @@ public final class TransportFailureRules { /** * Classifies {@code failure} by the first cause in its chain that the engine or the shared rules - * recognise, outermost first, and by the stage alone when none is recognised. + * recognise, outermost first. When none is recognised, a thread whose interrupt flag is set makes + * it a cancellation; otherwise the stage alone decides. * *

The whole chain is read because Spring and the engines wrap their exceptions: a wrapped * {@code ConnectException} still proves the request never left, and matching only the outer type @@ -65,6 +66,16 @@ public final class TransportFailureRules { return recognized; } } + if (Thread.currentThread().isInterrupted()) { + // Failures are classified on the thread that made the attempt, so a set flag means + // the attempt was cancelled, and a cancellation must not be retried. Interrupting a + // virtual thread blocked on a socket closes the socket: the read fails with + // SocketException("Closed by interrupt"), or ClosedByInterruptException on a channel, + // and the flag stays set. Neither is an InterruptedIOException, so read by the stage + // alone it was a truncated body, which the retry engine retries: cancelling a call + // sent it again. The flag is left as it is. + return conservative(lastObservedStage, FailureCategory.CANCELLED, "ATTEMPT_INTERRUPTED"); + } return unrecognized(lastObservedStage); } diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/TransportFailureClassifierContractTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/TransportFailureClassifierContractTest.java index 9d997a11..cbee59a6 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/TransportFailureClassifierContractTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/contract/TransportFailureClassifierContractTest.java @@ -169,7 +169,7 @@ class TransportFailureClassifierContractTest { } @AfterEach - void clearTheInterruptACancellationRestores() { + void clearTheInterruptFlag() { Thread.interrupted(); } @@ -197,6 +197,31 @@ class TransportFailureClassifierContractTest { assertThat(Thread.currentThread().isInterrupted()).isTrue(); } + /** + * What a virtual thread sees when it is interrupted in a socket read: the JDK closes the socket, + * throws a plain {@code SocketException}, and leaves the flag set. Read by the stage alone that + * was a truncated body, which the retry engine retries. + */ + @Test + void anUnrecognisedFailureOnAnInterruptedThreadIsACancellation() { + // given + Thread.currentThread().interrupt(); + + // when + TransportFailure classified = + classifier() + .classify(new SocketException("Closed by interrupt"), AttemptStage.RESPONSE_BODY); + + // then + assertThat(classified) + .isEqualTo( + new TransportFailure( + AttemptStage.RESPONSE_BODY, + ExecutionEvidence.PARTIAL_RESPONSE, + FailureCategory.CANCELLED, + "ATTEMPT_INTERRUPTED")); + } + private TransportFailureClassifier classifier() { return "jdk".equals(transport) ? new JdkFailureClassifier() : new ApacheFailureClassifier(); } -- 2.54.0