test(persistence-jpa): platform 계약 시험이 PostgreSQL 서버를 JVM에서 나눠 쓴다
pr / done (pull_request) Canceled after 0s

문제: `JpaPlatformContractSupport`의 Javadoc은 「서버를 JVM에서 공유한다」고
하지만, `start`는 부를 때마다 컨테이너를 새로 띄웠다. 클래스 42개가 저마다 띄워
desktop main 단계에서 platform 계약 lane이 컨테이너 75개(기동 181초), migration
lane이 36개(71초)를 썼다. 이 lane들은 build의 실서버 슬롯 하나 위에서 돌기 때문에,
이 기동 시간이 main job 시간에 그대로 더해졌다. release gate 셋과 nightly
행렬 셋에서도 같은 lane이 major마다 돈다.

고친 방법: Stable major마다 서버 하나를 JVM에서 처음 쓸 때 띄우고, JVM이 끝날 때
멈춘다(shutdown hook, reaper에 기대지 않는다). support마다 그 서버에 database를
하나 만들고(`create database contract_<n>`), close에서 pool을 다 닫은 뒤
지운다(`drop database ... with (force)`). 표·스키마·Flyway 이력은 database에
있어 클래스끼리 섞이지 않는다. 서버 전체에 걸리는 role은 섞이므로 Javadoc에
적었다. role을 만드는 계약은 `PostgreSqlSecurityContractTest` 하나이고, lane마다
JVM이 따로라 이름이 겹치지 않는다.

시험: 소유권 시험에 둘을 더한다. 두 번째 support가 같은 서버, 다른 database를
받는지, close가 database를 지우는지 본다. 공유를 되돌리면 앞의 것이, drop을
빼면 뒤의 것이 실패한다. close 시험의 이름은 「database를 지우기 전에 pool을
닫는다」로 고친다.

버린 대안: 컨테이너 tmpfs·fsync 끄기로 기동만 빠르게. 재시작·장애 복구 계약의
조건이 바뀐다. Testcontainers reuse: CI에서 일부러 끈 설정이다.

위험·한계: 한 클래스가 서버 설정(`ALTER SYSTEM`)을 바꾸면 같은 lane의 다음
클래스가 본다. 지금 그런 계약은 없다(검색으로 확인).
This commit is contained in:
DongHyeonka
2026-11-12 19:43:33 +09:00
parent 738fe7004e
commit 6c69384c76
2 changed files with 144 additions and 17 deletions
@@ -5,7 +5,10 @@ import com.zaxxer.hikari.HikariDataSource;
import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.PostgreSqlContainerFactory;
import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.PostgreSqlVersion;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -17,9 +20,16 @@ import org.testcontainers.postgresql.PostgreSQLContainer;
/**
* Starts one PostgreSQL per selected Stable version and hands out data sources (design §40).
*
* <p>The containers are shared for the JVM: the contracts verify server behaviour, which does not
* <p>The servers are shared for the JVM: the contracts verify server behaviour, which does not
* change between test classes, and starting a server per class turns a three-version matrix into
* minutes of container startup.
* minutes of container startup. Each support gets a database of its own on that server, created by
* {@code start} and dropped by {@code close}, so tables, schemas and Flyway history do not cross
* classes. What the server holds for every database — roles — does: a contract that creates a role
* owns that name for the whole lane.
*
* <p>Until 2026-11-12 every {@code start} started a server of its own although this comment said
* they were shared: 75 servers in the platform contract lane and 36 in the migration lane, 181 and
* 71 seconds of container start (desktop, 2026-11-12), on the build's one real-server slot.
*
* <p>Docker absence throws rather than skipping. A skipped contract reports success for a database
* nobody tested, and CI inherits that silence.
@@ -30,8 +40,16 @@ public final class JpaPlatformContractSupport implements AutoCloseable {
private static final java.security.SecureRandom PASSWORD_SOURCE =
new java.security.SecureRandom();
/** One server per Stable version, started on first use and stopped when the JVM exits. */
private static final Map<PostgreSqlVersion, PostgreSQLContainer> SERVERS =
new EnumMap<>(PostgreSqlVersion.class);
/** Names each support's database; the server outlives every support, so names never repeat. */
private static final AtomicInteger DATABASES = new AtomicInteger();
private final PostgreSqlVersion version;
private final PostgreSQLContainer container;
private final String database;
/**
* The pools this support owns, closed before the container stops.
@@ -48,9 +66,11 @@ public final class JpaPlatformContractSupport implements AutoCloseable {
private final AtomicInteger poolSequence = new AtomicInteger();
private JpaPlatformContractSupport(PostgreSqlVersion version, PostgreSQLContainer container) {
private JpaPlatformContractSupport(
PostgreSqlVersion version, PostgreSQLContainer container, String database) {
this.version = version;
this.container = container;
this.database = database;
}
/**
@@ -85,12 +105,47 @@ public final class JpaPlatformContractSupport implements AutoCloseable {
return start(selected.get(0));
}
/** Starts one specific Stable version. */
/** A fresh database on the shared server of one specific Stable version. */
public static JpaPlatformContractSupport start(PostgreSqlVersion version) {
Objects.requireNonNull(version, "version");
PostgreSQLContainer container = PostgreSqlContainerFactory.create(version);
container.start();
return new JpaPlatformContractSupport(version, container);
PostgreSQLContainer server = server(version);
String database = "contract_" + DATABASES.incrementAndGet();
administer(server, "create database " + database);
return new JpaPlatformContractSupport(version, server, database);
}
private static synchronized PostgreSQLContainer server(PostgreSqlVersion version) {
PostgreSQLContainer server = SERVERS.get(version);
if (server == null) {
if (SERVERS.isEmpty()) {
// Testcontainers' reaper would remove the containers too, but it is the part a remote
// Docker host cannot always reach; stopping them here does not depend on it.
Runtime.getRuntime()
.addShutdownHook(
new Thread(JpaPlatformContractSupport::stopServers, "jpa-contract-servers"));
}
server = PostgreSqlContainerFactory.create(version);
server.start();
SERVERS.put(version, server);
}
return server;
}
private static synchronized void stopServers() {
SERVERS.values().forEach(PostgreSQLContainer::stop);
SERVERS.clear();
}
/** Runs one statement as the server's owning role, connected to the server's own database. */
private static void administer(PostgreSQLContainer server, String sql) {
try (Connection connection =
DriverManager.getConnection(
server.getJdbcUrl(), server.getUsername(), server.getPassword());
Statement statement = connection.createStatement()) {
statement.execute(sql);
} catch (SQLException failure) {
throw new IllegalStateException("PostgreSQL contract server refused: " + sql, failure);
}
}
/** The versions this run was asked to cover. */
@@ -132,7 +187,7 @@ public final class JpaPlatformContractSupport implements AutoCloseable {
private HikariDataSource pool(String role, String username, String password, int maximumSize) {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(container.getJdbcUrl());
config.setJdbcUrl(jdbcUrl());
config.setUsername(username);
config.setPassword(password);
config.setMaximumPoolSize(maximumSize);
@@ -148,9 +203,14 @@ public final class JpaPlatformContractSupport implements AutoCloseable {
return dataSource().getConnection();
}
/** The running server's JDBC URL, for contracts that build their own pools. */
/** This support's database on the running server, for contracts that build their own pools. */
public String jdbcUrl() {
return container.getJdbcUrl();
return "jdbc:postgresql://"
+ container.getHost()
+ ":"
+ container.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT)
+ "/"
+ database;
}
/** The container's owning role. */
@@ -192,9 +252,10 @@ public final class JpaPlatformContractSupport implements AutoCloseable {
@Override
public synchronized void close() {
// Pools first, container last. Stopping the server while a pool is still open leaves that
// pool retrying against an address nobody is listening on, and its housekeeping thread outlives
// the test that created it.
// Pools first, database last. Dropping the database under an open pool leaves that pool
// retrying against a database that is gone, and its housekeeping thread outlives the test that
// created it. `with (force)` ends a connection a contract opened outside the pools. The server
// stays for the next class.
RuntimeException firstFailure = null;
for (HikariDataSource pool : pools.values()) {
try {
@@ -208,7 +269,15 @@ public final class JpaPlatformContractSupport implements AutoCloseable {
}
}
pools.clear();
container.stop();
try {
administer(container, "drop database if exists " + database + " with (force)");
} catch (RuntimeException failure) {
if (firstFailure == null) {
firstFailure = failure;
} else {
firstFailure.addSuppressed(failure);
}
}
if (firstFailure != null) {
throw firstFailure;
}
@@ -4,6 +4,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
@@ -66,8 +70,7 @@ class JpaPlatformContractSupportOwnershipTest {
}
@Test
@DisplayName("close shuts every pool before the container stops")
void closeShutsEveryPoolBeforeTheContainerStops() {
void closeShutsEveryPoolBeforeItsDatabaseIsDropped() {
HikariDataSource owned;
try (JpaPlatformContractSupport support = JpaPlatformContractSupport.start()) {
owned = (HikariDataSource) support.dataSource();
@@ -75,10 +78,65 @@ class JpaPlatformContractSupportOwnershipTest {
}
assertThat(owned.isClosed())
.as("stopping the container first leaves a live pool retrying against nothing")
.as("dropping the database first leaves a live pool retrying against nothing")
.isTrue();
}
@Test
void aSecondSupportSharesTheServerButNotTheDatabase() {
// given
String first;
try (JpaPlatformContractSupport support = JpaPlatformContractSupport.start()) {
first = support.jdbcUrl();
}
// when
String second;
try (JpaPlatformContractSupport support = JpaPlatformContractSupport.start()) {
second = support.jdbcUrl();
}
// then
assertThat(List.of(serverOf(second), databaseOf(second).equals(databaseOf(first))))
.as("one server per version for the JVM, a database of its own per support")
.containsExactly(serverOf(first), false);
}
@Test
void closeDropsTheSupportsDatabase() throws SQLException {
// given
String closed;
try (JpaPlatformContractSupport support = JpaPlatformContractSupport.start()) {
closed = databaseOf(support.jdbcUrl());
}
// when
Boolean exists;
try (JpaPlatformContractSupport support = JpaPlatformContractSupport.start();
Connection connection = support.connection();
PreparedStatement statement =
connection.prepareStatement(
"select exists(select 1 from pg_database where datname = ?)")) {
statement.setString(1, closed);
try (ResultSet row = statement.executeQuery()) {
exists = row.next() ? row.getBoolean(1) : null;
}
}
// then
assertThat(exists)
.as("a database left behind is one class's tables in the next class's server")
.isFalse();
}
private static String serverOf(String jdbcUrl) {
return jdbcUrl.substring(0, jdbcUrl.lastIndexOf('/'));
}
private static String databaseOf(String jdbcUrl) {
return jdbcUrl.substring(jdbcUrl.lastIndexOf('/') + 1);
}
@Test
@DisplayName("pools carry an identifiable name")
void poolsCarryAnIdentifiableName() {