diff --git a/docs/ledger/estimates.jsonl b/docs/ledger/estimates.jsonl index 2c8a143b..8d49bcfb 100644 --- a/docs/ledger/estimates.jsonl +++ b/docs/ledger/estimates.jsonl @@ -19,4 +19,5 @@ {"schema": 1, "kind": "estimate", "task": "r9-group-a", "transcript": "70449164-6ab3-49a9-9bcd-a4281e2a0759", "started_at": "2026-11-13T07:00+09:00", "base": "d3a90479", "task_kind": "improve", "size": "large", "minutes": {"p30": 160, "p50": 240, "p80": 370}, "calls": {"p30": 250, "p50": 380, "p80": 570}, "output_tokens": {"p30": 200000, "p50": 320000, "p80": 490000}, "basis": "발견 31건·PR 3개, 손 판단 결정 약 8(전송별 인가 전달, graphql 하위 좌표, test profile 기동 거부, broadcaster 목적지, metrics registry 맞추기 등), desktop 검증 약 8회(leaf·pr 단계); 원값 300/450/700분·400/600/900호출·350k/550k/850k에 보정 0.53·0.63·0.58을 곱함", "recorded_at": "2026-11-13T06:52+09:00"} {"schema": 1, "kind": "actual", "task": "r9-group-a", "transcript": "70449164-6ab3-49a9-9bcd-a4281e2a0759", "minutes": 383, "active_minutes": 215, "calls": 2295, "output_tokens": 1973586, "within": "p50", "result": "done", "commits": ["0fded57c", "2f0aefad", "01caee3c", "75df7615", "a7f44d8a", "354b7fc9"], "why": "시간은 p50 안이고 호출·출력은 p80을 넘었다. 새 눈 리뷰 4라운드(발견 약 90건 모두 고침), main 두 번 이동(rebase·재검증), desktop 잠금 대기 중 실행 교체가 호출을 늘렸다", "recorded_at": "2026-11-13T19:15+09:00"} {"schema": 1, "kind": "estimate", "task": "be-ci-next", "transcript": "7f6aac72-543c-4f2a-a47c-550e4c727f99", "started_at": "2026-11-19T17:44+09:00", "base": "59349a2b", "task_kind": "operate+improve", "size": "medium", "minutes": {"p30": 106, "p50": 159, "p80": 254}, "calls": {"p30": 220, "p50": 315, "p80": 470}, "output_tokens": {"p30": 145000, "p50": 232000, "p80": 348000}, "basis": "PR 셋(links 인자, API surface 거절 RED/GREEN·verify.sh main, BE-1 측정·고침과 BE-4). 결정 셋, runner PR run 3개 이상·nightly 로그 대기. 선례 w2-be-ci-perf 실측 555분(p50의 3.9배). 손 예측 200/300/480분·350/500/750호출·250k/400k/600k에 보정 0.53·0.63·0.58을 곱함", "recorded_at": "2026-11-19T17:51+09:00"} +{"schema": 1, "kind": "estimate", "task": "be-test-speed", "transcript": "46edb129-6c98-443f-b613-4c03a1995124", "started_at": "2026-11-19T18:37+09:00", "base": "9709404d", "task_kind": "improve", "size": "medium", "minutes": {"p30": 83, "p50": 121, "p80": 187}, "calls": {"p30": 132, "p50": 198, "p80": 297}, "output_tokens": {"p30": 87000, "p50": 133000, "p80": 203000}, "basis": "PR 둘(BE-9 시험 지원 코드+12개 클래스 기계적 치환, BE-10 grpc 시험 설정 한 줄씩). 결정 둘(공유 방식·drop 여부, Mongo 판단 한 줄). desktop 실행 BE-9 측정 전후 6회+섞기 3회+leaf+main, BE-10 전후 leaf 2회, PR CI 대기 2번. 손 예측 150/220/340분·200/300/450호출·150k/230k/350k에 보정 0.55·0.66·0.58을 곱함", "recorded_at": "2026-11-19T18:42+09:00"} {"schema": 1, "kind": "estimate", "task": "laptop-runner", "transcript": "27674009-98d8-4e0c-8946-fb1e590c4128", "started_at": "2026-11-20T07:00:00+09:00", "base": "a68ff147be881f6ede908a286c0fbc1f963f2307", "task_kind": "operate", "size": "large", "minutes": {"p30": 66, "p50": 99, "p80": 165}, "calls": {"p30": 165, "p50": 230, "p80": 330}, "output_tokens": {"p30": 145000, "p50": 203000, "p80": 290000}, "basis": "large 선례 7건 실측 중앙값에서 출발, 손 결정 6개·검증 run 3~4개와 대기, 보정 시간 0.55·호출 0.66·출력 0.58 곱함", "recorded_at": "2026-11-20T07:30+09:00"} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlBaseStreamUpgradeIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlBaseStreamUpgradeIntegrationTest.java index 75a2c0d9..e2518957 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlBaseStreamUpgradeIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlBaseStreamUpgradeIntegrationTest.java @@ -9,6 +9,8 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.migration.MigrationSc import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -50,10 +52,24 @@ class PostgreSqlBaseStreamUpgradeIntegrationTest { """ .formatted("0".repeat(64)); + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void startPostgreSql() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void stopPostgreSql() { + if (postgres != null) { + postgres.close(); + } + } + @Test @DisplayName("a fresh database runs the whole chain") void aFreshDatabaseRunsTheWholeChain() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { var result = runner(database.dataSource()).run(MigrationScenario.empty()); assertThat(result.migrationsExecuted) @@ -66,7 +82,7 @@ class PostgreSqlBaseStreamUpgradeIntegrationTest { @Test @DisplayName("the previous release upgrades, and its rows survive") void thePreviousReleaseUpgradesAndItsRowsSurvive() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { runner(database.dataSource()) .run( MigrationScenario.previousRelease( @@ -84,7 +100,7 @@ class PostgreSqlBaseStreamUpgradeIntegrationTest { @Test @DisplayName("the oldest supported release upgrades, and its rows survive") void theOldestSupportedReleaseUpgradesAndItsRowsSurvive() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { runner(database.dataSource()) .run( MigrationScenario.oldestSupported( @@ -100,7 +116,7 @@ class PostgreSqlBaseStreamUpgradeIntegrationTest { @Test @DisplayName("a checksum drift fails validation instead of migrating over it") void aChecksumDriftFailsValidation() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { Flyway flyway = Flyway.configure().dataSource(database.dataSource()).locations(LOCATION).load(); flyway.migrate(); @@ -128,7 +144,7 @@ class PostgreSqlBaseStreamUpgradeIntegrationTest { @Test @DisplayName("a lost seed row fails the scenario") void aLostSeedRowFailsTheScenario() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { assertThatThrownBy( () -> runner(database.dataSource()) diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDefaultPersistenceUnitIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDefaultPersistenceUnitIntegrationTest.java index 1da47ce0..2e52cafc 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDefaultPersistenceUnitIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDefaultPersistenceUnitIntegrationTest.java @@ -8,6 +8,8 @@ import jakarta.persistence.EntityManagerFactory; import java.util.Map; import javax.sql.DataSource; import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -37,10 +39,24 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; @Tag("jpa-migration") class PostgreSqlDefaultPersistenceUnitIntegrationTest { + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void startPostgreSql() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void stopPostgreSql() { + if (postgres != null) { + postgres.close(); + } + } + @Test @DisplayName("Hibernate validates the always-installed mapping against the migrated schema") void hibernateValidatesTheDefaultUnitAgainstTheMigratedSchema() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); assertThatCode(() -> entityManagerFactory(database.dataSource()).close()) @@ -56,7 +72,7 @@ class PostgreSqlDefaultPersistenceUnitIntegrationTest { "request_hash is varchar, which is what the entity maps and what the rest of the " + "table uses") void theIdempotencyHashColumnIsVarchar() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); String type = diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java index d2fef3bf..f6826268 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverMetadataStoreIntegrationTest.java @@ -546,7 +546,8 @@ class PostgreSqlFileserverMetadataStoreIntegrationTest extends FileMetadataPortC @Test void optionalStreamLifecycleIsNonDestructiveAndRecoversInterruptedMigration() throws Exception { - PostgreSqlOptionalStreamLifecycle.verify(PostgreSqlOptionalStreamLifecycle.fileserver()); + PostgreSqlOptionalStreamLifecycle.verify( + postgres, PostgreSqlOptionalStreamLifecycle.fileserver()); } private static void migrate(String location, String historyTable) { diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java index 7285703c..901b2692 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java @@ -474,7 +474,8 @@ class PostgreSqlIdempotencyIntegrationTest { @Test void optionalStreamLifecycleIsNonDestructiveAndRecoversInterruptedMigration() throws Exception { - PostgreSqlOptionalStreamLifecycle.verify(PostgreSqlOptionalStreamLifecycle.idempotency()); + PostgreSqlOptionalStreamLifecycle.verify( + postgres, PostgreSqlOptionalStreamLifecycle.idempotency()); } private static IdempotencyOwner claim(String claimOperation) { diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlInboxCutoffIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlInboxCutoffIntegrationTest.java index 20f4def0..10cea99f 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlInboxCutoffIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlInboxCutoffIntegrationTest.java @@ -8,6 +8,8 @@ import java.time.Instant; import java.util.List; import java.util.UUID; import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -30,10 +32,24 @@ class PostgreSqlInboxCutoffIntegrationTest { private static final Instant SHARED = Instant.parse("2026-08-15T00:00:00Z"); + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void startPostgreSql() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void stopPostgreSql() { + if (postgres != null) { + postgres.close(); + } + } + @Test @DisplayName("a cursor inside a same-timestamp group marks exactly that far and no further") void aCursorInsideASameTimestampGroupMarksExactlyThatFar() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); @@ -60,7 +76,7 @@ class PostgreSqlInboxCutoffIntegrationTest { @Test @DisplayName("an older timestamp is included whatever its id") void anOlderTimestampIsIncludedWhateverItsId() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); UUID cursor = UUID.fromString("00000000-0000-0000-0000-0000000000a0"); @@ -77,7 +93,7 @@ class PostgreSqlInboxCutoffIntegrationTest { @Test @DisplayName("no cursor marks everything the cap allows") void noCursorMarksEverythingTheCapAllows() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); for (int index = 0; index < 4; index++) { @@ -90,7 +106,7 @@ class PostgreSqlInboxCutoffIntegrationTest { @Test void markAllReadLeavesAnUnreadArchivedItemArchived() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { // given migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java index a61c3c0d..b7e1b5f8 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java @@ -92,7 +92,7 @@ class PostgreSqlMigrationIntegrationTest { @Test void freshCoreStreamInitializesWithoutLegacyHistory() throws Exception { - try (PostgreSqlReadinessSupport fresh = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport fresh = postgres.freshDatabase()) { Flyway.configure() .dataSource(fresh.dataSource()) .locations("classpath:db/migration/jpa/core") @@ -115,7 +115,7 @@ class PostgreSqlMigrationIntegrationTest { @Test void interruptedTransactionalMigrationRollsBackThenForwardRecovers() throws Exception { - try (PostgreSqlReadinessSupport interrupted = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport interrupted = postgres.freshDatabase()) { Flyway failing = Flyway.configure() .dataSource(interrupted.dataSource()) @@ -146,7 +146,7 @@ class PostgreSqlMigrationIntegrationTest { @Test void additiveRollingWindowSupportsOldAndNewArtifactsWithFiniteLockTimeout() throws Exception { - try (PostgreSqlReadinessSupport rolling = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport rolling = postgres.freshDatabase()) { Flyway versionOne = Flyway.configure() .dataSource(rolling.dataSource()) @@ -220,7 +220,7 @@ class PostgreSqlMigrationIntegrationTest { @Test void outboxCanonicalCompatibilityMigrationPreservesLegacyAndExactEnvelopeBytes() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { Flyway.configure() .dataSource(database.dataSource()) .locations("classpath:db/migration/postgresql") diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationDedupRaceIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationDedupRaceIntegrationTest.java index 2f27ad08..4d825e65 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationDedupRaceIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationDedupRaceIntegrationTest.java @@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.UUID; import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -34,10 +36,24 @@ class PostgreSqlNotificationDedupRaceIntegrationTest { + " ON CONFLICT (tenant_id, recipient_ref, category, dedup_key, window_bucket)" + " DO NOTHING"; + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void startPostgreSql() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void stopPostgreSql() { + if (postgres != null) { + postgres.close(); + } + } + @Test @DisplayName("the losing claim reads the winner in a transaction that is still usable") void theLoserReadsTheWinner() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); @@ -65,7 +81,7 @@ class PostgreSqlNotificationDedupRaceIntegrationTest { void aDifferentWindowIsNotADuplicate() { // Without this, the assertion above is satisfied by a conflict target so broad that every claim // collides — which would deduplicate notifications that are not duplicates at all. - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationIdempotencyRaceIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationIdempotencyRaceIntegrationTest.java index 9333ba01..0f496dc2 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationIdempotencyRaceIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationIdempotencyRaceIntegrationTest.java @@ -10,6 +10,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.sql.DataSource; import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -31,10 +33,24 @@ import org.springframework.jdbc.core.JdbcTemplate; @Tag("jpa-contract") class PostgreSqlNotificationIdempotencyRaceIntegrationTest { + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void startPostgreSql() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void stopPostgreSql() { + if (postgres != null) { + postgres.close(); + } + } + @Test @DisplayName("ON CONFLICT DO NOTHING leaves the transaction usable for the losing caller") void onConflictLeavesTheTransactionUsable() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); UUID winner = UUID.randomUUID(); @@ -76,7 +92,7 @@ class PostgreSqlNotificationIdempotencyRaceIntegrationTest { @Test @DisplayName("two concurrent callers produce one row and one winner") void twoConcurrentCallersProduceOneRow() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); CountDownLatch start = new CountDownLatch(1); @@ -116,7 +132,7 @@ class PostgreSqlNotificationIdempotencyRaceIntegrationTest { @Test @DisplayName("a different fingerprint under the same key is visible to the loser") void aDifferentFingerprintIsVisibleToTheLoser() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); claim(jdbc, UUID.randomUUID(), "key-2", "fingerprint-a"); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationInvariantIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationInvariantIntegrationTest.java index c2665481..609c505d 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationInvariantIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationInvariantIntegrationTest.java @@ -7,6 +7,8 @@ import java.util.List; import java.util.UUID; import javax.sql.DataSource; import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -25,10 +27,24 @@ import org.springframework.jdbc.core.JdbcTemplate; @Tag("jpa-migration") class PostgreSqlNotificationInvariantIntegrationTest { + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void startPostgreSql() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void stopPostgreSql() { + if (postgres != null) { + postgres.close(); + } + } + @Test @DisplayName("a recipient in another tenant cannot reference this tenant's request") void aRecipientInAnotherTenantCannotReferenceThisTenantsRequest() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); UUID request = insertRequest(jdbc, "tenant-a"); @@ -43,7 +59,7 @@ class PostgreSqlNotificationInvariantIntegrationTest { @Test @DisplayName("a recipient in the same tenant is accepted") void aRecipientInTheSameTenantIsAccepted() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); UUID request = insertRequest(jdbc, "tenant-a"); @@ -62,7 +78,7 @@ class PostgreSqlNotificationInvariantIntegrationTest { @Test @DisplayName("an attempt cannot name a contact point that does not exist") void anAttemptCannotNameAContactPointThatDoesNotExist() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); UUID request = insertRequest(jdbc, "tenant-a"); @@ -92,7 +108,7 @@ class PostgreSqlNotificationInvariantIntegrationTest { @Test @DisplayName("the expired-lease sweep is served by its own partial index") void theExpiredLeaseSweepIsServedByItsOwnPartialIndex() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationPersistenceUnitIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationPersistenceUnitIntegrationTest.java index 52bca244..18e28373 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationPersistenceUnitIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationPersistenceUnitIntegrationTest.java @@ -21,6 +21,8 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import javax.sql.DataSource; import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -48,10 +50,24 @@ import org.springframework.transaction.support.TransactionTemplate; @Tag("jpa-migration") class PostgreSqlNotificationPersistenceUnitIntegrationTest { + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void startPostgreSql() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void stopPostgreSql() { + if (postgres != null) { + postgres.close(); + } + } + @Test @DisplayName("Hibernate validates the notification mapping against the migrated schema") void hibernateValidatesTheMappingAgainstTheMigratedSchema() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); assertThatCode(() -> entityManagerFactory(database.dataSource()).close()) @@ -63,7 +79,7 @@ class PostgreSqlNotificationPersistenceUnitIntegrationTest { @Test @DisplayName("the columns Hibernate validates really are jsonb, not text that looks like JSON") void theJsonColumnsAreJsonb() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); UUID id = UUID.randomUUID(); @@ -110,7 +126,7 @@ class PostgreSqlNotificationPersistenceUnitIntegrationTest { @Test @DisplayName("an admin claim is completed in place and the next caller replays it") void adminClaimCompletesInPlaceAndReplays() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); try (EntityManagerFactory emf = entityManagerFactory(database.dataSource())) { @@ -174,7 +190,7 @@ class PostgreSqlNotificationPersistenceUnitIntegrationTest { @Test @DisplayName("a request with no locale is stored as absent, not as a guessed default") void anAbsentLocaleStaysAbsent() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { migrate(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); UUID id = UUID.randomUUID(); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationSchemaActivationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationSchemaActivationIntegrationTest.java index 2c8d80be..9c8050bf 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationSchemaActivationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationSchemaActivationIntegrationTest.java @@ -7,6 +7,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.outbound.persistence.notification.NotificationSchemaActivation; import dev.caskeleton.adapter.outbound.persistence.notification.NotificationSchemaStream; import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -31,10 +33,24 @@ class PostgreSqlNotificationSchemaActivationIntegrationTest { // silently leaving it asserting about a table nobody writes. private static final String HISTORY_TABLE = NotificationSchemaStream.HISTORY_TABLE; + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void startPostgreSql() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void stopPostgreSql() { + if (postgres != null) { + postgres.close(); + } + } + @Test @DisplayName("an unapplied stream fails startup instead of the first notification") void anUnappliedStreamFailsStartup() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { applyCore(database); var activation = new NotificationSchemaActivation(new JdbcTemplate(database.dataSource())); @@ -49,7 +65,7 @@ class PostgreSqlNotificationSchemaActivationIntegrationTest { @Test @DisplayName("an applied but unpromoted stream still fails: applying is not sanctioning") void anAppliedButUnpromotedStreamStillFails() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { applyCore(database); applyNotificationStream(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); @@ -65,7 +81,7 @@ class PostgreSqlNotificationSchemaActivationIntegrationTest { @Test @DisplayName("an applied and promoted stream starts") void anAppliedAndPromotedStreamStarts() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { applyCore(database); applyNotificationStream(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); @@ -79,7 +95,7 @@ class PostgreSqlNotificationSchemaActivationIntegrationTest { @Test @DisplayName("a missing registry reads as not promoted, never as fine") void aMissingRegistryReadsAsNotPromoted() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { var activation = new NotificationSchemaActivation(new JdbcTemplate(database.dataSource())); assertThatThrownBy(activation::requireActive) @@ -92,7 +108,7 @@ class PostgreSqlNotificationSchemaActivationIntegrationTest { @Test @DisplayName("the stream records into its own history table, not the primary one") void theStreamRecordsIntoItsOwnHistoryTable() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { applyCore(database); applyNotificationStream(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); @@ -115,7 +131,7 @@ class PostgreSqlNotificationSchemaActivationIntegrationTest { @Test @DisplayName("applying the stream twice is a no-op rather than a second application") void applyingTheStreamTwiceIsANoOp() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { applyCore(database); int first = applyNotificationStream(database); int second = applyNotificationStream(database); @@ -130,7 +146,7 @@ class PostgreSqlNotificationSchemaActivationIntegrationTest { @Test @DisplayName("every entity's table exists after the stream, which is what validate demands") void everyEntityTableExistsAfterTheStream() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { applyCore(database); applyNotificationStream(database); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); @@ -182,7 +198,7 @@ class PostgreSqlNotificationSchemaActivationIntegrationTest { @DisplayName("V1 to V4, disable, re-enable and an interrupted migration all recover") void theStreamLifecycleIsNonDestructiveAndRecoversInterruptedMigration() throws Exception { PostgreSqlOptionalStreamLifecycle.verify( - PostgreSqlOptionalStreamLifecycle.notificationPlatform()); + postgres, PostgreSqlOptionalStreamLifecycle.notificationPlatform()); } /** diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationSchemaManifestIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationSchemaManifestIntegrationTest.java index 2f880565..d56312ab 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationSchemaManifestIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationSchemaManifestIntegrationTest.java @@ -17,6 +17,8 @@ import java.util.TreeMap; import org.flywaydb.core.Flyway; import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.type.SqlTypes; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -40,10 +42,24 @@ import org.springframework.jdbc.core.JdbcTemplate; @Tag("jpa-migration") class PostgreSqlNotificationSchemaManifestIntegrationTest { + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void startPostgreSql() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void stopPostgreSql() { + if (postgres != null) { + postgres.close(); + } + } + @Test @DisplayName("every mapped column exists in the migrated schema") void everyMappedColumnExists() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { Map> schema = migrateAndDescribe(database); List missing = new ArrayList<>(); @@ -67,7 +83,7 @@ class PostgreSqlNotificationSchemaManifestIntegrationTest { @Test @DisplayName("every jsonb column is mapped as JSON, not as a string") void everyJsonbColumnDeclaresItsType() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { Map> schema = migrateAndDescribe(database); List untyped = new ArrayList<>(); @@ -92,7 +108,7 @@ class PostgreSqlNotificationSchemaManifestIntegrationTest { @Test @DisplayName("a declared length never exceeds the column's own limit") void declaredLengthsFitTheColumn() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { Map> schema = migrateAndDescribe(database); List overlong = new ArrayList<>(); @@ -127,7 +143,7 @@ class PostgreSqlNotificationSchemaManifestIntegrationTest { @Test @DisplayName("a nullable column is never mapped as non-null without a database default") void nonNullMappingsMatchTheColumn() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { Map> schema = migrateAndDescribe(database); List disagreements = new ArrayList<>(); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java index 78e88eb7..1e2bbf67 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java @@ -115,13 +115,15 @@ final class PostgreSqlOptionalStreamLifecycle { List.of()); } - static void verify(Stream stream) throws Exception { - verifyFreshDisabledEnableDisableReEnable(stream); - verifyInterruptedRecovery(stream); + /** Runs the matrix on two fresh databases of {@code server}, the calling test class's server. */ + static void verify(PostgreSqlReadinessSupport server, Stream stream) throws Exception { + verifyFreshDisabledEnableDisableReEnable(server, stream); + verifyInterruptedRecovery(server, stream); } - private static void verifyFreshDisabledEnableDisableReEnable(Stream stream) throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + private static void verifyFreshDisabledEnableDisableReEnable( + PostgreSqlReadinessSupport server, Stream stream) throws Exception { + try (PostgreSqlReadinessSupport database = server.freshDatabase()) { prepareFreshCoreAndPrerequisites(database, stream); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); @@ -155,8 +157,9 @@ final class PostgreSqlOptionalStreamLifecycle { } } - private static void verifyInterruptedRecovery(Stream stream) throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { + private static void verifyInterruptedRecovery(PostgreSqlReadinessSupport server, Stream stream) + throws Exception { + try (PostgreSqlReadinessSupport database = server.freshDatabase()) { prepareFreshCoreAndPrerequisites(database, stream); JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); Flyway flyway = diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java index fda534fe..7c58296b 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupport.java @@ -8,12 +8,31 @@ import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.Container.ExecResult; import org.testcontainers.postgresql.PostgreSQLContainer; import org.testcontainers.utility.MountableFile; -/** Shared no-skip PostgreSQL 16 container support for one readiness test class. */ +/** + * No-skip PostgreSQL 16 for the readiness and migration tests: one server per test class, and a + * fresh database on it for each test that needs an empty one. + * + *

A class starts its server once with {@code start} in {@code @BeforeAll} and closes it in + * {@code @AfterAll}. A test that must begin from nothing — a migration chain applied to an empty + * database, a schema nobody applied — takes {@link #freshDatabase()}: a new database created from + * {@code template1}, the way the container made its own first one, so it holds nothing an earlier + * test of the class wrote, whatever order the tests run in. + * + *

Until 2026-11-19 those tests each started a container of their own: 102 PostgreSQL containers + * in twenty minutes of the main stage, and three quarters of the platform migration lane's test + * time spent starting them (desktop, 2026-11-19). + * + *

A database does not separate what the server holds for all of them: roles, {@code ALTER + * SYSTEM} settings, the connection limit, a restart. A test that sets or asserts those starts a + * server of its own with {@code start} or {@code startTls}, as {@code + * PostgreSqlLifecycleIntegrationTest} and {@code PostgreSqlSecurityBaselineIntegrationTest} do. + */ final class PostgreSqlReadinessSupport implements AutoCloseable { private static final String IMAGE = @@ -22,10 +41,28 @@ final class PostgreSqlReadinessSupport implements AutoCloseable { private final PostgreSQLContainer container; private final HikariDataSource dataSource; + private final String jdbcUrl; + private final String databaseName; - private PostgreSqlReadinessSupport(PostgreSQLContainer container, HikariDataSource dataSource) { + /** True for the server {@code start} returns; a fresh database closes without stopping it. */ + private final boolean ownsServer; + + /** Names the fresh databases of one server, shared with them so a name never repeats on it. */ + private final AtomicInteger freshDatabases; + + private PostgreSqlReadinessSupport( + PostgreSQLContainer container, + HikariDataSource dataSource, + String jdbcUrl, + String databaseName, + boolean ownsServer, + AtomicInteger freshDatabases) { this.container = container; this.dataSource = dataSource; + this.jdbcUrl = jdbcUrl; + this.databaseName = databaseName; + this.ownsServer = ownsServer; + this.freshDatabases = freshDatabases; } /** Every SQLState in {@code failure}'s cause chain, outermost first. */ @@ -75,14 +112,37 @@ final class PostgreSqlReadinessSupport implements AutoCloseable { private static PostgreSqlReadinessSupport support( PostgreSQLContainer container, int maximumPoolSize, long connectionTimeoutMillis) { + return new PostgreSqlReadinessSupport( + container, + pool(container, container.getJdbcUrl(), maximumPoolSize, connectionTimeoutMillis), + container.getJdbcUrl(), + container.getDatabaseName(), + true, + new AtomicInteger()); + } + + private static HikariDataSource pool( + PostgreSQLContainer container, + String jdbcUrl, + int maximumPoolSize, + long connectionTimeoutMillis) { HikariConfig config = new HikariConfig(); - config.setJdbcUrl(container.getJdbcUrl()); + config.setJdbcUrl(jdbcUrl); config.setUsername(container.getUsername()); config.setPassword(container.getPassword()); config.setMaximumPoolSize(maximumPoolSize); config.setMinimumIdle(Math.min(1, maximumPoolSize)); config.setConnectionTimeout(connectionTimeoutMillis); - return new PostgreSqlReadinessSupport(container, new HikariDataSource(config)); + return new HikariDataSource(config); + } + + private static String databaseUrl(PostgreSQLContainer container, String name) { + return "jdbc:postgresql://" + + container.getHost() + + ":" + + container.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT) + + "/" + + name; } private static void configureTls(PostgreSQLContainer container, PostgreSqlTlsMaterial tlsMaterial) @@ -145,24 +205,24 @@ final class PostgreSqlReadinessSupport implements AutoCloseable { } Connection connection(String username, String password) throws SQLException { - return DriverManager.getConnection(container.getJdbcUrl(), username, password); + return DriverManager.getConnection(jdbcUrl, username, password); } Connection tlsConnection(String host, Path rootCertificate) throws SQLException { - String jdbcUrl = + String tlsUrl = "jdbc:postgresql://" + host + ":" + container.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT) + "/" - + container.getDatabaseName(); + + databaseName; Properties properties = new Properties(); properties.setProperty("user", container.getUsername()); properties.setProperty("password", container.getPassword()); properties.setProperty("sslmode", "verify-full"); properties.setProperty("sslrootcert", rootCertificate.toAbsolutePath().toString()); properties.setProperty("connectTimeout", "3"); - return DriverManager.getConnection(jdbcUrl, properties); + return DriverManager.getConnection(tlsUrl, properties); } /** @@ -171,20 +231,21 @@ final class PostgreSqlReadinessSupport implements AutoCloseable { */ HikariDataSource createDatabase(String name) throws SQLException { execute("CREATE DATABASE " + name); - HikariConfig config = new HikariConfig(); - config.setJdbcUrl( - "jdbc:postgresql://" - + container.getHost() - + ":" - + container.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT) - + "/" - + name); - config.setUsername(container.getUsername()); - config.setPassword(container.getPassword()); - config.setMaximumPoolSize(3); - config.setMinimumIdle(1); - config.setConnectionTimeout(1_000); - return new HikariDataSource(config); + return pool(container, databaseUrl(container, name), 3, 1_000); + } + + /** + * A new, empty database on this server for one test, with the pool {@code start()} gives. + * + *

Closing it closes its pool and drops the database; the server keeps running for the class's + * next test. + */ + PostgreSqlReadinessSupport freshDatabase() { + String name = "fresh_" + freshDatabases.incrementAndGet(); + administer("CREATE DATABASE " + name); + String url = databaseUrl(container, name); + return new PostgreSqlReadinessSupport( + container, pool(container, url, 5, 1_000), url, name, false, freshDatabases); } void execute(String sql) throws SQLException { @@ -194,9 +255,27 @@ final class PostgreSqlReadinessSupport implements AutoCloseable { } } + /** Runs one statement as the server's owning role, on the database the container created. */ + private void administer(String sql) { + try (Connection connection = + DriverManager.getConnection( + container.getJdbcUrl(), container.getUsername(), container.getPassword()); + Statement statement = connection.createStatement()) { + statement.execute(sql); + } catch (SQLException failure) { + throw new IllegalStateException("PostgreSQL readiness server refused: " + sql, failure); + } + } + @Override public void close() { dataSource.close(); - container.stop(); + if (ownsServer) { + container.stop(); + } else { + // The pool first: dropping the database under an open pool leaves it retrying against a + // database that is gone. `with (force)` ends a connection the test opened outside the pool. + administer("DROP DATABASE IF EXISTS " + databaseName + " WITH (FORCE)"); + } } } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupportOwnershipTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupportOwnershipTest.java new file mode 100644 index 00000000..60fb0e4e --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlReadinessSupportOwnershipTest.java @@ -0,0 +1,116 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.zaxxer.hikari.HikariDataSource; +import java.sql.SQLException; +import java.util.List; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * What a readiness or migration test leans on when its class shares one server. + * + *

Those tests apply a migration chain to an empty database and assert what it leaves. They used + * to get the empty database by starting a server of their own. Sharing the server is only safe if + * {@link PostgreSqlReadinessSupport#freshDatabase()} is another database on that server, holds + * nothing an earlier test wrote, and is gone once its test closes it. + */ +@Tag("jpa-migration") +class PostgreSqlReadinessSupportOwnershipTest { + + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void startPostgreSql() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void stopPostgreSql() { + if (postgres != null) { + postgres.close(); + } + } + + @Test + void aFreshDatabaseIsAnotherDatabaseOnTheSameServer() { + // given + Identity server = identify(postgres); + + // when + Identity fresh; + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { + fresh = identify(database); + } + + // then + assertThat(List.of(fresh.serverStartedAt(), fresh.database().equals(server.database()))) + .as("one server per class, a database of its own per test") + .containsExactly(server.serverStartedAt(), false); + } + + @Test + void aFreshDatabaseHoldsNoTableAnEarlierTestLeft() throws SQLException { + // given + try (PostgreSqlReadinessSupport earlier = postgres.freshDatabase()) { + earlier.execute("create table left_by_an_earlier_test (id integer)"); + } + + // when + List tables; + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { + tables = + new JdbcTemplate(database.dataSource()) + .queryForList( + "select tablename from pg_tables where schemaname = 'public' order by 1", + String.class); + } + + // then + assertThat(tables) + .as("a migration test asserts what its chain left; anything else in the database lies") + .isEmpty(); + } + + @Test + void closingAFreshDatabaseClosesItsPoolDropsItAndLeavesTheServerRunning() throws SQLException { + // when + String name; + HikariDataSource pool; + try (PostgreSqlReadinessSupport database = postgres.freshDatabase()) { + name = identify(database).database(); + pool = database.dataSource(); + } + + // then + assertThat(List.of(pool.isClosed(), databaseExists(name), serverAnswers())) + .as("a pool left open retries against a dropped database; the class's server stays up") + .containsExactly(true, false, true); + } + + private record Identity(String database, String serverStartedAt) {} + + private static Identity identify(PostgreSqlReadinessSupport support) { + return new JdbcTemplate(support.dataSource()) + .queryForObject( + "select current_database(), pg_postmaster_start_time()::text", + (row, index) -> new Identity(row.getString(1), row.getString(2))); + } + + private static boolean databaseExists(String name) { + return Boolean.TRUE.equals( + new JdbcTemplate(postgres.dataSource()) + .queryForObject( + "select exists(select 1 from pg_database where datname = ?)", Boolean.class, name)); + } + + private static boolean serverAnswers() throws SQLException { + try (var connection = postgres.connection()) { + return connection.isValid(2); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecipientLeaseFencingIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecipientLeaseFencingIntegrationTest.java index 55442488..88c4121a 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecipientLeaseFencingIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlRecipientLeaseFencingIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientLeaseStore; import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; +import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; import dev.caskeleton.application.notification.platform.dispatch.RecipientLease; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; @@ -13,8 +14,16 @@ import java.time.Instant; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import javax.sql.DataSource; import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -43,11 +52,31 @@ class PostgreSqlRecipientLeaseFencingIntegrationTest { private static final Duration LEASE = Duration.ofSeconds(30); + /** How long the test waits for one step of either worker. */ + private static final Duration STEP = Duration.ofSeconds(30); + + /** How long worker-a keeps its claim open at most; see the concurrent claim test. */ + private static final Duration WORKER_A_HOLDS_AT_MOST = STEP.multipliedBy(2); + + private static PostgreSqlReadinessSupport postgres; + + @BeforeAll + static void startPostgreSql() { + postgres = PostgreSqlReadinessSupport.start(); + } + + @AfterAll + static void stopPostgreSql() { + if (postgres != null) { + postgres.close(); + } + } + @Test @DisplayName("a late renew from a superseded holder changes nothing") void aLateRenewFromASupersededHolderChangesNothing() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { - Fixture fixture = Fixture.migrated(database); + try (PostgreSqlReadinessSupport database = postgres.freshDatabase(); + Fixture fixture = Fixture.migrated(database)) { UUID job = fixture.insertDueJob(); RecipientLease held = fixture.store("worker-a").claim("worker-a", 10, LEASE).getFirst(); @@ -79,8 +108,8 @@ class PostgreSqlRecipientLeaseFencingIntegrationTest { // expired during the submission came back and described an attempt that was no longer the live // one. The @Version column does not stop it: it detects a concurrent edit, not a superseded // writer, and this worker's read is recent enough to win. - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { - Fixture fixture = Fixture.migrated(database); + try (PostgreSqlReadinessSupport database = postgres.freshDatabase(); + Fixture fixture = Fixture.migrated(database)) { UUID job = fixture.insertDueJob(); RecipientLease held = fixture.store("worker-a").claim("worker-a", 10, LEASE).getFirst(); @@ -116,8 +145,8 @@ class PostgreSqlRecipientLeaseFencingIntegrationTest { @DisplayName("the holder that still owns the job does write its outcome") void theCurrentHolderWritesItsOutcome() throws Exception { // Without this, the assertion above is satisfied by a statement that matches nothing ever. - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { - Fixture fixture = Fixture.migrated(database); + try (PostgreSqlReadinessSupport database = postgres.freshDatabase(); + Fixture fixture = Fixture.migrated(database)) { UUID job = fixture.insertDueJob(); RecipientLease held = fixture.store("worker-a").claim("worker-a", 10, LEASE).getFirst(); @@ -143,8 +172,8 @@ class PostgreSqlRecipientLeaseFencingIntegrationTest { @Test @DisplayName("a superseded holder cannot release its replacement's lease") void aSupersededHolderCannotReleaseItsReplacementsLease() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { - Fixture fixture = Fixture.migrated(database); + try (PostgreSqlReadinessSupport database = postgres.freshDatabase(); + Fixture fixture = Fixture.migrated(database)) { UUID job = fixture.insertDueJob(); RecipientLease held = fixture.store("worker-a").claim("worker-a", 10, LEASE).getFirst(); @@ -169,8 +198,8 @@ class PostgreSqlRecipientLeaseFencingIntegrationTest { @Test @DisplayName("the still-held check refuses a stale lease before the side effect") void theStillHeldCheckRefusesAStaleLease() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { - Fixture fixture = Fixture.migrated(database); + try (PostgreSqlReadinessSupport database = postgres.freshDatabase(); + Fixture fixture = Fixture.migrated(database)) { UUID job = fixture.insertDueJob(); RecipientLease held = fixture.store("worker-a").claim("worker-a", 10, LEASE).getFirst(); @@ -186,33 +215,106 @@ class PostgreSqlRecipientLeaseFencingIntegrationTest { } @Test - @DisplayName("two workers claiming at once split the batch; neither sees the other's job") + @DisplayName("worker-a의 claim이 커밋 전이어도 worker-b는 그 잠금을 기다리지 않고 건너뛰어 나머지 batch를 가져간다") void twoWorkersClaimingAtOnceSplitTheBatch() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { - Fixture fixture = Fixture.migrated(database); + try (PostgreSqlReadinessSupport database = postgres.freshDatabase(); + Fixture fixture = Fixture.migrated(database)) { + // given for (int index = 0; index < 6; index++) { fixture.insertDueJob(); } + CountDownLatch firstClaimed = new CountDownLatch(1); + CountDownLatch firstMayCommit = new CountDownLatch(1); + ExecutorService workers = Executors.newFixedThreadPool(2); - List first = fixture.store("worker-a").claim("worker-a", 3, LEASE); - List second = fixture.store("worker-b").claim("worker-b", 3, LEASE); + // when + List first; + List second; + try { + // worker-a's claim keeps its row locks, uncommitted, while worker-b claims in a transaction + // on a connection of its own: the overlap two worker processes have. Started together on + // a barrier instead, two claims of a few milliseconds each mostly run one after the other, + // and the batch splits that way with or without the lock clause. + Future> claimA = + workers.submit( + () -> + fixture.inTransaction( + () -> { + List claimed; + try { + claimed = fixture.store("worker-a").claim("worker-a", 3, LEASE); + } finally { + // A failed claim surfaces through its future below, not as a wait. + firstClaimed.countDown(); + } + // Longer than the main thread waits for worker-b below, so a worker-b + // stuck behind these locks is what fails the test; the main thread's + // finally releases this wait either way. + awaitOrFail(firstMayCommit, WORKER_A_HOLDS_AT_MOST); + return claimed; + })); + awaitOrFail(firstClaimed, STEP); + Future> claimB = + workers.submit( + () -> + fixture.inTransaction( + () -> fixture.store("worker-b").claim("worker-b", 3, LEASE))); + second = + resultOf( + claimB, + "worker-b waited for worker-a's open claim instead of skipping the rows it locked"); + firstMayCommit.countDown(); + first = resultOf(claimA, "worker-a's claim did not commit once worker-b had claimed"); + } finally { + firstMayCommit.countDown(); + workers.shutdownNow(); + } - assertThat(first).hasSize(3); - assertThat(second).hasSize(3); - assertThat(first.stream().map(RecipientLease::recipientDeliveryId)) - .doesNotContainAnyElementsOf( - second.stream().map(RecipientLease::recipientDeliveryId).toList()); - assertThat(fixture.store("worker-c").claim("worker-c", 3, LEASE)) - .as("everything due is claimed; nothing is claimed twice") - .isEmpty(); + // then + List takenByA = + first.stream().map(RecipientLease::recipientDeliveryId).toList(); + assertThat( + List.of( + first.size(), + second.size(), + second.stream() + .map(RecipientLease::recipientDeliveryId) + .filter(takenByA::contains) + .toList(), + fixture.store("worker-c").claim("worker-c", 3, LEASE))) + .as( + "each takes half while the other's claim is open; neither takes a job the other" + + " holds; everything due is claimed and nothing is claimed twice") + .containsExactly(3, 3, List.of(), List.of()); + } + } + + /** A worker's claim, or a failure that says what it was stuck on, after {@link #STEP}. */ + private static T resultOf(Future claim, String stuck) throws Exception { + try { + return claim.get(STEP.toMillis(), TimeUnit.MILLISECONDS); + } catch (TimeoutException timeout) { + throw new AssertionError(stuck, timeout); + } + } + + /** Waits for the other worker's step; a step that never comes fails the test, not hangs it. */ + private static void awaitOrFail(CountDownLatch latch, Duration limit) { + try { + if (!latch.await(limit.toMillis(), TimeUnit.MILLISECONDS)) { + throw new IllegalStateException("the other worker did not arrive within " + limit); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted waiting for the other worker", interrupted); } } @Test @DisplayName("the holder that still owns the job can renew") void theCurrentHolderCanRenew() throws Exception { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { - Fixture fixture = Fixture.migrated(database); + try (PostgreSqlReadinessSupport database = postgres.freshDatabase(); + Fixture fixture = Fixture.migrated(database)) { fixture.insertDueJob(); RecipientLease held = fixture.store("worker-a").claim("worker-a", 10, LEASE).getFirst(); @@ -234,11 +336,21 @@ class PostgreSqlRecipientLeaseFencingIntegrationTest { * from a {@link JpaTransactionManager}, as in production: the lease store's writes refuse to run * outside a caller transaction ({@code CallerTransaction}), and a transaction opened on a private * {@code EntityManager} is not one Spring can see. + * + *

Each test builds its own entity manager factory on its own fresh database and closes it, + * before the database is dropped, by closing the fixture. */ private record Fixture( DataSource dataSource, + EntityManagerFactory factory, TransactionTemplate transactions, - RecipientDeliveryJpaRepository repository) { + RecipientDeliveryJpaRepository repository) + implements AutoCloseable { + + @Override + public void close() { + factory.close(); + } static Fixture migrated(PostgreSqlReadinessSupport database) { Flyway core = @@ -283,6 +395,7 @@ class PostgreSqlRecipientLeaseFencingIntegrationTest { SharedEntityManagerCreator.createSharedEntityManager(factory); return new Fixture( database.dataSource(), + factory, new TransactionTemplate(new JpaTransactionManager(factory)), new JpaRepositoryFactory(sharedEntityManager) .getRepository(RecipientDeliveryJpaRepository.class));