test(objectstorage): MinIO 시험이 준비 호출을 시험 대상의 2초 시한에 걸지 않는다 #49

Merged
donghyeon.kang merged 3 commits from claude/be-main-red2-minio-3 into main 2026-11-18 18:11:20 +00:00
4 changed files with 258 additions and 98 deletions
+2
View File
@@ -3,3 +3,5 @@
{"date": "2026-11-13", "test": "FailureInjectionContractTest#aSlowDripThroughToxiproxyEndsAtTheTotalDeadline[JDK]", "category": "fixed-time", "first_run": "228", "verdict": "runner 1회 실패(1.92초, 상한 1.5초). desktop 부하 6.5~8에서 10회 통과(호출 1,010~1,021ms)", "quarantined_until": "", "fixed_by": "백엔드 #34"}
{"date": "2026-11-13", "test": "LiveEventLogContractTest#concurrentWritersAllocateDistinctPositions", "category": "concurrency-order", "first_run": "260", "verdict": "replay 순서를 writer 제출 순서로 단언했다. 둘째 writer를 먼저 돌린 탐침에서 재현. 고침 PR 백엔드 #39(열림)", "quarantined_until": "", "fixed_by": ""}
{"date": "2026-11-13", "test": "JettyAttemptDeadlineTest#aSlowDripExchangeIsAbortedAtTheAttemptDeadline", "category": "fixed-time", "first_run": "desktop ~/w2-reloc-logs/w2-reloc-a.log (main c7a18ec7, prCheck, 시작 부하 11~15)", "verdict": "desktop 1회 실패(1.68초, 상한 1.5초). PR 단계 test라 runner PR run에서도 날 수 있다", "quarantined_until": "", "fixed_by": ""}
{"date": "2026-11-13", "test": "MinioS3ManagedObjectProviderContractTest#initializationError", "category": "fixed-time", "first_run": "304", "verdict": "재현 안 됨(desktop 1코어 기아 3회 통과, 첫 createBucket 최대 1.94초/acquire 2초)", "quarantined_until": "", "fixed_by": ""}
{"date": "2026-11-13", "test": "MinioManagedObjectFaultTest#connectionCutProducesABoundedFailureAndRecoveryWithoutMutationReplay", "category": "fixed-time", "first_run": "310", "verdict": "desktop 1코어 기아 3회 중 3회 실패(첫 createBucket 3.2~3.8초/apiCallTimeout 2초)", "quarantined_until": "", "fixed_by": ""}
@@ -17,6 +17,7 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.async.AsyncRequestBody;
@@ -71,7 +72,9 @@ class MinioManagedObjectContractTest {
.withEnv("MINIO_ROOT_USER", accessKey)
.withEnv("MINIO_ROOT_PASSWORD", secretKey)
.withEnv("MINIO_KMS_SECRET_KEY", kmsKey)
.withCommand("server", "/data");
.withCommand("server", "/data")
// Ready is MinIO answering its readiness probe, not its port accepting a connection.
.waitingFor(Wait.forHttp("/minio/health/ready").forPort(9000));
minio.start();
client =
S3AsyncClient.builder()
@@ -1,140 +1,277 @@
package dev.caskeleton.adapter.outbound.objectstorage.qualification;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.awaitility.Awaitility.await;
import eu.rekawek.toxiproxy.Proxy;
import eu.rekawek.toxiproxy.ToxiproxyClient;
import eu.rekawek.toxiproxy.model.Toxic;
import eu.rekawek.toxiproxy.model.ToxicDirection;
import java.net.URI;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.toxiproxy.ToxiproxyContainer;
import org.testcontainers.utility.DockerImageName;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException;
import software.amazon.awssdk.core.exception.ApiCallTimeoutException;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
/**
* A client with a one-second attempt and two-second call budget, behind a Toxiproxy whose
* connection the test cuts: the cut ends in the client's own timeout, and once it heals a read
* finds the object the setup wrote.
*
* <p>Only what is under test runs on that client and through the proxy. The bucket and the object
* are written beforehand by a second client straight to MinIO, without the tight budget: on a
* loaded main-stage runner those setup calls, the first S3 requests of the JVM, overran two seconds
* and failed the lane before the cut was ever made (main run of 99cc4f59, 2026-11-13). The client
* under test then shows it reaches MinIO through the proxy before the cut by waiting for that state
* rather than for a fixed time, and the recovery is the same wait: healed means a read through the
* proxy answers again, however long the runner takes to get there. Recovery is eventual: a read
* right after the heal may still fail on a connection the cut left behind, and only a read that
* never answers within the wait fails the test.
*/
class MinioManagedObjectFaultTest {
private static final int TOXIPROXY_CONTROL_PORT = 8474;
private static final int TOXIPROXY_PROXY_PORT = 8666;
private static final String CUT_CONNECTION_DOWNSTREAM = "CUT_CONNECTION_DOWNSTREAM";
private static final String CUT_CONNECTION_UPSTREAM = "CUT_CONNECTION_UPSTREAM";
private static final String BUCKET = "object-storage-fault";
private static final String KEY = "fault/exact";
private static final byte[] BODY = {1, 2, 3};
// Bounds a hang, not a latency. The client's own call budget is two seconds; a call still open
// after this long was not ended by that budget at all.
private static final Duration HANG_GUARD = Duration.ofSeconds(30);
private static final Duration STATE_WAIT = Duration.ofSeconds(60);
// Every container below is declared in try-with-resources; the fluent `withX` chain returns the
// same instance, which the compiler reads as a second, unclosed resource.
private static Network network;
private static GenericContainer<?> minio;
private static ToxiproxyContainer toxiproxy;
private static Proxy proxy;
private static String accessKey;
private static String secretKey;
private static String writtenETag;
@BeforeAll
// The containers are assigned to static fields and stopped in the matching @AfterAll; the fluent
// withX chain reads to the compiler as a second, unclosed instance.
@SuppressWarnings("resource")
@Test
void connectionCutProducesABoundedFailureAndRecoveryWithoutMutationReplay() throws Exception {
DockerImageName minioImage = QualificationImages.minio();
DockerImageName toxiproxyImage = QualificationImages.toxiproxy();
String accessKey = "a" + UUID.randomUUID().toString().replace("-", "");
String secretKey = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID();
try (Network network = Network.newNetwork();
GenericContainer<?> minio =
new GenericContainer<>(minioImage)
.withNetwork(network)
.withNetworkAliases("qualified-minio")
.withExposedPorts(9000)
.withEnv("MINIO_ROOT_USER", accessKey)
.withEnv("MINIO_ROOT_PASSWORD", secretKey)
.withCommand("server", "/data");
ToxiproxyContainer toxiproxy =
new ToxiproxyContainer(toxiproxyImage)
.withNetwork(network)
.withExposedPorts(TOXIPROXY_CONTROL_PORT, TOXIPROXY_PROXY_PORT)) {
minio.start();
toxiproxy.start();
ToxiproxyClient toxiproxyClient =
new ToxiproxyClient(toxiproxy.getHost(), toxiproxy.getControlPort());
Proxy proxy =
toxiproxyClient.createProxy(
"qualified-minio", "0.0.0.0:" + TOXIPROXY_PROXY_PORT, "qualified-minio:9000");
try (S3AsyncClient client =
S3AsyncClient.builder()
.endpointOverride(
URI.create(
"http://"
+ toxiproxy.getHost()
+ ":"
+ toxiproxy.getMappedPort(TOXIPROXY_PROXY_PORT)))
.region(Region.US_EAST_1)
.credentialsProvider(
StaticCredentialsProvider.create(
AwsBasicCredentials.create(accessKey, secretKey)))
.httpClient(
NettyNioAsyncHttpClient.builder()
.connectionTimeout(Duration.ofMillis(500))
.readTimeout(Duration.ofSeconds(1))
.writeTimeout(Duration.ofSeconds(1))
.maxConcurrency(2)
.maxPendingConnectionAcquires(2)
.build())
.overrideConfiguration(
ClientOverrideConfiguration.builder()
.apiCallAttemptTimeout(Duration.ofSeconds(1))
.apiCallTimeout(Duration.ofSeconds(2))
.build())
.forcePathStyle(true)
.multipartEnabled(false)
.build()) {
String bucket = "object-storage-fault";
client.createBucket(CreateBucketRequest.builder().bucket(bucket).build()).join();
byte[] body = {1, 2, 3};
client
.putObject(
PutObjectRequest.builder()
.bucket(bucket)
.key("fault/exact")
.ifNoneMatch("*")
.contentLength((long) body.length)
.build(),
AsyncRequestBody.fromByteBuffer(ByteBuffer.wrap(body)))
.join();
setConnectionCut(proxy, true);
long started = System.nanoTime();
assertThatThrownBy(
() ->
client
.headObject(
HeadObjectRequest.builder().bucket(bucket).key("fault/exact").build())
.join())
.isInstanceOf(CompletionException.class);
assertThat(Duration.ofNanos(System.nanoTime() - started)).isLessThan(Duration.ofSeconds(5));
setConnectionCut(proxy, false);
assertThat(
client
.headObject(
HeadObjectRequest.builder().bucket(bucket).key("fault/exact").build())
.join()
.contentLength())
.isEqualTo(body.length);
}
static void startMinioBehindToxiproxy() throws Exception {
accessKey = "a" + UUID.randomUUID().toString().replace("-", "");
secretKey = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID();
network = Network.newNetwork();
minio =
new GenericContainer<>(QualificationImages.minio())
.withNetwork(network)
.withNetworkAliases("qualified-minio")
.withExposedPorts(9000)
.withEnv("MINIO_ROOT_USER", accessKey)
.withEnv("MINIO_ROOT_PASSWORD", secretKey)
.withCommand("server", "/data")
// Ready is MinIO answering its readiness probe, not its port accepting a connection.
.waitingFor(Wait.forHttp("/minio/health/ready").forPort(9000));
toxiproxy =
new ToxiproxyContainer(QualificationImages.toxiproxy())
.withNetwork(network)
.withExposedPorts(TOXIPROXY_CONTROL_PORT, TOXIPROXY_PROXY_PORT);
minio.start();
toxiproxy.start();
proxy =
new ToxiproxyClient(toxiproxy.getHost(), toxiproxy.getControlPort())
.createProxy(
"qualified-minio", "0.0.0.0:" + TOXIPROXY_PROXY_PORT, "qualified-minio:9000");
try (S3AsyncClient setup = setupClient()) {
setup.createBucket(CreateBucketRequest.builder().bucket(BUCKET).build()).join();
writtenETag =
setup
.putObject(
PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.ifNoneMatch("*")
.contentLength((long) BODY.length)
.build(),
AsyncRequestBody.fromByteBuffer(ByteBuffer.wrap(BODY)))
.join()
.eTag();
}
}
private static void setConnectionCut(Proxy proxy, boolean shouldCutConnection) throws Exception {
@AfterAll
static void stopMinioBehindToxiproxy() {
if (toxiproxy != null) {
toxiproxy.stop();
}
if (minio != null) {
minio.stop();
}
if (network != null) {
network.close();
}
}
@AfterEach
void healTheConnection() throws Exception {
setConnectionCut(false);
}
@Test
void aCutConnectionEndsInTheClientsOwnTimeoutRatherThanAHang() throws Exception {
// given
try (S3AsyncClient client = impatientClientThroughProxy()) {
awaitReadThroughProxy(client);
setConnectionCut(true);
// when
Throwable failure =
catchThrowable(() -> head(client).get(HANG_GUARD.toSeconds(), TimeUnit.SECONDS));
// then
// The SDK ends the call with its call timeout, or wraps the last attempt's timeout in an
// SdkClientException once the attempts are spent; either way one of its own timeouts is in
// the chain (seen both ways under a starved CPU, 2026-11-18).
assertThat(causalChain(failure))
.anySatisfy(
cause ->
assertThat(cause)
.isInstanceOfAny(
ApiCallTimeoutException.class, ApiCallAttemptTimeoutException.class));
}
}
@Test
void aReadAfterTheCutHealsFindsTheObjectTheSetupWrote() throws Exception {
// given
try (S3AsyncClient client = impatientClientThroughProxy()) {
awaitReadThroughProxy(client);
setConnectionCut(true);
// A read made while the connection is cut. It must fail, or there was no cut to heal from;
// the other test asserts how it ends.
HeadObjectResponse duringCut =
head(client)
.handle((response, failure) -> response)
.get(HANG_GUARD.toSeconds(), TimeUnit.SECONDS);
if (duringCut != null) {
throw new IllegalStateException("a read through the cut proxy still answered");
}
setConnectionCut(false);
// when
HeadObjectResponse recovered =
await()
.atMost(STATE_WAIT)
.ignoreExceptions()
.until(
() -> head(client).get(HANG_GUARD.toSeconds(), TimeUnit.SECONDS),
Objects::nonNull);
// then
assertThat(recovered)
.extracting(HeadObjectResponse::contentLength, HeadObjectResponse::eTag)
.containsExactly((long) BODY.length, writtenETag);
}
}
private static List<Throwable> causalChain(Throwable failure) {
List<Throwable> chain = new ArrayList<>();
for (Throwable cause = failure;
cause != null && !chain.contains(cause);
cause = cause.getCause()) {
chain.add(cause);
}
return chain;
}
private static CompletableFuture<HeadObjectResponse> head(S3AsyncClient client) {
return client.headObject(HeadObjectRequest.builder().bucket(BUCKET).key(KEY).build());
}
// The client under test reaches MinIO through the proxy before the cut: the cut is then made on
// a path that worked, and the JVM's first S3 call is behind it rather than inside the budget.
private static void awaitReadThroughProxy(S3AsyncClient client) {
await()
.atMost(STATE_WAIT)
.ignoreExceptions()
.until(() -> head(client).get(HANG_GUARD.toSeconds(), TimeUnit.SECONDS), Objects::nonNull);
}
private static S3AsyncClient impatientClientThroughProxy() {
return S3AsyncClient.builder()
.endpointOverride(
URI.create(
"http://"
+ toxiproxy.getHost()
+ ":"
+ toxiproxy.getMappedPort(TOXIPROXY_PROXY_PORT)))
.region(Region.US_EAST_1)
.credentialsProvider(
StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)))
.httpClient(
NettyNioAsyncHttpClient.builder()
.connectionTimeout(Duration.ofMillis(500))
// Longer than the call budget, so the SDK's own budgets end a cut call rather than
// a socket idle timeout racing them; the first test can then say which ended it.
.readTimeout(Duration.ofSeconds(10))
.writeTimeout(Duration.ofSeconds(10))
.maxConcurrency(2)
.maxPendingConnectionAcquires(2)
.build())
.overrideConfiguration(
ClientOverrideConfiguration.builder()
.apiCallAttemptTimeout(Duration.ofSeconds(1))
.apiCallTimeout(Duration.ofSeconds(2))
.build())
.forcePathStyle(true)
.multipartEnabled(false)
.build();
}
// Straight to MinIO, with the SDK's connection defaults. The call budget only bounds a hang.
private static S3AsyncClient setupClient() {
return S3AsyncClient.builder()
.endpointOverride(URI.create("http://" + minio.getHost() + ":" + minio.getMappedPort(9000)))
.region(Region.US_EAST_1)
.credentialsProvider(
StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)))
.overrideConfiguration(
ClientOverrideConfiguration.builder().apiCallTimeout(STATE_WAIT).build())
.forcePathStyle(true)
.multipartEnabled(false)
.build();
}
private static void setConnectionCut(boolean shouldCutConnection) throws Exception {
if (shouldCutConnection) {
proxy.toxics().bandwidth(CUT_CONNECTION_DOWNSTREAM, ToxicDirection.DOWNSTREAM, 0);
proxy.toxics().bandwidth(CUT_CONNECTION_UPSTREAM, ToxicDirection.UPSTREAM, 0);
return;
}
proxy.toxics().get(CUT_CONNECTION_DOWNSTREAM).remove();
proxy.toxics().get(CUT_CONNECTION_UPSTREAM).remove();
for (Toxic toxic : proxy.toxics().getAll()) {
toxic.remove();
}
}
}
@@ -1,5 +1,7 @@
package dev.caskeleton.adapter.outbound.objectstorage.s3;
import static org.awaitility.Awaitility.await;
import dev.caskeleton.adapter.outbound.objectstorage.contract.ObjectStorageProviderContract;
import dev.caskeleton.adapter.outbound.objectstorage.provider.ObjectStorageProvider;
import dev.caskeleton.adapter.outbound.objectstorage.qualification.QualificationImages;
@@ -10,13 +12,16 @@ import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.util.Base64;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.utility.MountableFile;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.BucketVersioningStatus;
@@ -73,7 +78,11 @@ class MinioS3ManagedObjectProviderContractTest extends ObjectStorageProviderCont
.withEnv(
"MINIO_KMS_SECRET_KEY",
"contract-key:" + Base64.getEncoder().encodeToString(keyBytes))
.withCommand("server", "/data", "--certs-dir", "/certs");
.withCommand("server", "/data", "--certs-dir", "/certs")
// Ready is MinIO answering its readiness probe over the TLS it serves, not its port
// accepting a connection. The probe trusts any certificate: it only asks whether the
// server is up, and the client below is the one that checks the certificate.
.waitingFor(Wait.forHttps("/minio/health/ready").forPort(9000).allowInsecure());
minio.start();
// The production client factory, so the provider runs on the client it ships with (checksum
// calculation WHEN_REQUIRED, no SDK multipart, bounded Netty pool).
@@ -113,6 +122,15 @@ class MinioS3ManagedObjectProviderContractTest extends ObjectStorageProviderCont
S3ProviderBindingTest.pgstySettings(
ObjectStorageProvider.Capability.IMMUTABLE_CREATE)),
Clock.systemUTC());
// The first request of the JVM pays for the first TLS connection, the SDK's class loading and
// its signer, and on a loaded main-stage runner that took longer than the two-second
// connection acquire budget above: the lane failed here, in setup, before any contract case
// ran (main run of 6aac48a3, 2026-11-13). The budget is the client under test's and stays; the
// setup waits until a read on that client answers, so the cases start on a warm client.
await()
.atMost(Duration.ofSeconds(60))
.ignoreExceptions()
.until(() -> client.listBuckets().get(30, TimeUnit.SECONDS), Objects::nonNull);
client.createBucket(CreateBucketRequest.builder().bucket(binding.bucket()).build()).join();
client
.putBucketVersioning(