From 6da82806b3e2429dcdac2ed4b9c5a8d1da34261a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 21 Nov 2026 03:31:12 +0900 Subject: [PATCH] =?UTF-8?q?test(persistence-jpa):=20=ED=86=B5=ED=95=A9=20?= =?UTF-8?q?=EC=8B=9C=ED=97=98=20=EC=A0=95=EB=A6=AC=20TRUNCATE=209=EA=B3=B3?= =?UTF-8?q?=EC=9D=B4=20=EC=9E=A0=EA=B8=88=20=EB=8C=80=EA=B8=B0=20=EC=83=81?= =?UTF-8?q?=ED=95=9C=20helper=20=ED=95=98=EB=82=98=EB=A5=BC=20=EC=93=B4?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 통합 시험 9곳의 @BeforeEach 정리가 풀 연결로 TRUNCATE를 lock_timeout 없이(서버 기본값 0) 돈다. 앞 시험이 그 표를 잠근 트랜잭션을 남기면 정리가 lane 시한까지 기다리고, 보고는 잠근 쪽이 아니라 정리를 가리킨다. #66이 JpaDurableOperationStoreContractTest 한 곳만 고쳤고 나머지 8곳 (persistence-jpa 7, app 1)이 남았다. persistence-jpa testFixtures `testkit/postgresql/BoundedTruncate`에 truncate·truncateCascade를 둔다. #66 모양 그대로 트랜잭션 하나 + SET LOCAL lock_timeout 2초, 55P03이면 rollback 뒤 이 DB 사용자 표의 relation lock을 쥔·기다리는 다른 세션(pid, mode, 표, 상태, 열린 초, 마지막 문장)을 적고 IllegalStateException으로 실패한다. CASCADE는 나열하지 않은 참조 표도 잠그므로 holder 조회는 표를 좁히지 않는다. rollback·조회·조회 트랜잭션 끝내기·autocommit 복원 실패는 원래 예외에 suppressed로 붙인다. 조회가 연 트랜잭션은 rollback으로 끝낸다. autocommit은 풀에 맡기지 않고 finally에서 되돌린다(Hikari는 되돌리지만 돌려줄 때 초기화하지 않는 DataSource도 같은 연결을 받게). 표 이름은 따옴표 없는 식별자만 받는다. app integrationTest는 build.gradle 199행·30행으로 이미 이 testFixtures를 받으므로 새 모듈 의존이 없다. leaf마다 같은 모양을 복사하는 안은 버렸다(9곳이 한 곳을 쓰면 상한·진단을 한 번에 고친다). #66의 시험 안 구현은 helper로 옮겼다. helper 자기 시험 BoundedTruncateContractTest(jpa-contract, 자기 DB, 7개): 비움 두 갈래(나열한 표만, CASCADE 참조 표까지), holder가 나열한 표나 CASCADE만 닿는 참조 표를 잠갔을 때 holder pid·표를 적고 실패, 비운 뒤와 포기한 뒤 같은 물리 연결의 autocommit true·lock_timeout 0, autocommit 없이 빌려준 연결은 포기한 뒤 autocommit false 그대로이고 열린 트랜잭션이 없음(pg_stat_activity state = idle). holder는 idle_in_transaction_session_timeout 10초로 스스로 끝나서, 실패한 시험이 남는 holder가 되지 않고 상한이 깨져도 시험이 끝난다. 위험·한계: 남은 holder가 있으면 뒤 시험들이 2초씩 기다리다 실패한다. 조용히 기다리는 대신 holder를 적고 실패하는 쪽을 골랐다. 검증(트리 e1b10ac5, desktop): - 탐침 L(SpringTransactionContractTest에 시험을 잠깐 더함, 다른 세션이 표를 잠근 채 30초 idle): main be961e23은 30000ms 뒤 그냥 돌아오고, 이 트리는 2013ms 뒤 holder를 적은 IllegalStateException. - 자기 시험 7개 통과. 변이마다 자기 시험이 실패: M1 SET LOCAL 삭제 4, M2 세션 SET 1, M3 켜져 있던 autocommit 복원 건너뜀 2, M4 CASCADE 삭제 2, M5 holder 조회를 한 표로 좁힘 2, M6 조회 뒤 rollback 삭제 1. - lane(필터 없이) rc=0: jpaPlatformContractTest 462, postgresqlOutboxConcurrentRelayIntegrationTest 11, postgresqlFileserverReclamationIntegrationTest 23, :app-bootstrap:integrationTest 10. - 깨끗한 worktree에서 scripts/verify.sh rc=0: leaf :adapter:outbound:persistence-jpa --no-cache(683), leaf :app-bootstrap --no-cache(330), pr --no-cache(7270), docs. --- ...rationSubmissionOutboxIntegrationTest.java | 5 +- .../JpaDurableOperationStoreContractTest.java | 97 +------ .../platform/BoundedTruncateContractTest.java | 262 ++++++++++++++++++ .../readiness/FileserverPostgreSqlStack.java | 12 +- ...lFileserverReclamationIntegrationTest.java | 12 +- ...ficationBackgroundPassIntegrationTest.java | 12 +- ...boxClaimAndMaintenanceIntegrationTest.java | 3 +- ...lOutboxConcurrentRelayIntegrationTest.java | 3 +- .../SpringTransactionContractTest.java | 3 +- .../testkit/postgresql/BoundedTruncate.java | 204 ++++++++++++++ ...leOperationCompositionIntegrationTest.java | 6 +- 11 files changed, 510 insertions(+), 109 deletions(-) create mode 100644 src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/BoundedTruncateContractTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/BoundedTruncate.java diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java index 77366f9f..e7a7f940 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java @@ -8,6 +8,7 @@ import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.adapter.outbound.support.messaging.JsonIntegrationEventEncoder; import dev.caskeleton.application.idempotency.RequestFingerprint; @@ -97,8 +98,8 @@ class DurableOperationSubmissionOutboxIntegrationTest { } @BeforeEach - void empty() throws SQLException { - execute("TRUNCATE durable_operation, outbox_event"); + void empty() { + BoundedTruncate.truncate(support.dataSource(), "durable_operation", "outbox_event"); } @Test diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java index 11b16b5c..f15405d8 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.operation.DurableOperationClaim; @@ -17,12 +18,10 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.sql.Connection; -import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.Duration; import java.time.Instant; -import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -76,18 +75,6 @@ class JpaDurableOperationStoreContractTest extends DurableOperationStoreContract /** Longer than worker-b may queue and inside the transaction timeout, so worker-a commits. */ private static final Duration WORKER_A_HOLDS_AT_MOST = WORKER_B_QUEUES_AT_MOST.multipliedBy(2); - /** - * How long the cleanup's TRUNCATE may wait for a lock on the table before it fails. - * - *

Twice the 1 s {@code deadlock_timeout} after which PostgreSQL cancels an autovacuum that - * blocks the TRUNCATE, and a commit still in flight ends in milliseconds: a lock held longer is a - * transaction a test left open, which an unbounded TRUNCATE would wait for for good. - */ - private static final String CLEANUP_LOCK_TIMEOUT = "2s"; - - /** PostgreSQL's SQLSTATE for a lock wait that ran out its {@code lock_timeout}. */ - private static final String LOCK_NOT_AVAILABLE = "55P03"; - private static JpaPlatformContractSupport support; private static AnnotationConfigApplicationContext context; @@ -112,86 +99,10 @@ class JpaDurableOperationStoreContractTest extends DurableOperationStoreContract } } - /** - * Empties the table, or fails naming the session whose lock on it stopped the TRUNCATE. - * - *

{@code SET LOCAL} ends with this transaction: the connection goes back to the pool the - * adapter under test borrows from, and the adapter must not inherit the cleanup's bound. The pool - * restores autocommit when the connection goes back. - */ + /** Empties the table, or fails naming the session whose lock on it stopped the TRUNCATE. */ @BeforeEach - void empty() throws SQLException { - try (Connection connection = support.connection(); - Statement statement = connection.createStatement()) { - connection.setAutoCommit(false); - try { - statement.execute("SET LOCAL lock_timeout = '" + CLEANUP_LOCK_TIMEOUT + "'"); - statement.execute("TRUNCATE durable_operation"); - connection.commit(); - } catch (SQLException failure) { - // A broken connection fails the rollback too; that must not replace the original failure. - try { - connection.rollback(); - } catch (SQLException rollbackFailure) { - failure.addSuppressed(rollbackFailure); - throw failure; - } - if (!LOCK_NOT_AVAILABLE.equals(failure.getSQLState())) { - throw failure; - } - String holders; - try { - holders = lockHolders(statement); - } catch (SQLException lookFailure) { - failure.addSuppressed(lookFailure); - holders = "unknown, the lookup failed (suppressed below)"; - } - throw new IllegalStateException( - "the cleanup's TRUNCATE durable_operation gave up after waiting " - + CLEANUP_LOCK_TIMEOUT - + " for a lock on the table. Sessions locking it: " - + holders, - failure); - } - } - } - - /** Every other session's lock on the table, held or queued, and what it last ran. */ - private static String lockHolders(Statement statement) throws SQLException { - List holders = new ArrayList<>(); - try (ResultSet rows = - statement.executeQuery( - """ - SELECT l.pid, l.mode, l.granted, a.state, - extract(epoch FROM now() - a.xact_start)::int AS open_seconds, - left(a.query, 160) AS last_statement - FROM pg_locks l - JOIN pg_stat_activity a ON a.pid = l.pid - WHERE l.locktype = 'relation' - AND l.database = (SELECT oid FROM pg_database WHERE datname = current_database()) - AND l.relation = 'durable_operation'::regclass - AND l.pid <> pg_backend_pid() - ORDER BY l.pid, l.mode - """)) { - while (rows.next()) { - String lock = - "pid " - + rows.getInt("pid") - + " " - + rows.getString("mode") - + (rows.getBoolean("granted") ? " held" : " queued") - + ", " - + rows.getString("state"); - int openSeconds = rows.getInt("open_seconds"); - // No transaction start: the holder ended between reading pg_locks and pg_stat_activity. - String open = - rows.wasNull() ? ", no transaction open any more" : " for " + openSeconds + " s"; - holders.add(lock + open + ", last statement: " + rows.getString("last_statement")); - } - } - return holders.isEmpty() - ? "none any more; the holder ended between the timeout and this look" - : String.join("; ", holders); + void empty() { + BoundedTruncate.truncate(support.dataSource(), "durable_operation"); } @Test diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/BoundedTruncateContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/BoundedTruncateContractTest.java new file mode 100644 index 00000000..77b60602 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/BoundedTruncateContractTest.java @@ -0,0 +1,262 @@ +package dev.caskeleton.adapter.outbound.persistence.platform; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; + +/** + * The cleanup TRUNCATE the integration tests share, against a database of its own. + * + *

A test that locks a table on purpose becomes the leftover holder it is about when it fails + * halfway, which is why #66 kept no permanent test of its cleanup. Two things stop that here: the + * tables live in this class's own database, and every holder ends itself through {@code + * idle_in_transaction_session_timeout}. The second also ends the test when the bound is gone: the + * test thread would otherwise wait in the TRUNCATE for the holder it closes only afterwards. + */ +@Tag("jpa-contract") +class BoundedTruncateContractTest { + + /** Far past the TRUNCATE's 2 s wait, and short enough that a broken bound fails the test soon. */ + private static final String HOLDER_ENDS_ITSELF_AFTER = "10s"; + + private static JpaPlatformContractSupport support; + + @BeforeAll + static void start() throws SQLException { + support = JpaPlatformContractSupport.start(); + execute("CREATE TABLE truncate_parent (id int PRIMARY KEY)"); + execute( + "CREATE TABLE truncate_child" + + " (id int PRIMARY KEY, parent_id int NOT NULL REFERENCES truncate_parent (id))"); + execute("CREATE TABLE truncate_other (id int PRIMARY KEY)"); + } + + @AfterAll + static void stop() { + if (support != null) { + support.close(); + } + } + + @BeforeEach + void oneRowEach() throws SQLException { + execute("DELETE FROM truncate_child"); + execute("DELETE FROM truncate_parent"); + execute("DELETE FROM truncate_other"); + execute("INSERT INTO truncate_parent (id) VALUES (1)"); + execute("INSERT INTO truncate_child (id, parent_id) VALUES (1, 1)"); + execute("INSERT INTO truncate_other (id) VALUES (1)"); + } + + @Test + void truncateEmptiesTheNamedTablesAndNoOther() throws SQLException { + // when + BoundedTruncate.truncate(support.dataSource(), "truncate_child", "truncate_parent"); + + // then + assertThat(List.of(rows("truncate_child"), rows("truncate_parent"), rows("truncate_other"))) + .containsExactly(0, 0, 1); + } + + @Test + void truncateCascadeAlsoEmptiesATableThatReferencesANamedOne() throws SQLException { + // when + BoundedTruncate.truncateCascade(support.dataSource(), "truncate_parent"); + + // then + assertThat(List.of(rows("truncate_child"), rows("truncate_parent"), rows("truncate_other"))) + .containsExactly(0, 0, 1); + } + + @Test + void aLockLeftOnANamedTableFailsTheTruncateNamingItsHolder() throws SQLException { + try (Connection holder = holdingAccessShareOn("truncate_other")) { + // given + int holderPid = pidOf(holder); + + // when + Throwable thrown = + catchThrowable(() -> BoundedTruncate.truncate(support.dataSource(), "truncate_other")); + + // then + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("gave up after waiting 2000 ms for a lock") + .hasMessageContaining( + "pid " + holderPid + " AccessShareLock held on public.truncate_other") + .cause() + .isInstanceOfSatisfying( + SQLException.class, cause -> assertThat(cause.getSQLState()).isEqualTo("55P03")); + } + } + + @Test + void aLockOnAReferencingTableTheCascadeWasNotGivenIsNamedToo() throws SQLException { + try (Connection holder = holdingAccessShareOn("truncate_child")) { + // given + int holderPid = pidOf(holder); + + // when + Throwable thrown = + catchThrowable( + () -> BoundedTruncate.truncateCascade(support.dataSource(), "truncate_parent")); + + // then + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "pid " + holderPid + " AccessShareLock held on public.truncate_child"); + } + } + + @Test + void aConnectionComesBackWithAutocommitOnAndNoLockTimeoutAfterEmptying() throws SQLException { + try (Connection physical = ownConnection()) { + // when + BoundedTruncate.truncate(new SingleConnectionDataSource(physical, true), "truncate_other"); + + // then + assertThat(List.of(physical.getAutoCommit(), lockTimeoutOf(physical))) + .containsExactly(true, "0"); + } + } + + @Test + void aConnectionComesBackWithAutocommitOnAndNoLockTimeoutAfterGivingUp() throws SQLException { + try (Connection holder = holdingAccessShareOn("truncate_other"); + Connection physical = ownConnection()) { + // when + Throwable thrown = + catchThrowable( + () -> + BoundedTruncate.truncate( + new SingleConnectionDataSource(physical, true), "truncate_other")); + + // then + // A TRUNCATE that did not give up leaves no exception: compare that as null, not as an NPE. + assertThat( + Arrays.asList( + thrown == null ? null : thrown.getClass(), + physical.getAutoCommit(), + lockTimeoutOf(physical))) + .containsExactly(IllegalStateException.class, true, "0"); + } + } + + @Test + void aConnectionLentWithoutAutocommitComesBackWithNoTransactionOpenAfterGivingUp() + throws SQLException { + try (Connection holder = holdingAccessShareOn("truncate_other"); + Connection physical = ownConnection()) { + // given + int physicalPid = pidOf(physical); + physical.setAutoCommit(false); + + // when + Throwable thrown = + catchThrowable( + () -> + BoundedTruncate.truncate( + new SingleConnectionDataSource(physical, true), "truncate_other")); + + // then + assertThat( + Arrays.asList( + thrown == null ? null : thrown.getClass(), + physical.getAutoCommit(), + sessionStateOf(physicalPid))) + .containsExactly(IllegalStateException.class, false, "idle"); + } + } + + /** + * A connection outside every pool, so nothing resets it on return. + * + *

Hikari puts autocommit back itself when a connection goes back; a data source that does not + * is the one the class must still leave as it found it. + */ + private static Connection ownConnection() throws SQLException { + return DriverManager.getConnection(support.jdbcUrl(), support.username(), support.password()); + } + + /** A session left in a transaction that read the table, as a test that never committed. */ + private static Connection holdingAccessShareOn(String table) throws SQLException { + Connection holder = ownConnection(); + try (Statement statement = holder.createStatement()) { + statement.execute( + "SET idle_in_transaction_session_timeout = '" + HOLDER_ENDS_ITSELF_AFTER + "'"); + holder.setAutoCommit(false); + statement.execute("SELECT count(*) FROM " + table); + } catch (SQLException failure) { + holder.close(); + throw failure; + } + return holder; + } + + private static int pidOf(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("SELECT pg_backend_pid()")) { + row.next(); + return row.getInt(1); + } + } + + private static String lockTimeoutOf(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("SHOW lock_timeout")) { + row.next(); + return row.getString(1); + } + } + + /** + * What the server shows a session doing between statements, as another session sees it. + * + *

{@code idle in transaction} when a transaction is still open, {@code idle} when none is. + * Asked from outside because the driver, with autocommit off, begins a transaction on the session + * with the first statement it sends. + */ + private static String sessionStateOf(int pid) throws SQLException { + try (Connection connection = support.connection(); + PreparedStatement statement = + connection.prepareStatement("SELECT state FROM pg_stat_activity WHERE pid = ?")) { + statement.setInt(1, pid); + try (ResultSet row = statement.executeQuery()) { + row.next(); + return row.getString(1); + } + } + } + + private static int rows(String table) throws SQLException { + try (Connection connection = support.connection(); + Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("SELECT count(*) FROM " + table)) { + row.next(); + return row.getInt(1); + } + } + + private static void execute(String sql) throws SQLException { + try (Connection connection = support.connection(); + Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java index 068f1dc0..b3a28872 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileMetadata; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.application.fileserver.api.FileId; import dev.caskeleton.application.fileserver.api.StorageNamespace; import dev.caskeleton.application.fileserver.api.metadata.FileOwner; @@ -128,9 +129,14 @@ final class FileserverPostgreSqlStack implements AutoCloseable { /** Deletes every Fileserver row, children first. */ void empty() { - jdbc.execute( - "TRUNCATE fs_recovery_item, fs_cleanup_item, fs_quota_reservation," - + " fs_verification_result, fs_upload_session, fs_file CASCADE"); + BoundedTruncate.truncateCascade( + postgres.dataSource(), + "fs_recovery_item", + "fs_cleanup_item", + "fs_quota_reservation", + "fs_verification_result", + "fs_upload_session", + "fs_file"); } @Override diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java index eb67ee3a..4307724d 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java @@ -11,6 +11,7 @@ import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaReclaim; import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaRecoveryQueue; import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaStagingUploadLocator; import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaUploadSession; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.application.fileserver.api.ContentKey; import dev.caskeleton.application.fileserver.api.FileId; import dev.caskeleton.application.fileserver.api.FileState; @@ -135,9 +136,14 @@ class PostgreSqlFileserverReclamationIntegrationTest extends CleanupQueuePortCon @BeforeEach void truncate() { enqueueBy = Instant.now().plusSeconds(5); - jdbc.execute( - "TRUNCATE fs_recovery_item, fs_cleanup_item, fs_quota_reservation," - + " fs_verification_result, fs_upload_session, fs_file CASCADE"); + BoundedTruncate.truncateCascade( + postgres.dataSource(), + "fs_recovery_item", + "fs_cleanup_item", + "fs_quota_reservation", + "fs_verification_result", + "fs_upload_session", + "fs_file"); } @Test diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java index 02818b8d..c3617d73 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java @@ -13,6 +13,7 @@ import dev.caskeleton.adapter.outbound.persistence.notification.platform.reposit import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ProviderEventJpaRepository; import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.application.notification.platform.api.CollapseScope; import dev.caskeleton.application.notification.platform.api.CollapseSpec; @@ -134,10 +135,13 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { @BeforeEach void assemble() { jdbc = new JdbcTemplate(database.dataSource()); - jdbc.execute( - "TRUNCATE notification_provider_event, notification_delivery_attempt," - + " notification_recipient_delivery, notification_contact_point, notification_request" - + " CASCADE"); + BoundedTruncate.truncateCascade( + database.dataSource(), + "notification_provider_event", + "notification_delivery_attempt", + "notification_recipient_delivery", + "notification_contact_point", + "notification_request"); transactions = new SpringTransaction(context.getBean(PlatformTransactionManager.class)); RecipientDeliveryJpaRepository recipients = context.getBean(RecipientDeliveryJpaRepository.class); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java index f2bf2152..94c08f64 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; import dev.caskeleton.application.transaction.TransactionPort; @@ -72,7 +73,7 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { @BeforeEach void openContext() { jdbc = new JdbcTemplate(dataSource); - jdbc.execute("TRUNCATE outbox_event"); + BoundedTruncate.truncate(dataSource, "outbox_event"); context = OutboxIntegrationSupport.buildContext( dataSource, event -> {}, Clock.fixed(NOW, ZoneOffset.UTC)); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java index 54f253ca..44871d71 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxRelayResult; @@ -59,7 +60,7 @@ class PostgreSqlOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFencingC @BeforeEach void emptyOutbox() { - new JdbcTemplate(sharedDataSource).execute("TRUNCATE outbox_event"); + BoundedTruncate.truncate(sharedDataSource, "outbox_event"); } @AfterAll diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java index 2e30f995..7ea8c92a 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.transaction; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.transaction.testkit.TransactionPortContract; import dev.caskeleton.application.transaction.testkit.TransactionProbe; @@ -69,7 +70,7 @@ class SpringTransactionContractTest extends TransactionPortContract { @BeforeEach void empty() { - jdbc.execute("truncate transaction_contract_probe"); + BoundedTruncate.truncate(support.dataSource(), "transaction_contract_probe"); } @Override diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/BoundedTruncate.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/BoundedTruncate.java new file mode 100644 index 00000000..51827948 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/BoundedTruncate.java @@ -0,0 +1,204 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.postgresql; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; +import javax.sql.DataSource; + +/** + * Empties tables between integration tests without waiting for good on a lock somebody left. + * + *

A plain {@code TRUNCATE} on a pooled connection runs with the server's {@code lock_timeout}, + * which is 0: no bound. When an earlier test leaves a transaction open on one of the tables, the + * next test's cleanup waits for it until the lane's own timeout ends the run, and the report names + * the cleanup rather than the transaction that stopped it. This runs the {@code TRUNCATE} in one + * transaction after {@code SET LOCAL lock_timeout}, and when the wait runs out it fails with every + * session that holds or awaits a lock on a table of this database. + * + *

{@code SET LOCAL} ends with the transaction: the connection goes back to the pool the code + * under test borrows from, and that code must not inherit the cleanup's bound. Autocommit is put + * back by this class rather than left to the pool, so a data source that does not reset it on + * return gets the connection back as it lent it. + */ +public final class BoundedTruncate { + + /** + * How long the {@code TRUNCATE} may wait for its lock before it fails. + * + *

Twice the 1 s {@code deadlock_timeout} after which PostgreSQL cancels an autovacuum that + * blocks the {@code TRUNCATE}, and a commit still in flight ends in milliseconds: a lock held + * longer is a transaction a test left open. + */ + public static final Duration LOCK_TIMEOUT = Duration.ofSeconds(2); + + /** PostgreSQL's SQLSTATE for a lock wait that ran out its {@code lock_timeout}. */ + private static final String LOCK_NOT_AVAILABLE = "55P03"; + + /** An unquoted table name, optionally schema-qualified: nothing else reaches the statement. */ + private static final Pattern TABLE_NAME = + Pattern.compile("[a-z_][a-z0-9_]*(\\.[a-z_][a-z0-9_]*)?"); + + private BoundedTruncate() {} + + /** + * Empties the named tables, or fails naming the sessions whose locks stopped it. + * + * @throws IllegalStateException when the lock wait ran out, or the {@code TRUNCATE} failed + */ + public static void truncate(DataSource dataSource, String... tables) { + empty(dataSource, "TRUNCATE " + tableList(tables)); + } + + /** + * Empties the named tables and every table that references them. + * + *

{@code CASCADE} also locks the referencing tables it was not given, which is why a failure + * lists the locks on every table of the database, not only the named ones. + * + * @throws IllegalStateException when the lock wait ran out, or the {@code TRUNCATE} failed + */ + public static void truncateCascade(DataSource dataSource, String... tables) { + empty(dataSource, "TRUNCATE " + tableList(tables) + " CASCADE"); + } + + private static String tableList(String... tables) { + Objects.requireNonNull(tables, "tables"); + if (tables.length == 0) { + throw new IllegalArgumentException("name at least one table to truncate"); + } + for (String table : tables) { + if (table == null || !TABLE_NAME.matcher(table).matches()) { + throw new IllegalArgumentException("not an unquoted table name: " + table); + } + } + return String.join(", ", tables); + } + + private static void empty(DataSource dataSource, String truncate) { + Objects.requireNonNull(dataSource, "dataSource"); + try (Connection connection = dataSource.getConnection()) { + boolean autoCommit = connection.getAutoCommit(); + connection.setAutoCommit(false); + Throwable failure = null; + try { + inOneTransaction(connection, truncate); + } catch (Throwable thrown) { + failure = thrown; + throw thrown; + } finally { + restoreAutoCommit(connection, autoCommit, failure); + } + } catch (SQLException failure) { + throw new IllegalStateException("the cleanup's " + truncate + " failed", failure); + } + } + + private static void inOneTransaction(Connection connection, String truncate) throws SQLException { + try (Statement statement = connection.createStatement()) { + try { + statement.execute("SET LOCAL lock_timeout = '" + LOCK_TIMEOUT.toMillis() + "ms'"); + statement.execute(truncate); + connection.commit(); + } catch (SQLException failure) { + // A broken connection fails the rollback too; that must not replace the original failure. + try { + connection.rollback(); + } catch (SQLException rollbackFailure) { + failure.addSuppressed(rollbackFailure); + throw failure; + } + if (!LOCK_NOT_AVAILABLE.equals(failure.getSQLState())) { + throw failure; + } + String holders; + try { + holders = lockHolders(statement); + } catch (SQLException lookFailure) { + failure.addSuppressed(lookFailure); + holders = "unknown, the lookup failed (suppressed below)"; + } + // The lookup opened a transaction of its own; end it here rather than leave it to + // autocommit going back on, which does not happen when the connection was lent without it. + try { + connection.rollback(); + } catch (SQLException endFailure) { + failure.addSuppressed(endFailure); + } + throw new IllegalStateException( + "the cleanup's " + + truncate + + " gave up after waiting " + + LOCK_TIMEOUT.toMillis() + + " ms for a lock. Other sessions locking tables of this database: " + + holders, + failure); + } + } + } + + /** Puts autocommit back; a failure to do so rides on the original failure when there is one. */ + private static void restoreAutoCommit( + Connection connection, boolean autoCommit, Throwable failure) throws SQLException { + try { + connection.setAutoCommit(autoCommit); + } catch (SQLException restoreFailure) { + if (failure == null) { + throw restoreFailure; + } + failure.addSuppressed(restoreFailure); + } + } + + /** Every other session's lock on a table of this database, held or queued, and what it ran. */ + private static String lockHolders(Statement statement) throws SQLException { + List holders = new ArrayList<>(); + try (ResultSet rows = + statement.executeQuery( + """ + SELECT l.pid, n.nspname || '.' || c.relname AS locked_table, l.mode, l.granted, + a.state, + extract(epoch FROM now() - a.xact_start)::int AS open_seconds, + left(a.query, 160) AS last_statement + FROM pg_locks l + JOIN pg_class c ON c.oid = l.relation + JOIN pg_namespace n ON n.oid = c.relnamespace + JOIN pg_stat_activity a ON a.pid = l.pid + WHERE l.locktype = 'relation' + AND l.database = (SELECT oid FROM pg_database WHERE datname = current_database()) + AND c.relkind IN ('r', 'p') + AND n.nspname <> 'information_schema' + AND n.nspname NOT LIKE 'pg\\_%' + AND l.pid <> pg_backend_pid() + ORDER BY l.pid, locked_table, l.mode + """)) { + while (rows.next()) { + String lock = + "pid " + + rows.getInt("pid") + + " " + + rows.getString("mode") + + (rows.getBoolean("granted") ? " held" : " queued") + + " on " + + rows.getString("locked_table") + + ", " + + rows.getString("state"); + int openSeconds = rows.getInt("open_seconds"); + // No transaction start: the holder's transaction ended between reading pg_locks and + // pg_stat_activity while its session stayed connected. A session that disconnected in + // between has no pg_stat_activity row, so the join drops it. + String open = + rows.wasNull() ? ", no transaction open any more" : " for " + openSeconds + " s"; + holders.add(lock + open + ", last statement: " + rows.getString("last_statement")); + } + } + return holders.isEmpty() + ? "none any more; the holder ended between the timeout and this look" + : String.join("; ", holders); + } +} diff --git a/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java b/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java index 962d5b73..ea2f4adb 100644 --- a/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java +++ b/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java @@ -8,10 +8,12 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import com.jayway.jsonpath.JsonPath; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer; import dev.caskeleton.composition.runtime.context.DomainContextConfig; import java.util.List; import java.util.Set; +import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -74,6 +76,8 @@ class DurableOperationCompositionIntegrationTest { @Autowired private JdbcTemplate jdbc; + @Autowired private DataSource dataSource; + @DynamicPropertySource static void runtimeProperties(DynamicPropertyRegistry registry) { Flyway.configure() @@ -89,7 +93,7 @@ class DurableOperationCompositionIntegrationTest { @BeforeEach void empty() { SecurityContextHolder.clearContext(); - jdbc.execute("TRUNCATE durable_operation, outbox_event"); + BoundedTruncate.truncate(dataSource, "durable_operation", "outbox_event"); } @Test -- 2.54.0