docs(jpa): JPA 운영 문서를 한국어로 옮기고 코드와 맞춘다

문제: `docs/jpa`의 문서 12개가 영어였고 `security.md`도 영어 절이 남아 있었다.
`repository-adaptation.md`는 Spring Boot 버전과 leaf 개수를 복사했다(number 예외).
번역하며 대조하니 지금 코드와 다른 주장이 여럿 있었다.

고친 것:
- 13개를 번역했다. 코드·명령·경로·표 구조는 그대로다. `support-matrix.md`의 DB 표와
  gate 표는 `JpaReleaseRendering`이 읽는 모양(`| PostgreSQL 17 | Stable |`,
  `` | `osiv-disabled` | gate | ``)을 그대로 둔다. 절 번호(§1~§5)는 코드가 인용해 그대로다.
- 다른 문서·코드가 영어 절 제목으로 인용하는 곳("Who may change the schema", "Bound the
  lock wait", "Concurrent index builds", "An invalid index exists", "Associations")은
  한국어 제목 뒤 괄호에 영어를 남겼다.
- 코드에 맞춘 주장:
  - support-matrix: 없는 `JpaPlatformAutoConfiguration.capabilities()` →
    `JpaPlatformReport.platformCapabilities()`. COPY 수준은 보고대로 Advanced.
  - repository-adaptation: leaf 개수·Boot 버전 → registry와 `libs.versions.toml`,
    `src/testkit` → `src/testFixtures`, outbox relay `app-bootstrap` →
    `composition:outbox-relay`, 「build-logic이 없다」 → `src/build-logic` convention
    plugin, 없는 `runtime_memberships`, 없는 `JpaDataSourceSettings`, 여러 major 선택은
    `JpaPlatformContractSupport.start()`가 거부한다(`StablePostgreSqlMatrixContractTest`만
    여러 개를 받는다), 이미지는 `container-images.properties`의 digest.
  - experimental-promotion-checklist: 결과 이름은 지운 gate의 것임을 밝혔다.
- 테스트: `JpaDocumentationContractTest`가 H2 단락의 「운영 보장이 아니」·「PostgreSQL 계약
  증거」와 「알려진 빈틈」을 본다. `PoolLaneClaimTest`는 한국어 금지 문구 셋을 더 본다.
  고친 두 테스트의 영어 `@DisplayName`은 AGENTS.md 규칙대로 한국어로 바꿨다.
- 예외 목록에서 JPA language 줄 12개와 number 줄 2개를 지웠다.

버린 대안: H2 단락의 영어 문구를 괄호로 남겨 단언을 그대로 두기. 독자가 읽는 것은
한국어 문장이므로 단언도 그 문장을 붙잡아야 한다.

위험·한계: `PoolLaneClaimTest`의 한국어 금지 문구는 지금 문서를 기준으로 고른 것이라,
다른 말로 쓴 인증 주장은 잡지 못한다. 영어 문구 검사는 그대로 남아 있다.

검증: 최종 트리 기준(첫 커밋 본문 참고).

검증(desktop, 최종 트리 8295db89):
- `:adapter:outbound:persistence-jpa:check` rc=0(666개 실패 0. `JpaDocumentationContractTest` 4,
  `JpaReleaseRenderingTest` 13, `PoolLaneClaimTest` 3), `:mainCheck` rc=0, `testQualityCheck` rc=0.
- RED: 기준 커밋의 옛 문서에 대면 `JpaDocumentationContractTest`의 H2 단락·알려진 빈틈 2개가 실패한다.
  `PoolLaneClaimTest`는 금지 문구를 더한 것이라 옛 영어 문서에서도 통과한다(RED 없음).
This commit is contained in:
DongHyeonka
2026-11-07 17:56:34 +09:00
parent 5a860e1e6b
commit b1cda0307b
16 changed files with 700 additions and 873 deletions
+29 -38
View File
@@ -1,22 +1,19 @@
# JPA batch write configuration
# JPA batch 쓰기 설정
`HibernateJpaBatchExecutor` is an advanced opt-in. The template does not enable Hibernate batch
write settings globally because statistics and statement reordering add runtime cost even in
applications that never perform bulk writes.
`HibernateJpaBatchExecutor`는 고급 opt-in이다. 템플릿은 Hibernate batch 쓰기 설정을 전역으로 켜지 않는다. 통계와 문장
재정렬은 bulk 쓰기를 한 번도 하지 않는 애플리케이션에도 런타임 비용을 더하기 때문이다.
## What the executor owns
## executor가 가지는 것
A `JpaBatchProfile` owns the JDBC batch size for one batch run. Before the first item is written,
the executor applies `profile.jdbcBatchSize()` to the current Hibernate `Session`. The previous
Session value is restored in `finally`, including failed runs.
`JpaBatchProfile`이 batch 실행 한 번의 JDBC batch 크기를 가진다. executor는 첫 항목을 쓰기 전에
`profile.jdbcBatchSize()`를 지금 Hibernate `Session`에 적용한다. 앞 Session 값은 실패한 실행을 포함해 `finally`에서
되돌린다.
The executor does **not** open a transaction. The application service must enter a
`TransactionPort.inWrite(...)` boundary first.
executor는 트랜잭션을 열지 **않는다**. 애플리케이션 서비스가 먼저 `TransactionPort.inWrite(...)` 경계에 들어가야 한다.
## What the application must configure
## 애플리케이션이 설정할 것
If a profile requests insert or update ordering, the matching Hibernate setting must already be
enabled on the SessionFactory:
profile이 insert나 update 정렬을 요구하면, 맞는 Hibernate 설정이 SessionFactory에 이미 켜져 있어야 한다.
```yaml
spring:
@@ -28,37 +25,31 @@ spring:
generate_statistics: true
```
`hibernate.generate_statistics=true` is required because `BatchExecutionResult` reports measured
flush and prepared-statement deltas. A disabled statistics registry would turn those values into
convincing zeros.
`BatchExecutionResult`가 잰 flush와 prepared statement의 차이를 보고하므로 `hibernate.generate_statistics=true`가 필요하다.
통계 registry가 꺼져 있으면 그 값이 그럴듯한 0이 된다.
The `HibernateStatisticsCollector` must also receive an instrumented `JdbcBatchCounter`.
`HibernateStatisticsCollector.of(sessionFactory)` is intentionally insufficient for this executor:
Hibernate statistics do not expose actual JDBC batch executions.
`HibernateStatisticsCollector`는 계측된 `JdbcBatchCounter`도 받아야 한다. 이 executor에는
`HibernateStatisticsCollector.of(sessionFactory)`가 일부러 모자라다. Hibernate 통계는 실제 JDBC batch 실행을 드러내지 않는다.
`hibernate.default_batch_fetch_size` is unrelated to this write executor. It affects association
fetching and belongs to query/fetch tuning instead.
`hibernate.default_batch_fetch_size`는 이 쓰기 executor와 상관없다. 연관 fetch에 영향을 주고, 쿼리·fetch 조정에 속한다.
## Entity identifier constraint
## 엔티티 식별자 제약
When `JpaBatchProfile.batchingRequired()` is true, an entity using
`GenerationType.IDENTITY` is rejected by `HibernateBatchConfigurationGuard`. Hibernate must issue
each INSERT immediately to obtain the generated identifier, so JDBC insert batching cannot satisfy
that profile.
`JpaBatchProfile.batchingRequired()`가 참이면 `GenerationType.IDENTITY`를 쓰는 엔티티는 `HibernateBatchConfigurationGuard`가
거부한다. Hibernate는 생성된 식별자를 얻으려고 INSERT마다 바로 실행해야 하므로, JDBC insert batching으로는 그 profile을
채울 수 없다.
Prefer a sequence-based identifier when a workload requires insert batching. Keep the sequence
allocation size aligned with the database migration.
insert batching이 필요한 작업에는 sequence 기반 식별자를 쓴다. sequence의 allocation size는 DB 마이그레이션과 맞춰 둔다.
## Failure behavior
## 실패 동작
Configuration is checked before the persister receives the first item:
설정은 persister가 첫 항목을 받기 전에 확인한다.
- missing `hibernate.order_inserts=true` when the profile requests insert ordering: fail;
- missing `hibernate.order_updates=true` when the profile requests update ordering: fail;
- disabled Hibernate statistics: fail;
- missing JDBC batch instrumentation: fail;
- no caller-owned transaction: fail.
- profile이 insert 정렬을 요구하는데 `hibernate.order_inserts=true`가 없다: 실패.
- profile이 update 정렬을 요구하는데 `hibernate.order_updates=true`가 없다: 실패.
- Hibernate 통계가 꺼져 있다: 실패.
- JDBC batch 계측이 없다: 실패.
- 호출자가 가진 트랜잭션이 없다: 실패.
These failures are deliberate. A batch API that silently degrades to one statement per row produces
correct data but false performance evidence, which is harder to detect than a startup or invocation
failure.
이 실패는 일부러다. 행마다 문장 하나로 조용히 떨어지는 batch API는 데이터는 맞지만 성능 증거는 거짓이고, 그것은 기동이나
호출 실패보다 알아채기 어렵다.
+68 -93
View File
@@ -1,117 +1,92 @@
# Entity Mapping Guide
# 엔티티 매핑 가이드
Design §10-§13. The rules here exist because each one has a failure mode that is invisible in review
and expensive in production.
설계서 §10-§13. 여기 있는 규칙마다, 리뷰에서는 보이지 않고 운영에서는 비싼 실패 꼴이 있다.
## The domain owns the model
## 모델은 도메인이 가진다
The platform defines no business entity. Table names, column semantics, keys, unique and check
requirements, associations, cascade rules, lock policy, and soft-delete policy all belong to the
domain module. There is no `GenericRepository<T, ID>` and no platform base repository, because a
single generic API forces every aggregate through the same operations — and one aggregate's later
requirement then changes behaviour for all of them.
플랫폼은 업무 엔티티를 정의하지 않는다. 테이블 이름, 열의 뜻, 키, unique·check 요구, 연관, cascade 규칙, lock 정책,
soft-delete 정책은 모두 도메인 모듈의 것이다. `GenericRepository<T, ID>`도 플랫폼 base repository도 없다. generic API
하나는 모든 aggregate를 같은 연산으로 몰아넣고, 그러면 한 aggregate의 나중 요구가 모두의 동작을 바꾼다.
## Entities must be proxyable
## 엔티티는 proxy가 될 수 있어야 한다
- Not `final`. Hibernate creates a lazy proxy by generating a subclass; a final entity cannot be
subclassed, so *every* association to it loads eagerly whatever the mapping says. Nothing errors.
- A non-private no-arg constructor. The provider instantiates entities reflectively before
populating fields.
- `final`이 아니다. Hibernate는 subclass를 만들어 lazy proxy를 만든다. final 엔티티는 subclass를 만들 수 없으므로 그것으로의
연관은 매핑이 뭐라고 하든 *모두* eager로 읽힌다. 아무 오류도 나지 않는다.
- private이 아닌 인자 없는 생성자. provider는 칸을 채우기 전에 reflection으로 엔티티를 만든다.
`EntityMappingCondition` in the testkit enforces both.
testkit의 `EntityMappingCondition`이 둘을 강제한다.
## Identifiers
## 식별자
Default to a sequence with an `allocationSize` that matches the migration's `INCREMENT BY`. When
they disagree, the provider hands out identifiers the sequence has not reserved and the collision
surfaces later as a primary-key violation under load.
기본은 sequence이고, `allocationSize`는 마이그레이션의 `INCREMENT BY`와 맞춘다. 둘이 다르면 provider가 sequence가 예약하지
않은 식별자를 내주고, 충돌은 나중에 부하에서 primary key 위반으로 드러난다.
`GenerationType.IDENTITY` is supported and limited: the key is assigned on insert, so the provider
must execute each insert immediately to learn it, which disables JDBC insert batching entirely.
`HibernateBatchConfigurationGuard` fails a batch profile that targets an IDENTITY entity rather than
letting the import silently run an order of magnitude slower.
`GenerationType.IDENTITY`는 지원하지만 제한이 있다. 키가 insert 때 정해지므로 provider는 키를 알려고 insert마다 바로
실행해야 하고, 그러면 JDBC insert batching이 아예 꺼진다. `HibernateBatchConfigurationGuard`는 IDENTITY 엔티티를 대상으로
하는 batch profile을, import가 조용히 열 배 느리게 돌게 두는 대신 실패시킨다.
UUIDv7 (`UuidV7Generator`) is the application-side option. It is preferred over UUIDv4 for a primary
key because v4 is uniformly random: every insert lands on a random leaf of the B-tree, so the index
never stays in cache and write amplification grows with the table.
UUIDv7(`UuidV7Generator`)은 애플리케이션 쪽 선택지다. primary key로는 UUIDv4보다 낫다. v4는 고르게 무작위라서 insert마다
B-tree의 무작위 leaf에 떨어지고, 인덱스가 캐시에 머물지 못하며, 쓰기 증폭이 테이블과 함께 커진다.
## Values
## 값
- Enums are `EnumType.STRING` or an explicit converter. **Never** `ORDINAL` — it stores the
constant's position, so inserting a new constant anywhere but the end silently reinterprets every
existing row.
- Money is `BigDecimal` with explicit precision and scale. `double` cannot represent `0.1`, so sums
drift and reconciliation disagrees with the ledger.
- `Duration` goes through a converter that stores milliseconds. The ISO-8601 text form sorts and
compares wrongly in SQL.
- `Instant` and `OffsetDateTime` map differently; a column typed for one cannot faithfully store the
other.
- enum은 `EnumType.STRING`이나 명시적 converter다. `ORDINAL`은 **절대** 쓰지 않는다. 상수의 위치를 저장하므로, 끝이 아닌
곳에 새 상수를 넣으면 기존 행이 모두 조용히 다른 뜻이 된다.
- 금액은 정밀도와 scale을 명시한 `BigDecimal`이다. `double`은 `0.1`을 나타내지 못해서 합계가 어긋나고 맞추기가 장부와
다른 말을 한다.
- `Duration`은 밀리초를 저장하는 converter를 거친다. ISO-8601 문자열 꼴은 SQL에서 정렬과 비교가 틀린다.
- `Instant`와 `OffsetDateTime`은 다르게 매핑된다. 한쪽에 맞춘 열은 다른 쪽을 그대로 저장하지 못한다.
## Associations
## 연관 (Associations)
Map each association from **one side only**. A JPA association between two entities is one foreign
key column. A bidirectional pair (`@ManyToOne` on the child plus `@OneToMany(mappedBy = ...)` on
the parent) stores that one column in two Java fields, and JPA writes only the owning one. The pair
stays consistent only while every caller remembers to update both fields, and nothing fails when
someone forgets.
연관은 **한쪽에서만** 매핑한다. 두 엔티티 사이의 JPA 연관은 foreign key 열 하나다. 양방향 짝(자식의 `@ManyToOne`과 부모의
`@OneToMany(mappedBy = ...)`)은 그 열 하나를 Java 칸 둘에 저장하고, JPA는 소유하는 쪽만 쓴다. 짝은 모든 호출자가 두 칸을
함께 고치는 것을 기억할 때만 맞고, 누가 잊어도 아무것도 실패하지 않는다.
What to use, in order of preference:
쓸 것, 고르는 순서대로:
1. **An ID reference between aggregates.** Hold the other aggregate's identifier as a plain column
(`UUID ownerId`). This is what every production entity in the template does today. Loading the
other aggregate is an explicit repository call, so a cross-aggregate load is visible in the code.
2. **A unidirectional `@ManyToOne` inside one aggregate**, always `fetch = FetchType.LAZY`. JPA's
default for a to-one association is `EAGER`, so every query that loads a child also queries for
its parent — the most common accidental N+1 in a JPA application.
3. **A collection is a query, not a field.** "The children of X" is a repository method
(`findByParentId`, or a fetch-join or projection query that pages in SQL). The query states its
own fetch plan and page, where a mapped collection hides both.
4. **Values the aggregate owns** — a list of tags, a set of codes — are `@ElementCollection`
(`LAZY`), not entities.
1. **aggregate 사이에는 ID 참조.** 다른 aggregate의 식별자를 평범한 열로 든다(`UUID ownerId`). 지금 템플릿의 모든 운영 엔티티가
이렇게 한다. 다른 aggregate를 읽는 것은 명시적인 repository 호출이라, aggregate를 넘는 읽기가 코드에 보인다.
2. **한 aggregate 안에서는 단방향 `@ManyToOne`**, 늘 `fetch = FetchType.LAZY`. JPA의 to-one 기본값은 `EAGER`라서, 자식을
읽는 모든 쿼리가 부모도 조회한다. JPA 애플리케이션에서 가장 흔한 실수 N+1이다.
3. **collection은 칸이 아니라 쿼리다.** 「X의 자식들」은 repository 메서드다(`findByParentId`, 또는 SQL에서 페이지를 나누는
fetch join이나 projection 쿼리). 쿼리는 자기 fetch 계획과 페이지를 말하고, 매핑한 collection은 둘 다 숨긴다.
4. **aggregate가 가진 값**(태그 목록, 코드 집합)은 엔티티가 아니라 `@ElementCollection`(`LAZY`)이다.
A unidirectional `@OneToMany` with its own `@JoinColumn` is the exception, not the default. Use it
only for child entities the root genuinely owns and changes only through itself (the testkit's
`LifecycleParent` and `PagedParent` are this shape). It still costs an `UPDATE` per child when the
join column is nullable, and the collection still loads as a unit. The child then has no
association back to the root — not even a read-only `@ManyToOne` on the same join column
(`insertable = false, updatable = false`): that is the bidirectional pair again, without the
`mappedBy` that names it. If the child needs the root, it holds the root's ID.
자기 `@JoinColumn`이 있는 단방향 `@OneToMany`는 기본이 아니라 예외다. root가 정말 가지고 root를 통해서만 바꾸는 자식
엔티티에만 쓴다(testkit의 `LifecycleParent`와 `PagedParent`가 이 모양이다). join 열이 nullable이면 자식마다 `UPDATE` 한
번이 들고, collection은 여전히 한 덩어리로 읽힌다. 그러면 자식에는 root로 돌아가는 연관이 없다. 같은 join 열에 읽기 전용
`@ManyToOne`(`insertable = false, updatable = false`)도 두지 않는다. 그것은 이름을 붙이는 `mappedBy`만 없을 뿐 다시 양방향
짝이다. 자식이 root가 필요하면 root의 ID를 든다.
`CascadeType.ALL` with `orphanRemoval` is correct only for a child the aggregate genuinely owns.
Between independent aggregates it deletes rows another part of the system still owns — another
reason those are ID references.
`orphanRemoval`과 함께 쓰는 `CascadeType.ALL`은 aggregate가 정말 가진 자식에만 맞다. 독립된 aggregate 사이에서는 시스템의
다른 부분이 아직 가진 행을 지운다. 그것들이 ID 참조인 또 하나의 이유다.
`JpaArchitectureRules.associationsAreMappedFromOneSideOnly()` (testkit) fails the build on every
bidirectional pair, on `@Entity`, `@MappedSuperclass` and `@Embeddable` types: an association that
declares `mappedBy` (only that inverse half is reported), and two entities whose associations point
at each other without `mappedBy` (both halves are reported — the `@JoinColumn` form above, review
RR-03-04). The message says how the pair keeps the link: one join column mapped from both ends, or
the link stored twice — a `@OneToMany` without `@JoinColumn` in a join table beside the child's own
`@ManyToOne` column (what a forgotten `mappedBy` produces), or two `@ManyToMany` each owning a join
table (re-review round 3, RR3-02-05). That last check also refuses two entities that each hold their own foreign key to the
other (`Order.@OneToOne latestInvoice` with `Invoice.@ManyToOne order`). It is not one link mapped
twice, and the message says so; it is refused on purpose, because the two tables then reference each
other: neither row can be inserted or deleted first, one key has to be nullable and written by a
second `UPDATE`, and the entity graph is a cycle. Keep the association on one side and give the other
an ID or a query (re-review round 2, RR-02-15). A class that links to itself is a pair only when a
second member points back the other way (`@ManyToOne parent` with `@OneToMany children`); two
`@ManyToOne` links of a class to itself (a manager and a mentor) pass, because both keys point into
the one table and there are no two tables to order. 이 규칙은 `JpaProductionArchitectureTest`(app-bootstrap
`architectureTest`)가 운영 그래프 전체에 건다.
The failure message names the fields and these alternatives.
`JpaArchitectureRules.associationsAreMappedFromOneSideOnly()`(testkit)는 `@Entity`, `@MappedSuperclass`, `@Embeddable` 타입의
모든 양방향 짝에서 빌드를 실패시킨다. `mappedBy`를 선언한 연관(그 반대쪽 반만 보고한다), 그리고 `mappedBy` 없이 서로를
가리키는 두 엔티티(두 반을 다 보고한다. 위의 `@JoinColumn` 꼴, review RR-03-04)다. 메시지는 짝이 링크를 어떻게 가지는지
말한다. 양 끝에서 매핑한 join 열 하나이거나, 링크를 두 번 저장한 것이다. 두 번 저장한 것은 자식 자신의 `@ManyToOne` 열 옆
join 테이블의, `@JoinColumn` 없는 `@OneToMany`(`mappedBy`를 잊으면 생긴다)이거나, 저마다 join 테이블을 가진 `@ManyToMany`
둘이다(재확인 리뷰 round 3, RR3-02-05). 그 마지막 검사는 서로에게 저마다 foreign key를 든 두 엔티티도 거부한다
(`Order.@OneToOne latestInvoice`와 `Invoice.@ManyToOne order`). 링크 하나를 두 번 매핑한 것은 아니고, 메시지도 그렇게
말한다. 일부러 거부한다. 그러면 두 테이블이 서로를 참조해서, 어느 행도 먼저 넣거나 지울 수 없고, 키 하나는 nullable이어야
하고 두 번째 `UPDATE`로 써야 하며, 엔티티 그래프가 cycle이 된다. 연관은 한쪽에 두고 다른 쪽에는 ID나 쿼리를 준다(재확인
리뷰 round 2, RR-02-15). 자기 자신에 링크하는 클래스는, 두 번째 멤버가 반대로 가리킬 때만 짝이다(`@ManyToOne parent`와
`@OneToMany children`). 자기 자신으로의 `@ManyToOne` 링크 둘(manager와 mentor)은 통과한다. 두 키가 모두 한 테이블을 가리켜서
순서를 정할 두 테이블이 없기 때문이다. 이 규칙은 `JpaProductionArchitectureTest`(app-bootstrap `architectureTest`)가 운영
그래프 전체에 건다. 실패 메시지가 칸 이름과 이 대안들을 알려 준다.
Chosen and rejected:
고른 것과 버린 것:
| Option | Decision | Why |
| 선택지 | 결정 | 이유 |
| --- | --- | --- |
| One side only (ID reference, unidirectional `@ManyToOne`, collection by query), enforced by ArchUnit | Chosen | The link lives in one field, so there is nothing to keep in step. The rule turns a developer-memory convention into a build failure |
| Bidirectional with `mappedBy` and an `addChild`/`removeChild` helper that sets both sides | Rejected | The helper is the only thing keeping the two fields in step, and it must be remembered by every caller, every serializer (cycles in `toString`/JSON) and every cascade decision. A missed update leaves a row unlinked or a graph that disagrees with the database, with no error |
| Ban `@OneToMany` entirely | Rejected for now | It also bans a root-owned child collection, which has no second field to forget. Revisit if a real need for child entities that are read or changed on their own appears — that need is a sign they are a separate aggregate |
| Document only | Rejected | A convention the build does not check is invisible where the mapping is written, and the next copy of the template inherits whatever the examples show |
| 한쪽만(ID 참조, 단방향 `@ManyToOne`, 쿼리로 읽는 collection), ArchUnit으로 강제 | 고름 | 링크가 칸 하나에 있어서 맞춰 둘 것이 없다. 규칙이 개발자의 기억에 맡긴 관례를 빌드 실패로 바꾼다 |
| `mappedBy`와 양쪽을 다 설정하는 `addChild`/`removeChild` helper를 둔 양방향 | 버림 | 두 칸을 맞춰 두는 것은 helper뿐이고, 모든 호출자, 모든 serializer(`toString`·JSON의 cycle), 모든 cascade 결정이 그것을 기억해야 한다. 고치기를 하나 놓치면 링크 없는 행이나 DB와 다른 그래프가 남고, 오류는 없다 |
| `@OneToMany`를 아예 금지 | 지금은 버림 | root가 가진 자식 collection도 막는데, 그것에는 잊을 두 번째 칸이 없다. 자식 엔티티를 따로 읽거나 바꿀 실제 필요가 생기면 다시 본다. 그 필요는 그것이 별도 aggregate라는 신호다 |
| 문서만 | 버림 | 빌드가 확인하지 않는 관례는 매핑을 쓰는 자리에서 보이지 않고, 템플릿의 다음 사본은 예시가 보여 주는 것을 그대로 물려받는다 |
## Entities never leave the transaction
## 엔티티는 트랜잭션 밖으로 나가지 않는다
A controller must not return an entity, or a collection or `Optional` of one. Response serialisation
happens after the transaction closes, so a lazy association touched by the serialiser either throws
or — with OSIV on, which this platform forbids — issues a query from the view layer, one per element.
`EntityExposureCondition` checks generic type arguments, not just the erased return type.
controller는 엔티티를, 또는 엔티티의 collection이나 `Optional`을 돌려주지 않는다. 응답 직렬화는 트랜잭션이 닫힌 뒤에 일어나므로,
serializer가 건드린 lazy 연관은 예외를 던지거나, OSIV가 켜져 있으면(이 플랫폼은 금지한다) view 계층에서 원소마다 쿼리를 낸다.
`EntityExposureCondition`은 지워진 반환 타입만이 아니라 generic 타입 인자까지 확인한다.
+31 -33
View File
@@ -1,45 +1,43 @@
# Experimental Promotion Checklist
# Experimental 승격 점검 목록
A reviewer evaluates this checklist. Every technical item, then the ADR. (The
`ExperimentalPromotionGate` class that encoded it in main code was removed on 2026-09-25; nothing
called it.)
리뷰어가 이 목록을 판정한다. 기술 항목을 모두 본 뒤 ADR을 본다. (이것을 main 코드로 담았던 `ExperimentalPromotionGate`
클래스는 부르는 곳이 없어 2026-09-25에 지웠다.)
## Technical evidence
## 기술 증거
- [ ] **Compatibility** — the Stable contract suite passes on the experimental target, twice, on two
supported patch releases. One passing run is a coincidence.
- [ ] **Security** — for tenancy features, cross-tenant read *and* write are both proven impossible,
including through native SQL, bulk DML, `getReference`, and the second-level cache. A filter
that covers only entity queries covers none of those.
- [ ] **Failure** — connection reuse does not leak tenant context; a failover does not silently route
a read-after-write to a stale replica; the commit-ambiguity scenarios still behave.
- [ ] **Migration** — per-tenant migration is resumable after a partial failure, and rate-limited.
With one schema per tenant, a run is N independent migrations and "it failed" is not an answer.
- [ ] **Performance** — pool capacity, replica lag under load, and per-tenant memory are measured,
not estimated. Database-per-tenant fails as a sum, not as an individual pool.
- [ ] **호환성** — Stable 계약 suite가 experimental 대상에서, 지원하는 patch 릴리스 둘에서, 두 번 통과한다. 한 번의 통과는
우연이다.
- [ ] **보안** — tenancy 기능이면 다른 테넌트의 읽기 *와* 쓰기가 둘 다 불가능함을 증명한다. native SQL, bulk DML,
`getReference`, second-level cache를 통한 것도 포함한다. 엔티티 쿼리만 덮는 필터는 그중 어느 것도 덮지 않는다.
- [ ] **장애** — 연결 재사용이 테넌트 context를 흘리지 않는다. failover가 쓰기 뒤 읽기를 조용히 낡은 replica로 보내지 않는다.
커밋 모호함 시나리오가 여전히 맞게 동작한다.
- [ ] **마이그레이션** — 테넌트별 마이그레이션은 부분 실패 뒤 이어서 할 수 있고, 속도가 제한된다. 테넌트마다 schema가 하나면
실행 한 번은 독립 마이그레이션 N개이고, 「실패했다」는 답이 아니다.
- [ ] **성능** — 풀 용량, 부하에서의 replica 지연, 테넌트별 메모리를 어림하지 않고 잰다. 테넌트마다 DB를 두는 방식은 풀
하나가 아니라 합으로 실패한다.
## Decision
## 결정
- [ ] **Reviewed ADR** — recording what is being promised, the operational burden it carries, and
what would cause it to be withdrawn.
- [ ] **검토한 ADR** — 무엇을 약속하는지, 그것이 지우는 운영 부담, 무엇이 생기면 거두는지를 기록한다.
The ADR is not a formality. The technical suites establish that something works; the ADR records
that the platform should promise it, which is a different question with a different cost.
ADR은 형식이 아니다. 기술 suite는 무언가가 동작함을 세우고, ADR은 플랫폼이 그것을 약속해야 함을 기록한다. 다른 질문이고
비용도 다르다.
## What does not count as evidence
## 증거로 치지 않는 것
- The version being generally available.
- The feature working in one environment.
- A passing suite that skipped because Docker was unavailable.
- A green lane whose assertions were relaxed to make it pass.
- 그 버전이 GA라는 사실.
- 그 기능이 한 환경에서 동작한다는 사실.
- Docker가 없어서 건너뛰고 통과한 suite.
- 통과시키려고 단언을 느슨하게 한 초록 lane.
## Outcomes
## 결과
| Decision | Meaning |
결과 이름은 지운 `ExperimentalPromotionGate`가 쓰던 것이고, 지금은 리뷰어가 판정을 적는 말이다.
| 결정 | 뜻 |
|---|---|
| `BLOCKED_TECHNICAL` | at least one suite has not passed |
| `BLOCKED_MISSING_ADR` | evidence is complete; no reviewed decision exists |
| `ELIGIBLE_FOR_STABLE_REVIEW` | both; Stable review may begin |
| `BLOCKED_TECHNICAL` | 통과하지 않은 suite가 하나 이상 있다 |
| `BLOCKED_MISSING_ADR` | 증거는 다 있고, 검토한 결정이 없다 |
| `ELIGIBLE_FOR_STABLE_REVIEW` | 둘 다 있다. Stable 리뷰를 시작해도 된다 |
The two blocked states are distinct because they need different work: one needs evidence, the other
needs a decision.
막힌 상태 둘을 나누는 이유는 필요한 일이 달라서다. 하나는 증거가, 다른 하나는 결정이 필요하다.
+26 -34
View File
@@ -1,43 +1,35 @@
# Experimental Support Matrix
# Experimental 지원 매트릭스
Experimental code is library code in `dev.caskeleton.adapter.outbound.persistence.experimental`.
Nothing composes it and no setting turns it on: a deployment that wants one of these creates the
entry point in its own adapter code, and that call is the opt-in. None of it is part of the Stable
composition, and `JpaModuleBoundaryTest` keeps Stable packages from depending on it.
Experimental 코드는 `dev.caskeleton.adapter.outbound.persistence.experimental`의 라이브러리 코드다. 그것을 조립하는 것도, 켜는
설정도 없다. 이 중 하나를 원하는 배포는 자기 어댑터 코드에서 진입점을 만들고, 그 호출이 opt-in이다. 어느 것도 Stable 조립에
들어가지 않고, `JpaModuleBoundaryTest`가 Stable 패키지가 그것에 의존하지 못하게 막는다.
| Feature | Entry point | Evidence (PostgreSQL lane unless noted) | State |
| 기능 | 진입점 | 증거(따로 적지 않으면 PostgreSQL lane) | 상태 |
|---|---|---|---|
| Shared-schema multi-tenancy (column) | `tenant.TenantContext`, `tenant.TenantAwareRepositoryGuard` | `TenantColumnIsolationTest` | Experimental |
| 공유 schema multi-tenancy(열) | `tenant.TenantContext`, `tenant.TenantAwareRepositoryGuard` | `TenantColumnIsolationTest` | Experimental |
| PostgreSQL RLS multi-tenancy | `rls.RlsTenantSessionBinder`, `rls.RlsPolicyVerifier` | `RlsIsolationFailureTest` | Experimental |
| Schema-per-tenant | `schema.SchemaMultiTenantConnectionProvider`, `schema.SchemaTenantMigrationOrchestrator` | `SchemaTenantMigrationContractTest` | Experimental |
| Database-per-tenant pool budget | `database.TenantDataSourceRegistry`, `database.TenantPoolBudget` | `TenantPoolCapacityContractTest` | Experimental |
| Consistency-aware read replica | `replica.ConsistencyAwareDataSourceRouter` (you implement `ReplicaLagMonitor`) | `ReadAfterWriteRoutingContractTest` | Experimental |
| Jakarta Persistence 4.0, Hibernate ORM 8, PostgreSQL 19 | none — probes in `.github/workflows/jpa-next.yml` record `NOT_EXECUTABLE` | `Jpa4CompatibilityTest`, `Hibernate8CompatibilityTest`, `PostgreSql19CompatibilityTest` (unit-lane version canaries) | Not executable |
| 테넌트마다 schema | `schema.SchemaMultiTenantConnectionProvider`, `schema.SchemaTenantMigrationOrchestrator` | `SchemaTenantMigrationContractTest` | Experimental |
| 테넌트마다 DB의 풀 예산 | `database.TenantDataSourceRegistry`, `database.TenantPoolBudget` | `TenantPoolCapacityContractTest` | Experimental |
| 일관성을 아는 read replica | `replica.ConsistencyAwareDataSourceRouter`(`ReplicaLagMonitor`는 직접 구현) | `ReadAfterWriteRoutingContractTest` | Experimental |
| Jakarta Persistence 4.0, Hibernate ORM 8, PostgreSQL 19 | 없음 — `.github/workflows/jpa-next.yml`의 probe가 `NOT_EXECUTABLE`을 기록 | `Jpa4CompatibilityTest`, `Hibernate8CompatibilityTest`, `PostgreSql19CompatibilityTest`(unit lane의 버전 canary) | 실행 불가 |
The `backend.jpa.experimental.*` flags and `ExperimentalFeatureGate` that used to front these were
removed on 2026-09-25: no code read the flags from configuration, so setting one did nothing, and
the gate only checked a map the caller built itself.
> 이력: 이것들 앞에 있던 `backend.jpa.experimental.*` 스위치와 `ExperimentalFeatureGate`는 2026-09-25에 지웠다. 어떤 코드도
> 설정에서 스위치를 읽지 않아서 켜도 아무 일이 없었고, gate는 호출자가 스스로 만든 map만 확인했다.
## Known constraints
## 알려진 제약
- Tenant context is fail-closed. An unbound tenant in a shared-schema deployment means a query with
no tenant predicate, which returns every tenant's rows.
- A Hibernate filter is not the security boundary. It does not apply to native SQL, bulk DML,
`getReference`, or the second-level cache.
- RLS requires all three of: `ENABLE ROW LEVEL SECURITY`, `FORCE ROW LEVEL SECURITY` (the owner is
otherwise exempt from its own policies), and a runtime role without `BYPASSRLS`.
- Tenant bindings are transaction-local. A session-local setting survives the connection's return to
the pool.
- `readOnly=true` never routes to a replica on its own. Read-after-write uses a consistency token or
the primary.
- Unavailable replica lag evidence means the primary. Absence of evidence is not evidence of
freshness.
- Per-tenant pools are bounded globally. Fifty tenants with a modest pool each is five hundred
connections against a server that permits a hundred.
- Tenant ids never become metric tags. Tenant cardinality is unbounded by definition.
- 테넌트 context는 닫힌 채 실패한다. 공유 schema 배포에서 테넌트가 묶이지 않으면 테넌트 조건 없는 쿼리가 되고, 모든 테넌트의
행을 돌려준다.
- Hibernate filter는 보안 경계가 아니다. native SQL, bulk DML, `getReference`, second-level cache에 적용되지 않는다.
- RLS에는 셋이 모두 필요하다. `ENABLE ROW LEVEL SECURITY`, `FORCE ROW LEVEL SECURITY`(그렇지 않으면 소유자는 자기 정책에서
빠진다), `BYPASSRLS` 없는 런타임 역할.
- 테넌트 묶기는 트랜잭션 로컬이다. 세션 로컬 설정은 연결이 풀로 돌아간 뒤에도 남는다.
- `readOnly=true`만으로는 replica로 보내지 않는다. 쓰기 뒤 읽기는 일관성 token이나 primary를 쓴다.
- replica 지연 증거를 얻을 수 없으면 primary다. 증거가 없다는 것은 최신이라는 증거가 아니다.
- 테넌트별 풀은 전역으로 제한한다. 적당한 풀을 가진 테넌트 50개는 연결 100개를 허용하는 서버에 대한 연결 500개다.
- 테넌트 id는 메트릭 태그가 되지 않는다. 테넌트 수는 정의상 상한이 없다.
## Lanes never change Stable
## lane은 Stable을 바꾸지 않는다
A compatibility lane publishes nothing and changes no Stable contract. If Hibernate 8 generates
different SQL for the fetch-pagination gate, that is a finding about Hibernate 8 — the 7.x gate keeps
asserting what 7.x must do, because that is what deployments run.
호환성 lane은 아무것도 게시하지 않고 어떤 Stable 계약도 바꾸지 않는다. Hibernate 8이 fetch-pagination gate에 다른 SQL을
만들면 그것은 Hibernate 8에 대한 발견이다. 7.x gate는 7.x가 해야 할 것을 계속 단언한다. 배포가 돌리는 것이 그것이기 때문이다.
+131 -164
View File
@@ -1,198 +1,165 @@
# Migration Guide
# 마이그레이션 가이드
Design §31-§32. Flyway owns the schema; Hibernate only validates.
설계서 §31-§32. 스키마는 Flyway가 가지고, Hibernate는 검증만 한다.
## Who may change the schema
이 문서의 절 셋은 코드와 다른 문서가 영어 제목으로 가리킨다. 그래서 그 절 제목에는 영어 이름을 괄호로 함께 둔다:
「누가 스키마를 바꾸나 (Who may change the schema)」, 「잠금 대기에 상한을 둔다 (Bound the lock wait)」,
「동시 인덱스 빌드 (Concurrent index builds)」.
| Environment | Mode |
## 누가 스키마를 바꾸나 (Who may change the schema)
| 환경 | 방식 |
|---|---|
| local, test, dev | migrate at startup with the migration credential |
| staging, prod | deployment-owned migration; the application validates only |
| local, test, dev | 마이그레이션 자격 증명으로 기동할 때 migrate한다 |
| staging, prod | 배포가 가진 마이그레이션. 애플리케이션은 검증만 한다 |
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.
운영에서 애플리케이션 안에서 migrate하면 rolling deploy의 모든 인스턴스가 같은 스크립트를 적용하려고 경주하고, 진 쪽의
실패는 진짜 실패와 구별되지 않는다.
Whoever runs the migration holds Flyway's PostgreSQL migration lock for the session, not in a
transaction: `flyway.postgresql.transactional.lock=false`. Flyway's default (`true`) keeps a
transaction open until the whole run ends, and a concurrent index build waits for every transaction
older than itself, Flyway's own included — the deploy stops with no error and no time limit
("Concurrent index builds" below). The template sets it for every Flyway it runs: the module
defaults (`config/module-defaults/persistence-jpa.yml`, `spring.flyway.postgresql.transactional-lock:
false`) for the one Spring Boot builds at startup, and `FlywaySchemaPolicy.configure()` for every
stream it builds itself — a service's own stream starts from it too, and `JpaProductionArchitectureTest`
refuses production code that builds a Flyway any other way: calling `Flyway.configure()`, or
constructing a configuration itself (`new FluentConfiguration()`, `new ClassicConfiguration()`, a
subclass of either, or `FluentConfiguration::new`). `new Flyway(...)` over the policy's configuration
is allowed. The deployment-owned migration of
staging and prod is outside this repository: give its tool the same value
(`FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK=false`, or the key above in its configuration file).
마이그레이션을 돌리는 쪽은 Flyway의 PostgreSQL 마이그레이션 잠금을 트랜잭션이 아니라 세션에 둔다:
`flyway.postgresql.transactional.lock=false`. Flyway의 기본값(`true`)은 실행 전체가 끝날 때까지 트랜잭션을 열어 두고,
동시 인덱스 빌드는 Flyway 자신의 것을 포함해 자기보다 오래된 모든 트랜잭션을 기다린다. 그러면 배포가 오류도 시간 상한도
없이 멈춘다(아래 「동시 인덱스 빌드」). 템플릿은 자기가 돌리는 모든 Flyway에 이 값을 둔다. Spring Boot가 기동할 때 만드는
Flyway에는 module defaults(`config/module-defaults/persistence-jpa.yml`, `spring.flyway.postgresql.transactional-lock:
false`)가, 스스로 만드는 stream에는 `FlywaySchemaPolicy.configure()`가 그렇게 한다. 서비스 자신의 stream도 거기서
시작하고, `JpaProductionArchitectureTest`는 다른 방법으로 Flyway를 만드는 운영 코드를 거부한다. `Flyway.configure()`를
부르거나, 설정을 직접 만드는 것(`new FluentConfiguration()`, `new ClassicConfiguration()`, 그 둘의 subclass,
`FluentConfiguration::new`)이다. 정책의 설정 위에 `new Flyway(...)`를 하는 것은 허용한다. staging과 prod의 배포 쪽
마이그레이션은 이 저장소 밖에 있다. 그 도구에도 같은 값을 준다(`FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK=false`, 또는 그 도구
설정 파일의 위 키).
A session lock assumes the connection Flyway takes stays its own for the whole run, which the
template's direct Hikari connection gives. Behind a pooler in transaction mode (PgBouncer
`pool_mode = transaction`) the unlock can reach another server connection and release nothing, and
the next migration waits for a lock that a pooled connection still holds. Run migrations over a
direct connection or a session-mode pool.
세션 잠금은 Flyway가 잡은 연결이 실행 내내 Flyway의 것으로 남는다고 가정한다. 템플릿의 직접 Hikari 연결이 그것을 준다.
트랜잭션 모드 pooler(PgBouncer `pool_mode = transaction`) 뒤에서는 unlock이 다른 서버 연결로 가서 아무것도 풀지 못하고,
다음 마이그레이션은 풀의 연결이 아직 쥔 잠금을 기다린다. 마이그레이션은 직접 연결이나 세션 모드 풀로 돌린다.
`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.
`ddl-auto`는 `validate`나 `none`이다. `update`는 절대 쓰지 않는다. 그것은 아무것도 지우거나 좁히지 않으므로, 옛 스키마도
아니고 마이그레이션이 설명하는 스키마도 아닌 스키마를 만든다. 조용히, 먼저 뜬 인스턴스에서.
## Validation fails closed and never repairs
## 검증은 닫힌 채 실패하고, repair하지 않는다
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.
기동할 때 Flyway 자신의 검증(과 Hibernate `ddl-auto=validate`)이 checksum 불일치, 빠진 마이그레이션, Hibernate가 동의하지
않는 스키마를 거부한다. 애플리케이션의 어떤 것도 `repair`를 부르지 않는다. 테스트에서는 testkit의 `FlywayValidationGate`가
실패한 `ValidateResult`를 `SchemaMismatchException`으로 바꾸고, 마이그레이션 계약 테스트가 그것을 쓴다.
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).
repair는 schema history 테이블을 디스크에 있는 스크립트에 맞춰 다시 쓴다. 그것은 증거를 지워서 증상을 없앤다. checksum
불일치는 배포한 스크립트가 적용된 것과 다르다는 뜻이고, 물어야 할 것은 이 DB에 어느 변경이 빠졌느냐다. repair는 그 질문을
물을 수 없게 만든다. repair는 운영자, 이유, 승인이 있는 명시적 관리 작업으로만 있다(설계서 §8.4).
The one change to the history an operator makes is narrower than repair: after a concurrent index
migration fails, the failed row of that one version is deleted so that the version can run again
("Concurrent index builds" below). Every applied row, and its checksum, stays as it was.
운영자가 이력에 하는 변경은 repair보다 좁은 것 하나다. 동시 인덱스 마이그레이션이 실패한 뒤, 그 버전을 다시 돌릴 수 있게
그 한 버전의 실패 행을 지운다(아래 「동시 인덱스 빌드」). 적용된 행과 그 checksum은 모두 그대로다.
Only Flyway's structured error codes reach the exception. Its messages embed the script path and
part of the failing statement.
예외에는 Flyway의 구조화된 오류 코드만 닿는다. Flyway의 메시지는 스크립트 경로와 실패한 문장 일부를 담는다.
## Bound the lock wait
## 잠금 대기에 상한을 둔다 (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.
이미 쓰는 테이블을 잠그는 마이그레이션은, 잠금을 잡는 첫 문장 전에 `SET LOCAL lock_timeout = '5s';`로 시작한다.
`ALTER TABLE`은 가장 강한 잠금을 잡아 평범한 읽기와도 부딪친다. 동시가 아닌 `CREATE INDEX`는 모든 쓰기를 멈추는 잠금을
잡는다. `UPDATE`와 `DELETE`는 다른 트랜잭션이 쥔 행을 기다린다. 상한이 없으면 마이그레이션은 그 테이블을 건드린 가장 오래된
열린 트랜잭션을 기다린다. psql에서 운영자가 잊은 `BEGIN`에는 마감이 없다. 그사이 도착하는 모든 읽기와 쓰기가 마이그레이션
뒤에 줄을 서고, 기다리는 동안 풀 연결을 쥔다. 상한이 있으면 마이그레이션은 5초 뒤 실패하고, Flyway가 통째로 롤백하고, DB는
그 앞 버전에 남고, 새 릴리스는 뜨지 않는다. 장애 대신 실패한 배포다. 그 트랜잭션이 끝난 뒤 다시 배포한다.
`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.
`LOCAL`인 이유: 평범한 `SET`은 Flyway가 빌린 풀 연결에서 마이그레이션보다 오래 남아, 나중에 그 연결에서 도는 모든 문장을
바꾼다. 값은 0이 아니다. `lock_timeout = 0`(또는 `DEFAULT`, 뒤의 `RESET`)은 상한이 아니다. `executeInTransaction=false`인
마이그레이션은 그것을 쓸 수 없다. 트랜잭션 밖의 `SET LOCAL`은 경고만 하기 때문이다. 그래서 테이블을 잠그는 문장은
트랜잭션 안에서 도는 마이그레이션에 넣는다. 같은 마이그레이션이 방금 만든 테이블에 대한 문장은 기다릴 것이 없어 상한이
필요 없다. `CREATE TABLE IF NOT EXISTS`는 해당하지 않는다. 테이블이 이미 있을 수 있기 때문이다.
Flyway also takes a migration out of its transaction on its own, without a `.sql.conf`: on
PostgreSQL 12 and later, any statement that starts with `VACUUM`, `CREATE [UNIQUE] INDEX
CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `REINDEX [VERBOSE] SCHEMA|DATABASE|SYSTEM`, `CREATE` or
`DROP DATABASE|TABLESPACE|SUBSCRIPTION`, `ALTER SYSTEM` or `DISCARD ALL` (Flyway 11,
`PostgreSQLParser`; words inside parentheses are skipped, so `VACUUM (FULL)` and `REINDEX (VERBOSE)
SCHEMA` count). One such statement puts the whole script outside a transaction. Next to any other
statement — a `SET LOCAL lock_timeout` included — Flyway refuses the migration at deploy under its
default `mixed=false`; a service that sets `mixed=true` gets it run, with the bound silently gone.
Put such a statement in a migration of its own. `REINDEX TABLE|INDEX CONCURRENTLY` is not on
Flyway's list: Flyway runs it in the transaction, PostgreSQL refuses it there, and it needs
`executeInTransaction=false` (below). A locking statement that cannot run in a transaction at all —
`VACUUM FULL`, a non-concurrent `REINDEX SCHEMA|DATABASE|SYSTEM` — can never be bounded this way and
does not belong in a migration: run it by hand as an operations step, outside a deploy, in a psql
session that sets `SET lock_timeout = '5s';` first (the session ends with the step, so the plain
`SET` is the bound there). A `.sql.conf` with `executeInTransaction=true` does not change that: it
keeps the statement and its `SET LOCAL` in the transaction only for PostgreSQL to refuse it at
deploy, and the inspector below refuses it as well.
Flyway는 `.sql.conf` 없이도 스스로 마이그레이션을 트랜잭션 밖으로 뺀다. PostgreSQL 12 이상에서 `VACUUM`, `CREATE [UNIQUE]
INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `REINDEX [VERBOSE] SCHEMA|DATABASE|SYSTEM`, `CREATE`나
`DROP DATABASE|TABLESPACE|SUBSCRIPTION`, `ALTER SYSTEM`, `DISCARD ALL`로 시작하는 문장이 있으면 그렇다(Flyway 11,
`PostgreSQLParser`. 괄호 안의 낱말은 건너뛰므로 `VACUUM (FULL)`과 `REINDEX (VERBOSE) SCHEMA`도 센다). 그런 문장 하나가
스크립트 전체를 트랜잭션 밖에 둔다. 다른 문장(`SET LOCAL lock_timeout` 포함) 옆에 두면 Flyway는 기본값 `mixed=false`에서
배포 때 그 마이그레이션을 거부한다. `mixed=true`로 둔 서비스는 그것을 돌리지만 상한이 조용히 사라진다. 그런 문장은 따로
마이그레이션 하나에 넣는다. `REINDEX TABLE|INDEX CONCURRENTLY`는 Flyway의 목록에 없다. Flyway는 그것을 트랜잭션 안에서
돌리고 PostgreSQL이 거기서 거부하므로 `executeInTransaction=false`가 필요하다(아래). 트랜잭션 안에서 아예 돌 수 없는 잠그는
문장(`VACUUM FULL`, 동시가 아닌 `REINDEX SCHEMA|DATABASE|SYSTEM`)은 이 방법으로 상한을 둘 수 없고 마이그레이션에 넣지 않는다.
배포 밖에서 운영 단계로 손으로 돌린다. 먼저 `SET lock_timeout = '5s';`를 거는 psql 세션에서 한다(세션이 그 단계와 함께
끝나므로 거기서는 평범한 `SET`이 상한이다). `executeInTransaction=true`인 `.sql.conf`도 이것을 바꾸지 못한다. 그 문장과
`SET LOCAL`을 트랜잭션 안에 둘 뿐이고, 배포 때 PostgreSQL이 거부하며, 아래의 inspector도 거부한다.
Enforced, not remembered: `LockWaitMigrationInspector` (persistence-jpa testkit) reads a script —
and the `.sql.conf` beside it, as Flyway reads it (a properties file, `false` in any case), and
otherwise the statements Flyway takes out of the transaction on its own — 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`는 이 leaf의 데이터베이스가 돌리는 모든 트리에 이 검사를 건다. 서비스
스트림은 이 테스트를 복사해 자기 폴더를 넣는다. 이 테스트는 Flyway와 같은 방식으로 마이그레이션을 찾고, 소수
버전(`V22_1__`)도 포함한다(`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; it also compares the inspector's copy of Flyway's list with Flyway itself for the statements it
lists (each is named by the inspector exactly when Flyway refuses it next to a `SET LOCAL`), and
shows a `VACUUM FULL` run under `mixed=true` waiting out a reader despite its `SET LOCAL`. A
statement a Flyway upgrade adds to the list is outside that comparison; `LockWaitMigrationInspectorTest`
pins Flyway's own patterns (`PostgreSQLParser`), so such an upgrade fails the pull request's `ci`
until the copy follows. The gRPC ledger's tree lives in the
optional build, which cannot depend on 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. It finds and orders that tree with the testkit's own
`VersionedMigrationFiles`, which the ledger's `build.gradle` copies into its integration-test sources
at build time (`sharedMigrationFileSources`), so both builds read one definition. A concurrent index
build in that tree runs outside a transaction and is no case for a held ledger: it goes in the
test's `RUN_OUTSIDE_A_TRANSACTION` with its reason, and the same test holds each file listed there to
`ConcurrentIndexMigrationInspector`, copied the same way ("Concurrent index builds"). Every ledger
lane applies the tree one file at a time, as Flyway does, so such a file is not refused inside the
implicit transaction of one string holding many. 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; round 4, RR4-02-01; round 6, RR6-03-02,
RR6-03-03; round 7, RR7-03-01).
기억에 맡기지 않고 강제한다. `LockWaitMigrationInspector`(persistence-jpa testkit)가 스크립트를 읽는다. 옆의 `.sql.conf`도
Flyway처럼 읽고(properties 파일, 대소문자 상관없이 `false`), 그 밖에는 Flyway가 스스로 트랜잭션 밖으로 빼는 문장을 본다.
그리고 상한 없이 이미 있는 테이블을 잠그는, 자기 목록의 문장을 이름 댄다: `ALTER TABLE`, `LOCK TABLE`, `TRUNCATE`,
`DROP TABLE`; `CONCURRENTLY` 없는 `CREATE INDEX`, `DROP INDEX`, `REINDEX`, `REFRESH MATERIALIZED VIEW`, `CLUSTER`,
`VACUUM FULL`; 참조하는 테이블에 대한 `REFERENCES`(새 테이블에서도 `ALTER TABLE`에서도. foreign key는 추가되는 동안 부모
테이블의 쓰기를 막는다); 그 테이블의 `CREATE TRIGGER`와 `DROP TRIGGER`; `UPDATE`와 `DELETE`. 텍스트를 읽으므로 목록 밖의
문장은 확인하지 않는다. `MigrationLockWaitTest`는 이 leaf의 데이터베이스가 돌리는 모든 트리에 이 검사를 건다. 서비스
스트림은 이 테스트를 복사해 자기 폴더를 넣는다. 이 테스트는 Flyway와 같은 방식으로 마이그레이션을 찾고, 소수 버전
(`V22_1__`)도 포함한다(`VersionedMigrationFiles`, testkit). 규칙 전에 나간 마이그레이션은 상한 없이 기다리고 그대로 둔다
(이미 적용됐고, 적용된 파일은 고치지 않는다). 테스트가 그것을 나열하고 새것은 거부한다.
## Concurrent index builds
`PostgreSqlMigrationLockWaitIntegrationTest`(`postgresqlMigrationLockWaitIntegrationTest`)가 실제 PostgreSQL에서 보인다.
다른 트랜잭션이 테이블을 쥔 동안 상한 있는 마이그레이션은 상한 안에 포기하고 그 아래 버전을 남긴다. 또 inspector가 가진
Flyway 목록 사본을 그것이 나열한 문장에 대해 Flyway 자신과 비교하고(inspector는 Flyway가 `SET LOCAL` 옆에서 거부하는 바로
그때 그 문장을 이름 댄다), `mixed=true`에서 돈 `VACUUM FULL`이 `SET LOCAL`에도 불구하고 읽는 쪽을 기다리는 것도 보인다.
Flyway 업그레이드가 목록에 더한 문장은 그 비교 밖이다. `LockWaitMigrationInspectorTest`가 Flyway 자신의 패턴
(`PostgreSQLParser`)을 고정하므로, 그런 업그레이드는 사본이 따라올 때까지 pull request의 `ci`를 실패시킨다.
`CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY` and `REINDEX … CONCURRENTLY` cannot run
inside a transaction block. Flyway runs a script outside a transaction on its own when it holds
`CREATE`/`DROP INDEX CONCURRENTLY` or `REINDEX SCHEMA|DATABASE`, with or without `CONCURRENTLY`
(above). It runs `REINDEX INDEX|TABLE … CONCURRENTLY` — `REINDEX (CONCURRENTLY) TABLE` included — in
the transaction, where PostgreSQL refuses it. `PostgreSqlMigrationLockWaitIntegrationTest` shows the
five forms on real PostgreSQL. Write the companion configuration for every concurrent statement
anyway, so the file says what it needs and no reader has to know Flyway's list:
gRPC ledger의 트리는 optional 빌드에 있어서 testkit에 의존할 수 없다. 그래서 그 `GrpcOperationLedgerMigrationLockWaitIT`가
트리에서 읽은 V001 뒤의 모든 ledger 마이그레이션을 대신 쥔 ledger에 대고 돌리므로, 다음 마이그레이션도 실제 PostgreSQL에서
확인된다. 그 트리를 찾고 순서를 매기는 것은 testkit 자신의 `VersionedMigrationFiles`다. ledger의 `build.gradle`이 빌드 때
그것을 통합 테스트 소스로 복사하므로(`sharedMigrationFileSources`) 두 빌드가 한 정의를 읽는다. 그 트리의 동시 인덱스 빌드는
트랜잭션 밖에서 돌므로 쥔 ledger로 시험할 경우가 아니다. 그런 파일은 이유와 함께 테스트의 `RUN_OUTSIDE_A_TRANSACTION`에
넣고, 같은 테스트가 거기 나열한 파일마다 같은 방식으로 복사한 `ConcurrentIndexMigrationInspector`를 건다(「동시 인덱스
빌드」). 모든 ledger lane은 Flyway처럼 트리를 파일 하나씩 적용하므로, 그런 파일이 여러 문장을 담은 문자열 하나의 암묵적
트랜잭션 안에서 거부되지 않는다.
이 규칙은 같은 커밋에서 V21에는 상한이 있고 V22에는 없었던 데서 나왔다(재확인 리뷰 2026-11-03 round 2, RR-02-09; round 3,
RR3-02-01, RR3-02-03, RR3-02-04; round 4, RR4-02-01; round 6, RR6-03-02, RR6-03-03; round 7, RR7-03-01).
## 동시 인덱스 빌드 (Concurrent index builds)
`CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `REINDEX … CONCURRENTLY`는 트랜잭션 블록 안에서 돌 수 없다. Flyway는
스크립트가 `CREATE`/`DROP INDEX CONCURRENTLY`나 `REINDEX SCHEMA|DATABASE`(`CONCURRENTLY`가 있든 없든)를 담으면 스스로
트랜잭션 밖에서 돌린다(위). `REINDEX INDEX|TABLE … CONCURRENTLY`(`REINDEX (CONCURRENTLY) TABLE` 포함)는 트랜잭션 안에서
돌리고, PostgreSQL이 거기서 거부한다. `PostgreSqlMigrationLockWaitIntegrationTest`가 다섯 꼴을 실제 PostgreSQL에서 보인다.
그래도 모든 동시 문장에 짝 설정을 쓴다. 파일이 자기에게 필요한 것을 말하고, 읽는 사람이 Flyway의 목록을 알 필요가 없다.
```conf
# V42__order_index.sql.conf
executeInTransaction=false
```
Outside a transaction, `CREATE INDEX CONCURRENTLY` and `REINDEX … CONCURRENTLY` still wait until
every transaction older than them has ended. Under Flyway's default lock that includes the
transaction Flyway itself keeps open, and Flyway waits for the build in turn: the deploy never ends,
and the table's other DDL and autovacuum queue behind the build meanwhile. The template's Flyway
holds its lock for the session instead ("Who may change the schema"), so the build waits only for
other transactions; a deployment tool left on Flyway's default stops on the first such migration.
`DROP INDEX CONCURRENTLY` does not wait that way: it waits only for the transactions that hold a
lock on its table. `PostgreSqlConcurrentIndexMigrationIntegrationTest`
(`postgresqlConcurrentIndexMigrationIntegrationTest`) applies both builds as a second deploy, with
the Flyway Spring Boot builds from the module defaults and with `FlywaySchemaPolicy.configure()`,
on real PostgreSQL. The other transactions still count: a long one an operator or a report keeps
open holds the build, and the drop too once it has touched the table, and a file run outside a
transaction cannot bound that wait with `SET LOCAL`. Look for old transactions
(`pg_stat_activity.xact_start`) before deploying one.
트랜잭션 밖에서도 `CREATE INDEX CONCURRENTLY`와 `REINDEX … CONCURRENTLY`는 자기보다 오래된 모든 트랜잭션이 끝날 때까지
기다린다. Flyway 기본 잠금에서는 Flyway 자신이 열어 둔 트랜잭션도 거기 들고, Flyway는 다시 빌드를 기다린다. 배포가 끝나지
않고, 그동안 그 테이블의 다른 DDL과 autovacuum이 빌드 뒤에 줄을 선다. 템플릿의 Flyway는 대신 세션에 잠금을 둔다(「누가
스키마를 바꾸나」). 그래서 빌드는 다른 트랜잭션만 기다린다. Flyway 기본값에 둔 배포 도구는 그런 첫 마이그레이션에서 멈춘다.
`DROP INDEX CONCURRENTLY`는 그렇게 기다리지 않는다. 그 테이블에 잠금을 쥔 트랜잭션만 기다린다.
`PostgreSqlConcurrentIndexMigrationIntegrationTest`(`postgresqlConcurrentIndexMigrationIntegrationTest`)가 두 빌드를 두 번째
배포로, module defaults로 Spring Boot가 만드는 Flyway와 `FlywaySchemaPolicy.configure()`로, 실제 PostgreSQL에 적용한다.
다른 트랜잭션은 여전히 센다. 운영자나 리포트가 열어 둔 긴 트랜잭션은 빌드를 붙잡고, 테이블을 건드린 뒤라면 삭제도 붙잡는다.
트랜잭션 밖에서 도는 파일은 그 대기에 `SET LOCAL`로 상한을 둘 수 없다. 그런 마이그레이션을 배포하기 전에 오래된 트랜잭션
(`pg_stat_activity.xact_start`)을 찾는다.
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.
Next to another statement, a concurrent one makes Flyway refuse the file before any of it runs when
nothing configures it; with `executeInTransaction=false` Flyway commits each statement on its own,
and a failed build leaves the statements before it applied — state to reconstruct by hand.
testkit의 `ConcurrentIndexMigrationInspector`가 마이그레이션 테스트에서 스크립트를 이 관점으로 확인하고(기동 때 확인하는
것은 없다), 그 마이그레이션에 다른 것이 없기를 더 요구한다. 다른 문장 옆에 두면, 아무것도 설정하지 않았을 때 동시 문장은
Flyway가 파일을 하나도 돌리기 전에 거부하게 만든다. `executeInTransaction=false`면 Flyway는 문장마다 따로 커밋하고, 실패한
빌드는 그 앞 문장을 적용된 채 남긴다. 손으로 다시 맞춰야 하는 상태다.
Alone, a failed statement leaves an invalid index and a history row with `success = false` for its
version, and Flyway refuses every later deploy ("Detected failed migration to version …") until that
row is gone: dropping the index is not enough. The recovery is
[migration-failed.md](../runbooks/migration-failed.md) "Recover a failed concurrent index migration":
confirm no build is running, remove the cause, drop the invalid index a failed build or rebuild
left, delete that version's failed row and nothing else, deploy again. A failed `DROP INDEX
CONCURRENTLY` leaves invalid the index it was dropping; the runbook leaves that one for the deploy
again to drop, since dropped by hand it makes the same statement fail. It is not `flyway repair`,
which would also rewrite the remaining rows' checksums. `PostgreSqlConcurrentIndexMigrationIntegrationTest`
(`postgresqlConcurrentIndexMigrationIntegrationTest`) runs the runbook's SQL, read from the runbook,
after a unique build that failed on a duplicate and after a rebuild and a drop cancelled while they
waited for an open transaction, and shows both mixed files above.
혼자 있는 문장이 실패하면 무효 인덱스와 그 버전의 `success = false` 이력 행을 남기고, 그 행이 사라질 때까지 Flyway는 뒤의
모든 배포를 거부한다("Detected failed migration to version …"). 인덱스를 지우는 것만으로는 안 된다. 복구는
[migration-failed.md](../runbooks/migration-failed.md) 「실패한 동시 인덱스 마이그레이션 복구 (Recover a failed concurrent
index migration)」다. 도는 빌드가 없는지 확인하고, 원인을 없애고, 실패한 빌드나 재빌드가 남긴 무효 인덱스를 지우고, 그
버전의 실패 행만 지우고, 다시 배포한다. 실패한 `DROP INDEX CONCURRENTLY`는 지우던 인덱스를 무효로 남긴다. runbook은 그것을
다시 배포가 지우도록 남긴다. 손으로 지우면 같은 문장이 실패하기 때문이다. 이것은 `flyway repair`가 아니다. repair는 남은 행의
checksum도 다시 쓴다. `PostgreSqlConcurrentIndexMigrationIntegrationTest`(`postgresqlConcurrentIndexMigrationIntegrationTest`)가
runbook에서 읽은 runbook의 SQL을, 중복으로 실패한 unique 빌드 뒤와, 열린 트랜잭션을 기다리다 취소된 재빌드와 삭제 뒤에 돌리고,
위의 섞인 파일 둘도 보인다.
An invalid index is not merely useless — the planner ignores it while every write still maintains
it. [runbooks.md](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.
무효 인덱스는 쓸모없기만 한 게 아니다. planner는 그것을 무시하는데 모든 쓰기는 여전히 그것을 유지한다. 찾는 쿼리는
[runbooks.md](runbooks.md)에 있다. 아무것도 그것을 자동으로 지우지 않는다. 무효 인덱스는 아직 도는 빌드를 뜻할 수도 있고,
카탈로그만으로는 둘을 구별할 수 없다.
## 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 |
| `empty` | 뒤 마이그레이션에 맞추려고 고친 앞 마이그레이션이 새 DB에 더는 적용되지 않음 |
| `previous-release` | 실제 배포 경로. 이 릴리스의 마이그레이션을 돌리는 유일한 시나리오 |
| `oldest-supported` | 최근 DB에만 있는 상태를 몰래 가정하는 마이그레이션 |
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.
시나리오마다 스키마 버전만이 아니라 데이터 불변식을 단언한다. 열 이름을 바꾸면서 내용을 잃은 마이그레이션은 버전은 맞고
데이터는 사라진 채로 남는다.
+35 -44
View File
@@ -1,58 +1,49 @@
# Observability
# 관측
Design §37. What is measured, and what must never appear in a measurement.
설계서 §37. 무엇을 재고, 측정에 무엇이 절대 나타나면 안 되나.
## What is emitted by default
## 기본으로 내는 것
Nothing JPA-specific. No composition constructs a `MeterRegistry`-backed observation for the
platform, and `SpringTransaction` records no transaction metric. The `jpa.transaction.*` meters
this page used to list (`duration`, `rollback`, `timeout`, `completion.unknown`) were produced by
`JpaTransactionObservation`, which nothing constructed; it was removed on 2026-09-25
(`docs/capability-status.md`). Transaction outcomes are visible through the shared persistence error
codes and the application's own metrics, not through a JPA meter.
JPA 고유의 것은 없다. 어떤 조립도 플랫폼에 `MeterRegistry` 기반 observation을 만들지 않고, `SpringTransaction`은 트랜잭션
메트릭을 기록하지 않는다. 트랜잭션 결과는 JPA meter가 아니라 공유 영속성 오류 코드와 애플리케이션 자신의 메트릭으로 보인다.
## Query metrics — only when the caller asks
> 이력: 이 문서가 전에 적던 `jpa.transaction.*` meter(`duration`, `rollback`, `timeout`, `completion.unknown`)는
> `JpaTransactionObservation`이 만들었는데, 그것을 만드는 곳이 없어서 2026-09-25에 지웠다(`docs/capability-status.md`).
`jpa.query.duration` and `jpa.query.rows` are recorded by `MicrometerQueryObservation`, and only
when a service passes it to a library executor that accepts a `QueryObservation`
(`JpaStreamExecutor`, `HibernateBulkDmlExecutor`). The default is `NoopQueryObservation`. Rows are
measured as well as duration because a query that issues one statement and hydrates twenty thousand
rows is fast per statement and catastrophic per request — a duration metric alone reports it as
merely slow.
## 쿼리 메트릭 — 호출자가 요청할 때만
## Bounded tags, always
`jpa.query.duration`과 `jpa.query.rows`는 `MicrometerQueryObservation`이 기록한다. 서비스가 `QueryObservation`을 받는 라이브러리
executor(`JpaStreamExecutor`, `HibernateBulkDmlExecutor`)에 그것을 넘길 때만이다. 기본값은 `NoopQueryObservation`이다. 걸린
시간뿐 아니라 행도 재는 이유가 있다. 문장 하나를 내고 행 2만 개를 채우는 쿼리는 문장으로는 빠르고 요청으로는 재앙이다. 걸린
시간 메트릭만으로는 그저 느리다고 보고된다.
Every meter `MicrometerQueryObservation` records carries exactly five tags: persistence unit,
operation, query, outcome, failure category (`JpaMetricTags`). All five are registered identifiers,
validated by `LowCardinality` at construction rather than at the registry — so an unbounded value
fails where it was introduced instead of surviving until a dashboard stops loading.
## 태그는 늘 상한이 있다
Never a tag: entity id, tenant id, SQL parameter, exception message, JDBC URL. Each is unbounded, so
each creates a time series per row or per failure; several are also the data the platform keeps out
of logs, which a metrics backend would store just as durably and export just as widely.
`MicrometerQueryObservation`이 기록하는 meter는 모두 태그를 정확히 다섯 가진다. persistence unit, operation, query, outcome,
failure category(`JpaMetricTags`)다. 다섯 다 등록된 식별자이고, registry가 아니라 만들 때 `LowCardinality`가 검증한다. 그래서
상한 없는 값은 대시보드가 안 열릴 때까지 살아남지 않고, 들어온 자리에서 실패한다.
## Query names in SQL
절대 태그가 아닌 것: entity id, tenant id, SQL 파라미터, 예외 메시지, JDBC URL. 하나하나가 상한이 없어서 행마다나 실패마다
시계열을 만든다. 몇은 플랫폼이 로그에서도 빼는 데이터이고, 메트릭 backend는 그것을 로그만큼 오래 저장하고 넓게 내보낸다.
`JpaRepositoryFragmentSupport` sets the registered query name as the `org.hibernate.comment` hint;
Hibernate writes it into the SQL only when `hibernate.use_sql_comments=true`. The alternative is
`NamedStatementInspector`, which prefixes a statement with the query name bound by
`JpaStreamExecutor`, `JpaKeysetQuerySupport` or `JpaRepositoryFragmentSupport.observing(..)`.
Neither is on by default: a deployment enables the inspector with
`spring.jpa.properties.hibernate.session_factory.statement_inspector=dev.caskeleton.adapter.outbound.persistence.hibernate.NamedStatementInspector`.
The comment then travels into `pg_stat_activity`, `auto_explain`, and the slow-query log. Without it,
"which endpoint issues this query" is answered by grepping the codebase for fragments of SQL.
## SQL 안의 쿼리 이름
## Diagnostics
`JpaRepositoryFragmentSupport`는 등록한 쿼리 이름을 `org.hibernate.comment` hint로 둔다. Hibernate는
`hibernate.use_sql_comments=true`일 때만 그것을 SQL에 쓴다. 다른 길은 `NamedStatementInspector`다. `JpaStreamExecutor`,
`JpaKeysetQuerySupport`, `JpaRepositoryFragmentSupport.observing(..)`이 묶은 쿼리 이름을 문장 앞에 붙인다. 둘 다 기본으로 꺼져
있다. 배포는
`spring.jpa.properties.hibernate.session_factory.statement_inspector=dev.caskeleton.adapter.outbound.persistence.hibernate.NamedStatementInspector`로
inspector를 켠다. 그러면 주석이 `pg_stat_activity`, `auto_explain`, slow query 로그로 간다. 그것이 없으면 「어느 엔드포인트가 이
쿼리를 내나」는 코드에서 SQL 조각을 grep해서 답한다.
`SqlDiagnosticRedactor.redact(sql)` removes string literals, numbers, and anything email-shaped. It is
a utility for code that is about to log SQL; nothing in the platform logs SQL through it. Redaction
is blunt on purpose: preserving "harmless" values would require knowing which columns hold personal
data.
## 진단
## The actuator endpoint
`SqlDiagnosticRedactor.redact(sql)`은 문자열 literal, 숫자, 이메일 모양의 모든 것을 지운다. SQL을 곧 로그에 쓸 코드를 위한
도구다. 플랫폼 안의 어떤 것도 그것을 거쳐 SQL을 로그에 쓰지 않는다. 지우기는 일부러 거칠다. 「해롭지 않은」 값을 남기려면
어느 열이 개인정보를 담는지 알아야 한다.
`jpaplatform` reports database major version, provider version, schema version, OSIV state, runtime
role verification, and capability levels. It reports no JDBC URL, no username, no SQL, and no entity
catalog — an actuator endpoint is reachable by anyone who reaches the management port, and each of
those would be a free reconnaissance answer. It is read-only: an endpoint that could trigger a
migration or a repair would be an admin capability exposed over HTTP.
## actuator 엔드포인트
`jpaplatform`은 DB major 버전, provider 버전, 스키마 버전, OSIV 상태, 런타임 역할 검증, capability 수준을 보고한다. JDBC URL,
사용자 이름, SQL, 엔티티 목록은 보고하지 않는다. actuator 엔드포인트는 management 포트에 닿는 누구나 닿을 수 있고, 그 하나하나가
공짜 정찰 답이 된다. 읽기 전용이다. 마이그레이션이나 repair를 일으킬 수 있는 엔드포인트는 HTTP로 드러난 관리 capability가 된다.
+25 -32
View File
@@ -1,50 +1,43 @@
# PostgreSQL Extensions
# PostgreSQL 확장 기능
Design §8.3, §21, §30. What the platform uses beyond portable JPA, and what each is guarded by.
설계서 §8.3, §21, §30. 플랫폼이 이식 가능한 JPA 너머에서 무엇을 쓰고, 각각을 무엇이 지키나.
Everything here is core PostgreSQL. No server extension is required.
여기 있는 것은 모두 PostgreSQL core다. 서버 extension은 필요 없다.
## Locking
## 잠금
`SELECT ... FOR UPDATE` with a finite bound, always. `PostgreSqlLockOptions` refuses an unbounded
lock request because it waits as long as the holder holds it, turning one slow transaction into a
pile-up of blocked connections.
`SELECT ... FOR UPDATE`에는 늘 유한한 상한을 둔다. `PostgreSqlLockOptions`는 상한 없는 잠금 요청을 거부한다. 쥔 쪽이 쥐는 만큼
기다리므로, 느린 트랜잭션 하나가 막힌 연결 더미가 된다.
`NOWAIT` and a wait timeout are separate requests, not two spellings of one — modelling them as a
single field with a magic zero is how "no wait" becomes "wait forever".
`NOWAIT`와 대기 시간 상한은 같은 것의 두 표기가 아니라 다른 요청이다. 둘을 마법의 0을 가진 칸 하나로 모델링하면 「기다리지
않음」이 「영원히 기다림」이 된다.
`55P03` (lock not available) and `40P01` (deadlock) drive opposite recovery and are never collapsed:
the first leaves the transaction alive and the caller in control; the second has already been rolled
back by the server.
`55P03`(잠금을 얻을 수 없음)과 `40P01`(교착)은 반대 복구로 이어지므로 합치지 않는다. 앞의 것은 트랜잭션을 살려 두고 호출자에게
통제를 남긴다. 뒤의 것은 서버가 이미 롤백했다.
## JSONB
`JsonDocument` carries a schema name and version alongside the payload. A JSONB column is schemaless
at the database level, so without an envelope the only record of what a stored document means is the
code that wrote it — and a document written two releases ago is indistinguishable from a current one.
`JsonDocument`는 payload와 함께 schema 이름과 버전을 싣는다. JSONB 열은 DB 수준에서 schema가 없으므로, envelope가 없으면 저장된
문서가 무엇을 뜻하는지 기록한 것은 그것을 쓴 코드뿐이다. 두 릴리스 전에 쓴 문서와 지금 문서를 구별할 수 없다.
The payload never carries a Java class name. Type metadata in a JSONB column is a deserialization
gadget: whoever can write a row chooses the class the reader instantiates.
payload에는 Java 클래스 이름을 절대 싣지 않는다. JSONB 열의 타입 메타데이터는 deserialization gadget이다. 행을 쓸 수 있는 누구나
읽는 쪽이 만들 클래스를 고른다.
Query paths are registered. A JSON path is part of the SQL text and cannot be bound, so forwarding a
request field into one is concatenating untrusted input into a statement. Values are always bound.
쿼리 경로는 등록한다. JSON 경로는 SQL 문장의 일부라 묶을 수 없으므로, 요청 칸을 그것에 넘기면 믿을 수 없는 입력을 문장에 이어
붙이는 것이다. 값은 늘 묶는다.
## Arrays and ranges
## 배열과 범위
Arrays are built with `Connection.createArrayOf`, never by formatting a literal — hand-formatting is
where quoting bugs live, and a tag containing a comma changes the array's shape rather than its
content.
배열은 literal을 꾸미지 않고 `Connection.createArrayOf`로 만든다. 손으로 꾸미면 quoting 버그가 생기고, 쉼표가 든 태그는 배열의
내용이 아니라 모양을 바꾼다.
`PgRange` models both endpoints as independently optional and independently inclusive, because that
is what a PostgreSQL range is. Whether `[09:00, 10:00)` and `[10:00, 11:00)` overlap depends on the
bracket, not the values, and a pair of `timestamptz` columns cannot express it.
`PgRange`는 두 끝을 저마다 선택적으로, 저마다 포함 여부를 따로 모델링한다. PostgreSQL range가 그렇기 때문이다.
`[09:00, 10:00)`과 `[10:00, 11:00)`이 겹치는지는 값이 아니라 괄호가 정하고, `timestamptz` 열 한 쌍으로는 그것을 나타낼 수 없다.
## COPY (J4 admin)
`COPY` bypasses the Persistence Context, entity callbacks, version checks, and Envers entirely. That
is why it is fast and why it is an admin capability with a registered statement, a bounded stream, a
row and byte cap, a finite server-side `statement_timeout`, and a named operator.
`COPY`는 Persistence Context, 엔티티 callback, 버전 확인, Envers를 모두 건너뛴다. 그래서 빠르고, 그래서 관리 capability다. 등록한
문장, 상한 있는 stream, 행·바이트 상한, 유한한 서버 쪽 `statement_timeout`, 이름 있는 운영자가 필요하다.
The registry accepts only `COPY ... FROM STDIN`. `COPY ... FROM '/path'` reads a file on the
*database server* as the server's OS user; it is superuser-only for exactly that reason and does not
belong behind an application API.
registry는 `COPY ... FROM STDIN`만 받는다. `COPY ... FROM '/path'`는 *DB 서버*의 파일을 서버 OS 사용자로 읽는다. 바로 그
이유로 superuser 전용이고, 애플리케이션 API 뒤에 둘 것이 아니다.
+41 -53
View File
@@ -1,75 +1,63 @@
# Query and Fetch Guide
# 쿼리와 fetch 가이드
Design §23-§28. How queries are chosen, bounded, and proven.
설계서 §23-§28. 쿼리를 어떻게 고르고, 제한하고, 증명하나.
## Named queries
## 이름 있는 쿼리
Every registered query carries a `QueryName`. It is the tag `MicrometerQueryObservation` records
under and the SQL comment that appears in `pg_stat_activity` and the slow-query log — which is the
only thing that connects a statement on the server back to the use case that issued it. Neither is on
by default; [observability.md](observability.md) says how a deployment turns each on. The format rejects raw
SQL for a reason: a metric tag built from a query string is unbounded by construction, and one built
from a parameterised value leaks row data into telemetry.
등록한 쿼리는 모두 `QueryName`을 가진다. 그것은 `MicrometerQueryObservation`이 기록하는 태그이고, `pg_stat_activity`와
slow query 로그에 나타나는 SQL 주석이다. 서버의 문장을 그것을 낸 use case와 잇는 것은 그것뿐이다. 둘 다 기본으로 꺼져
있다. 배포가 각각을 켜는 법은 [observability.md](observability.md)에 있다. 형식이 원본 SQL을 거부하는 데는 이유가 있다. 쿼리
문자열로 만든 메트릭 태그는 처음부터 상한이 없고, 파라미터 값으로 만든 것은 행 데이터를 원격 측정으로 흘린다.
## Fetch plans, not eager mappings
## eager 매핑이 아니라 fetch 계획
N+1 is solved per use case with a registered entity graph, not by making an association `EAGER` in
the mapping. The eager fix repairs the one query that needed it and imposes the extra join on every
other query against that entity, including the ones that only wanted the id.
N+1은 매핑에서 연관을 `EAGER`로 만들어서가 아니라 use case마다 등록한 entity graph로 푼다. eager 고침은 그것이 필요했던 쿼리
하나를 고치고, 그 엔티티에 대한 다른 모든 쿼리에 추가 join을 지운다. id만 원했던 쿼리까지.
`fetchgraph` and `loadgraph` are different: a fetch graph is exhaustive (attributes outside it are
lazy whatever the mapping says), a load graph is additive. Choosing the wrong one produces either
missing data or the amplification the graph was meant to avoid.
`fetchgraph`와 `loadgraph`는 다르다. fetch graph는 빠짐없는 목록이고(그 밖의 속성은 매핑이 뭐라고 하든 lazy다), load graph는
더하는 것이다. 잘못 고르면 데이터가 빠지거나, graph가 피하려던 증폭이 생긴다.
## Measuring, not guessing
## 짐작하지 말고 잰다
`QueryMeasurement` records statements, hydrated entities, rows, fetches, and elapsed time. Statement
count alone cannot distinguish the two failures that matter:
`QueryMeasurement`는 문장, 채운 엔티티, 행, fetch, 걸린 시간을 기록한다. 문장 수만으로는 중요한 두 실패를 가릴 수 없다.
- **N+1** — many statements, few rows.
- **Cartesian fetch** — one statement, an enormous number of rows.
- **N+1** — 문장은 많고 행은 적다.
- **Cartesian fetch** — 문장은 하나이고 행은 엄청나게 많다.
A suite asserting only on statement count passes the second one every time.
문장 수만 단언하는 suite는 두 번째를 늘 통과시킨다.
## Pagination
## 페이지 나누기
Offset pagination makes the database walk and discard `n` rows before returning any. Keyset
pagination replaces it:
offset 페이지 나누기는 DB가 무엇이든 돌려주기 전에 `n`행을 지나가며 버리게 한다. keyset 페이지 나누기가 그것을 대신한다.
- The predicate is lexicographic. For an ordering of `(createdAt, id)`, "after `(t, x)`" is
`createdAt < t OR (createdAt = t AND id < x)` — **not** `createdAt <= t AND id < x`, which reads
plausibly and silently drops rows from the middle of the result set.
- The ordering must end in a unique column. Without one, a page boundary inside a run of equal
values duplicates and skips rows.
- `size + 1` rows are fetched and `size` returned. That extra row answers `hasNext` without a count
query, which would be a second full scan whose answer is stale on arrival.
- 조건은 사전순이다. `(createdAt, id)` 정렬에서 「`(t, x)` 다음」은 `createdAt < t OR (createdAt = t AND id < x)`다.
`createdAt <= t AND id < x`가 **아니다.** 그것은 그럴듯해 보이지만 결과 중간의 행을 조용히 빠뜨린다.
- 정렬은 unique 열로 끝나야 한다. 그렇지 않으면 같은 값이 이어지는 구간 안의 페이지 경계가 행을 중복하고 건너뛴다.
- `size + 1`행을 읽고 `size`를 돌려준다. 그 한 행이 count 쿼리 없이 `hasNext`에 답한다. count 쿼리는 두 번째 전체 scan이고,
답이 도착할 때 이미 낡았다.
Cursors are signed. An unsigned cursor is client-controlled ordering state: rewriting it lets a
caller seek to arbitrary keys.
cursor에는 서명한다. 서명 없는 cursor는 클라이언트가 다루는 정렬 상태다. 그것을 고치면 호출자가 아무 키로나 건너뛸 수 있다.
## Sorting
## 정렬
Client sort parameters are mapped through `SafeSortRegistry`, never passed through. A sort field
reaches the query as part of the ORDER BY clause rather than as a bound value, so forwarding the
client's string means the client writes part of the statement. `JpaSort.unsafe` has no call site in
this platform.
클라이언트의 정렬 파라미터는 그대로 넘기지 않고 `SafeSortRegistry`로 매핑한다. 정렬 칸은 묶은 값이 아니라 ORDER BY 절의
일부로 쿼리에 닿으므로, 클라이언트의 문자열을 넘기면 클라이언트가 문장의 일부를 쓰게 된다. `JpaSort.unsafe`는 이 플랫폼에서
부르는 곳이 없다.
The registry's tie-breaker is always appended, because a sort that does not end in a unique column
has no total order and paging over a non-total order duplicates and skips rows.
registry의 tie-breaker는 늘 덧붙인다. unique 열로 끝나지 않는 정렬은 전체 순서가 없고, 전체 순서가 아닌 것으로 페이지를
나누면 행이 중복되고 건너뛰어진다.
## Streaming
## streaming
A JPA `Stream` is a live cursor holding a `ResultSet`, a statement, and a connection. `JpaStreamExecutor`
consumes it inside a try-with-resources and never returns it, because a stream returned past the
transaction boundary is a connection leak that presents as unrelated timeouts elsewhere. A read-only
transaction is required: streaming inside a write transaction pins a write connection for the whole
traversal.
JPA `Stream`은 `ResultSet`, 문장, 연결을 쥔 살아 있는 cursor다. `JpaStreamExecutor`는 그것을 try-with-resources 안에서 다 쓰고
절대 돌려주지 않는다. 트랜잭션 경계 밖으로 돌려준 stream은 연결 누수이고, 다른 곳의 상관없어 보이는 시간 초과로 나타난다.
읽기 전용 트랜잭션이 필요하다. 쓰기 트랜잭션 안의 streaming은 순회 내내 쓰기 연결을 붙잡는다.
## Batching
## batching
Configuring `hibernate.jdbc.batch_size` proves nothing. `BatchExecutionResult.jdbcBatches` comes from
counting real `executeBatch()` calls at the JDBC layer, because an IDENTITY generator, an interleaved
select, or a mid-loop flush disables batching while the configuration still says it is on.
`hibernate.jdbc.batch_size`를 설정한 것은 아무것도 증명하지 않는다. `BatchExecutionResult.jdbcBatches`는 JDBC 층에서 실제
`executeBatch()` 호출을 세서 나온다. IDENTITY generator, 끼어든 select, 반복 중간의 flush는 설정이 켜져 있다고 말하는 동안
batching을 꺼 버리기 때문이다.
Flush and clear are separate boundaries. Flushing alone sends the statements and keeps every entity
in the Persistence Context — the classic bulk-import out-of-memory.
flush와 clear는 다른 경계다. flush만 하면 문장은 보내지만 모든 엔티티를 Persistence Context에 남긴다. 대량 import의 전형적인
메모리 부족이다.
+102 -120
View File
@@ -1,165 +1,147 @@
# JPA Relational Persistence Platform — Repository Adaptation Contract
# JPA 관계형 영속성 플랫폼 — 저장소 대응 계약
**Design source:** `docs/design/2026-08-11-jpa-persistence-platform-design.md`
**Stable plan source:** `docs/history/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md`
**Experimental plan source:** `docs/history/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md`
**설계 출처:** `docs/design/2026-08-11-jpa-persistence-platform-design.md`
**Stable 계획 출처:** `docs/history/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md`
**Experimental 계획 출처:** `docs/history/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md`
The design package states its own adaptation rule (§3.2): the assumed package paths and Gradle
structure are explicit implementation *assumptions* made because the real Backend Skeleton
repository was not supplied. Before implementing, paths are adjusted to the repository's existing
conventions and root package while the public contracts and policy semantics are preserved.
설계 패키지는 자기 대응 규칙을 스스로 밝힌다(§3.2). 가정한 패키지 경로와 Gradle 구조는 실제 Backend Skeleton 저장소를
받지 못해서 둔 명시적 구현 *가정*이다. 구현 전에 공개 계약과 정책 의미는 지키면서 경로를 저장소의 기존 관례와 root 패키지에
맞춘다.
This file is the single record of *how* that mapping was performed. Only paths, build DSL, and
composition-root ownership changed. Public contracts, policy order, retry semantics, and error
semantics are implemented as specified.
이 파일은 그 대응을 *어떻게* 했는지 적는 유일한 기록이다. 바뀐 것은 경로, 빌드 DSL, 조립 루트 소유뿐이다. 공개 계약, 정책
순서, 재시도 의미, 오류 의미는 명세대로 구현했다.
## 1. Why the module layout differs
## 1. 모듈 배치가 다른 이유
The plan assumes a greenfield library with 18 Stable Gradle projects under `modules/jpa/` plus 7
Experimental projects under `modules/jpa-experimental/`. This repository is a Clean Architecture
template whose **fail-closed registry** (`src/config/architecture/modules.json`, enforced by
`src/settings.gradle` and `verifyCleanArchitectureDependencies`) declares **exactly 19 leaf
identities**, and `src/settings.gradle` throws when the registry does not contain exactly 19
modules. Creating 25 more Gradle projects would violate HARD-STOP #5 in `AGENTS.md`.
계획은 `modules/jpa/` 아래 Stable Gradle 프로젝트 18개와 `modules/jpa-experimental/` 아래 Experimental 프로젝트 7개를 둔
새 라이브러리를 가정한다. 이 저장소는 **fail-closed registry**(`src/config/architecture/modules.json`)를 가진 Clean
Architecture 템플릿이다. `src/settings.gradle`은 registry를 읽고 검증한 뒤 등록된 프로젝트만 들이고,
`verifyCleanArchitectureDependencies`가 그 밖의 edge를 막는다. leaf 목록은 registry가 정한다. 계획의 Gradle 프로젝트를
새로 만들면 `AGENTS.md`의 HARD-STOP #5를 어긴다.
Therefore the plan's library modules become **package boundaries inside the registered leaf**
`:adapter:outbound:persistence-jpa`, with two exceptions driven by this repository's own rules.
This is the same adaptation already applied to the HTTP client platform
(`docs/httpclient/repository-adaptation.md`).
그래서 계획의 라이브러리 모듈은 등록 leaf `:adapter:outbound:persistence-jpa` **안의 패키지 경계**가 된다. 예외는 이 저장소
자신의 규칙에서 나온 둘이다. HTTP 클라이언트 플랫폼에 이미 한 것과 같은 대응이다(`docs/httpclient/repository-adaptation.md`).
| Plan module | Repository home | Reason |
| 계획 모듈 | 저장소 위치 | 이유 |
|---|---|---|
| `jpa-spring-boot-starter` | `:adapter:outbound:persistence-jpa` (`…persistence.autoconfigure`, `…persistence.startup`) | Relational persistence is a capability module selected by one build line (`AGENTS.md` capability rules): the leaf registers its own auto-configuration, startup validation, actuator view and shipped settings, and the default composition does not carry it. Use-case assembly over its ports (the outbox relay) stays in `app-bootstrap`. |
| `jpa-testkit`, `jpa-testkit-postgresql`, `jpa-testkit-migration`, `jpa-testkit-queryplan` | `:adapter:outbound:persistence-jpa` `src/testkit/java/**/testkit` | The plan forbids production modules depending on the testkit. A source set whose dependencies are declared only on test configurations gives the same guarantee without a new Gradle project, and more than one lane consumes it. |
| `jpa-spring-boot-starter` | `:adapter:outbound:persistence-jpa` (`…persistence.autoconfigure`, `…persistence.startup`) | 관계형 영속성은 빌드 한 줄로 고르는 capability 모듈이다(`AGENTS.md` capability 규칙). leaf가 자기 auto-configuration, 기동 검증, actuator view, 내보내는 설정을 등록하고, 기본 조립은 그것을 싣지 않는다. 그 port 위의 use case 조립(outbox relay)은 `composition:outbox-relay`에 있다. |
| `jpa-testkit`, `jpa-testkit-postgresql`, `jpa-testkit-migration`, `jpa-testkit-queryplan` | `:adapter:outbound:persistence-jpa` `src/testFixtures/java/**/testkit` | 계획은 운영 모듈이 testkit에 의존하는 것을 막는다. 의존을 test 설정에만 선언한 source set이 새 Gradle 프로젝트 없이 같은 보장을 주고, 여러 lane이 그것을 쓴다. |
The package boundary is enforced by `JpaModuleBoundaryTest`. It holds a closed catalog of the
production root's direct child packages, compares that catalog against the tree for exact equality,
checks every observed top-level edge against the declared ones, and rejects cycles.
패키지 경계는 `JpaModuleBoundaryTest`가 강제한다. 운영 root의 바로 아래 자식 패키지를 닫힌 목록으로 들고, 그 목록을
트리와 정확히 같은지 비교하고, 관찰한 최상위 edge를 모두 선언한 것과 대조하고, cycle을 거부한다.
This used to be a stronger claim than the test. The catalog listed thirteen packages while the tree
held twenty-two, so nine — `audit`, `config`, `failure`, `fileserver`, `h2`, `idempotency`, `lock`,
`notification`, `outbox` — were governed by nothing, and a `transaction → postgresql` /
`postgresql → transaction` cycle passed. Both are closed now, and the catalog's exact-equality check
is what keeps a new package from being green by omission.
> 이력: 전에는 문서의 주장이 테스트보다 강했다. 목록은 패키지 13개였는데 트리에는 22개가 있어서, 아홉 개(`audit`,
> `config`, `failure`, `fileserver`, `h2`, `idempotency`, `lock`, `notification`, `outbox`)를 아무것도 다스리지 않았고
> `transaction → postgresql` / `postgresql → transaction` cycle이 통과했다. 둘 다 닫았다. 새 패키지가 빠져서 초록이 되지
> 않게 막는 것은 목록의 정확히-같음 검사다.
**Known gap.** The catalog governs top-level packages. Sub-package edges inside one top-level
package are not checked, and the target tree in the review's JPA-023 (a `capability/*` layout) is
not implemented — the notification configuration facade is the first step toward it.
**알려진 빈틈.** 목록은 최상위 패키지를 다스린다. 한 최상위 패키지 안의 하위 패키지 edge는 확인하지 않는다. 리뷰
JPA-023의 목표 트리(`capability/*` 배치)는 구현하지 않았다. 알림 설정 facade가 그쪽으로 가는 첫걸음이다.
## 2. Package mapping
## 2. 패키지 대응
Root package: `io.backend.skeleton.jpa` → `dev.caskeleton.adapter.outbound.persistence`.
root 패키지: `io.backend.skeleton.jpa` → `dev.caskeleton.adapter.outbound.persistence`.
| Plan module | Plan package | Repository package |
| 계획 모듈 | 계획 패키지 | 저장소 패키지 |
|---|---|---|
| `jpa-core-api` | `…jpa.api` (+ `.capability`, `.error`, `.query`, `.transaction`) | `dev.caskeleton.adapter.outbound.persistence.api` (+ same subpackages) |
| `jpa-core-api` | `…jpa.api` (+ `.capability`, `.error`, `.query`, `.transaction`) | `dev.caskeleton.adapter.outbound.persistence.api` (+ 같은 하위 패키지) |
| `jpa-transaction` | `…jpa.transaction` | `…persistence.transaction` |
| `jpa-spring-data` | `…jpa.springdata` | `…persistence.springdata` |
| `jpa-querydsl` | `…jpa.querydsl` | `…persistence.querydsl` |
| `jpa-hibernate` | `…jpa.hibernate` (+ `.batch`, `.bulk`, `.stateless`) | `…persistence.hibernate` (+ same subpackages) |
| `jpa-postgresql` | `…jpa.postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.write`) | `…persistence.postgresql` (+ same subpackages except `.write`, removed 2026-09-25) |
| `jpa-hibernate` | `…jpa.hibernate` (+ `.batch`, `.bulk`, `.stateless`) | `…persistence.hibernate` (+ 같은 하위 패키지) |
| `jpa-postgresql` | `…jpa.postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.write`) | `…persistence.postgresql` (+ `.write`를 뺀 같은 하위 패키지. `.write`는 2026-09-25에 지움) |
| `jpa-postgresql-copy` | `…jpa.postgresql.copy` | `…persistence.postgresql.copy` |
| `jpa-migration-flyway` | `…jpa.migration` | `…persistence.migration` |
| `jpa-auditing` | `…jpa.auditing` | none — removed; `…persistence.audit.AuditableEntity` is the one audit mechanism |
| `jpa-auditing` | `…jpa.auditing` | 없음 — 지웠다. `…persistence.audit.AuditableEntity`가 유일한 감사 방식이다 |
| `jpa-envers` | `…jpa.envers` | `…persistence.envers` |
| `jpa-cache-hibernate` | `…jpa.cache` | `…persistence.cache` |
| `jpa-observability` | `…jpa.observation` | `…persistence.observation` |
| `jpa-security` | `…jpa.security` | `…persistence.security` |
| `jpa-spring-boot-starter` | `…jpa.autoconfigure` | `…persistence.autoconfigure`, `…persistence.startup` |
| `jpa-testkit*` | `…jpa.testkit` (+ `.id`, `.mapping`, `.lifecycle`, `.query`, `.fetch`, `.postgresql`, `.migration`, `.queryplan`, `.failure`, `.pool`, `.release`) | `…persistence.testkit` (+ same subpackages), `testkit` source set |
| `jpa-experimental/*` | `…jpa.experimental` (+ `.tenant`, `.rls`, `.schema`, `.database`, `.replica`, `.next`) | `…persistence.experimental` (+ same subpackages except `.next`, removed 2026-09-25) |
| `jpa-testkit*` | `…jpa.testkit` (+ `.id`, `.mapping`, `.lifecycle`, `.query`, `.fetch`, `.postgresql`, `.migration`, `.queryplan`, `.failure`, `.pool`, `.release`) | `…persistence.testkit` (+ 같은 하위 패키지), `testFixtures` source set |
| `jpa-experimental/*` | `…jpa.experimental` (+ `.tenant`, `.rls`, `.schema`, `.database`, `.replica`, `.next`) | `…persistence.experimental` (+ `.next`를 뺀 같은 하위 패키지. `.next`는 2026-09-25에 지움) |
The existing `…persistence.transaction` and `…persistence.postgresql` packages already hold this
leaf's `TransactionPort` implementation and PostgreSQL vendor composition. The platform types are
**additive**: no existing type was renamed, moved, or replaced, and no plan type collides with an
existing name.
이미 있던 `…persistence.transaction`과 `…persistence.postgresql` 패키지는 이 leaf의 `TransactionPort` 구현과 PostgreSQL
vendor 조립을 이미 가지고 있다. 플랫폼 타입은 **더하기만** 했다. 이름을 바꾸거나 옮기거나 대신한 기존 타입은 없고, 기존
이름과 부딪치는 계획 타입도 없다.
## 3. Test-suite mapping
## 3. 테스트 suite 대응
The plan declares seven JVM test suites (`test`, `integrationTest`, `contractTest`,
`migrationTest`, `failureTest`, `performanceTest`, `compatibilityTest`). This leaf already owns a
Docker-backed `postgresqlIntegrationTest` source set and its readiness Gradle tasks are registered
as strict lanes in this leaf's `build.gradle`; `JpaReadinessRegistryTest` holds the readiness cards
to those lanes (it replaced the build-tools `verifyJpaReadinessRegistry`).
계획은 JVM 테스트 suite 일곱을 선언한다(`test`, `integrationTest`, `contractTest`, `migrationTest`, `failureTest`,
`performanceTest`, `compatibilityTest`). 이 leaf는 이미 Docker를 쓰는 `postgresqlIntegrationTest` source set을 가지고,
그 readiness Gradle 태스크는 이 leaf의 `build.gradle`에 strict lane으로 등록돼 있다. `JpaReadinessRegistryTest`가 readiness
card를 그 lane과 대조한다(build-tools의 `verifyJpaReadinessRegistry`를 대신했다).
| Plan suite | Repository lane |
| 계획 suite | 저장소 lane |
|---|---|
| `test` | `src/test` — hermetic unit lane, `./gradlew :adapter:outbound:persistence-jpa:test` |
| `contractTest`, `integrationTest`, `migrationTest`, `failureTest`, `compatibilityTest` | `src/postgresqlIntegrationTest` — real PostgreSQL containers; selected by the `jpaPlatform*` Gradle tasks |
| `performanceTest` | `src/jpaPlatformPerformanceTest` — pool and `REQUIRES_NEW` connection behaviour, run by `jpaPlatformPoolContractTest`; never part of `check`. The source set keeps the plan's name; the lane asserts behaviour rather than measuring, and no numeric performance bound is claimed anywhere from it. |
| `test` | `src/test` — 밀폐된 unit lane, `./gradlew :adapter:outbound:persistence-jpa:test` |
| `contractTest`, `integrationTest`, `migrationTest`, `failureTest`, `compatibilityTest` | `src/postgresqlIntegrationTest` — 실제 PostgreSQL 컨테이너. `jpaPlatform*` Gradle 태스크가 고른다 |
| `performanceTest` | `src/jpaPlatformPerformanceTest` — 풀과 `REQUIRES_NEW` 연결 동작. `jpaPlatformPoolContractTest`가 돌리고, `check`에는 절대 들어가지 않는다. source set은 계획의 이름을 그대로 쓴다. 이 lane은 측정하지 않고 동작을 단언하며, 그로부터 어떤 성능 수치도 주장하지 않는다. |
Docker-dependent lanes fail closed rather than skipping, matching the existing
`PostgreSqlReadinessSupport.assertDockerAvailable()` convention in this leaf.
Docker가 필요한 lane은 건너뛰지 않고 닫힌 채 실패한다. 이 leaf의 기존 관례 `PostgreSqlReadinessSupport.assertDockerAvailable()`과
같다.
## 4. Other deliberate substitutions
## 4. 그 밖에 일부러 바꾼 것
| Plan assumption | Repository reality | Adaptation |
| 계획의 가정 | 저장소의 실제 | 대응 |
|---|---|---|
| Gradle Kotlin DSL, `build-logic` convention plugin, `jpa-library-conventions.gradle.kts` | Groovy DSL, root `src/build.gradle` conventions (spotless google-java-format, checkstyle, SpotBugs + FindSecBugs, ErrorProne, `-Werror`, one-type-per-file), `LockMode.STRICT` dependency locking | Source sets and dependencies declared in `src/adapter/outbound/persistence-jpa/build.gradle`; `gradle.lockfile` regenerated with `resolveAndLockAll --write-locks`. |
| Spring Boot 4.1 dependency management, Spring Data JPA 4.1 | Repository baseline is Spring Boot 4.0.8 | Versions are inherited from the repository BOM and never pinned per module, exactly as the plan requires ("do not override Hibernate/Flyway/Hikari versions outside the Boot BOM"). |
| Hibernate ORM 7.4 is the Stable provider | Boot 4.0.0 resolves `org.hibernate.orm:hibernate-core:7.1.8.Final` | The *declared* Stable provider baseline of the design stays 7.4 in `HibernateProviderPolicy`; the runtime provider version is read from Hibernate itself and reported. The collection-fetch-pagination gate runs against whatever provider the BOM resolves, and `HibernateProviderPolicy.driftsFromDeclaredBaseline()` makes the difference visible instead of hiding it behind a green check. |
| PostgreSQL 16·17·18 Stable matrix | This leaf's existing evidence image is `postgres:16-alpine` | `PostgreSqlVersion` declares exactly PG 16, 17, 18. The default lane runs the repository's existing 16 image; 17 and 18 are selected by `-Pjpa.matrix.versions=16,17,18`, and an unknown or empty selection is an error rather than a skip. |
| `settings.gradle.kts` module registration | Fail-closed 19-leaf registry | No registry change: leaf identity, Gradle path, allowed dependencies, and runtime memberships are unchanged. |
| Gradle Kotlin DSL, `build-logic` convention plugin, `jpa-library-conventions.gradle.kts` | Groovy DSL, `src/build-logic`의 convention plugin(Java로 씀: spotless google-java-format, checkstyle, SpotBugs + FindSecBugs, ErrorProne, `-Werror`, 파일 하나에 타입 하나), `LockMode.STRICT` 의존성 잠금 | source set과 의존성은 `src/adapter/outbound/persistence-jpa/build.gradle`에 선언했다. `gradle.lockfile`은 `resolveAndLockAll --write-locks`로 다시 만들었다. |
| Spring Boot 4.1 의존성 관리, Spring Data JPA 4.1 | 저장소 기준선은 `src/gradle/libs.versions.toml`의 Spring Boot 버전이다 | 버전은 저장소 BOM에서 물려받고 모듈마다 고정하지 않는다. 계획이 요구하는 그대로다("do not override Hibernate/Flyway/Hikari versions outside the Boot BOM"). |
| Hibernate ORM 7.4가 Stable provider | 저장소 BOM이 `org.hibernate.orm:hibernate-core:7.1.8.Final`을 푼다(release registry의 `stable-tested-baseline`) | 설계의 *선언* Stable provider 기준선은 `HibernateProviderPolicy`에서 7.4로 남는다. 런타임 provider 버전은 Hibernate 자신에게서 읽어 보고한다. collection-fetch-pagination gate는 BOM이 푸는 provider에서 돌고, `HibernateProviderPolicy.driftsFromDeclaredBaseline()`이 차이를 초록 검사 뒤에 숨기지 않고 드러낸다. |
| PostgreSQL 16·17·18 Stable matrix | 컨테이너 이미지는 `src/config/testing/container-images.properties`에 digest로 고정한다 | `PostgreSqlVersion`이 PG 16, 17, 18을 정확히 선언한다. 기본 lane은 16이고, 다른 major는 `-Pjpa.matrix.versions=<major>`로 고른다. 계약 suite(`JpaPlatformContractSupport.start()`)는 JVM 하나에 major 하나만 받는다. 여러 major를 한 번에 받는 것은 `StablePostgreSqlMatrixContractTest`뿐이다. 모르는 값이나 빈 선택은 건너뛰지 않고 오류다. |
| `settings.gradle.kts` 모듈 등록 | fail-closed registry | registry는 바꾸지 않았다. leaf 신원, Gradle path, 허용 의존은 그대로다. |
| `infra/jpa/{postgres,roles,toxiproxy}` | 이 repo는 운영 인프라 파일을 두지 않는다(2026-11-07 소유자 결정) | 2026-11-07에 지웠다(쓰는 곳이 없거나 운영 인프라 파일). 운영 DB 조건은 `docs/jpa/security.md`로 옮겼다. |
| `docs/jpa/**`, `docs/adr/ADR-JPA-*`, `.github/workflows/jpa-*.yml` | Repository already owns `docs/` and `.github/workflows/` | Created at the same repository-relative paths. |
| release blocking aggregate | `jpaReleaseQualification` (persistence-jpa `build.gradle`) over `persistence-jpa/release/release-registry.json`, run per PostgreSQL major by the `jpa-release-gate` job in `.github/workflows/release.yml` | The registry names the blocking lanes; Gradle defines how each lane runs; CI only schedules the matrix. | |
| Per-task `git add` + `git commit` | `AGENTS.md`: commit policy is `human-only`; agents do not stage, commit, amend, or push | Implementation is delivered unstaged. This is the only plan step intentionally not executed, and it is recorded here. |
| Querydsl as an optional module dependency | Querydsl is not part of this repository's dependency set | `querydsl` is implemented against the plan's contracts with the Querydsl types kept behind `compileOnly`, so the Stable runtime classpath never carries Querydsl and a deployment opting in adds the artifact itself. |
| Hibernate Envers as a module dependency | Envers is not part of this repository's dependency set | Same treatment as Querydsl: `compileOnly` + explicit opt-in, matching the plan's "Envers is opt-in and never enabled by a global base class". |
| `build-logic/src/test/kotlin/JpaModuleBoundaryTest.kt` | There is no `build-logic` project and no Kotlin source set; module boundaries are enforced by the registry itself | `verifyCleanArchitectureDependencies` plus `:app-bootstrap:architectureTest` assert the same property against `src/config/architecture/modules.json`, which is the authority the plan's test would have had to duplicate. |
| `PostgreSqlRuntimeRoleVerifierIntegrationTest` (Task 45) | The security lane is one suite in this leaf rather than a per-module `integrationTest` | `PostgreSqlSecurityContractTest` (tag `jpa-security`) exercises `PostgreSqlRuntimeRoleVerifier.verify` and `.requireSafe` against a real restricted role on a real server. |
| `JpaSafetyProperties`, `JpaDataSourceProperties` | `NamingConventionTest` requires every `@ConfigurationProperties` type to end in `Settings` or `Policy` | Renamed to `JpaSafetySettings` and `JpaDataSourceSettings`. The bound property prefixes and every field are unchanged; only the class names move to this repository's convention. |
| `docs/jpa/**`, `docs/adr/ADR-JPA-*`, `.github/workflows/jpa-*.yml` | 저장소가 이미 `docs/`와 `.github/workflows/`를 가진다 | 같은 저장소 상대 경로에 만들었다. |
| 릴리스를 막는 집계 | `persistence-jpa/release/release-registry.json` 위의 `jpaReleaseQualification`(persistence-jpa `build.gradle`). `.github/workflows/release.yml`의 `jpa-release-gate` job이 PostgreSQL major마다 돌린다 | registry가 막는 lane을 이름 대고, Gradle이 lane마다 도는 법을 정하고, CI는 matrix 일정만 잡는다. | |
| task마다 `git add` + `git commit` | `AGENTS.md`: 커밋 정책은 `human-only`다. 에이전트는 stage, commit, amend, push를 하지 않는다 | 구현은 stage하지 않은 채로 넘겼다. 일부러 하지 않은 계획 단계는 이것 하나이고, 여기에 기록한다. |
| Querydsl을 선택 모듈 의존성으로 | Querydsl은 이 저장소의 의존성 묶음에 없다 | `querydsl`은 계획의 계약대로 구현하되 Querydsl 타입을 `compileOnly` 뒤에 둔다. 그래서 Stable 런타임 classpath에는 Querydsl이 없고, 쓰기로 한 배포가 artifact를 직접 더한다. |
| Hibernate Envers를 모듈 의존성으로 | Envers는 이 저장소의 의존성 묶음에 없다 | Querydsl과 같다. `compileOnly` + 명시적 opt-in. 계획의 "Envers is opt-in and never enabled by a global base class"와 맞는다. |
| `build-logic/src/test/kotlin/JpaModuleBoundaryTest.kt` | `src/build-logic`은 있지만 Kotlin source set은 없다 | 패키지 경계는 이 leaf의 `JpaModuleBoundaryTest`(§1)가, leaf 경계는 `verifyCleanArchitectureDependencies`와 `:app-bootstrap:architectureTest`가 `src/config/architecture/modules.json`을 정본으로 강제한다. |
| `PostgreSqlRuntimeRoleVerifierIntegrationTest` (Task 45) | 보안 lane은 모듈마다의 `integrationTest`가 아니라 이 leaf의 suite 하나다 | `PostgreSqlSecurityContractTest`(tag `jpa-security`)가 실제 서버의 실제 제한 역할에 대고 `PostgreSqlRuntimeRoleVerifier.verify`와 `.requireSafe`를 돌린다. |
| `JpaSafetyProperties`, `JpaDataSourceProperties` | `NamingConventionTest`는 모든 `@ConfigurationProperties` 타입 이름이 `Settings`나 `Policy`로 끝나기를 요구한다 | `JpaSafetySettings`로 이름을 바꿨다. 묶는 속성 prefix와 모든 칸은 그대로이고 클래스 이름만 이 저장소 관례로 옮겼다. `JpaDataSourceProperties`에 해당하는 설정 클래스는 지금 없다. datasource 검사는 `JpaDataSourceProfileValidator`가 한다. |
### Types relocated to keep the dependency direction legal
### 의존 방향을 지키려고 옮긴 타입
The plan's module map forbids `jpa-core-api` from depending on any other platform module. Three
value-only types the design places in a downstream module are consumed by a core contract, so they
live in the core here instead. Each is a pure value with no framework dependency, so the relocation
costs nothing and the alternative — a core contract importing an adapter package — would break the
boundary the module map exists to hold.
계획의 모듈 지도는 `jpa-core-api`가 다른 플랫폼 모듈에 의존하는 것을 막는다. 설계가 하위 모듈에 둔 값 타입 셋을 core 계약이
쓰므로, 여기서는 core에 둔다. 셋 다 framework 의존이 없는 순수 값이라 옮기는 비용이 없다. 대안인, core 계약이 어댑터 패키지를
import하는 것은 모듈 지도가 지키려는 경계를 깬다.
| Type | Plan module | Repository package | Consumed by |
| 타입 | 계획 모듈 | 저장소 패키지 | 쓰는 곳 |
|---|---|---|---|
| `TransactionCompletionEvidence` | `jpa-transaction` | `…persistence.api.transaction` | `TransactionCompletionUnknownException` (design §17.3 types the field) |
| `ConstraintCode` | `jpa-postgresql` | `…persistence.api.error` | `ConstraintViolationDetails` (design §22.4) |
| `SqlExceptionSqlStateResolver` | `jpa-transaction` | `…persistence.api.error` | the PostgreSQL translators |
| `TransactionCompletionEvidence` | `jpa-transaction` | `…persistence.api.transaction` | `TransactionCompletionUnknownException`(설계서 §17.3이 칸의 타입을 정한다) |
| `ConstraintCode` | `jpa-postgresql` | `…persistence.api.error` | `ConstraintViolationDetails`(설계서 §22.4) |
| `SqlExceptionSqlStateResolver` | `jpa-transaction` | `…persistence.api.error` | PostgreSQL translator들 |
The ArchUnit rule pack (`JpaArchitectureRules`, `EntityMappingCondition`, `EntityExposureCondition`)
is placed in the `testkit` source set rather than in `…persistence.security` production code. ArchUnit
is a test library; putting the rule pack in `main` would drag it onto every deployment's runtime
classpath to serve code that only ever runs in a test.
ArchUnit 규칙 묶음(`JpaArchitectureRules`, `EntityMappingCondition`, `EntityExposureCondition`)은 `…persistence.security` 운영
코드가 아니라 `testFixtures` source set에 둔다. ArchUnit은 테스트 라이브러리다. 규칙 묶음을 `main`에 두면 테스트에서만 도는
코드를 위해 모든 배포의 런타임 classpath에 그것을 끌고 간다.
### 실제 서버에서 계약이 찾은 것
### Findings the contracts produced against a real server
설계의 규칙 둘이 조금 틀리게 적혀 있었고, 그것을 보여 준 것은 컨테이너 lane이다. 설계서 본문은 여전히 옛 내용이라 여기에
기록한다.
Two of the design's rules turned out to be stated slightly wrong, and the container lanes are what
showed it. Both are recorded here because the design text still reads the old way.
- **§17.2 커밋 모호함은 SQLSTATE class `08`만이 아니다.** 커밋이 진행 중인 backend에 `pg_terminate_backend`를 하면 연결
class 상태가 아니라 `57P01`(`admin_shutdown`)을 보고하고, 그것이 도착할 때 커밋 기록은 이미 WAL에 있을 수 있다. 이것을
담았던 classifier(`CommitFailureClassifier`)는 2026-09-25에 두 번째 트랜잭션 엔진과 함께 지웠다.
`PostgreSqlConcurrencyFailureContractTest`가 여전히 주입 지점을 고정한다.
- **schema-per-tenant 상태는 실행 결과로 짐작하지 말고 다시 읽어야 한다.** `MigrateResult`의 대상 버전은 이미 최신이던
tenant에서 비어 있어서, 그것을 기록하면 부분 rollout 중 마이그레이션한 tenant를 안 한 것으로 보고했다.
`SchemaTenantMigrationOrchestrator`가 이제 tenant의 schema history에서 적용된 버전을 읽는다.
- **§17.2 commit ambiguity is not only SQLSTATE class `08`.** `pg_terminate_backend` on a backend
with a commit in flight reports `57P01` (`admin_shutdown`), not a connection-class state — and the
commit record may already be in the WAL when it arrives. The classifier that encoded this
(`CommitFailureClassifier`) was removed with the second transaction engine on 2026-09-25;
`PostgreSqlConcurrencyFailureContractTest` still pins the injection points.
- **Schema-per-tenant status must be read back, not inferred from the run.** `MigrateResult`'s
target version is empty for a tenant that was already current, so recording it reported migrated
tenants as unmigrated during a partial rollout. `SchemaTenantMigrationOrchestrator` now reads the
applied version from the tenant's schema history.
## 5. 설계에서 바뀌지 않은 것
## 5. What is unchanged from the design
- Domain owns Entity, Embeddable, Repository, Query, index requirements, lock/soft-delete/audit
policy. No `GenericRepository<T, ID>` and no Spring Data CRUD re-implementation exists.
- Application Service owns the transaction boundary; OSIV is false in every runtime profile.
- `TransactionCompletionUnknownException` always reports `completionUnknown=true`,
`retryable=false`, and is never automatically retried — reconciliation handles it.
- Retry re-executes the whole use case in a new transaction and a new Persistence Context.
- SQLSTATE classification is structural (`40001`, `40003`, `40P01`, `23505`, `23503`, `23514`,
`55P03`) and never parses localized message text.
- Flyway is the source of truth for production schema change; Hibernate only validates;
`ddl-auto` never mutates a deployed schema.
- `CREATE INDEX CONCURRENTLY` requires an explicit non-transactional migration marker.
- Metric labels and ordinary logs never carry SQL parameters, entity IDs, tenant IDs, or PII.
- Experimental features (multi-tenancy, RLS, schema/database tenancy, read replica) are library code
a deployment constructs itself and never enter the Stable composition. JPA 4, Hibernate 8 and
PostgreSQL 19 are `NOT_EXECUTABLE` probes, not features. The `backend.jpa.experimental.*` flags
were removed on 2026-09-25: nothing read them.
- 도메인이 Entity, Embeddable, Repository, Query, 인덱스 요구, lock·soft-delete·감사 정책을 가진다. `GenericRepository<T, ID>`도,
Spring Data CRUD를 다시 구현한 것도 없다.
- Application Service가 트랜잭션 경계를 가진다. OSIV는 모든 런타임 profile에서 false다.
- `TransactionCompletionUnknownException`은 늘 `completionUnknown=true`, `retryable=false`를 보고하고, 자동으로 다시 시도하지
않는다. 맞추기가 처리한다.
- 재시도는 use case 전체를 새 트랜잭션과 새 Persistence Context에서 다시 돌린다.
- SQLSTATE 분류는 구조적이다(`40001`, `40003`, `40P01`, `23505`, `23503`, `23514`, `55P03`). 지역화된 메시지 문장을 파싱하지
않는다.
- 운영 스키마 변경의 정본은 Flyway다. Hibernate는 검증만 하고, `ddl-auto`는 배포된 스키마를 바꾸지 않는다.
- `CREATE INDEX CONCURRENTLY`에는 명시적인 비트랜잭션 마이그레이션 표시가 필요하다.
- 메트릭 label과 보통 로그에는 SQL 파라미터, entity ID, tenant ID, PII를 싣지 않는다.
- Experimental 기능(multi-tenancy, RLS, schema·database tenancy, read replica)은 배포가 직접 만드는 라이브러리 코드이고 Stable
조립에 들어가지 않는다. JPA 4, Hibernate 8, PostgreSQL 19는 기능이 아니라 `NOT_EXECUTABLE` probe다.
`backend.jpa.experimental.*` 스위치는 아무것도 읽지 않아서 2026-09-25에 지웠다.
+50 -63
View File
@@ -1,65 +1,56 @@
# JPA Platform Runbooks
# JPA 플랫폼 runbook
Operator procedures for the failures this platform is designed to surface rather than hide.
이 플랫폼이 숨기지 않고 드러내도록 설계한 실패에 대한 운영자 절차다.
## A transaction reported completion unknown
## 트랜잭션이 완료를 모른다고 보고했다
**Signal:** a write use case failed with a commit-phase error (connection lost, `57P01`, class
`08`) from `TransactionPort`.
**신호:** 쓰기 use case가 `TransactionPort`에서 커밋 단계 오류(연결 끊김, `57P01`, class `08`)로 실패했다.
**What it means:** the commit may or may not have happened. It is not a rollback.
**뜻:** 커밋이 됐을 수도 안 됐을 수도 있다. 롤백이 아니다.
**Do not** re-run the use case. That is what the platform refused to do automatically, for the same
reason.
use case를 다시 돌리지 **않는다**. 플랫폼이 같은 이유로 자동으로 하기를 거부한 일이다.
**Procedure:**
**절차:**
1. Take the idempotency key or operation id of the failed request.
2. Check the idempotency record for that key.
3. Check the business row the use case would have written.
4. Check the outbox for a corresponding event.
5. If all three agree the write happened, stop — the request succeeded.
6. If all three agree it did not, the use case may be re-run.
7. If they disagree or are inconclusive, escalate. An inconclusive answer is a legitimate outcome;
guessing is not.
1. 실패한 요청의 멱등 키나 operation id를 꺼낸다.
2. 그 키의 멱등성 기록을 확인한다.
3. use case가 썼을 업무 행을 확인한다.
4. outbox에 그에 맞는 이벤트가 있는지 확인한다.
5. 셋이 모두 쓰기가 일어났다고 하면 멈춘다. 요청은 성공했다.
6. 셋이 모두 일어나지 않았다고 하면 use case를 다시 돌려도 된다.
7. 서로 다르거나 결론이 나지 않으면 넘긴다. 결론 없음은 정당한 결과다. 짐작은 아니다.
## Deadlock or serialization rate rising
## 교착이나 직렬화 실패 비율이 오른다
**Signal:** `DB_DEADLOCK` / serialization failures rising in the persistence error codes.
**신호:** 영속성 오류 코드에서 `DB_DEADLOCK`·직렬화 실패가 오른다.
`SpringTransaction` does not retry, so each one reaches the caller.
`SpringTransaction`은 다시 시도하지 않으므로 하나하나가 호출자에게 닿는다.
1. Group the failures by operation. A single operation dominating means a hot row or an
inconsistent lock order.
2. For deadlocks, check whether two operations take the same rows in opposite orders — that is a
code fix, not a tuning one.
3. For serialization failures under `SERIALIZABLE`, confirm the isolation is actually required.
1. 실패를 operation별로 묶는다. operation 하나가 압도하면 hot row나 어긋난 잠금 순서다.
2. 교착이면 두 operation이 같은 행을 반대 순서로 잡는지 확인한다. 그것은 조정이 아니라 코드를 고칠 일이다.
3. `SERIALIZABLE`에서의 직렬화 실패면 그 격리 수준이 정말 필요한지 확인한다.
## Pool exhaustion
## 풀 고갈
**Signal:** connection acquisition timeouts; `PoolMeasurement.pending` non-zero.
**신호:** 연결 획득 시간 초과. `PoolMeasurement.pending`이 0이 아니다.
1. Check `REQUIRES_NEW` usage. It takes a second connection while pinning the first, so the pool
must satisfy `(threads x (1 + depth)) + 1`.
2. Check for streaming outside a bounded scope — a `Stream` returned past the transaction holds its
connection until the pool notices.
3. Check for external calls inside a DB transaction. The design forbids them precisely because an
HTTP timeout then holds a connection for its whole duration.
1. `REQUIRES_NEW` 사용을 확인한다. 첫 연결을 쥔 채 두 번째 연결을 잡으므로, 풀은 `(threads x (1 + depth)) + 1`을 채워야 한다.
2. 상한 있는 범위 밖의 streaming을 확인한다. 트랜잭션 밖으로 돌려준 `Stream`은 풀이 알아챌 때까지 연결을 쥔다.
3. DB 트랜잭션 안의 외부 호출을 확인한다. 설계가 그것을 금지하는 이유가 바로 그것이다. 그러면 HTTP 시간 초과가 그 시간
내내 연결을 쥔다.
## Flyway validation failed at startup
## 기동할 때 Flyway 검증이 실패했다
The deployment is running against a schema it was not built for. It failed closed, which is correct.
배포가 맞지 않는 스키마에서 돌고 있다. 닫힌 채 실패했고, 그것이 맞다.
1. Read the reported error codes (the messages are deliberately not propagated).
2. `CHECKSUM_MISMATCH` — an applied migration was edited afterwards. Find which change is missing
from this database. **Do not run `repair`**: it rewrites history to match the scripts, which
resolves the symptom by deleting the evidence.
3. `MISSING_SCRIPT` — a migration applied here is not in this build. Usually a rollback to an older
artifact.
1. 보고된 오류 코드를 읽는다(메시지는 일부러 전달하지 않는다).
2. `CHECKSUM_MISMATCH` — 적용된 마이그레이션을 나중에 고쳤다. 이 DB에 어느 변경이 빠졌는지 찾는다. **`repair`를 돌리지
않는다.** repair는 이력을 스크립트에 맞춰 다시 써서, 증거를 지워 증상을 없앤다.
3. `MISSING_SCRIPT` — 여기 적용된 마이그레이션이 이 빌드에 없다. 보통 옛 산출물로 되돌린 것이다.
## An invalid index exists
## 무효 인덱스가 있다 (An invalid index exists)
**Signal:** this query returns rows.
**신호:** 이 쿼리가 행을 돌려준다.
```sql
select n.nspname || '.' || i.relname as invalid_index
@@ -69,28 +60,24 @@ join pg_namespace n on n.oid = i.relnamespace
where not x.indisvalid;
```
A concurrent build, rebuild or drop failed. The index is ignored by the planner and maintained by
every write.
동시 빌드, 재빌드, 삭제가 실패했다. planner는 그 인덱스를 무시하고, 모든 쓰기는 그것을 유지한다.
1. Confirm no build is currently running. An in-progress build looks identical in the catalog.
2. If a migration was building, rebuilding or dropping it, Flyway recorded that version as failed
(`success = false`) and refuses every later deploy until that row is gone: dropping the index
does not clear it. Follow [migration-failed.md](../runbooks/migration-failed.md) "Recover a
failed concurrent index migration" instead of the next step. It removes the cause, drops the
index a failed build or rebuild left, and deletes that one row. It leaves the index a failed
`DROP INDEX CONCURRENTLY` left, for the deploy again to drop: dropped by hand, that statement
finds no index and fails again.
3. Otherwise run `DROP INDEX CONCURRENTLY IF EXISTS <invalid_index>;` outside a migration, and
re-apply the index migration.
1. 지금 도는 빌드가 없는지 확인한다. 진행 중인 빌드도 카탈로그에서는 똑같이 보인다.
2. 마이그레이션이 그것을 빌드, 재빌드, 삭제하던 중이었으면, Flyway는 그 버전을 실패(`success = false`)로 기록했고 그 행이
사라질 때까지 뒤의 모든 배포를 거부한다. 인덱스를 지워도 풀리지 않는다. 다음 단계 대신
[migration-failed.md](../runbooks/migration-failed.md) 「실패한 동시 인덱스 마이그레이션 복구 (Recover a failed
concurrent index migration)」를 따른다. 그 절차는 원인을 없애고, 실패한 빌드나 재빌드가 남긴 인덱스를 지우고, 그 한 행을
지운다. 실패한 `DROP INDEX CONCURRENTLY`가 남긴 인덱스는 다시 배포가 지우도록 남긴다. 손으로 지우면 그 문장이 인덱스를
찾지 못해 다시 실패한다.
3. 그렇지 않으면 마이그레이션 밖에서 `DROP INDEX CONCURRENTLY IF EXISTS <invalid_index>;`를 돌리고, 인덱스 마이그레이션을
다시 적용한다.
The platform does not drop these automatically: on a rolling deploy every instance would race to
drop an index another instance was about to finish building.
플랫폼은 이것을 자동으로 지우지 않는다. rolling deploy에서는 모든 인스턴스가, 다른 인스턴스가 곧 빌드를 끝낼 인덱스를
지우려고 경주한다.
## The runtime role failed verification
## 런타임 역할이 검증에 실패했다
Startup refused because the runtime credential holds `CREATE`, or `search_path` contains an
unapproved schema.
런타임 자격 증명이 `CREATE`를 가지거나 `search_path`에 승인하지 않은 schema가 있어서 기동이 거부됐다.
This is not a false positive to be worked around. `docs/jpa/security.md` 「역할과 권한 — 운영 DB가
갖춰야 할 것」대로 권한을 다시 맞춘다. 애플리케이션 자격 증명이 DDL을 가지면 다른 schema 보장을 하나도
지킬 수 없다.
돌아갈 오탐이 아니다. `docs/jpa/security.md` 「역할과 권한 — 운영 DB가 갖춰야 할 것」대로 권한을 다시 맞춘다. 애플리케이션
자격 증명이 DDL을 가지면 다른 schema 보장을 하나도 지킬 수 없다.
+33 -36
View File
@@ -1,18 +1,18 @@
# Security
# 보안
Design §36. Credential separation, privilege verification, and what never leaves the process.
설계서 §36. 자격 증명 분리, 권한 검증, 프로세스 밖으로 절대 나가지 않는 것.
## Three credentials
## 자격 증명 셋
| Role | May |
| 역할 | 할 수 있는 것 |
|---|---|
| `app_migration` | own the schema, apply migrations (DDL) |
| `app_runtime` | select, insert, update, delete (DML only) |
| `app_admin` | J4 operations — COPY, backfill, maintenance |
| `app_migration` | schema 소유, 마이그레이션 적용(DDL) |
| `app_runtime` | select, insert, update, delete(DML만) |
| `app_admin` | J4 작업 — COPY, backfill, 정비 |
The separation is what makes "Flyway owns schema change" enforceable rather than aspirational. If
the application's own credential cannot execute DDL, then no code path, no library, and no injected
statement can alter the schema at runtime, regardless of what the application intended.
이 분리가 「schema 변경은 Flyway가 가진다」를 바람이 아니라 강제할 수 있는 규칙으로 만든다. 애플리케이션 자신의 자격 증명이
DDL을 실행할 수 없으면, 애플리케이션이 무엇을 의도했든 어떤 코드 경로도, 라이브러리도, 주입된 문장도 실행 중에 schema를 바꿀
수 없다.
### 역할과 권한 — 운영 DB가 갖춰야 할 것
@@ -50,9 +50,9 @@ statement can alter the schema at runtime, regardless of what the application in
확장(extension)은 필요 없다. JSONB, 배열, 범위, `SKIP LOCKED`, `ON CONFLICT`는 모두 PostgreSQL 본체 기능이다.
## Startup verification
## 기동 검증
`PostgreSqlRuntimeRoleVerifier` asks the *server* what the connection can do:
`PostgreSqlRuntimeRoleVerifier`가 연결이 무엇을 할 수 있는지 *서버*에 묻는다.
```sql
select current_user,
@@ -61,38 +61,35 @@ select current_user,
has_database_privilege(current_user, current_database(), 'CREATE')
```
Configuration cannot answer this. Effective privileges come from direct grants, inherited role
memberships, `PUBLIC` grants, and schema ownership, and no reading of a deployment manifest
reconstructs that combination reliably.
설정으로는 이것에 답할 수 없다. 실제 권한은 직접 grant, 물려받은 역할 membership, `PUBLIC` grant, schema 소유에서 오고, 배포
manifest를 읽어서는 그 조합을 믿을 만하게 되살릴 수 없다.
Startup fails when the runtime role is not on the allowlist, or holds `CREATE` on the schema or the
database.
런타임 역할이 허용 목록에 없거나, schema나 데이터베이스에 `CREATE`를 가지면 기동이 실패한다.
## search_path
`SearchPathPolicy` is an allowlist. `search_path` decides which schema an unqualified name resolves
to, so a writable untrusted schema on it — classically `public`, where `CREATE` was granted broadly
before PostgreSQL 15 — lets a planted table, function, or operator shadow the real one, and the
application executes it without noticing. `$user` is exempt: only the connected role owns it.
`SearchPathPolicy`는 허용 목록이다. `search_path`는 이름만 쓴 객체가 어느 schema로 풀리는지 정한다. 그래서 그 위에 쓸 수 있는
믿지 못할 schema가 있으면(전형적으로 `public`. PostgreSQL 15 전에는 `CREATE`가 넓게 주어졌다) 심어 둔 테이블, 함수, 연산자가
진짜 것을 가리고, 애플리케이션은 알아채지 못한 채 그것을 실행한다. `$user`는 예외다. 연결한 역할만 그것을 소유한다.
Refusing the runtime role `CREATE` closes the same route from the other side.
런타임 역할에게 `CREATE`를 주지 않는 것이 같은 길을 반대쪽에서 막는다.
## What never leaves the process
## 프로세스 밖으로 절대 나가지 않는 것
- SQL parameter values, entity ids, tenant ids, and PII: not in exception messages, not in metric
tags, not in logs. `JpaFailureContext` composes messages from bounded values only.
- Constraint names reach the application as registered `ConstraintCode`s; an unregistered physical
name maps to a bounded unknown code rather than being passed through.
- Cursors are HMAC-signed. An unsigned cursor is client-controlled ordering state.
- The actuator report carries no JDBC URL, username, or SQL.
- SQL 파라미터 값, entity id, tenant id, PII. 예외 메시지에도, 메트릭 태그에도, 로그에도 없다. `JpaFailureContext`는 상한 있는
값으로만 메시지를 만든다.
- 제약 이름은 등록된 `ConstraintCode`로 애플리케이션에 닿는다. 등록되지 않은 물리 이름은 그대로 넘기지 않고 상한 있는 unknown
코드로 매핑한다.
- cursor는 HMAC으로 서명한다. 서명 없는 cursor는 클라이언트가 다루는 정렬 상태다.
- actuator 보고에는 JDBC URL, 사용자 이름, SQL이 없다.
## Injection surfaces, and how each is closed
## 주입 표면과 각각을 막는 법
| Surface | Why it cannot be a parameter | Closed by |
| 표면 | 파라미터가 될 수 없는 이유 | 막는 것 |
|---|---|---|
| sort field | part of ORDER BY | `SafeSortRegistry` allowlist |
| JSON path | part of the statement | registered `JsonPathName` |
| schema name | an identifier | registered `SchemaTenantRegistry` |
| COPY table | an identifier | registered `RegisteredCopyStatement` |
| 정렬 칸 | ORDER BY의 일부 | `SafeSortRegistry` 허용 목록 |
| JSON 경로 | 문장의 일부 | 등록한 `JsonPathName` |
| schema 이름 | 식별자 | 등록한 `SchemaTenantRegistry` |
| COPY 테이블 | 식별자 | 등록한 `RegisteredCopyStatement` |
Values are always bound. Identifiers are always registered.
값은 늘 묶는다. 식별자는 늘 등록한다.
+81 -95
View File
@@ -1,89 +1,79 @@
# JPA Persistence Platform — Support Matrix
# JPA 영속성 플랫폼 — 지원 매트릭스
**This document is a rendering. The machine-readable source is
[`src/adapter/outbound/persistence-jpa/release/release-registry.json`](../../src/adapter/outbound/persistence-jpa/release/release-registry.json).**
**이 문서는 렌더링이다. 기계가 읽는 정본은
[`src/adapter/outbound/persistence-jpa/release/release-registry.json`](../../src/adapter/outbound/persistence-jpa/release/release-registry.json)이다.**
`JpaReleaseManifest` used to parse this file with regular expressions: every `PostgreSQL NN` it
mentioned became a supported version, whatever table or sentence produced the match. An Experimental
major joined the Stable list, a version named once in prose counted as supported, and demoting a
major changed nothing so long as the string survived somewhere in the document. Now the registry
declares a support level per major as a field, each gate names the Gradle task that produces its
evidence, and this document describes what the registry says.
registry는 major마다 지원 수준을 칸으로 선언하고, gate마다 그 증거를 만드는 Gradle 태스크를 이름 댄다. 이 문서는
registry가 말하는 것을 설명한다. 표를 고치지 말고 registry를 고친다. 표가 따라오지 않으면 빌드가 실패한다.
Being a rendering used to be a claim rather than a mechanism: the tables below were still typed by
hand, so a major demoted in the registry stayed Stable here and kept its full release job.
`JpaReleaseRenderingTest` now compares the database table, the gate table and `release.yml`'s JPA
matrix and promotion lists to the registry, and the `jpaReleaseQualification` aggregate depends on
every blocking gate's task, so a gate naming a task that does not exist fails when the task graph is
built. Edit the registry; these tables follow, or the build fails.
- `JpaReleaseRenderingTest`가 DB 표, gate 표, `release.yml`의 JPA matrix와 승격 목록을 registry와 비교한다.
- `jpaReleaseQualification` 집계 태스크는 막는 gate마다 그 태스크에 의존한다. 그래서 없는 태스크를 이름 댄 gate는 태스크
그래프를 만들 때 실패한다.
- `jpa-nightly.yml`의 matrix도 같은 비교를 받는다. Experimental major는 `.github/workflows`의 어떤 lane이 그것을 대상으로
기록해야 하고, Stable lane은 그것을 돌리면 안 된다.
Two renderings stayed outside that comparison until they were added to it. `jpa-nightly.yml` runs
its own matrix and nothing checked it, so a demotion corrected the release lane and left the nightly
lane certifying the major. And an Experimental major's "compatibility lane only" named no file: the
lane existed, but the registry, this document and the release workflow could each be read end to end
without establishing that, so a reader looking for it concluded there was none. An Experimental major
now has to be recorded as the target of a lane in `.github/workflows`, and a Stable lane may not run
it.
> 이력: 전에는 `JpaReleaseManifest`가 이 파일을 정규식으로 읽었다. 어느 표나 문장에서 나왔든 `PostgreSQL NN`이 지원
> 버전이 됐다. Experimental major가 Stable 목록에 들어갔고, 본문에 한 번 나온 버전이 지원으로 셌고, 문자열이 문서
> 어딘가에 남아 있는 한 major를 내려도 아무것도 바뀌지 않았다. registry로 옮긴 뒤에도 한동안 아래 표는 손으로 썼다.
> 그래서 registry에서 내린 major가 여기서는 Stable로 남고 자기 전체 릴리스 job을 계속 가졌다. `jpa-nightly.yml`은 자기
> matrix를 아무도 확인하지 않아서, 내리기가 릴리스 lane만 고치고 nightly lane은 그 major를 계속 인증했다. Experimental
> major의 「compatibility lane only」는 어떤 파일도 가리키지 않았다. lane은 있었지만 registry, 이 문서, 릴리스 workflow를
> 끝까지 읽어도 그것을 알 수 없어서, 찾던 사람은 없다고 결론 냈다.
## Database
## 데이터베이스
| Database | Support | Evidence |
|---|---|---|
| PostgreSQL 16 | Stable | full contract suite, release lane (own matrix job) |
| PostgreSQL 17 | Stable | full contract suite, release lane (own matrix job) |
| PostgreSQL 18 | Stable | full contract suite, release lane (own matrix job) |
| PostgreSQL 19 | Experimental | [`jpa-next.yml`](../../.github/workflows/jpa-next.yml) — `NOT_EXECUTABLE`: no `postgres:19-alpine` is published, so no container of that major has been started; promotion requires an ADR |
| H2 | Local convenience | **never** evidence of PostgreSQL behaviour |
| PostgreSQL 16 | Stable | 전체 계약 suite, 릴리스 lane(자기 matrix job) |
| PostgreSQL 17 | Stable | 전체 계약 suite, 릴리스 lane(자기 matrix job) |
| PostgreSQL 18 | Stable | 전체 계약 suite, 릴리스 lane(자기 matrix job) |
| PostgreSQL 19 | Experimental | [`jpa-next.yml`](../../.github/workflows/jpa-next.yml) — `NOT_EXECUTABLE`: `postgres:19-alpine`이 게시되지 않아 그 major의 컨테이너를 띄운 적이 없다. 승격에는 ADR이 필요하다 |
| H2 | Local convenience | PostgreSQL 동작의 증거가 **절대** 아니다 |
Each major gets its **own release job**, because for a while it did not. The release lane passed
`-Pjpa.matrix.versions=16,17,18` to a `JpaPlatformContractSupport.start()` that used
`selectedVersions().get(0)`, so the whole integration suite ran against PostgreSQL 16 and this table
recorded 17 and 18 as fully covered on the strength of a three-assertion smoke test. `start()` now
refuses a multi-version selection outright, the `jpa-release-gate` job in `release.yml` fans out to one job per major, and a
promotion job requires all three majors' evidence to carry the same commit SHA — so a removed major
removes the release, not the evidence for it.
major마다 **자기 릴리스 job**이 있다. `release.yml`의 `jpa-release-gate` job이 major마다 job 하나로 펼치고, 승격 job은 세
major의 증거가 모두 같은 커밋 SHA를 지니기를 요구한다. 그래서 major 하나가 빠지면 그 증거가 아니라 릴리스가 빠진다.
`JpaPlatformContractSupport.start()`는 여러 버전 선택을 아예 거부한다.
**Provider baseline.** The gates run against the Hibernate version the Spring Boot BOM resolves —
**7.1.8.Final** — which the registry records as `stable-tested-baseline`. This document previously
called 7.4 the Stable baseline and the pagination gate was named `hibernate-7.4-fetch-pagination`,
so every run of that gate produced evidence labelled with a provider it had never executed against.
7.4 is recorded as `compatibility-target`; it becomes the baseline when a full lane has actually run
on it.
> 이력: 한동안 그렇지 않았다. 릴리스 lane이 `-Pjpa.matrix.versions=16,17,18`을 `selectedVersions().get(0)`을 쓰는
> `JpaPlatformContractSupport.start()`에 넘겼으므로, 통합 suite 전체가 PostgreSQL 16에만 돌았다. 이 표는 단언 셋짜리
> smoke test를 근거로 17과 18을 전부 덮었다고 적었다.
H2 is not a second production target. It reports different SQLSTATEs for the same violation, no JSONB
operators, no range types, and no concurrent index builds. A green H2 run is evidence that the code
compiles and runs, and nothing more.
**provider 기준선.** gate는 Spring Boot BOM이 푸는 Hibernate 버전 **7.1.8.Final**에서 돈다. registry는 그것을
`stable-tested-baseline`으로 기록한다. 7.4는 `compatibility-target`으로 기록하고, 전체 lane이 실제로 그 버전에서 돈 뒤에
기준선이 된다.
`SKIP LOCKED` needs its own sentence, because two documents said different things about it. The
module's `CLAUDE.md` records a measurement: H2 2.4.240 accepts `FOR UPDATE SKIP LOCKED` and does
genuinely skip locked rows, which is why the outbox claim SQL is identical on both vendors. This
document previously said H2 has no such guarantee. Both are right about different questions, and
the distinction is the point: **observed behaviour in the version we measured is not a production
guarantee, and it is never PostgreSQL contract evidence.** The measurement is why the claim SQL
needs no vendor branch; the absence of a guarantee is why every concurrency contract still runs
against a real PostgreSQL.
> 이력: 이 문서는 전에 7.4를 Stable 기준선이라 불렀고 페이지네이션 gate 이름도 `hibernate-7.4-fetch-pagination`이었다.
> 그래서 그 gate를 돌릴 때마다 한 번도 돌려 보지 않은 provider 이름이 붙은 증거가 나왔다.
## Specification and provider
H2는 두 번째 운영 대상이 아니다. 같은 위반에 다른 SQLSTATE를 보고하고, JSONB 연산자도, range 타입도, 동시 인덱스
빌드도 없다. H2에서 통과한 실행은 코드가 컴파일되고 돈다는 증거일 뿐이다.
| Component | Stable | Experimental |
`SKIP LOCKED`는 따로 한 문장이 필요하다. 두 문서가 다른 말을 했기 때문이다. 모듈의 `CLAUDE.md`는 측정을 기록한다.
H2 2.4.240은 `FOR UPDATE SKIP LOCKED`를 받고 잠긴 행을 정말로 건너뛴다. 그래서 outbox claim SQL이 두 vendor에서 같다. 이
문서는 전에 H2에 그런 보장이 없다고 했다. 둘은 서로 다른 질문에 각각 맞았고, 그 구별이 요점이다. **측정한 버전에서 관찰한
동작은 운영 보장이 아니고, PostgreSQL 계약 증거는 더욱 아니다.** 측정 덕분에 claim SQL에 vendor 분기가 필요 없고, 보장이
없으므로 모든 동시성 계약은 여전히 실제 PostgreSQL에서 돈다.
## 명세와 provider
| 구성 요소 | Stable | Experimental |
|---|---|---|
| Jakarta Persistence | 3.2 | 4.0 (lane) |
| Hibernate ORM | 7.4 declared baseline | 8 (lane) |
| Spring Boot | repository BOM | — |
| Hibernate ORM | 7.4 선언 기준선 | 8 (lane) |
| Spring Boot | 저장소 BOM | — |
The Hibernate row needs a note. The design declares 7.4 as the Stable provider; this repository's
Spring Boot BOM resolves 7.1.x. `HibernateProviderPolicy` holds both — the declared baseline as a
constant, the resolved version read from Hibernate itself — and `driftsFromDeclaredBaseline()` makes
the difference visible instead of asserting a constant against itself. See
[repository-adaptation.md](repository-adaptation.md) §4.
Hibernate 줄에는 설명이 필요하다. 설계서는 7.4를 Stable provider로 선언하고, 이 저장소의 Spring Boot BOM은 7.1.x를 푼다.
`HibernateProviderPolicy`가 둘을 다 가진다. 선언 기준선은 상수로, 풀린 버전은 Hibernate 자신에게서 읽는다.
`driftsFromDeclaredBaseline()`이 상수를 상수와 비교하는 대신 그 차이를 드러낸다.
[repository-adaptation.md](repository-adaptation.md) §4를 본다.
## Capability support levels
## capability 지원 수준
The levels are the ones `JpaPlatformAutoConfiguration.capabilities()` reports through the
`jpaplatform` actuator endpoint. Advanced and Experimental rows are library code a service calls
itself (`src/adapter/outbound/persistence-jpa/README.md` "라이브러리 API").
수준은 `jpaplatform` actuator 엔드포인트가 `JpaPlatformReport.platformCapabilities()`로 보고하는 값이다. 마지막 세
줄(기술 감사, multi-tenancy, read replica)은 그 보고에 없고 이 문서가 정한다. Advanced와 Experimental 줄은 서비스가 직접
부르는 라이브러리 코드다(`src/adapter/outbound/persistence-jpa/README.md` 「라이브러리 API」).
| Capability | Level |
| capability | 수준 |
|---|---|
| Keyset pagination | Stable |
| Flyway schema gate | Stable |
@@ -95,44 +85,40 @@ itself (`src/adapter/outbound/persistence-jpa/README.md` "라이브러리 API").
| PostgreSQL array and range | Advanced |
| Bulk DML | Advanced |
| Hibernate `StatelessSession` | Advanced |
| PostgreSQL `COPY` | Admin (J4) |
| PostgreSQL `COPY` | Advanced (admin 자격 증명 필요) |
| Hibernate second-level cache | Advanced |
| Hibernate Envers | Advanced |
| Technical auditing — `audit/AuditableEntity` | Stable (canonical) |
| 기술 감사 — `audit/AuditableEntity` | Stable (canonical) |
| Multi-tenancy (column, RLS, schema, database) | Experimental |
| Consistency-aware read replica | Experimental |
| 일관성을 아는 read replica | Experimental |
## Release gates
## 릴리스 gate
Each row is a way the platform could pass its tests and still be wrong in production.
줄마다, 플랫폼이 테스트를 통과하고도 운영에서 틀릴 수 있는 길 하나다.
| Gate | Kind | What it prevents |
| Gate | Kind | 막는 것 |
|---|---|---|
| `postgresql-contract` | gate | a release whose only database evidence came from H2 |
| `completion-unknown-no-retry` | gate | automatically re-running a write that may already have committed |
| `osiv-disabled` | gate | lazy loading from the view layer, one query per rendered row |
| `flyway-validate` | gate | Hibernate mutating a deployed schema, or running against one it was not built for |
| `runtime-role-no-ddl` | gate | the application's own credential being able to alter or drop schema objects |
| `collection-fetch-pagination` | gate | a paged collection fetch silently reading the whole table and paginating in memory |
| `postgresql-contract` | gate | DB 증거가 H2에서만 나온 릴리스 |
| `completion-unknown-no-retry` | gate | 이미 커밋됐을 수 있는 쓰기를 자동으로 다시 돌림 |
| `osiv-disabled` | gate | view 계층에서의 lazy loading, 렌더링한 행마다 쿼리 하나 |
| `flyway-validate` | gate | Hibernate가 배포된 스키마를 바꾸거나, 맞지 않는 스키마에서 돎 |
| `runtime-role-no-ddl` | gate | 애플리케이션 자신의 자격 증명으로 스키마 객체를 바꾸거나 지울 수 있음 |
| `collection-fetch-pagination` | gate | 페이지 단위 collection fetch가 몰래 테이블 전체를 읽고 메모리에서 페이지를 나눔 |
### The audit mechanism
### 감사 방식
`audit/AuditableEntity` is the only one: `created_*`/`updated_*`, a 256-character actor, stamped
explicitly by the repository adapter. 서비스의 엔티티는 이것을 상속하고, 마이그레이션도 이 열에
맞춰 썼다. A second, Spring Data listener-based mechanism (`auditing/AuditMetadata`) was never
composed and has been removed; `JpaAuditMechanismRule.entitiesUseExactlyOneAuditMechanism` keeps it
from coming back on an entity.
감사 방식은 `audit/AuditableEntity` 하나다. `created_*`/`updated_*`, 256자 actor이고, repository 어댑터가 명시적으로
찍는다. 서비스의 엔티티는 이것을 상속하고, 마이그레이션도 이 열에 맞춰 썼다. 두 번째 방식인 Spring Data listener 기반
(`auditing/AuditMetadata`)은 한 번도 조립되지 않아서 지웠다. `JpaAuditMechanismRule.entitiesUseExactlyOneAuditMechanism`이
그것이 엔티티에 돌아오지 못하게 막는다.
The mechanism does not reach a bulk or native update. It stamps on an ordinary save in the adapter,
so a statement that goes straight to the database leaves the audit columns showing the previous save.
A bulk update of an audited entity must therefore set the audit column in the statement, which
`JpaAuditMechanismRule.bulkUpdatesOfAuditedEntitiesStampAudit` checks over the production graph.
이 방식은 bulk·native update에 닿지 않는다. 어댑터의 보통 save에서 찍으므로, DB로 바로 가는 문장은 감사 열을 앞 save의
값으로 남긴다. 그래서 감사 대상 엔티티의 bulk update는 문장 안에서 감사 열을 설정해야 하고,
`JpaAuditMechanismRule.bulkUpdatesOfAuditedEntitiesStampAudit`가 운영 그래프에서 그것을 확인한다.
## Explicitly unsupported
## 지원하지 않는다고 밝힌 것
- Reactive JPA. JPA is a blocking specification; a reactive facade over it moves the blocking call
onto an event loop rather than removing it.
- Hibernate as the production schema writer. `ddl-auto` never mutates a deployed schema.
- A platform-owned generic CRUD repository. Domains own their repositories (design §10.1).
- Automatic reconciliation of a completion-unknown transaction. The platform records; the domain
resolves.
- Reactive JPA. JPA는 blocking 명세다. 그 위의 reactive facade는 blocking 호출을 없애는 게 아니라 event loop로 옮긴다.
- 운영 스키마를 쓰는 Hibernate. `ddl-auto`는 배포된 스키마를 절대 바꾸지 않는다.
- 플랫폼이 가진 generic CRUD repository. 도메인이 자기 repository를 가진다(설계서 §10.1).
- 완료를 모르는 트랜잭션의 자동 맞추기. 플랫폼은 기록하고, 도메인이 푼다.
+34 -43
View File
@@ -1,65 +1,56 @@
# Transaction Guide
# 트랜잭션 가이드
Design §15-§20. What owns a transaction, what may be retried, and what must never be.
설계서 §15-§20. 무엇이 트랜잭션을 가지고, 무엇을 다시 시도해도 되고, 무엇은 절대 안 되나.
## The application service owns the boundary
## 경계는 애플리케이션 서비스가 가진다
Repository adapters do not open transactions. The use case does, through `TransactionPort`,
because the unit of work is a business decision and only the use case knows where it starts and
ends. `SpringTransaction` is the only implementation: one pre-built `TransactionTemplate` per
mode over Spring's `PlatformTransactionManager`, every mode running at `READ_COMMITTED` and
bounded in time.
repository 어댑터는 트랜잭션을 열지 않는다. use case가 `TransactionPort`로 연다. 작업 단위는 업무 결정이고, 그것이 어디서
시작하고 끝나는지는 use case만 알기 때문이다. 구현은 `SpringTransaction` 하나다. Spring의 `PlatformTransactionManager` 위에
mode마다 미리 만든 `TransactionTemplate` 하나를 두고, 모든 mode가 `READ_COMMITTED`로 돌며 시간 상한이 있다.
- **Isolation** is pinned on the pool, not per transaction: the module defaults set
`spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED` and
`HikariPoolConstraintValidator` refuses any other level. A template that names the level makes
pgjdbc ask the server for it (`SHOW TRANSACTION ISOLATION LEVEL`) at every begin.
- **Time bound**: `app.persistence-jpa.transaction.write-timeout` (`inWrite`, `inRootWrite`) and
`read-timeout` (`inRead`), 30 s each by default; `inNew` is fixed at 30 s. Spring hands the
remaining time to each statement, so the server cancels a slow statement or lock wait
(`DB_QUERY_CANCELED`) and the connection returns to the pool. A unit of work that needs longer
is usually a batch job that should be split, not a reason to raise the bound.
- **격리 수준**은 트랜잭션마다가 아니라 풀에 고정한다. module defaults가
`spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED`를 두고, `HikariPoolConstraintValidator`가 다른
수준을 거부한다. 수준을 이름 대는 template은 begin마다 pgjdbc가 서버에 그것을 묻게 한다(`SHOW TRANSACTION ISOLATION LEVEL`).
- **시간 상한**: `app.persistence-jpa.transaction.write-timeout`(`inWrite`, `inRootWrite`)과 `read-timeout`(`inRead`), 기본값은
각각 30 s다. `inNew`는 30 s로 고정이다. Spring이 남은 시간을 문장마다 넘기므로 서버가 느린 문장이나 잠금 대기를 취소하고
(`DB_QUERY_CANCELED`) 연결은 풀로 돌아간다. 더 오래 걸려야 하는 작업 단위는 보통 상한을 올릴 이유가 아니라 나눠야 할 batch
작업이다.
| Call | Propagation | When |
| 호출 | 전파 | 언제 |
|---|---|---|
| `inWrite` | `REQUIRED`, read-write | command default |
| `inRootWrite` | `REQUIRED`, read-write, rejects an ambient transaction before running | orchestration that must prove a physical commit |
| `inRead` | `REQUIRED`, read-only | query default |
| `inNew` | `REQUIRES_NEW`, read-write | outbox / audit / compensation that must commit on its own |
| `inWrite` | `REQUIRED`, 읽기-쓰기 | command 기본 |
| `inRootWrite` | `REQUIRED`, 읽기-쓰기, 돌기 전에 바깥 트랜잭션을 거부 | 물리 커밋을 증명해야 하는 조율 |
| `inRead` | `REQUIRED`, 읽기 전용 | query 기본 |
| `inNew` | `REQUIRES_NEW`, 읽기-쓰기 | 혼자 커밋해야 하는 outbox / 감사 / 보상 |
Open Session In View is off in every runtime profile. It is on by default in Spring Boot, which is
why `JpaDangerousConfigurationGuard` fails startup rather than trusting configuration review.
Open Session In View는 모든 런타임 profile에서 꺼져 있다. Spring Boot에서는 기본으로 켜져 있어서, 설정 리뷰를 믿지 않고
`JpaDangerousConfigurationGuard`가 기동을 실패시킨다.
`REQUIRES_NEW` acquires a second physical connection while pinning the first, so the pool must
satisfy:
`REQUIRES_NEW`는 첫 물리 연결을 쥔 채 두 번째를 잡으므로 풀은 다음을 채워야 한다.
```text
maximumPoolSize >= (concurrent_threads x (1 + max_requires_new_depth)) + 1
```
## Nothing is retried by the port
## port는 아무것도 다시 시도하지 않는다
`SpringTransaction` runs the action once. A failure rolls back and propagates, translated to
the shared persistence error codes where the SQLSTATE is known; a lost `@Version` race has no
SQLSTATE and is reported as `DB_OPTIMISTIC_CONFLICT` (409). A caller that decides to retry must
re-run the whole use case in a new transaction — never re-issue one statement — because an
optimistic conflict or a serialization failure means the state the attempt computed against is no
longer the committed state.
`SpringTransaction`은 action을 한 번 돌린다. 실패하면 롤백하고 넘기며, SQLSTATE를 알면 공유 영속성 오류 코드로 바꾼다.
잃은 `@Version` 경주는 SQLSTATE가 없고 `DB_OPTIMISTIC_CONFLICT`(409)로 보고한다. 다시 시도하기로 한 호출자는 문장 하나를 다시
보내지 말고 use case 전체를 새 트랜잭션에서 다시 돌린다. 낙관적 충돌이나 직렬화 실패는 시도가 기준으로 계산한 상태가 더는
커밋된 상태가 아니라는 뜻이기 때문이다.
A second engine with named policies, deadline budgets, transaction-local timeouts and automatic
full-transaction retry (`SpringJpaTransactionExecutor`, `FullTransactionRetryCoordinator`,
`PolicyTransactionPort`) existed next to this one and was removed on 2026-09-25. Its last commit is
recorded in `docs/capability-status.md`.
> 이력: 이름 있는 정책, 마감 예산, 트랜잭션 로컬 시간 상한, 자동 전체 트랜잭션 재시도를 가진 두 번째 엔진
> (`SpringJpaTransactionExecutor`, `FullTransactionRetryCoordinator`, `PolicyTransactionPort`)이 이것 옆에 있다가
> 2026-09-25에 지워졌다. 마지막 커밋은 `docs/capability-status.md`에 있다.
## Completion unknown
## 완료를 모름
A connection can break while a commit is in flight; the server may have committed and only the
acknowledgement was lost. `TransactionCompletionUnknownException` is never retried, and the type
system enforces it: `JpaFailureContext` refuses to represent a retryable completion-unknown failure.
The port itself retries nothing, so such a commit surfaces to the caller as a failure exactly once
커밋이 진행 중일 때 연결이 끊길 수 있다. 서버는 커밋했고 확인 응답만 잃었을 수 있다. `TransactionCompletionUnknownException`은
절대 다시 시도하지 않고, 타입 체계가 그것을 강제한다. `JpaFailureContext`는 다시 시도할 수 있는 완료 모름 실패를 표현하기를
거부한다. port 자신은 아무것도 다시 시도하지 않으므로, 그런 커밋은 호출자에게 실패로 정확히 한 번 나타난다
(`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsCompletionUnknownAndIsNeverRetried`).
Recovery is reconciliation, not retry:
복구는 재시도가 아니라 맞추기다.
```text
check the idempotency record -> check the business row -> check the outbox