Files
clean-architecture-backend-…/docs/jpa/migration-guide.md
T
DongHyeonka f40c03c6d3 fix: 3차 확인 리뷰의 Minor 19건을 고친다
문제: 3차 수정의 확인 리뷰가 새 Important 없이 Minor 19건을 남겼다.
동작에 닿는 것이 셋이다. JDK read-idle watchdog이 공용 ForkJoinPool에서
돌아 그 풀이 바쁘면 300ms timeout이 6초 가까이 늦었다. 붙여 쓴
-x<task>를 verifyStrictLaneStages가 읽지 않아 lane을 뺀 workflow가
통과했다. 사용자 전송이 중간 클래스를 거쳐 @SystemCaller bean을 부르면
ArchUnit 규칙을 지났다. 잠금 대기 검사기는 FK·trigger·REINDEX와
lock_timeout = 0을 못 봤고, 쿼터 보정 SQL은 코드와 다른 모양의 행을
넣었다.

방법: 영역별 4묶음이 맡은 Minor만 test-driven-development 절차로
고쳤다(재리뷰 README 12절).
- watchdog은 전용 데몬 스레드 하나에서 돌고 스트림을 닫으면 작업을
  취소한다. read당 비용은 그대로다(21–24ns).
- 사용자 전송 → @SystemCaller는 직접·간접 의존 모두 거부한다. 리뷰가
  권한 직접 의존 검사는 중간 클래스 하나로 다시 열려서 버렸다.
- 검사기를 보강하면서 새로 걸린 이미 배포된 마이그레이션 5개는 내용을
  바꾸지 않고 동결 목록에 더했다(main과 blob이 같다).
- 비밀 목록 bean은 규칙보다 먼저 만들어 실제 클래스로 검사한다.

위험·한계: 회복 필요 예외 메시지 끝에 scope digest가 붙고 기동 실패
문구가 바뀌어, 문구 전체에 맞추던 로그 매처는 고쳐야 한다. 코드가 든
Redis 계정 참조의 fixture- 검사는 문서로만 막았다(코드로 막으려면 새
의존 edge가 필요하다). failure-retention ≥ replay-ttl 기동 검사는 넣지
않았다. -mx 같은 짧은 플래그 묶음과 graphql 전송 fixture는 남았다.
spotbugsTestFixtures(게이트 밖)의 정규식 경고가 15건으로 늘었다.

검증: ci, 두 빌드의 verifyStrictLaneStages --dry-run, mainCheck,
:integrationCheck, -p optional-platforms ci integrationCheck
performanceCheck, :performanceCheck, :releaseCheck(-PgitRevision),
verify-compose-profile-contracts(18 lane) 첫 실행 통과. watchdog은
공용 풀을 채운 상태에서 300ms 설정이 300ms에 끝나는 것을 쟀다.

Refs: docs/reviews/2026-11-03-rereview/README.md 11·12절, round3/
2026-11-04 03:00:21 +09:00

6.4 KiB

Migration Guide

Design §31-§32. Flyway owns the schema; Hibernate only validates.

Who may change the schema

Environment Mode
local, test, dev migrate at startup with the migration credential
staging, prod deployment-owned migration; the application validates only

Migrating from inside the application in production means every instance of a rolling deploy races to apply the same script, and the loser's failure is indistinguishable from a real one.

ddl-auto is validate or none. Never update: it never drops or narrows anything, so it produces a schema that is neither the old one nor the one the migrations describe — silently, on whichever instance started first.

Validation fails closed and never repairs

At startup Flyway's own validation (and Hibernate ddl-auto=validate) refuses a checksum mismatch, a missing migration, or a schema Hibernate disagrees with. Nothing in the application calls repair. In tests, the testkit's FlywayValidationGate turns a failed ValidateResult into SchemaMismatchException; the migration contract tests use it.

Repair rewrites the schema history table to match whatever scripts are on disk. That resolves the symptom by deleting the evidence: a checksum mismatch means the deployed script differs from the applied one, and the interesting question is which change is missing from this database. Repair makes that question unaskable. It exists only as an explicit admin operation with an operator, a reason, and an approval (design §8.4).

Only Flyway's structured error codes reach the exception. Its messages embed the script path and part of the failing statement.

Bound the lock wait

A migration that locks a table already in use starts with SET LOCAL lock_timeout = '5s';, before the first statement that takes the lock. ALTER TABLE takes the strongest lock there is, which conflicts even with a plain read; a non-concurrent CREATE INDEX takes one that stops every write; UPDATE and DELETE wait on the rows other transactions hold. Unbounded, the migration waits for the oldest open transaction that touched the table — an operator's forgotten BEGIN in psql has no deadline — and every read and write that arrives meanwhile queues behind the migration, holding a pool connection while it waits. With the bound, the migration fails after five seconds, Flyway rolls it back whole, the database stays on the version before it and the new release does not start: a failed deploy instead of an outage. Deploy again when the transaction has ended.

LOCAL, because a plain SET outlives the migration on the pooled connection Flyway borrowed and changes every statement that later runs on it. The value is not zero: lock_timeout = 0 (or DEFAULT, or a later RESET) is no bound at all. A migration with executeInTransaction=false cannot use it — SET LOCAL outside a transaction only warns — so a statement that locks a table goes into a migration that runs in one. A statement on a table the same migration created a moment earlier waits for nothing and needs no bound; CREATE TABLE IF NOT EXISTS does not count, because the table may already be there.

Enforced, not remembered: LockWaitMigrationInspector (persistence-jpa testkit) reads a script — and the .sql.conf beside it — and names the statements from its list that lock an existing table with no bound in force: ALTER TABLE, LOCK TABLE, TRUNCATE, DROP TABLE; CREATE INDEX, DROP INDEX, REINDEX and REFRESH MATERIALIZED VIEW without CONCURRENTLY, CLUSTER, VACUUM FULL; REFERENCES on the table it references, in a new table as much as in an ALTER TABLE (a foreign key locks its parent against writes while it is added); CREATE TRIGGER and DROP TRIGGER on their table; UPDATE and DELETE. It reads text, so a statement outside the list is not checked. MigrationLockWaitTest runs it over every tree this leaf's database runs, SampleMigrationLockWaitTest over the sample's stream; a service stream copies the latter with its own directory. Both find the migrations the way Flyway does, decimal versions (V22_1__) included (VersionedMigrationFiles, testkit). The migrations released before the rule wait unbounded and stay that way (they are applied, and applied files are never edited); the test lists them and refuses any new one. PostgreSqlMigrationLockWaitIntegrationTest (postgresqlMigrationLockWaitIntegrationTest) shows on real PostgreSQL that a bounded migration gives up within the bound while another transaction holds the table, and leaves the version below it. The gRPC ledger's tree lives in the optional build, which cannot reach the testkit: its GrpcOperationLedgerMigrationLockWaitIT runs every ledger migration after V001, read from the tree, against a held ledger instead, so its next migration is checked on real PostgreSQL. The rule came from V21 having the bound and V22, in the same commit, not having it (re-review 2026-11-03 round 2, RR-02-09; round 3, RR3-02-01, RR3-02-03, RR3-02-04).

Concurrent index builds

CREATE INDEX CONCURRENTLY cannot run inside a transaction block, and Flyway wraps migrations in one by default. The migration therefore needs a companion configuration:

# V42__order_index.sql.conf
executeInTransaction=false

The testkit's ConcurrentIndexMigrationInspector checks a script for this in a migration test (nothing checks it at startup), and additionally requires the migration to contain nothing else. A failed concurrent build leaves an invalid index behind; recovering is a single DROP INDEX when the migration did nothing else, and a manual reconstruction of partial state when it did.

An invalid index is not merely useless — the planner ignores it while every write still maintains it. runbooks.md has the query that finds them. Nothing drops them automatically: an invalid index can also mean a build is still running, and the two are indistinguishable from the catalog alone.

Upgrade scenarios

Three, each catching something the others do not:

Scenario Catches
empty an early migration edited to match a later one, no longer applying to a fresh database
previous-release the actual deployment path; the only one exercising this release's migrations
oldest-supported a migration that silently assumes state only recent databases have

Each asserts a data invariant, not just the schema version. A migration that renames a column and loses its contents leaves the version correct and the data gone.