Merge branch 'claude/d2c-ops-docs-1-c22c9f' — runbook·알림·JPA·관측·호환·storage 문서 번역

충돌: scripts/check-docs-exceptions.txt. 두 쪽 모두 줄을 지우기만 했다(앞 병합까지 92줄, D2c 67줄, 겹침 0).
기준의 줄 중 두 쪽이 모두 남긴 줄만 남겼다(128 → 61줄).
This commit is contained in:
DongHyeonka
2026-11-07 18:07:16 +09:00
83 changed files with 2266 additions and 2566 deletions
@@ -1,60 +1,55 @@
# gRPC advanced capability support matrix
# gRPC advanced capability 지원 매트릭스
Every capability in `:grpc-advanced:*`, its grade, and what it would take to raise it.
`GrpcAdvancedSupportMatrix` is the machine-readable form; `GrpcAdvancedCapability.defaultGrade`
carries the same values.
`:grpc-advanced:*`의 모든 capability, 그 등급, 그리고 등급을 올리는 데 필요한 것이다. 기본 등급의 정본은
`GrpcAdvancedCapability.defaultGrade`다. 근거가 있는 배포는 `GrpcAdvancedFeatureFlags.withGrade`로 바꾼다.
All capabilities are off by default. Flags are `app.grpc.advanced.<capability>.enabled`.
capability는 모두 기본으로 꺼져 있다. 스위치는 `app.grpc.advanced.<capability>.enabled`다.
## Grades
## 등급
| Grade | May start | Production needs a separate approval |
| 등급 | 뜰 수 있나 | 운영에 별도 승인이 필요한가 |
| --- | --- | --- |
| `ADVANCED_STABLE` | Yes | No |
| `EXPERIMENTAL` | Yes | Yes |
| `WATCH` | No | — |
| `DISABLED` | No | — |
| `ADVANCED_STABLE` | 예 | 아니요 |
| `EXPERIMENTAL` | 예 | 예 |
| `WATCH` | 아니요 | — |
| `DISABLED` | 아니요 | — |
## Capabilities
## capability
| Capability | Flag | Grade | Real infrastructure its evidence needs |
| capability | 스위치 | 등급 | 증거에 필요한 실제 인프라 |
| --- | --- | --- | --- |
| Protobuf Edition 2024 | `edition-2024` | `ADVANCED_STABLE` | — |
| Protobuf Edition 2026 | `edition-2026` | `WATCH` | — |
| Client streaming | `client-streaming` | `ADVANCED_STABLE` | — |
| Bidirectional streaming | `bidi-streaming` | `ADVANCED_STABLE` | — |
| Manual flow control | `manual-flow-control` | `ADVANCED_STABLE` | — |
| Read-only unary hedging | `hedging` | `EXPERIMENTAL` | — |
| Custom name resolver | `custom-resolver` | `ADVANCED_STABLE` | — |
| Custom load balancer | `custom-load-balancer` | `EXPERIMENTAL` | — |
| Proxyless xDS | `xds` | `EXPERIMENTAL` | xDS control plane |
| client streaming | `client-streaming` | `ADVANCED_STABLE` | — |
| bidirectional streaming | `bidi-streaming` | `ADVANCED_STABLE` | — |
| 수동 flow control | `manual-flow-control` | `ADVANCED_STABLE` | — |
| 읽기 전용 unary hedging | `hedging` | `EXPERIMENTAL` | — |
| 사용자 정의 name resolver | `custom-resolver` | `ADVANCED_STABLE` | — |
| 사용자 정의 load balancer | `custom-load-balancer` | `EXPERIMENTAL` | — |
| proxyless xDS | `xds` | `EXPERIMENTAL` | xDS control plane |
| gRPC-Web | `grpc-web` | `ADVANCED_STABLE` | gRPC-Web proxy |
| Servlet HTTP/2 | `servlet-compat` | `ADVANCED_STABLE` (flag only; no Servlet transport code since 2026-09-25) | Servlet container |
| Servlet HTTP/2 | `servlet-compat` | `ADVANCED_STABLE`(스위치만 있다. 2026-09-25부터 Servlet 전송 코드가 없다) | Servlet 컨테이너 |
| Spring Integration bridge | `integration-bridge` | `ADVANCED_STABLE` | — |
| Reactor adapter | `reactor` | `ADVANCED_STABLE` | — |
| Reactor 어댑터 | `reactor` | `ADVANCED_STABLE` | — |
| Kotlin coroutine / Flow | `kotlin` | `ADVANCED_STABLE` | Kotlin toolchain |
| Channelz / CSDS diagnostics | `channel-diagnostics` | `ADVANCED_STABLE` | — |
| Channelz / CSDS 진단 | `channel-diagnostics` | `ADVANCED_STABLE` | — |
## What the grades mean here, concretely
## 여기서 등급이 구체적으로 뜻하는 것
**Grade is a statement about the contract, not about a deployment.** Every capability's contract is
implemented and tested in this repository. What no capability has is evidence from a real deployment:
`GrpcAdvancedPromotionEvidence` for each one is empty, and no promotion has been granted.
**등급은 배포가 아니라 계약에 대한 말이다.** 모든 capability의 계약은 이 저장소에서 구현되고 시험됐다. 실제 배포에서 나온
증거는 어느 capability에도 없고, 승격된 것도 없다.
**Four capabilities cannot produce meaningful evidence here at all**, because the infrastructure they
need is absent (gRPC-Web proxy, Servlet container, xDS control plane, Kotlin toolchain), and a suite
that runs without its infrastructure passes and establishes nothing.
**capability 넷은 여기서 의미 있는 증거를 아예 낼 수 없다.** 필요한 인프라(gRPC-Web proxy, Servlet 컨테이너, xDS control
plane, Kotlin toolchain)가 없고, 인프라 없이 돈 suite는 통과해도 아무것도 세우지 않기 때문이다.
**Kotlin is the sharpest case.** This repository has no Kotlin toolchain, so Kotlin is not
supportable here until one exists. Only the Java-side coroutine cancellation bridge
(`GrpcCoroutineContextBridge`) is implemented and tested; there is no compile lane.
**Kotlin이 가장 날카로운 경우다.** 이 저장소에는 Kotlin toolchain이 없으므로 그것이 생기기 전까지 Kotlin은 여기서 지원할 수
없다. Java 쪽 coroutine 취소 bridge(`GrpcCoroutineContextBridge`)만 구현되고 시험됐다. 컴파일 lane은 없다.
## Promotion thresholds
## 승격 기준
| To | Soak | Also required |
| 목표 | soak | 그 밖에 필요한 것 |
| --- | --- | --- |
| `ADVANCED_STABLE` | 7 days | compatibility evidence, security review, fault evidence, performance evidence, ADR, runbook, real-environment test |
| Stable default | 30 days | all of the above, plus a dependency, security and operational-cost review |
| `ADVANCED_STABLE` | 7일 | 호환성 증거, 보안 리뷰, 장애 증거, 성능 증거, ADR, runbook, 실제 환경 시험 |
| Stable 기본값 | 30일 | 위의 모두와 의존성·보안·운영 비용 리뷰 |
`WATCH` becomes `EXPERIMENTAL` before anything else. Promotions are independent: promoting one
capability changes no other's grade.
`WATCH`는 무엇보다 먼저 `EXPERIMENTAL`이 된다. 승격은 서로 독립이다. 한 capability를 올려도 다른 것의 등급은 바뀌지 않는다.
+48 -51
View File
@@ -1,77 +1,74 @@
# gRPC platform support matrix
# gRPC 플랫폼 지원 매트릭스
What the Stable gRPC platform (`:grpc:*`) is certified against, what it is only checked against, and
what is merely watched. The distinction is the point: "works with Spring Boot" is not a statement
anyone can act on.
Stable gRPC 플랫폼(`:grpc:*`)이 무엇에 대해 인증됐고, 무엇에 대해서는 확인만 하고, 무엇은 지켜보기만 하는지다. 그 구별이
요점이다. 「Spring Boot와 동작한다」는 누구도 행동에 옮길 수 없는 말이다.
The release gate is the `grpc-stable-release-gate` job in `.github/workflows/release.yml`: each
certified lane is a strict test lane that fails when it runs nothing. The in-code
`GrpcCompatibilityMatrix`/`GrpcStableReleaseGate` pair was removed (review 2026-09-24 S5-lead-4):
no production or build code called it, so it gated nothing.
릴리스 gate는 `.github/workflows/release.yml`의 `grpc-stable-release-gate` job이다. 인증된 lane마다 아무것도 돌리지 않으면
실패하는 strict test lane이다.
## Lanes
> 이력: 코드 안의 `GrpcCompatibilityMatrix`/`GrpcStableReleaseGate` 짝은 지웠다(리뷰 2026-09-24 S5-lead-4). 운영 코드도 빌드
> 코드도 그것을 부르지 않아서 아무것도 막지 않았다.
| Lane | Grade | Failure blocks a release |
## lane
| lane | 등급 | 실패하면 릴리스를 막나 |
| --- | --- | --- |
| Boot-managed platform (Spring Boot 4.0.8 BOM) | Certified | Yes |
| proto3 with explicit `optional` | Certified | Yes |
| `grpc-netty-shaded` | Certified | Yes |
| `grpc-netty` (unshaded) | Compatibility | No |
| Upstream gRPC Java version override | Compatibility | No |
| Protobuf Edition 2024 | Watch | No |
| Protobuf Edition 2026 | Watch | No |
| Boot가 관리하는 플랫폼(저장소의 Spring Boot BOM) | Certified | 예 |
| 명시적 `optional`을 쓰는 proto3 | Certified | 예 |
| `grpc-netty-shaded` | Certified | 예 |
| `grpc-netty`(shade하지 않음) | Compatibility | 아니요 |
| upstream gRPC Java 버전 override | Compatibility | 아니요 |
| Protobuf Edition 2024 | Watch | 아니요 |
| Protobuf Edition 2026 | Watch | 아니요 |
## Runtime baseline
## 런타임 기준선
| | |
| --- | --- |
| Java | 21 |
| Spring Boot | 4.0.8 (the repository baseline; the plans assume 4.1) |
| io.grpc | `ext.grpcVersion` in `src/build.gradle` |
| Protobuf | `ext.protobufVersion` in `src/build.gradle` |
| Stable transport | Netty (shaded) |
| Stable RPC shapes | Unary, Server Streaming |
| Stable resolvers | Static, DNS, Unix domain socket |
| Spring Boot | 저장소 기준선, `src/gradle/libs.versions.toml`(계획은 4.1을 가정한다) |
| io.grpc | `src/gradle/libs.versions.toml`의 `grpc`. `GrpcPlatformModuleConventionPlugin`이 그 BOM을 모듈 범위로 import한다 |
| Protobuf | `src/gradle/libs.versions.toml`의 protobuf 항목(어느 leaf가 어느 것을 쓰는지는 그 파일의 주석이 적는다) |
| Stable 전송 | Netty(shaded) |
| Stable RPC 모양 | Unary, Server Streaming |
| Stable resolver | Static, DNS, Unix domain socket |
| Stable load balancing | `pick_first`, `round_robin` |
## Evidence grades
## 증거 등급
A capability may only be advertised on evidence of a grade that can establish it.
`GrpcEvidenceGrade.requireCertifies` enforces this, and `GrpcReleaseEvidence.supports` refuses a
claim backed by the wrong lane.
capability는 그것을 세울 수 있는 등급의 증거로만 광고한다. `GrpcEvidenceGrade.requireCertifies`가 이것을 강제하고,
`GrpcReleaseEvidence.supports`가 맞지 않는 lane이 뒷받침하는 주장을 거부한다.
| Grade | Lane | Establishes |
| 등급 | lane | 세우는 것 |
| --- | --- | --- |
| `CONTRACT` | `grpcInProcessContractTest` | adapter, interceptor order, status mapping, validation, idempotency replay, context propagation |
| `TRANSPORT` | `grpcNettyContractTest` | HTTP/2, TLS, mTLS, metadata limit, message limit, GOAWAY, keepalive, graceful shutdown |
| `FAULT` | `grpcFaultTest` | connection loss, completion unknown, partial stream, evidence classifier |
| `PERFORMANCE` | `grpcPerformanceTest` | latency, stream saturation, executor saturation, drain budget |
| `CONTRACT` | `grpcInProcessContractTest` | 어댑터, interceptor 순서, 상태 매핑, 검증, 멱등 replay, context 전파 |
| `TRANSPORT` | `grpcNettyContractTest` | HTTP/2, TLS, mTLS, metadata 한도, 메시지 한도, GOAWAY, keepalive, graceful shutdown |
| `FAULT` | `grpcFaultTest` | 연결 끊김, 완료 모름, 부분 stream, 증거 분류기 |
| `PERFORMANCE` | `grpcPerformanceTest` | 지연, stream 포화, executor 포화, drain 예산 |
In-process results are never transport evidence. The in-process transport does not negotiate TLS,
does not frame HTTP/2 and does not enforce transport-level limits, so a suite that passes there has
tested the adapter and not the transport.
in-process 결과는 절대 전송 증거가 아니다. in-process 전송은 TLS를 협상하지 않고, HTTP/2 frame을 만들지 않고, 전송 수준 한도를
강제하지 않는다. 그래서 거기서 통과한 suite는 전송이 아니라 어댑터를 시험한 것이다.
## What is not supported
## 지원하지 않는 것
| | Where it lives |
| | 있는 곳 |
| --- | --- |
| Client streaming, bidirectional streaming | `grpc-advanced` (`streaming`) |
| Manual flow control | `grpc-advanced` (`streaming`) |
| client streaming, bidirectional streaming | `grpc-advanced` (`streaming`) |
| 수동 flow control | `grpc-advanced` (`streaming`) |
| Hedging | `grpc-advanced` (`resilience`) |
| Custom name resolver, custom load balancer | `grpc-advanced` (`resilience`) |
| 사용자 정의 name resolver, 사용자 정의 load balancer | `grpc-advanced` (`resilience`) |
| xDS | `grpc-advanced` (`resilience`) |
| gRPC-Web, Servlet HTTP/2, Spring Integration, Reactor, Kotlin | `grpc-advanced-compat` |
| Channelz / CSDS diagnostics | `grpc-advanced` (`diagnostics`) |
| Channelz / CSDS 진단 | `grpc-advanced` (`diagnostics`) |
## Current release status
## 지금 릴리스 상태
Not released. Every `:grpc:*` leaf is `runtime_memberships: []` in the module registry, so the
platform is build-only: it compiles, its lanes run, and no deployed artifact carries it.
릴리스하지 않았다. registry에서 모든 `:grpc:*` leaf는 `"build": "optional-grpc"`라 주 빌드 밖에 있고 어느 조립에도 들어가지
않는다. 플랫폼은 빌드만 된다. 컴파일되고 lane이 돌지만, 배포되는 산출물 어디에도 실리지 않는다.
Two release gate inputs are outstanding and are the work between here and a release:
릴리스 gate 입력 둘이 남아 있고, 그것이 지금부터 릴리스까지의 일이다.
- **Performance baseline.** The performance lane runs and asserts shape — ordered percentiles, a gate
that reads them — rather than absolute numbers. A recorded baseline on a known runner is what turns
it into a regression gate.
- **Schema codegen.** No `protoc` runs in this build (ADR-GRPC-002), so the descriptor artifact and
the consumer-compile fixture are governed as policy rather than produced from a compiled schema.
- **성능 기준선.** 성능 lane은 돌고, 절대 수치가 아니라 모양을 단언한다. 순서 있는 백분위수와 그것을 읽는 gate다. 알려진
runner에서 기록한 기준선이 생겨야 회귀 gate가 된다.
- **schema codegen.** 이 빌드에서는 `protoc`가 돌지 않는다(ADR-GRPC-002). 그래서 descriptor 산출물과 consumer-compile fixture는
컴파일한 schema에서 만들어지지 않고 정책으로 다스린다.
+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
+77 -87
View File
@@ -1,77 +1,53 @@
# Notification payload at rest — threat model and decision (NTF-INT-007)
# 저장된 알림 payload — 위협 모델과 결정 (NTF-INT-007)
Wave 2 Task D6 offers two branches and requires that one be chosen and implemented fully:
결론: 템플릿 변수(payload)는 저장소 경계에서 암호화한다(branch (a)). 변수를 「민감하지 않은 값」으로 제한하는 길
(branch (b))은 쓸 수 없다. 변수가 곧 메시지의 내용이기 때문이다.
- **(a) encryption** — a codec/port, ciphertext envelope, key id, rotation and history, row migration,
and a decryption-failure contract;
- **(b) restriction** — this document plus a static restriction proving the variable types cannot
carry sensitive values.
Wave 2 Task D6은 두 길을 주고, 하나를 골라 끝까지 구현하라고 요구했다.
The plan recommends (b) **"if and only if the variable types can genuinely be restricted to
non-sensitive values"**. They cannot. This document records why, what that leaves, and when the
remaining branch lands.
- **(a) 암호화** — codec·port, 암호문 envelope, key id, 교체와 이력, 행 마이그레이션, 복호화 실패 계약.
- **(b) 제한** — 이 문서, 그리고 변수 타입이 민감한 값을 담을 수 없음을 보이는 정적 제한.
## What is stored, and where
계획은 **「변수 타입을 정말로 민감하지 않은 값으로 제한할 수 있을 때만」** (b)를 권했다. 제한할 수 없다. 이 문서는
그 이유와, 그래서 고른 (a)가 지금 어떻게 들어가 있는지를 적는다.
`CanonicalNotificationPlanWriter.request(...)` puts `encoded.variablesPayload()` into
`NotificationRequestRecord` verbatim. `JpaNotificationRequestStore` writes that record to
`notification_request.variables_payload` with no transformation. There is no encryption anywhere on
this path.
## 지금 상태
## Why the restriction branch is unavailable
- `NotificationPayloadProtection`이 애플리케이션이 가진 port이고, `AesGcmNotificationPayloadProtection`이 AES-GCM
구현이다.
- `NotificationRecordMapper`가 그것을 **필수** 생성자 인자로 받아 적용한다. 그래서 payload를 평문으로 둔 채 알림
저장소를 조립할 수 없다.
- 쓰기 경로는 조립에서 닿는다. `NotificationJpaPersistenceFacade`는 persistence-notification leaf의
`AutoConfiguration.imports`가 올린다.
- 평문 행이 이미 있는 배포는 마이그레이션에서 멈춘다. `V10__variables_payload_envelope_guard.sql`은 행을 다시
암호화하지 않고, 보호되지 않은 행이 있으면 실패한다.
- `NotificationPayloadAtRestContractTest`가 이 문서가 기대는 사실을 모두 단언한다. 하나라도 거짓이 되면 그 테스트가
실패하므로, 결정이 저절로 낡지 않는다.
- 알림은 Stable이 아니다(`docs/notification/support-matrix.md`).
Template variables are a closed algebra — `NotificationVariable` permits `TextValue`, `NumberValue`,
`BooleanValue`, `NullValue`, `ListValue`, `ObjectValue` — which is a real improvement over the
`Map<String, Object>` it replaced. But `TextValue` holds an arbitrary UTF-8 string of up to 8 KiB,
and that is not an oversight to be tightened: **the variables are the recipient-specific content of
the message**. A password-reset code, an order total, a delivery address, a patient's appointment
time — those are what a notification is for.
## 무엇이 어디에 저장되나
A restriction to "non-sensitive values" would therefore be one of two things, and both are worse
than the problem:
`CanonicalNotificationPlanWriter.request(...)`는 `encoded.variablesPayload()`를 그대로 `NotificationRequestRecord`에
넣는다. 애플리케이션은 그것을 렌더링해야 하므로 여기서는 평문이 맞다. 「저장된(at rest)」은 행 안을 뜻하므로
envelope는 여기가 아니라 저장소 경계에서 씌운다. `notification_request.variables_payload`에는 base64 AES-GCM
envelope가 들어간다.
- **unenforceable** — a comment saying callers should not put sensitive data in a field designed to
carry the message's content, which is a policy no type checks and no reviewer can see violated;
- **enforced and useless** — a type that refuses free text, which does not restrict the capability so
much as delete it.
## 제한 가지를 쓸 수 없는 이유
The precondition on the plan's recommendation is false. Branch (b) is not available.
템플릿 변수는 닫힌 대수다. `NotificationVariable`은 `TextValue`, `NumberValue`, `BooleanValue`, `NullValue`,
`ListValue`, `ObjectValue`만 허용한다. 이것이 대신한 `Map<String, Object>`보다 확실히 낫다. 그러나 `TextValue`는 8 KiB까지의
아무 UTF-8 문자열을 담고, 그것은 조여야 할 실수가 아니다. **변수는 메시지의 수신자별 내용이다.** 비밀번호 재설정
코드, 주문 합계, 배송 주소, 환자의 예약 시각, 알림은 그것을 보내려고 있다.
> **Status: branch (a) implemented at the storage boundary.** `NotificationPayloadProtection` is the
> application-owned port, `AesGcmNotificationPayloadProtection` the AES-GCM implementation, and
> `NotificationRecordMapper` applies it — as a **required** constructor argument, so a composition
> cannot assemble the notification stores while leaving the payload in plaintext. What remains before
> the facade can be imported is the row migration for any deployment that already has plaintext rows,
> and the `local-notification-*` lanes. The analysis below is kept as written, because it is what the
> decision rests on.
그래서 「민감하지 않은 값」으로의 제한은 둘 중 하나가 되고, 둘 다 문제보다 나쁘다.
## Decision: branch (a), landing with the persistence wiring
- **강제할 수 없음** — 메시지 내용을 담으려고 만든 칸에 민감한 데이터를 넣지 말라는 주석. 어떤 타입도 확인하지
않고, 어떤 리뷰어도 위반을 볼 수 없는 정책이다.
- **강제하지만 쓸모없음** — 자유 텍스트를 거부하는 타입. capability를 제한한다기보다 지운다.
Encryption is therefore the required branch. Its scope is unchanged from the plan: a codec behind an
application port, a ciphertext envelope carrying its key id, key rotation with history so an old row
stays readable, a migration for existing rows, and an explicit contract for what a decryption failure
does to a request.
계획의 권고에 붙은 전제가 거짓이다. (b)는 쓸 수 없다.
**It lands in the change unit that makes the write path reachable, and not before.** The reason is a
fact the spec did not have: `NotificationJpaPersistenceFacade`, which assembles
`JpaNotificationRequestStore`, is imported by nothing. The composition root's component scan excludes
the persistence package by design, and no configuration imports the facade — so the notification
capability has **no JPA persistence at all**, and no deployment currently writes this payload
anywhere. The defect is real in the code and latent in the runtime.
Designing key rotation and a row migration for rows that no deployment produces would be building the
migration before the table. Worse, it would settle the envelope's shape before the store that has to
read it is wired, which is the order that produces an envelope the store cannot use.
**One correction, learned by trying it.** This section said the envelope "lands with the wiring".
Wiring the facade first — to register the SMTP assembler — made
`NotificationPayloadAtRestContractTest` fail on the case asserting the write path is reachable from
no composition, which is exactly what that case is for. The wave forbids connecting wiring over a
known security finding on a runtime path, so the wiring was reverted and the envelope built first.
The honest ordering is **envelope before or with the wiring, never after**, and the contract test now
enforces it by failing on the wiring alone.
### The envelope, and why it has a key id
## envelope와 key id를 두는 이유
```
byte version always 1
@@ -81,36 +57,50 @@ byte[12] nonce
byte[] ciphertext + GCM tag
```
The key id is the reason there is a format at all. This repository's callback protection stores nonce
and ciphertext and nothing else, so the day the active key changes, every row written under the
previous one becomes unreadable and nothing in the row can say which key it needed — that is not a
rotation story with a gap in it, it is the absence of one. `SecretMaterialProvider` already exposes
`keyById`, so reading the id back and asking for that specific key makes rotation a change of default
rather than a data migration. The version byte costs one byte and is what allows the format to change
at all.
형식을 두는 이유는 key id다. 이 저장소의 콜백 보호는 한때 nonce와 암호문만 저장했다. 그러면 활성 키가 바뀌는 날
앞 키로 쓴 행은 모두 읽을 수 없게 되고, 행 안의 어떤 것도 어느 키가 필요했는지 말하지 못한다. 틈 있는 교체가 아니라
교체가 없는 것이다. `SecretMaterialProvider`가 이미 `keyById`를 드러내므로, id를 다시 읽어 바로 그 키를 달라고 하면
교체는 데이터 마이그레이션이 아니라 기본값 변경이 된다. version 바이트는 1바이트이고, 형식을 바꿀 수 있게 해 준다.
The header is passed as **AAD**, not merely prefixed: without that, the key id is attacker-editable
and an envelope could be redirected at a key of the attacker's choosing.
header는 앞에 붙이기만 하는 것이 아니라 **AAD**로 넘긴다. 그러지 않으면 공격자가 key id를 고쳐 envelope를 자기가
고른 키로 돌릴 수 있다.
A failed decryption throws `NotificationPayloadUnreadableException` rather than returning empty. A
caller handed an empty payload renders every variable as nothing and sends "Hello , your code is " to
a real person — the failure delivered instead of reported. All three causes (unknown key, wrong key,
modified ciphertext) collapse into one message, because telling them apart tells an attacker which of
the three they achieved.
복호화에 실패하면 빈 값을 돌려주지 않고 `NotificationPayloadUnreadableException`을 던진다. 빈 payload를 받은
호출자는 모든 변수를 빈 값으로 렌더링해 실제 사람에게 "Hello , your code is "를 보낸다. 실패를 보고하는 대신 실패를
배달하는 것이다. 세 원인(모르는 키, 틀린 키, 고쳐진 암호문)은 한 메시지로 합친다. 셋을 구별해 주면 공격자에게 셋 중
무엇을 해냈는지 알려 주기 때문이다.
## What must not be done instead
## 키 교체 순서
**Requiring `PAYLOAD_ENCRYPTION` in `INGEST_ONLY` is not a fix.** That secret is consumed by exactly
one thing — `AesGcmCallbackPayloadProtection`, which protects raw callback bodies — and by nothing on
the accept path. Demanding it would make a deployment supply a key that protects nothing while the
payload it appears to be about stays in plaintext. The repository already has one defect of that
exact shape: `app.graphql.cursor.key-ids` (key removed 2026-09-25), which production refuses to start without and which no
code signs a cursor with (GQL-INT-003). Adding a second would make the pattern a habit.
설정 키는 `app.notification.platform.secrets` 아래에 있다(`notification.yml`).
## Consequence
1. 새 키 값과 새 key id를 같은 배포에서 바꾼다(예: `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY`와
`APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY_ID`). 고정된 id는 교체를 앞 키와 구별할 수 없게 한다.
2. 같은 배포에서 밀려난 키 값을 `historical-keys.<목적>.<옛 id>` 아래에 둔다(예:
`historical-keys.PAYLOAD_ENCRYPTION.payload-2026-01`). 목적은 id에서 알아낼 수 없고, id로 키를 푸는 쪽은 목적이 다른
키를 거부한다. 그러니 다른 목적 아래 둔 옛 키는 풀리기는 해도 거부된다.
3. 옛 키로 쓴 행이 남아 있는 동안 옛 키를 그대로 둔다. `SettingsSecretMaterialProvider.keyById`는 모르는 id를 현재
키로 대신하지 않고 거부한다. 대신하면 이력의 모든 행이 읽을 때 인증 tag 실패가 된다.
Notification is **not promoted to Stable**, per the index's scope boundaries, until branch (a) is
complete. The three notification Compose lanes stay non-blocking. `NotificationPayloadAtRestContractTest`
holds every fact this decision rests on, so the decision expires automatically if any of them stops
being true — in particular, the assertion that no encryption sits on the accept path fails the moment
somebody adds one, which is the change this document is waiting for.
## 결정의 이력
> 이력: 결정 당시(Wave 2) `NotificationJpaPersistenceFacade`는 아무도 import하지 않았다. 조립 루트의 component scan은
> 설계상 persistence 패키지를 빼고, 어떤 설정도 facade를 import하지 않아서, 알림 capability에는 JPA 영속성이 아예 없었다.
> 결함은 코드에는 있고 런타임에는 숨어 있었다. 그래서 처음에는 「envelope는 그 wiring과 함께 들어간다」고 정했다.
> 아무 배포도 만들지 않는 행을 위해 키 교체와 행 마이그레이션을 설계하는 것은 테이블보다 마이그레이션을 먼저 짓는
> 일이었다.
>
> 해 보고 배운 정정이 하나 있다. SMTP assembler를 등록하려고 facade를 먼저 wiring하자,
> `NotificationPayloadAtRestContractTest`의 「쓰기 경로가 어느 조립에서도 닿지 않는다」 단언이 실패했다. 그 단언은 바로
> 그것을 잡으려고 있었다. Wave는 런타임 경로에 알려진 보안 발견을 둔 채 wiring을 잇는 것을 막았으므로 wiring을 되돌리고
> envelope를 먼저 지었다. 맞는 순서는 **envelope를 wiring 전이나 함께, 뒤에는 절대 아니다**이다.
>
> 결정 당시 `PAYLOAD_ENCRYPTION` secret을 쓰는 곳은 원본 콜백 본문을 보호하는 `AesGcmCallbackPayloadProtection` 하나뿐이었고
> 받기 경로에는 없었다. 그래서 `INGEST_ONLY`에서 그것을 요구하는 것은 고침이 아니었다. 아무것도 보호하지 않는 키를
> 배포에 요구하고, 그것이 다룬다고 보이는 payload는 평문으로 남는다. 저장소에는 이미 그런 꼴의 결함이 하나 있었다.
> `app.graphql.cursor.key-ids`(2026-09-25에 키를 지움)는 운영이 그것 없이는 뜨지 않으면서, 어떤 코드도 그것으로 cursor에
> 서명하지 않았다(GQL-INT-003). 지금은 `AesGcmNotificationPayloadProtection` 하나가 같은 envelope로 받은 payload와 보관하는
> 콜백을 모두 덮고, `NotificationSecretRequirements`가 이 목적을 모든 설정에서 요구한다.
>
> 결정 당시 결론은 이랬다. 알림은 색인의 범위 경계에 따라 (a)가 끝날 때까지 Stable로 올리지 않는다. 알림 Compose
> lane 셋은 막지 않는 lane으로 둔다.
+27 -28
View File
@@ -1,6 +1,6 @@
# Callbacks and reconciliation
# 콜백과 맞추기(reconciliation)
## Ingestion order
## 받는 순서
```text
body size limit
@@ -16,41 +16,40 @@ body size limit
→ 2xx
```
Appending before projecting is what makes a fast 2xx honest. The provider is told the event is
recorded, and a projector defect becomes a replay problem rather than a lost event.
projection보다 ledger 추가를 먼저 하기 때문에 빠른 2xx가 정직하다. provider에게는 이벤트가 기록됐다고 알리고,
projector 결함은 이벤트 유실이 아니라 replay 문제가 된다.
A rejected signature is recorded in the security audit, never in the provider event ledger. Writing
it to the ledger would let anyone who can reach the endpoint fill a delivery history with noise.
서명이 거부된 콜백은 provider event ledger가 아니라 보안 감사에 기록한다. ledger에 쓰면 엔드포인트에 닿는 누구나
전달 이력을 잡음으로 채울 수 있다.
## Duplicates and ordering
## 중복과 순서
Duplicate suppression uses `(providerProfileId, providerEventId)` where the provider supplies an
event id, and a deterministic fingerprint over profile, request id, event type, occurrence time and
payload digest where it does not. A duplicate is acknowledged and projected exactly once.
중복 억제는 provider가 event id를 주면 `(providerProfileId, providerEventId)`를 쓰고, 주지 않으면 profile, request id,
event 종류, 발생 시각, payload digest로 만든 결정적 fingerprint를 쓴다. 중복은 확인 응답하고 projection은 정확히 한 번
한다.
Out-of-order callbacks are normal. Ordering is resolved by event semantics, not by arrival time.
순서가 뒤바뀐 콜백은 보통이다. 순서는 도착 시각이 아니라 이벤트의 뜻으로 정한다.
## Unknown fields
## 모르는 칸
Callback parsers tolerate unknown JSON fields. Normalization only rejects a payload when a field
required to identify the attempt is missing. Providers add fields; that must not stop ingestion.
콜백 parser는 모르는 JSON 칸을 받아들인다. 정규화는 attempt를 가리키는 데 필요한 칸이 없을 때만 payload를 거부한다.
provider는 칸을 더한다. 그것 때문에 받기가 멈추면 안 된다.
## Reconciliation
## 맞추기
Reconciliation targets:
맞추기 대상:
- attempts stuck in `DISPATCHING` past their lease
- ambiguous submissions
- accepted attempts whose callback SLA has expired
- unmatched provider events
- lease가 지나도 `DISPATCHING`에 멈춘 attempt
- 모호한 제출
- 콜백 SLA가 지난, 수락된 attempt
- 짝이 없는 provider 이벤트
A confirmed query result is appended to the same ledger with `source = RECONCILIATION` and projected
by the same projector, so projection replay stays possible: there is no privileged second path that
writes projections directly.
확인된 조회 결과는 `source = RECONCILIATION`으로 같은 ledger에 추가하고 같은 projector가 projection한다. 그래서
projection replay가 계속 가능하다. projection을 직접 쓰는 특별한 두 번째 길은 없다.
Where a provider has no status-query capability, the platform records `Unsupported` and leaves the
attempt ambiguous. It does not infer a final status.
provider에 상태 조회 기능이 없으면 플랫폼은 `Unsupported`를 기록하고 attempt를 모호한 채로 둔다. 최종 상태를 짐작하지
않는다.
The shipped families, SES and SMTP, have no reconciliation: their assemblers contribute no
`ReconciliationCapability`, so every reconciliation job for them ends `Unsupported`. The slot on
`AssembledProvider` is for a provider family an adopter assembles with a status query of its own.
내보내는 family인 SES와 SMTP는 맞추기가 없다. 그 assembler는 `ReconciliationCapability`를 보태지 않으므로, 둘의 맞추기
작업은 모두 `Unsupported`로 끝난다. `AssembledProvider`의 그 자리는 도입하는 쪽이 자기 상태 조회와 함께 조립하는 provider
family를 위한 것이다.
+144 -153
View File
@@ -1,211 +1,202 @@
# Configuration reference
# 설정 참조
The notification delivery platform binds under `app.notification.platform`. The tree lives in
`src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml`,
which the support leaf's `ModuleDefaultsEnvironmentPostProcessor` loads at the lowest precedence,
so an application without the module carries none of it. The module is in no default composition: a
service selects it with `runtimeOnly project(':composition:notification-platform')` (plus the
persistence-jpa line) in `app-bootstrap/build.gradle`, and it is on when present. Every value carries
an inline default, so a deployment that switches the platform off supplies nothing.
알림 전달 플랫폼은 `app.notification.platform` 아래에 묶인다. 설정 트리는
`src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml`에 있고,
support leaf의 `ModuleDefaultsEnvironmentPostProcessor`가 가장 낮은 우선순위로 읽는다. 그래서 이 모듈이 없는
애플리케이션에는 이 설정이 하나도 없다. 이 모듈은 어느 기본 조립에도 없다. 서비스가
`app-bootstrap/build.gradle`에 `runtimeOnly project(':composition:notification-platform')`(와 persistence-jpa 줄)를
더해 고르고, 모듈이 있으면 켜진다. 값마다 기본값이 붙어 있으므로 플랫폼을 끄는 배포는 아무것도 주지 않아도 된다.
Until 2026-08-15 this page named properties the binding did not have — `max-retry-concurrency`,
`scheduler-poll-interval`, `callback-worker-concurrency` — and omitted three it did. There was no
tree in `application.yml` at all, so the only way to configure the platform was to guess environment
variable names from Boot's relaxed binding. `NotificationEnvironmentRegistryTest`
(`:composition:notification-platform:test`) now fails when the shipped YAML and
`docs/registries/env-keys.yaml` disagree.
> 이력: 2026-08-15까지 이 문서는 바인딩에 없는 속성(`max-retry-concurrency`, `scheduler-poll-interval`,
> `callback-worker-concurrency`)을 적었고, 있는 속성 셋을 빠뜨렸다. `application.yml`에 트리가 아예 없어서, 플랫폼을
> 설정하려면 Boot의 relaxed binding으로 환경 변수 이름을 짐작해야 했다.
## Master switch
지금은 내보내는 YAML과 `docs/registries/env-keys.yaml`이 다르면 `NotificationEnvironmentRegistryTest`
(`:composition:notification-platform:test`)가 실패한다.
| Property | Environment variable | Default | Meaning |
## 주 스위치
| 속성 | 환경 변수 | 기본값 | 뜻 |
|---|---|---|---|
| `enabled` | `APP_NOTIFICATION_PLATFORM_ENABLED` | `true` | On while the module is present. `false` binds nothing at all: no runtime, no schema check, no scheduler thread, no secret required |
| `mode` | `APP_NOTIFICATION_PLATFORM_MODE` | `SERVING` | `SERVING` refuses to start without a working provider; `INGEST_ONLY` stores requests and does not dispatch: it builds no provider runtime but records each enabled profile's route, so a request accepted now is delivered later on that route by a `SERVING` deployment (handoff) |
| `enabled` | `APP_NOTIFICATION_PLATFORM_ENABLED` | `true` | 모듈이 있으면 켜진다. `false`면 아무것도 묶지 않는다. 런타임도, 스키마 검사도, scheduler 스레드도, 필요한 secret도 없다 |
| `mode` | `APP_NOTIFICATION_PLATFORM_MODE` | `SERVING` | `SERVING`은 동작하는 provider가 없으면 뜨기를 거부한다. `INGEST_ONLY`는 요청을 저장만 하고 보내지 않는다. provider 런타임을 만들지 않지만 켜진 profile마다 route를 기록하므로, 지금 받은 요청은 나중에 `SERVING` 배포가 그 route로 보낸다(handoff) |
## Dispatch
## 발송
| Property | Environment variable | Default | Bound |
| 속성 | 환경 변수 | 기본값 | 범위 |
|---|---|---|---|
| `dispatch.claim-batch-size` | `APP_NOTIFICATION_PLATFORM_CLAIM_BATCH_SIZE` | `50` | 1..1000 |
| `dispatch.lease-duration` | `APP_NOTIFICATION_PLATFORM_LEASE_DURATION` | `2m` | positive, finite |
| `dispatch.poll-interval` | `APP_NOTIFICATION_PLATFORM_POLL_INTERVAL` | `1s` | positive, finite |
| `dispatch.max-global-concurrency` | `APP_NOTIFICATION_PLATFORM_MAX_CONCURRENCY` | `64` | positive |
| `dispatch.max-additional-attempts` | `APP_NOTIFICATION_PLATFORM_MAX_ADDITIONAL_ATTEMPTS` | `4` | non-negative |
| `dispatch.max-queue-age` | `APP_NOTIFICATION_PLATFORM_MAX_QUEUE_AGE` | `24h` | positive |
| `dispatch.lease-duration` | `APP_NOTIFICATION_PLATFORM_LEASE_DURATION` | `2m` | 양수, 유한 |
| `dispatch.poll-interval` | `APP_NOTIFICATION_PLATFORM_POLL_INTERVAL` | `1s` | 양수, 유한 |
| `dispatch.max-global-concurrency` | `APP_NOTIFICATION_PLATFORM_MAX_CONCURRENCY` | `64` | 양수 |
| `dispatch.max-additional-attempts` | `APP_NOTIFICATION_PLATFORM_MAX_ADDITIONAL_ATTEMPTS` | `4` | 0 이상 |
| `dispatch.max-queue-age` | `APP_NOTIFICATION_PLATFORM_MAX_QUEUE_AGE` | `24h` | 양수 |
| `dispatch.allow-ambiguous-fallback` | `APP_NOTIFICATION_PLATFORM_ALLOW_AMBIGUOUS_FALLBACK` | `false` | boolean |
Every value is bounded. "Unlimited" is not an accepted configuration.
모든 값에 상한이 있다. 「무제한」은 받는 설정이 아니다.
The lease must outlast a provider call plus its timeout. Below that, a delivery a live worker is
still waiting on gets claimed by a second worker, and the recipient receives the notification twice.
lease는 provider 호출과 그 시간 상한보다 길어야 한다. 그보다 짧으면, 살아 있는 worker가 아직 기다리는 전달을 두 번째
worker가 claim하고, 수신자는 알림을 두 번 받는다.
## Callbacks
## 콜백
| Property | Environment variable | Default | Bound |
| 속성 | 환경 변수 | 기본값 | 범위 |
|---|---|---|---|
| `callbacks.enabled` | `APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED` | `false` | boolean |
| `callbacks.max-body-bytes` | `APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES` | `65251` | 1..65251 |
| `callbacks.replay-skew` | `APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW` | `1h` | positive; SNS messages whose `Timestamp` is further than this from receipt, either way, are rejected. The default is SNS's longest HTTP/S retry period (3,600 s), so a bounce or complaint SNS redelivers after an outage is still accepted; a replay inside the window is a duplicate in the provider event ledger, not a second event (review 05-20) |
| `callbacks.trusted-proxies` | `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES` | *(empty)* | CSV of peer addresses |
| `callbacks.replay-skew` | `APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW` | `1h` | 양수. `Timestamp`가 받은 시각에서 이보다 멀리(앞이든 뒤든) 떨어진 SNS 메시지는 거절한다. 기본값은 SNS의 HTTP/S 재시도 기간 중 가장 긴 값(3,600 s)이라, 장애 뒤에 SNS가 다시 보내는 bounce·complaint도 받는다. 창 안의 replay는 provider event ledger에서 중복이지 두 번째 이벤트가 아니다(review 05-20) |
콜백 응답: 기록(중복 포함) `204`, 거절 `400`(서명·topic·시각·형식), 본문 초과 `413`. SNS 서명 인증서를 가져오지 못하면(5xx·408·429·네트워크 실패) 거절하지 않고 `503`+`Retry-After`로 답한다 — SNS는 4xx를 처리 완료로 보고 재전송을 멈추지만 5xx는 다시 보낸다(review 05-20). 인증서 URL이 그 밖의 4xx(403·404 등)로 답하면 SNS가 발급하지 않은 인증서를 가리킨 위조 콜백이므로 서명 검증 실패로 `400` 거절하고 보안 감사(`callbackSignatureRejected`)에 남긴다(review 2026-11-03 RR-07-03). 호스트 검사를 통과한 URL이라 답하는 쪽은 SNS다.
콜백 응답: 기록(중복 포함) `204`, 거절 `400`(서명·topic·시각·형식), 본문 초과 `413`. SNS 서명 인증서를 가져오지
못하면(5xx·408·429·네트워크 실패) 거절하지 않고 `503`+`Retry-After`로 답한다. SNS는 4xx를 처리 완료로 보고 재전송을
멈추지만 5xx는 다시 보낸다(review 05-20). 인증서 URL이 그 밖의 4xx(403·404 등)로 답하면 SNS가 발급하지 않은 인증서를
가리킨 위조 콜백이므로 서명 검증 실패로 `400` 거절하고 보안 감사(`callbackSignatureRejected`)에 남긴다(review
2026-11-03 RR-07-03). 호스트 검사를 통과한 URL이라 답하는 쪽은 SNS다.
여러 provider가 요청 URL에 서명하므로, 그 URL을 잘못 재구성하면 정상 webhook이 전부 서명 실패가 된다.
`trusted-proxies`가 비어 있으면 forwarded 헤더를 **믿지 않고** 컨테이너가 관측한 값을 쓴다. 무조건 믿으면
아무 호출자나 자기 서명이 검증될 URL을 고를 수 있어 서명 자체가 무의미해진다. 로드밸런서 뒤에 있는 배포는
그 peer를 명시한다.
여러 provider가 요청 URL에 서명하므로, 그 URL을 잘못 재구성하면 정상 webhook이 전부 서명 실패가 된다. provider가
서명한 URL은 컨테이너가 보고한 값으로 다시 만든다. 콜백 전용 proxy 목록은 없다. 로드밸런서 뒤에 있는 배포는
`APP_SERVER_FORWARD_HEADERS_STRATEGY=native`로 두고 그 proxy를 `server.tomcat.remoteip.internal-proxies`에 적는다.
forwarded 헤더를 무조건 믿으면 아무 호출자나 자기 서명이 검증될 URL을 고를 수 있어 서명 자체가 무의미해진다.
65251 is not a round number by accident: it is the ciphertext column's 65536 bytes minus the largest
envelope the protector writes — a version byte, a key-id length byte, a key id of up to 255 bytes, the
AES-GCM nonce and tag. A larger configured value is refused when the settings bind, so the capability
does not start; before that check existed it passed every layer above the database and failed the
`CHECK` constraint after the callback had already been acknowledged to the provider. The shipped
default was 65508 (nonce and tag only) for a while after the envelope gained its key id, and every
deployment that turned the platform on failed to start until it was corrected (review 2026-11-01
r3-i, found by booting the compose lanes).
65251은 우연히 고른 수가 아니다. 암호문 칸의 65536바이트에서 protector가 쓰는 가장 큰 envelope를 뺀 값이다. version
바이트, key id 길이 바이트, 255바이트까지의 key id, AES-GCM nonce와 tag다. 이보다 큰 값은 설정을 묶을 때 거부되므로
capability가 뜨지 않는다. 그 검사가 생기기 전에는 DB 위의 모든 층을 통과한 뒤, 콜백을 provider에 이미 확인 응답한 다음
`CHECK` 제약에서 실패했다.
## Provider profiles
> 이력: envelope에 key id가 붙은 뒤에도 한동안 내보낸 기본값이 65508(nonce와 tag만 뺀 값)이었고, 플랫폼을 켠 배포는 그
> 값을 고칠 때까지 모두 뜨지 못했다(review 2026-11-01 r3-i, compose lane을 띄워서 찾음).
Profiles are a map under `providers`, keyed by profile id. Arbitrary deployment-chosen ids can be
supplied as YAML or through Spring relaxed binding (`APP_NOTIFICATION_PLATFORM_PROVIDERS_<ID>_<FIELD>`).
The shipped reference profiles `smtp` and `ses` additionally expose explicit `APP_NOTIFICATION_PLATFORM_SMTP_*`
and `APP_NOTIFICATION_PLATFORM_SES_*` aliases so operators do not have to invent binding names.
## provider profile
| Field | Meaning |
profile은 `providers` 아래의 map이고, 키는 profile id다. 배포가 정한 아무 id나 YAML이나 Spring relaxed binding
(`APP_NOTIFICATION_PLATFORM_PROVIDERS_<ID>_<FIELD>`)으로 줄 수 있다. 내보내는 참조 profile `smtp`와 `ses`는 그 밖에
`APP_NOTIFICATION_PLATFORM_SMTP_*`와 `APP_NOTIFICATION_PLATFORM_SES_*` 별칭도 드러내므로, 운영자가 바인딩 이름을
지어낼 필요가 없다.
| 칸 | 뜻 |
|---|---|
| `type` | `SES`, `SMTP` — a closed enum, so an unknown value fails binding rather than assembling into nothing |
| `enabled` | A disabled profile is bound and validated but contributes no runtime |
| `primary-for-channel` | Exactly one primary per channel |
| `environment` | Required when enabled |
| `credential-profile` | Provider credential key id resolved through `SecretMaterialProvider`; never inline secret material |
| `timeout` | Positive and finite |
| `max-concurrency` | Positive |
| `rate-per-second` | Positive |
| `type` | `SES`, `SMTP`. 닫힌 enum이라 모르는 값은 아무것도 조립하지 않고 넘어가는 대신 바인딩에서 실패한다 |
| `enabled` | 꺼진 profile도 묶이고 검증되지만 런타임에 아무것도 보태지 않는다 |
| `primary-for-channel` | 채널마다 primary는 정확히 하나 |
| `environment` | 켜면 필요하다 |
| `credential-profile` | `SecretMaterialProvider`로 푸는 provider 자격 증명 key id. secret 값을 직접 적지 않는다 |
| `timeout` | 양수, 유한 |
| `max-concurrency` | 양수 |
| `rate-per-second` | 양수 |
A profile pins provider type, environment, credential profile, timeouts, concurrency and rate limit.
Sender identity and credential profile are separate concerns.
profile 하나가 provider 종류, 환경, 자격 증명 profile, 시간 상한, 동시성, 속도 제한을 고정한다. 보내는 쪽 신원과 자격
증명 profile은 서로 다른 문제다.
### SES profile fields
### SES profile 칸
An enabled SES profile adds a typed `ses` block:
켜진 SES profile에는 타입이 있는 `ses` 블록이 더해진다.
| Field | Meaning |
| 칸 | 뜻 |
|---|---|
| `ses.endpoint` | SES API base URI, used as the AWS SDK client's endpoint override |
| `ses.region` | AWS region the SDK signs for |
| `ses.sender-identity` | verified SES From identity |
| `ses.access-key-id` | AWS access key id; identifier only, not secret material |
| `ses.configuration-set` | optional SES configuration-set name |
| `ses.allowed-topic-arns` | SNS topic ARNs whose SES events this profile accepts (`APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS`, comma-separated). Required when `callbacks.enabled=true`: binding fails without it, because a valid SNS signature only proves AWS sent the message and anyone can own a topic |
| `credential-profile` | key id for the secret access-key material; generation 1 is activated at assembly |
| `ses.endpoint` | SES API 기본 URI. AWS SDK 클라이언트의 endpoint override로 쓴다 |
| `ses.region` | SDK가 서명하는 AWS region |
| `ses.sender-identity` | 검증된 SES From 신원 |
| `ses.access-key-id` | AWS access key id. 식별자일 뿐 secret 값이 아니다 |
| `ses.configuration-set` | 선택. SES configuration-set 이름 |
| `ses.allowed-topic-arns` | 이 profile이 SES 이벤트를 받는 SNS topic ARN(`APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS`, 쉼표로 구분). `callbacks.enabled=true`면 필요하다. 없으면 바인딩이 실패한다. 유효한 SNS 서명은 AWS가 메시지를 보냈다는 것만 증명하고, topic은 누구나 가질 수 있기 때문이다 |
| `credential-profile` | secret access key 값의 key id. 조립할 때 세대 1이 활성화된다 |
The shipped reference profile is `providers.ses` and is disabled by default. It is controlled by
`APP_NOTIFICATION_PLATFORM_SES_*`; its secret material comes from
`APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY`, whose active key id must match
`APP_NOTIFICATION_PLATFORM_SES_CREDENTIAL_KEY_ID`.
내보내는 참조 profile은 `providers.ses`이고 기본으로 꺼져 있다. `APP_NOTIFICATION_PLATFORM_SES_*`로 다룬다. secret 값은
`APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY`에서 오고, 그 활성 key id는
`APP_NOTIFICATION_PLATFORM_SES_CREDENTIAL_KEY_ID`와 같아야 한다.
`type` lists only the families the shipped composition can assemble. Current shipped
reachability is:
`type`에는 내보내는 조립이 만들 수 있는 family만 있다. 지금 내보내는 것으로 닿는 범위는 다음과 같다.
| Provider type | Contract/adapter code | Shipped dispatch assembler | Shipped callback assembler | What happens when enabled for dispatch |
| provider 종류 | 계약·어댑터 코드 | 내보내는 발송 assembler | 내보내는 콜백 assembler | 발송용으로 켜면 |
|---|---|---|---|---|
| `SMTP` | yes | **yes** | no | assembles when Spring Mail relay settings are complete |
| `SES` | yes | **yes** | **yes** | assembles an EMAIL runtime from the typed `ses` block; SNS callback verification remains available in `INGEST_ONLY` |
| `SMTP` | 있음 | **있음** | 없음 | Spring Mail relay 설정이 다 있으면 조립한다 |
| `SES` | 있음 | **있음** | **있음** | 타입 있는 `ses` 블록으로 EMAIL 런타임을 조립한다. SNS 콜백 검증은 `INGEST_ONLY`에서도 쓸 수 있다 |
APNs, FCM, Twilio, Web Push and Webhook adapters used to ship as protocol code with no assembler, so
enabling one failed startup. They were removed; the `docs/capability-status.md` "제거된 코드" table
names the last commit that had them. Adding a family back means adding its adapter, a
`ProviderRuntimeAssembler`, its `ProviderType` constant and the settings/secret inputs it actually
needs, together.
APNs, FCM, Twilio, Web Push, Webhook 어댑터는 assembler 없이 프로토콜 코드로만 들어 있어서 켜면 기동이 실패했다. 그래서
지웠다. 마지막으로 그것을 가진 커밋은 `docs/capability-status.md` 「제거된 코드」 표가 적는다. family를 다시 더하려면
그 어댑터, `ProviderRuntimeAssembler`, `ProviderType` 상수, 실제로 필요한 설정·secret 입력을 함께 더한다.
## SMTP relay
The one provider profile the template ships, off. A deployment that wants the common case sets
`APP_NOTIFICATION_PLATFORM_SMTP_ENABLED=true` and the relay address; one that wants a different
profile id or a second family declares it in its own YAML instead.
템플릿이 내보내는 provider profile 하나이고, 꺼져 있다. 흔한 경우를 원하는 배포는
`APP_NOTIFICATION_PLATFORM_SMTP_ENABLED=true`와 relay 주소를 준다. 다른 profile id나 두 번째 family를 원하는 배포는
대신 자기 YAML에 선언한다.
The profile and the relay are separate tables below because they answer different questions. The
profile says *which* provider serves EMAIL and under what limits; the relay says *what the transport
is*. Host, port and credentials are not here at all — they stay `spring.mail.*`, because Spring
already owns them and a second spelling would be a second thing to keep in step.
profile과 relay는 다른 질문에 답하므로 아래 두 표로 나눈다. profile은 *어느* provider가 EMAIL을 어떤 한도로 맡는지를
말하고, relay는 *전송이 무엇인지*를 말한다. host, port, 자격 증명은 여기에 아예 없다. `spring.mail.*`에 그대로 둔다.
Spring이 이미 그것을 가지고 있고, 두 번째 표기는 맞춰 둘 것을 하나 더 만든다.
| Property | Environment variable | Default | Bound |
| 속성 | 환경 변수 | 기본값 | 범위 |
|---|---|---|---|
| `providers.smtp.enabled` | `APP_NOTIFICATION_PLATFORM_SMTP_ENABLED` | `false` | boolean |
| `providers.smtp.primary-for-channel` | `APP_NOTIFICATION_PLATFORM_SMTP_PRIMARY` | `true` | boolean; exactly one primary per channel |
| `providers.smtp.environment` | `APP_NOTIFICATION_PLATFORM_SMTP_ENVIRONMENT` | `local` | required when enabled |
| `providers.smtp.credential-profile` | `APP_NOTIFICATION_PLATFORM_SMTP_CREDENTIAL_PROFILE` | `default` | resolved through `SecretMaterialProvider`, never inline material |
| `providers.smtp.timeout` | `APP_NOTIFICATION_PLATFORM_SMTP_TIMEOUT` | `10s` | positive, finite |
| `providers.smtp.max-concurrency` | `APP_NOTIFICATION_PLATFORM_SMTP_MAX_CONCURRENCY` | `4` | positive |
| `providers.smtp.rate-per-second` | `APP_NOTIFICATION_PLATFORM_SMTP_RATE_PER_SECOND` | `10` | positive |
| `providers.smtp.primary-for-channel` | `APP_NOTIFICATION_PLATFORM_SMTP_PRIMARY` | `true` | boolean. 채널마다 primary는 정확히 하나 |
| `providers.smtp.environment` | `APP_NOTIFICATION_PLATFORM_SMTP_ENVIRONMENT` | `local` | 켜면 필요하다 |
| `providers.smtp.credential-profile` | `APP_NOTIFICATION_PLATFORM_SMTP_CREDENTIAL_PROFILE` | `default` | `SecretMaterialProvider`로 푼다. 값을 직접 적지 않는다 |
| `providers.smtp.timeout` | `APP_NOTIFICATION_PLATFORM_SMTP_TIMEOUT` | `10s` | 양수, 유한 |
| `providers.smtp.max-concurrency` | `APP_NOTIFICATION_PLATFORM_SMTP_MAX_CONCURRENCY` | `4` | 양수 |
| `providers.smtp.rate-per-second` | `APP_NOTIFICATION_PLATFORM_SMTP_RATE_PER_SECOND` | `10` | 양수 |
| Property | Environment variable | Default | Bound |
| 속성 | 환경 변수 | 기본값 | 범위 |
|---|---|---|---|
| `smtp.sender-identity` | `APP_NOTIFICATION_PLATFORM_SMTP_SENDER_IDENTITY` | `no-reply@example.invalid` | address |
| `smtp.dispatch-concurrency` | `APP_NOTIFICATION_PLATFORM_SMTP_DISPATCH_CONCURRENCY` | `4` | positive |
| `smtp.sender-identity` | `APP_NOTIFICATION_PLATFORM_SMTP_SENDER_IDENTITY` | `no-reply@example.invalid` | 주소 |
| `smtp.dispatch-concurrency` | `APP_NOTIFICATION_PLATFORM_SMTP_DISPATCH_CONCURRENCY` | `4` | 양수 |
SMTP transport configuration has one owner: Spring Mail. The actual `JavaMailSenderImpl` must use required STARTTLS (`mail.smtp.starttls.enable=true` plus `mail.smtp.starttls.required=true`) or implicit TLS (`mail.smtp.ssl.enable=true`). It must also have positive `mail.smtp.connectiontimeout`, `mail.smtp.timeout`, and `mail.smtp.writetimeout` values. SMTP assembly fails before serving traffic when those properties are absent or invalid.
SMTP 전송 설정의 소유자는 Spring Mail 하나다. 실제 `JavaMailSenderImpl`은 필수 STARTTLS
(`mail.smtp.starttls.enable=true`와 `mail.smtp.starttls.required=true`)나 암묵적 TLS(`mail.smtp.ssl.enable=true`)를
써야 한다. `mail.smtp.connectiontimeout`, `mail.smtp.timeout`, `mail.smtp.writetimeout`도 양수여야 한다. 이 속성이
없거나 틀리면 SMTP 조립이 트래픽을 받기 전에 실패한다.
The native environment contract is `SPRING_MAIL_HOST`, `SPRING_MAIL_PORT`, optional
`SPRING_MAIL_USERNAME` / secret `SPRING_MAIL_PASSWORD`, plus the
`SPRING_MAIL_PROPERTIES_MAIL_SMTP_*` TLS and timeout keys listed in `.env.example`. These names stay
Spring-native because Spring Boot itself owns and consumes `spring.mail.*`; the notification module
does not create a second alias for the same relay.
환경 변수 계약은 Spring 그대로다. `SPRING_MAIL_HOST`, `SPRING_MAIL_PORT`, 선택인 `SPRING_MAIL_USERNAME`과 secret
`SPRING_MAIL_PASSWORD`, 그리고 `.env.example`에 있는 `SPRING_MAIL_PROPERTIES_MAIL_SMTP_*` TLS·시간 상한 키다. Spring
Boot 자신이 `spring.mail.*`를 가지고 읽으므로 이름을 Spring 그대로 둔다. 알림 모듈은 같은 relay에 두 번째 별칭을
만들지 않는다.
The default sender is an RFC 2606 reserved domain that resolves nowhere, so a deployment that forgot
to set one produces a traceable bounce instead of mail apparently sent from an address it does not
own.
기본 보내는 주소는 어디로도 풀리지 않는 RFC 2606 예약 도메인이다. 그래서 보내는 주소 설정을 잊은 배포는, 자기가
가지지 않은 주소로 메일을 보낸 것처럼 보이는 대신 추적할 수 있는 bounce를 낸다.
## Startup failures
## 기동 실패
Startup fails rather than degrading when:
다음이면 기능을 줄여 뜨지 않고 기동이 실패한다.
- a payload or queue setting is unbounded
- a timeout is negative
- a TTL-required profile has no expiry source
- a callback signing secret is missing
- a production profile enables trust-all
- an SES profile is missing its `ses` block, or callbacks are on and `ses.allowed-topic-arns` is empty
- two provider profiles share an id
- a route points only at disabled providers
- `mode` is `SERVING` and no provider profile is enabled
- the notification schema stream is not applied and promoted
- payload나 큐 설정에 상한이 없다
- 시간 상한이 음수다
- TTL이 필요한 profile에 만료 출처가 없다
- 콜백 서명 secret이 없다
- 운영 profile이 trust-all을 켠다
- SES profile에 `ses` 블록이 없거나, 콜백이 켜졌는데 `ses.allowed-topic-arns`가 비어 있다
- 두 provider profile의 id가 같다
- route가 꺼진 provider만 가리킨다
- `mode`가 `SERVING`인데 켜진 provider profile이 없다
- 알림 스키마 stream이 적용·승격되지 않았다
## Secrets
## secret
All key material arrives through `SecretMaterialProvider`. Nothing is read from source, from a
committed file, or from a plaintext log. Contact point encryption and lookup HMAC keys must be
distinct, and the encryption key must be exactly 256 bits.
키 값은 모두 `SecretMaterialProvider`로 들어온다. 소스, 커밋한 파일, 평문 로그에서는 아무것도 읽지 않는다. 연락처
암호화 키와 조회 HMAC 키는 서로 달라야 하고, 암호화 키는 정확히 256비트여야 한다.
Seven purposes, seven keys. Each is base64 of at least 32 bytes and each must differ from every
other; the platform decodes them at startup and refuses to boot if one is blank, short or shared. A
blank value used to be skipped, which meant the platform started without the key and found out on
the first contact point — in production, on a recipient's notification.
목적 일곱, 키 일곱이다. 각각 32바이트 이상의 base64이고 다른 모든 키와 달라야 한다. 플랫폼은 기동할 때 키를 풀어
보고, 하나라도 비었거나 짧거나 겹치면 뜨기를 거부한다. 전에는 빈 값을 건너뛰었고, 그래서 플랫폼이 키 없이 뜬 뒤 첫
연락처에서야, 운영에서는 수신자의 알림에서야 그것을 알았다.
Every default below is **unset**, deliberately. Supply the values out of band, per environment. Do
not write one into this table, into `application.yml`, into an `.env` file that is tracked, or into
any example: a value that appears in the repository is a value that has been disclosed.
아래 기본값은 모두 일부러 **비어 있다**. 값은 환경마다 따로 준다. 이 표, `application.yml`, 추적되는 `.env` 파일, 어느
예시에도 값을 쓰지 않는다. 저장소에 나타난 값은 이미 드러난 값이다.
| Purpose | Key material | Active key id |
| 목적 | 키 값 | 활성 key id |
|---|---|---|
| Contact point encryption | `APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY` | `APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY_ID` |
| Contact point lookup HMAC | `APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY_ID` |
| Callback signing | `APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY` | `APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY_ID` |
| Callback fingerprint HMAC | `APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY_ID` |
| Provider credential encryption | `APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY` | `APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY_ID` |
| Provider request lookup HMAC | `APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY_ID` |
| Payload encryption | `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY` | `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY_ID` |
| 연락처 암호화 | `APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY` | `APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY_ID` |
| 연락처 조회 HMAC | `APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY_ID` |
| 콜백 서명 | `APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY` | `APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY_ID` |
| 콜백 fingerprint HMAC | `APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_CALLBACK_FINGERPRINT_HMAC_KEY_ID` |
| provider 자격 증명 암호화 | `APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY` | `APP_NOTIFICATION_PLATFORM_PROVIDER_CREDENTIAL_KEY_ID` |
| provider 요청 조회 HMAC | `APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY` | `APP_NOTIFICATION_PLATFORM_PROVIDER_REQUEST_LOOKUP_HMAC_KEY_ID` |
| payload 암호화 | `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY` | `APP_NOTIFICATION_PLATFORM_PAYLOAD_ENCRYPTION_KEY_ID` |
A key id is not secret — an id identifies key material without revealing it — but it is required,
and it has no default on purpose. A constant id makes a rotation indistinguishable from the key it
replaced, so nothing could decrypt what was written before it. Change the id in the same deployment
that changes the material, and keep the superseded key readable under its old id until the data it
wrote has been re-encrypted. The rotation sequence is in
[at-rest-threat-model.md](at-rest-threat-model.md).
key id는 secret이 아니다. id는 키 값을 드러내지 않고 그것을 가리킨다. 그래도 필요하고, 일부러 기본값이 없다. 고정된
id는 교체를 바뀌기 전 키와 구별할 수 없게 만들어서, 그 전에 쓴 것을 아무것도 풀지 못하게 한다. 키 값을 바꾸는 배포에서
id도 함께 바꾸고, 밀려난 키는 그 키로 쓴 데이터를 다시 암호화할 때까지 옛 id로 읽을 수 있게 둔다. 교체 순서는
[at-rest-threat-model.md](at-rest-threat-model.md)에 있다.
## Readiness
## readiness
The platform contributes a `notifications` actuator endpoint and a health indicator. It reports DOWN
when a provider's credentials were rejected, when a configured provider has no channel route, and
when the measured backlog, stuck-lease count, projection lag or reconciliation lag passes the
thresholds in `NotificationServingThresholds`. See [operations.md](operations.md).
플랫폼은 `notifications` actuator 엔드포인트와 health indicator를 보탠다. provider 자격 증명이 거부됐을 때, 설정된
provider에 채널 route가 없을 때, 그리고 잰 backlog, 멈춘 lease 수, projection 지연, 맞추기(reconciliation) 지연이
`NotificationServingThresholds`의 임계값을 넘을 때 DOWN을 보고한다. [operations.md](operations.md)를 본다.
+29 -32
View File
@@ -1,6 +1,6 @@
# Delivery evidence model
# 전달 증거 모델
## The shape
## 모양
```text
NotificationRequest
@@ -12,39 +12,37 @@ NotificationRequest
+ EngagementFacts + SuppressionFacts
```
Four identities, four lifecycles. A logical request is not a recipient job, a recipient job is not a
provider attempt, and a provider attempt is not the event stream that describes it.
신원 넷, 수명 주기 넷이다. 논리 요청은 수신자 작업이 아니고, 수신자 작업은 provider attempt가 아니고, provider attempt는
그것을 설명하는 이벤트 흐름이 아니다.
## Why not one status enum
## 상태 enum 하나가 아닌 이유
A single linear status would have to answer "what happened?" with one value, and the real answers do
not fit on one line:
일직선 상태 하나는 「무슨 일이 있었나」에 값 하나로 답해야 하는데, 실제 답은 한 줄에 들어가지 않는다.
- An email can be `DELIVERED` and then generate a complaint. Both facts are true and both matter:
one for reporting, the other for suppression.
- Twilio does not guarantee callback ordering, so `sent` routinely arrives after `delivered`. Under
an ordinal rule the later, weaker event silently overwrites the stronger one.
- APNs may accept a notification and then store, replace or discard it.
- 이메일은 `DELIVERED`가 된 뒤 complaint를 낼 수 있다. 두 사실이 다 참이고 다 중요하다. 하나는 보고에, 다른 하나는
억제에 쓴다.
- Twilio는 콜백 순서를 보장하지 않아서 `sent`가 `delivered` 뒤에 오는 일이 흔하다. 순번 규칙에서는 뒤에 온 약한
이벤트가 강한 이벤트를 조용히 덮어쓴다.
- APNs는 알림을 수락한 뒤 저장하거나, 바꾸거나, 버릴 수 있다.
So the ledger stores events and a channel projector merges them through an explicit transition table.
`StandardDeliveryProjector` holds the shared rules; provider projectors add only their own event
vocabulary.
그래서 ledger는 이벤트를 저장하고, channel projector가 명시한 전이 표로 그것을 합친다. 공통 규칙은
`StandardDeliveryProjector`가 가지고, provider projector는 자기 이벤트 어휘만 더한다.
## Merge rules
## 합치는 규칙
| Transition | Result |
| 전이 | 결과 |
|---|---|
| `sent` → `delivered` | applied |
| `delivered` → `sent` | ignored, event still stored |
| `delivered` → `complaint` | complaint fact added, delivery preserved |
| `complaint` → `delivered` | delivery applied, complaint preserved |
| `accepted` → `bounced` | applied |
| `read` → `displayed` | ignored |
| hard bounce → `delivered` | ignored, hard bounce is terminal |
| `sent` → `delivered` | 적용 |
| `delivered` → `sent` | 무시, 이벤트는 저장 |
| `delivered` → `complaint` | complaint 사실을 더하고 전달은 유지 |
| `complaint` → `delivered` | 전달을 적용하고 complaint는 유지 |
| `accepted` → `bounced` | 적용 |
| `read` → `displayed` | 무시 |
| hard bounce → `delivered` | 무시, hard bounce는 끝 상태 |
Engagement (`opened`, `clicked`) is stored beside the delivery outcome and never changes it.
참여(`opened`, `clicked`)는 전달 결과 옆에 저장하고 그것을 바꾸지 않는다.
## Ambiguity
## 모호함
```text
platform ──── send ────▶ provider
@@ -53,10 +51,9 @@ platform ──── send ────▶ provider
✗ connection reset
```
The platform may hold no provider request id while the notification really was sent. The attempt
records `requestStarted`, `requestBodyCommitted`, `providerResponseReceived` and an
`EvidenceCertainty` for each, so a later decision can tell "we know nothing was sent" apart from "we
could not read the answer".
알림이 실제로 보내졌는데 플랫폼은 provider request id를 하나도 가지지 못할 수 있다. attempt는 `requestStarted`,
`requestBodyCommitted`, `providerResponseReceived`와 그 각각의 `EvidenceCertainty`를 기록한다. 그래서 나중의 판단이
「아무것도 보내지 않았음을 안다」와 「답을 읽지 못했다」를 가릴 수 있다.
`ProviderSubmissionResult` enforces this: an ambiguous result may not claim `PROVIDER_ACCEPTED`, and
no submission result of any kind may carry a delivery outcome.
`ProviderSubmissionResult`가 이것을 강제한다. 모호한 결과는 `PROVIDER_ACCEPTED`를 주장할 수 없고, 어떤 제출 결과도
전달 결과를 실을 수 없다.
+24 -31
View File
@@ -1,45 +1,38 @@
# Migration guide
# 이행 안내
## From the R0 routing seam
## R0 routing seam에서
The pre-existing `dev.caskeleton.adapter.outbound.notification` router (`RoutingNotifier`,
`FailOpenNotificationProvider`, the Google email and Slack webhook seams) stays untouched. The
delivery platform lives beside it under `…notification.platform` and does not modify or delete any
R0 class.
이미 있던 `dev.caskeleton.adapter.outbound.notification` router(`RoutingNotifier`, `FailOpenNotificationProvider`, Google
email과 Slack webhook seam)는 건드리지 않는다. 전달 플랫폼은 그 옆 `…notification.platform` 아래에 있고, R0 클래스를
고치거나 지우지 않는다.
Migration order per capability:
capability마다 이행 순서:
1. Register the contact points behind `ContactPointStorePort` so the platform owns protected values.
2. Publish the template version, and pin the template id, version and locale at every call site.
3. Move the call site from the router to the N1 typed facade for the channel.
4. Verify evidence in the snapshot rather than in the caller's return value: `submit()` is durable
acceptance and nothing more.
5. Remove the R0 route only after the platform route has produced provider evidence in the target
environment.
1. 플랫폼이 보호된 값을 가지도록 연락처를 `ContactPointStorePort` 뒤에 등록한다.
2. 템플릿 버전을 게시하고, 모든 호출 지점에서 템플릿 id, 버전, locale을 고정한다.
3. 호출 지점을 router에서 그 채널의 N1 typed facade로 옮긴다.
4. 증거는 호출자의 반환값이 아니라 snapshot에서 확인한다. `submit()`은 durable 수락일 뿐이다.
5. 대상 환경에서 플랫폼 route가 provider 증거를 낸 뒤에만 R0 route를 지운다.
## Return-value semantics change
## 반환값의 뜻이 바뀐다
The R0 seam returned a send-shaped result. `NotificationReceipt` returns `notificationId`, a request
status and an acceptance time. Callers that treated the old return value as proof of delivery must be
changed; there is no compatibility shim, because a shim would have to invent the delivery claim this
platform exists to avoid.
R0 seam은 보낸 결과 모양을 돌려줬다. `NotificationReceipt`는 `notificationId`, 요청 상태, 수락 시각을 돌려준다. 옛
반환값을 전달 증거로 다룬 호출자는 고쳐야 한다. 호환 shim은 없다. shim은 이 플랫폼이 피하려고 있는 전달 주장을 지어내야
하기 때문이다.
## FCM target migration
## FCM 대상 이행
Registration tokens keep working through `LegacyFcmRegistrationToken`. New registrations should use
`FcmInstallationId`. The two are distinct types, so a migration is a compile-time task rather than a
runtime guess.
registration token은 `LegacyFcmRegistrationToken`으로 계속 쓸 수 있다. 새 등록은 `FcmInstallationId`를 쓴다. 둘은 서로
다른 타입이라 이행은 런타임 짐작이 아니라 컴파일 시점의 일이다.
## R1의 처분 (NOTIF-ADR-005)
이 문서는 R0 router → platform 이행만 설명해 왔고, `dev.caskeleton.application.notification` 직속의
R1 public type 100개를 어떻게 할 것인지 다루지 않았다. 그래서 새 consumer가 어느 API를 써야 하는지
문서 어디에도 답이 없었다.
이 문서는 R0 router → platform 이행만 설명해 왔고, `dev.caskeleton.application.notification` 직속의 R1 public type
100개를 어떻게 할 것인지 다루지 않았다. 그래서 새 consumer가 어느 API를 써야 하는지 문서 어디에도 답이 없었다.
- **canonical은 `..notification.platform..`이다.** NOTIF-ADR-005가 근거와 함께 정한다.
- **application R1 public type은 2026-09-25에 삭제했다.** production consumer가 0건이었다. 남은 것은
단순 알림 포트 `NotificationPort`·`Notification`·`NotificationChannel`뿐이다.
- R1을 따라 만들어졌지만 composition root에서 한 번도 조립되지 않았던 outbound adapter의
`catalog/`, `provider/`, `template/` 실험 구현도 제거했다. 실제 runtime은
`dev.caskeleton.adapter.outbound.notification.platform..`만 사용한다.
- **application R1 public type은 2026-09-25에 삭제했다.** production consumer가 0건이었다. 남은 것은 단순 알림 포트
`NotificationPort`·`Notification`·`NotificationChannel`뿐이다.
- R1을 따라 만들어졌지만 composition root에서 한 번도 조립되지 않았던 outbound adapter의 `catalog/`, `provider/`,
`template/` 실험 구현도 제거했다. 실제 runtime은 `dev.caskeleton.adapter.outbound.notification.platform..`만 사용한다.
- 삭제 목록과 마지막 커밋은 `docs/capability-status.md`의 「제거된 코드」 표에 있다.
+61 -73
View File
@@ -1,39 +1,37 @@
# Notification Delivery Platform — module mapping
# 알림 전달 플랫폼 — 모듈 대응표
> Source design: `docs/design/2026-08-10-notification-platform-design.md`
> 출처 설계서: `docs/design/2026-08-10-notification-platform-design.md`
>
> Source plan: `docs/history/plans/2026-08-10-notification-platform-implementation-plan.md`
> 출처 계획서: `docs/history/plans/2026-08-10-notification-platform-implementation-plan.md`
## Why a mapping exists
## 대응표가 있는 이유
The plan was written against a hypothetical repository (`modules/notification/**`, root package
`io.backend.skeleton.notification`, 31 Gradle projects). This repository is a fail-closed
19-leaf Clean Architecture template: `src/settings.gradle` rejects any registry that does not
contain exactly the 19 modules in `src/config/architecture/modules.json`, and
`verifyCleanArchitectureDependencies` rejects any project edge outside `allowed_dependencies`.
계획은 가상의 저장소(`modules/notification/**`, root 패키지 `io.backend.skeleton.notification`, Gradle 프로젝트 31개)를
두고 쓰였다. 이 저장소는 fail-closed Clean Architecture 템플릿이다. `src/settings.gradle`은 registry
(`src/config/architecture/modules.json`)를 읽고 검증한 뒤 등록된 프로젝트만 들이고, `verifyCleanArchitectureDependencies`는
`allowed_dependencies` 밖의 프로젝트 edge를 거부한다.
Creating 31 new Gradle projects would violate HARD-STOP #5 of `AGENTS.md`. The package README
anticipates this and instructs the implementer to map dependency catalog and package/file paths onto
the host repository's rules while preserving the public contracts and reliability semantics.
Gradle 프로젝트 31개를 새로 만들면 `AGENTS.md`의 HARD-STOP #5를 어긴다. 패키지 README도 이것을 내다보고, 공개 계약과
신뢰성 의미를 지키면서 의존성 카탈로그와 패키지·파일 경로를 받는 저장소의 규칙에 맞추라고 구현자에게 지시한다.
Every logical module of the plan is therefore implemented as a **package** inside the registered leaf
that owns its responsibility. No public contract, evidence rule, or reliability semantic is dropped.
그래서 계획의 논리 모듈마다 그 책임을 가진 등록 leaf 안의 **패키지**로 구현했다. 공개 계약, 증거 규칙, 신뢰성 의미는
하나도 빠지지 않았다.
## Logical module → registered leaf
## 논리 모듈 → 등록 leaf
| Plan module | Registered leaf | Package |
| 계획 모듈 | 등록 leaf | 패키지 |
|---|---|---|
| `notification-core-api` | `application-core` | `dev.caskeleton.application.notification.platform.api` |
| `notification-content-api` | `application-core` | `…platform.api.content` |
| `notification-contact-api` | `application-core` | `…platform.contact` |
| `notification-template-api` | `application-core` | `…platform.template` |
| `notification-policy` | `application-core` | `…platform.policy` |
| `notification-provider-spi` | `application-core` | `…platform.provider` |
| `notification-callback-api` | `application-core` | `…platform.callback` |
| `notification-inbox-api` | `application-core` | `…platform.inbox` |
| `notification-admin-api` | `application-core` | `…platform.admin` |
| `notification-security` (ports) | `application-core` | `…platform.security` |
| `notification-observability` (ports) | `application-core` | `…platform.observation` |
| `notification-core-api` | `application-notification` | `dev.caskeleton.application.notification.platform.api` |
| `notification-content-api` | `application-notification` | `…platform.api.content` |
| `notification-contact-api` | `application-notification` | `…platform.contact` |
| `notification-template-api` | `application-notification` | `…platform.template` |
| `notification-policy` | `application-notification` | `…platform.policy` |
| `notification-provider-spi` | `application-notification` | `…platform.provider` |
| `notification-callback-api` | `application-notification` | `…platform.callback` |
| `notification-inbox-api` | `application-notification` | `…platform.inbox` |
| `notification-admin-api` | `application-notification` | `…platform.admin` |
| `notification-security` (ports) | `application-notification` | `…platform.security` |
| `notification-observability` (ports) | `application-notification` | `…platform.observation` |
| `notification-dispatch-runtime` | `adapter:outbound:notification` | `dev.caskeleton.adapter.outbound.notification.platform.dispatch` |
| `notification-security` (AES-GCM/HMAC impl) | `adapter:outbound:notification` | `…platform.security` |
| `notification-template-thymeleaf` (reference renderer) | `adapter:outbound:notification` | `…platform.template` |
@@ -42,20 +40,20 @@ that owns its responsibility. No public contract, evidence rule, or reliability
| `notification-observability` (Micrometer impl) | `adapter:outbound:notification` | `…platform.observation` |
| `notification-admin-runtime` | `adapter:outbound:notification` | `…platform.admin` |
| `notification-spring-boot-starter` | `adapter:outbound:notification` | `…platform.autoconfigure` |
| `notification-persistence-jpa` | `adapter:outbound:persistence-notification` | `dev.caskeleton.adapter.outbound.persistence.notification.platform` (store adapters), `….platform.entity` (JPA rows), `….platform.repository` (Spring Data interfaces and SQL text) |
| `notification-inbox-jpa` | `adapter:outbound:persistence-notification` | `…persistence.notification.platform` (`JpaNotificationInbox`, `InboxCommitEventPublisher`, `InboxOutboxRecordFactory`); row and repository in `….platform.entity` / `….platform.repository` |
| `notification-persistence-jpa` | `adapter:outbound:persistence-notification` | `dev.caskeleton.adapter.outbound.persistence.notification.platform`(저장소 어댑터), `….platform.entity`(JPA 행), `….platform.repository`(Spring Data interface와 SQL 문) |
| `notification-inbox-jpa` | `adapter:outbound:persistence-notification` | `…persistence.notification.platform`(`JpaNotificationInbox`, `InboxCommitEventPublisher`, `InboxOutboxRecordFactory`). 행과 repository는 `….platform.entity` / `….platform.repository` |
| `notification-callback-mvc` | `adapter:inbound:web-notification` | `dev.caskeleton.adapter.inbound.web.notification.platform.callback` |
| `notification-submission-mvc` | `adapter:inbound:web-notification` | `dev.caskeleton.adapter.inbound.web.notification.platform.submission` |
| application composition (use cases, callback bridge, `config/module-defaults/notification.yml`) | `composition:notification-platform` | `dev.caskeleton.composition.notification` |
| `notification-testkit` | test source sets of the owning leaves | `…platform.testkit` |
| 애플리케이션 조립(use case, 콜백 bridge, `config/module-defaults/notification.yml`) | `composition:notification-platform` | `dev.caskeleton.composition.notification` |
| `notification-testkit` | 소유 leaf의 test source set | `…platform.testkit` |
## Dependency-direction consequences
## 의존 방향의 결과
The plan's module DAG (`*-api` → `provider-spi`/`policy` → runtime/adapters → starter) is preserved
by the leaf DAG that the registry already enforces:
계획의 모듈 DAG(`*-api` → `provider-spi`/`policy` → runtime/adapters → starter)는 registry가 이미 강제하는 leaf DAG로
지켜진다.
```text
application-core (all *-api, provider SPI, policy, callback contracts)
application-notification (all *-api, provider SPI, policy, callback contracts; → application-core)
↑ ↑ ↑
adapter:outbound:notification adapter:outbound:persistence-notification adapter:inbound:web-notification
↑ ↑ (runtimeOnly, with persistence-jpa) ↑ (→ adapter:inbound:web)
@@ -64,50 +62,40 @@ adapter:outbound:notification adapter:outbound:persistence-notification ad
app-bootstrap (one line)
```
Two plan edges cannot be expressed as project edges in this repository, and are replaced by ports:
계획의 edge 둘은 이 저장소에서 프로젝트 edge로 표현할 수 없어서 port로 바꿨다.
1. `notification-email-ses` → `httpclient platform`. (The Twilio, FCM, APNs, Web Push and
Webhook adapters that shared this edge were removed: none had an assembler.)
`adapter-outbound-notification` is not allowed to depend on `adapter-outbound-httpclient`, and
SES no longer needs it: the SES adapter sends through the AWS SDK v2 `sesv2` client (owner
decision 17), which signs requests itself. The adapter-local JDK HTTP gateway and SigV4 signer
were deleted with that change. The client is built per profile with SDK retries off, no default
credential chain (each request carries its profile's credential) and the profile's endpoint,
which still passes the notification routability guard.
2. `notification-inbox-jpa` → `optional messaging outbox integration`.
`adapter-outbound-persistence-notification` may not depend on `adapter-outbound-messaging`; the inbox
publishes through the existing persistence outbox tables plus the
`NotificationInboxSignalPort` application port, and `app-bootstrap` binds the relay.
1. `notification-email-ses` → `httpclient platform`. (이 edge를 함께 쓰던 Twilio, FCM, APNs, Web Push, Webhook 어댑터는
assembler가 없어서 지웠다.) `adapter-outbound-notification`은 `adapter-outbound-httpclient`에 의존할 수 없고, SES는
이제 그것이 필요 없다. SES 어댑터는 스스로 요청에 서명하는 AWS SDK v2 `sesv2` 클라이언트로 보낸다(소유자 결정 17).
어댑터 안의 JDK HTTP gateway와 SigV4 signer는 그 변경과 함께 지웠다. 클라이언트는 profile마다 SDK 재시도를 끄고,
기본 credential chain 없이(요청마다 자기 profile의 자격 증명을 싣는다), profile의 endpoint로 만든다. 그 endpoint는
여전히 알림 routability guard를 통과한다.
2. `notification-inbox-jpa` → `optional messaging outbox integration`. `adapter-outbound-persistence-notification`은
`adapter-outbound-messaging`에 의존할 수 없다. inbox는 이미 있는 persistence outbox 테이블과 애플리케이션 port
`NotificationInboxSignalPort`로 내보내고, outbox relay는 `composition:outbox-relay`가 조립한다.
## Commit policy
## 커밋 정책
`AGENTS.md` pins commit policy to `human-only`. Step 5 (`git add` / `git commit`) of every plan task
is therefore intentionally **not** executed by the agent; the working tree carries the change and the
human owner commits.
`AGENTS.md`는 커밋 정책을 `human-only`로 고정한다. 그래서 계획의 모든 task에 있는 Step 5(`git add` / `git commit`)는
에이전트가 일부러 **하지 않았다**. 작업 트리가 변경을 싣고, 사람 소유자가 커밋한다.
## Runtime reachability after the R1 adapter cleanup
## R1 어댑터 정리 뒤 런타임 도달 범위
The application R1 contract covered by NOTIF-ADR-005 is a separate question from the abandoned
outbound implementation that had been built around it. The latter is gone: the notification leaf no
longer contains top-level `catalog/`, `provider/`, or `template/` R1 adapter packages. They had no
production composition consumer and were proved only by their own fakes.
NOTIF-ADR-005가 다루는 애플리케이션 R1 계약은, 그것을 둘러싸고 만들었다가 버린 outbound 구현과는 다른 문제다. 뒤의 것은
없어졌다. 알림 leaf에는 최상위 `catalog/`, `provider/`, `template/` R1 어댑터 패키지가 더는 없다. 그것들은 운영 조립의
consumer가 없었고 자기 fake로만 증명됐다.
The useful rendering invariant from that experiment was not discarded. R2
`platform.template.TemplateSlotPolicy` now validates the final HTML against the reviewed tag and
attribute subset in addition to escaping substituted values. Active script markup, event-handler
attributes and non-HTTPS HTML links are refused.
그 실험의 쓸모 있던 렌더링 불변식은 버리지 않았다. R2 `platform.template.TemplateSlotPolicy`가 이제 치환한 값을
escape하는 것에 더해, 최종 HTML을 검토한 태그·속성 부분집합과 대조한다. 실행되는 script markup, event handler 속성,
HTTPS가 아닌 HTML 링크는 거부한다.
R2 provider protocol packages remain because they implement the canonical platform SPI and have
contract tests. Their presence does **not** make them shipped dispatch runtimes. Current composition
reachability is SMTP and SES for dispatch, with SES also available for callback ingestion; the remaining
provider packages are extension assets until a composition contributes a `ProviderRuntimeAssembler`
with the settings and secret sources that family requires. See `support-matrix.md` for the explicit table.
R2 provider 프로토콜 패키지는 canonical 플랫폼 SPI를 구현하고 계약 테스트가 있어서 남아 있다. 남은 것은 `ses`와
`smtp`이고, 둘 다 내보내는 조립이 발송에 쓴다(SES는 콜백 받기에도 쓴다). 다른 family는 조립이 그 family에 필요한 설정·secret
출처와 함께 `ProviderRuntimeAssembler`를 보탤 때 생긴다. 표는 `support-matrix.md`에 있다.
## R1 public types (NOTIF-ADR-005)
## R1 public type (NOTIF-ADR-005)
NOTIF-ADR-005 made `..notification.platform..` canonical. The R1 types directly under
`dev.caskeleton.application.notification` had no production consumer and were removed on
2026-09-25, together with the ArchUnit rule that kept the two namespaces apart. What remains there
is the simple notification port the adapter core implements — `NotificationPort`, `Notification`,
`NotificationChannel`. The removed types and their last commit are listed in
`docs/capability-status.md` under "제거된 코드".
NOTIF-ADR-005가 `..notification.platform..`을 canonical로 정했다. `dev.caskeleton.application.notification` 바로 아래의
R1 타입은 운영 consumer가 없어서, 두 namespace를 떼어 놓던 ArchUnit 규칙과 함께 2026-09-25에 지웠다. 거기 남은 것은
어댑터 core가 구현하는 단순 알림 port `NotificationPort`, `Notification`, `NotificationChannel`이다. 지운 타입과 마지막
커밋은 `docs/capability-status.md` 「제거된 코드」에 있다.
+21 -25
View File
@@ -1,6 +1,6 @@
# Operations
# 운영
## Runtime shape
## 런타임 모양
```text
durable queue (PostgreSQL, FOR UPDATE SKIP LOCKED)
@@ -12,35 +12,31 @@ durable queue (PostgreSQL, FOR UPDATE SKIP LOCKED)
→ provider adapter
```
Provider calls run outside every database transaction. The attempt row is committed first, so after a
crash the row is either absent (nothing was sent) or present in `DISPATCHING` (reconciliation has
something to ask about).
provider 호출은 모든 DB 트랜잭션 밖에서 돈다. attempt 행을 먼저 커밋하므로, 장애 뒤 그 행은 없거나(아무것도 보내지
않음) `DISPATCHING`으로 있다(맞추기가 물어볼 것이 있음).
## Guards that exist for specific incidents
## 특정 장애를 막으려고 있는 장치
| Guard | The incident it prevents |
| 장치 | 막는 장애 |
|---|---|
| Credential failure opens the provider route | One expired key multiplied by a queue becomes a self-inflicted outage |
| Retry budget per provider profile | A provider outage turning every queued notification into its own retry loop |
| Ambiguous attempts block automatic fallback | A push whose response was lost arriving alongside the "just in case" SMS |
| Permits released during backoff | A slow provider pinning the whole concurrency budget on work that is only waiting |
| Fail-fast intake on capacity | An unbounded in-memory queue absorbing a burst it cannot survive |
| 자격 증명 실패가 provider route를 연다 | 만료된 키 하나가 큐만큼 곱해져 스스로 만든 장애가 된다 |
| provider profile마다 재시도 예산 | provider 장애가 큐의 모든 알림을 저마다의 재시도 반복으로 만든다 |
| 모호한 attempt는 자동 전환을 막는다 | 응답을 잃은 push와 「혹시 몰라」 보낸 SMS가 함께 도착한다 |
| 백오프 동안 허가를 돌려준다 | 느린 provider가 기다리기만 하는 일로 동시성 예산 전체를 붙잡는다 |
| 용량이 차면 받기를 바로 거부한다 | 상한 없는 메모리 큐가 버틸 수 없는 폭주를 받아들인다 |
## Scheduling
## 일정
`scheduleAt` activates the job, `notBefore` is the earliest permitted provider submission, and
`expiresAt` blocks new attempts, retries and fallbacks. Suppression and expiry are re-checked
immediately before dispatch, because a scheduled notification can sit in the queue for hours and the
user may have opted out in the meantime.
`scheduleAt`은 작업을 활성화하고, `notBefore`는 provider 제출을 허용하는 가장 이른 시각이고, `expiresAt`은 새 attempt,
재시도, 전환을 막는다. 억제와 만료는 발송 직전에 다시 확인한다. 예약된 알림은 큐에서 몇 시간을 기다릴 수 있고, 그동안
사용자가 수신을 거부했을 수 있다.
## Redrive
## 다시 보내기(redrive)
A redrive preserves `NotificationId` and `RecipientDeliveryId`, creates a new `DeliveryAttemptId`, and
reuses the pinned template version and rendered digest. Sending different content is a new
notification, not a redrive. Redriving an ambiguous attempt requires explicit duplicate-risk approval,
because the platform genuinely cannot tell whether the first submission reached the user.
redrive는 `NotificationId`와 `RecipientDeliveryId`를 유지하고, 새 `DeliveryAttemptId`를 만들고, 고정된 템플릿 버전과
렌더링 digest를 다시 쓴다. 다른 내용을 보내는 것은 redrive가 아니라 새 알림이다. 모호한 attempt를 redrive하려면 중복
위험 승인을 명시해야 한다. 첫 제출이 사용자에게 닿았는지 플랫폼이 정말로 알 수 없기 때문이다.
## Actuator surface
## actuator 표면
Provider runtime states and generations, queue depth and age, callback and reconciliation health.
Never addresses, never credentials.
provider 런타임 상태와 세대, 큐 깊이와 나이, 콜백과 맞추기 상태. 주소와 자격 증명은 절대 싣지 않는다.
+19 -19
View File
@@ -1,34 +1,34 @@
# Provider runbooks
# provider runbook
## SMTP
| Symptom | Classification | Action |
| 증상 | 분류 | 조치 |
|---|---|---|
| Final `2xx` after `DATA` | `CONFIRMED_ACCEPTED` / `PROVIDER_ACCEPTED` | None; this is acceptance, not inbox delivery |
| `4yz` | `TRANSIENT_PROVIDER` | Retry under budget and deadline |
| `5yz` | `PERMANENT_PROVIDER` or `INVALID_RECIPIENT` | Stop, or invalidate the contact point |
| Connection lost after `DATA` | `AMBIGUOUS_SUBMISSION` | Reconcile or escalate; do not resend automatically |
| `DATA` 뒤 최종 `2xx` | `CONFIRMED_ACCEPTED` / `PROVIDER_ACCEPTED` | 없음. 받은편지함 도착이 아니라 수락이다 |
| `4yz` | `TRANSIENT_PROVIDER` | 예산과 마감 안에서 다시 시도한다 |
| `5yz` | `PERMANENT_PROVIDER` 또는 `INVALID_RECIPIENT` | 멈추거나, 연락처를 무효로 한다 |
| `DATA` 뒤 연결 끊김 | `AMBIGUOUS_SUBMISSION` | 맞추거나 넘긴다. 자동으로 다시 보내지 않는다 |
Connection, read, write and pool-acquire timeouts are all finite. There is no unbounded timeout.
연결, 읽기, 쓰기, 풀 획득 시간 상한은 모두 유한하다. 상한 없는 시간 상한은 없다.
## Amazon SES
`MessageId` is acceptance evidence. SES itself documents that it can accept a request and then not
send, so `MessageId` is never mapped to `DELIVERED`.
`MessageId`는 수락 증거다. SES 자신이 요청을 수락한 뒤 보내지 않을 수 있다고 문서에 적으므로, `MessageId`는 절대
`DELIVERED`로 매핑하지 않는다.
| Event | Normalized |
| 이벤트 | 정규화 |
|---|---|
| `Send` | reinforces `PROVIDER_ACCEPTED` |
| `Send` | `PROVIDER_ACCEPTED`를 보강한다 |
| `Delivery` | `DELIVERY_CONFIRMED` / `NETWORK_OR_CARRIER_ACCEPTED` |
| `DeliveryDelay` | delay fact |
| `Bounce` (permanent) | `BOUNCED_HARD` plus hard-bounce suppression |
| `Bounce` (transient) | `BOUNCED_SOFT`; retry policy input, not a suppression reason |
| `Complaint` | complaint fact plus suppression |
| `DeliveryDelay` | 지연 사실 |
| `Bounce` (permanent) | `BOUNCED_HARD`와 hard bounce 억제 |
| `Bounce` (transient) | `BOUNCED_SOFT`. 억제 사유가 아니라 재시도 정책의 입력이다 |
| `Complaint` | complaint 사실과 억제 |
| `Reject` | `PROVIDER_REJECTED` |
| `RenderingFailure` | `TEMPLATE_FAILURE` |
## Removed provider families
## 지운 provider family
Twilio, FCM, APNs, Web Push and Webhook adapters were removed because nothing assembled them; their
runbooks went with them. The last commit that had both is named in `docs/capability-status.md`
(제거된 코드). A deployment that adds one of these providers back writes its runbook here with it.
Twilio, FCM, APNs, Web Push, Webhook 어댑터는 아무것도 조립하지 않아서 지웠고, 그 runbook도 함께 지웠다. 둘을 모두
가진 마지막 커밋은 `docs/capability-status.md`(제거된 코드)에 있다. 이 provider 중 하나를 다시 더하는 배포는 그 runbook을
여기에 함께 쓴다.
+26 -36
View File
@@ -1,54 +1,44 @@
# Security and privacy
# 보안과 개인정보
## Protected values
## 보호하는 값
Email addresses, phone numbers, FCM installation ids and legacy tokens, APNs device tokens, Web Push
endpoints and keys, VAPID private keys, provider credentials, callback signing secrets, template
variables, rendered bodies, attachment references and unsubscribe tokens.
이메일 주소, 전화번호, FCM installation id와 legacy token, APNs device token, Web Push endpoint와 키, VAPID private key,
provider 자격 증명, 콜백 서명 secret, 템플릿 변수, 렌더링한 본문, 첨부 참조, 수신 거부 token.
## At rest
## 저장할 때
Contact points are encrypted with AES-256-GCM. Equality lookup uses a separate HMAC-SHA-256
fingerprint.
연락처는 AES-256-GCM으로 암호화한다. 같은지 찾는 조회는 따로 둔 HMAC-SHA-256 fingerprint를 쓴다.
Two keys, not one, because the requirements are opposite: the ciphertext must be non-deterministic so
two records of the same address are not visibly identical, while equality lookup must be
deterministic. The fingerprint is keyed rather than a plain digest because phone numbers and email
addresses come from a small, enumerable space — an unkeyed hash of a phone number is recoverable in
seconds.
요구가 반대라서 키가 하나가 아니라 둘이다. 암호문은 결정적이지 않아야 같은 주소의 두 기록이 겉으로 같아 보이지 않고,
같은지 찾는 조회는 결정적이어야 한다. fingerprint를 그냥 digest가 아니라 키가 있는 것으로 두는 이유는 전화번호와 이메일
주소가 작고 셀 수 있는 공간에서 오기 때문이다. 키 없는 전화번호 hash는 몇 초면 되살린다.
The contact point kind is bound into the GCM associated data, so a ciphertext cannot be moved between
contact kinds without failing the authentication tag.
연락처 종류를 GCM associated data에 묶으므로, 암호문을 다른 연락처 종류로 옮기면 인증 tag가 실패한다.
An unknown key id is refused rather than silently falling back to the current key: a silent fallback
would turn every historical row into a tag failure at read time.
모르는 key id는 현재 키로 조용히 대신하지 않고 거부한다. 조용히 대신하면 이력의 모든 행이 읽을 때 tag 실패가 된다.
## Never logged, never a metric tag
## 로그에도 메트릭 태그에도 넣지 않는 것
Addresses, tokens, Web Push endpoints and keys, message bodies, template variables, provider
credentials, unsubscribe tokens, attachment URLs, raw callback payloads and raw provider request ids.
주소, token, Web Push endpoint와 키, 메시지 본문, 템플릿 변수, provider 자격 증명, 수신 거부 token, 첨부 URL, 원본 콜백
payload, 원본 provider request id.
`CardinalityGuard` enforces this for metrics rather than convention: it validates every metric tag
against a closed allowlist.
메트릭은 관례가 아니라 `CardinalityGuard`가 강제한다. 모든 메트릭 태그를 닫힌 허용 목록과 대조한다.
An allowlist rather than a denylist, because the failure mode of a denylist is that the one field
nobody thought of is the one that leaks.
거부 목록이 아니라 허용 목록인 이유가 있다. 거부 목록이 실패하는 꼴은, 아무도 생각하지 못한 그 칸 하나가 새는 것이다.
Every contact point value type overrides `toString()` to print `[redacted]`. That covers the case a
central redactor cannot: a value interpolated into a log line by accident.
모든 연락처 값 타입은 `toString()`을 고쳐 `[redacted]`를 찍는다. 그것은 중앙 redactor가 막지 못하는 경우, 실수로 로그
줄에 끼워 넣은 값을 막는다.
## Web Push endpoints
## Web Push endpoint
RFC 8030 defines the push URI as a capability URL — knowing it is sufficient to push to the
subscriber. It is handled as a secret, not as a URL.
RFC 8030은 push URI를 capability URL로 정의한다. 그것을 알면 구독자에게 push할 수 있다. 그래서 URL이 아니라 secret으로
다룬다.
## Callbacks
## 콜백
TLS, provider signature verification over the exact received bytes and external URL, replay defence
where a timestamp or nonce is available, body-size and content-type limits, profile binding, rate
limiting, idempotent ingestion and a security audit trail for rejections.
TLS, 받은 그대로의 바이트와 외부 URL에 대한 provider 서명 검증, timestamp나 nonce가 있으면 replay 방어, 본문 크기와
content type 한도, profile 묶기, 속도 제한, 멱등한 받기, 거부를 남기는 보안 감사 기록.
## Tenant isolation
## 테넌트 격리
Every store port carries the tenant boundary in its signature. Administrative operations require an
explicit tenant or a global authority.
모든 저장소 port는 시그니처에 테넌트 경계를 싣는다. 관리 작업에는 명시한 테넌트나 전역 권한이 필요하다.
+63 -70
View File
@@ -1,109 +1,102 @@
# Notification support matrix
# 알림 지원 매트릭스
What each channel can actually prove, and what the platform refuses to claim.
채널마다 실제로 증명할 수 있는 것과, 플랫폼이 주장하기를 거부하는 것이다.
The grade column is not an opinion. `docs/notification/evidence-manifest.json` declares which claims
each grade requires and which executable artifact proves each claim, and
`NotificationEvidenceVerifierTest` (in `:adapter:outbound:notification:test`) refuses a grade whose
claims are not all backed by a file that exists. Raising a grade means adding the artifact first.
등급 칸은 의견이 아니다. `docs/notification/evidence-manifest.json`이 등급마다 필요한 claim과 claim마다 그것을 증명하는
실행 산출물을 선언하고, `NotificationEvidenceVerifierTest`(`:adapter:outbound:notification:test`)가 claim이 모두 실제
파일로 뒷받침되지 않은 등급을 거부한다. 등급을 올리려면 산출물을 먼저 더한다.
Five channels read `Stable` until 2026-08-15. Nothing in the pipeline had ever sent a request to a
provider — the sandbox job's whole body was two `echo` statements behind `continue-on-error` — and
no test killed a worker mid-dispatch. The protocols are implemented and their contracts are proven
against real PostgreSQL; the wire and the crash are not. That is what the grade now says.
2026-08-15까지 다섯 채널이 `Stable`이었다. 파이프라인의 어떤 것도 provider에 요청을 보낸 적이 없었고(sandbox job의 본문
전체가 `continue-on-error` 뒤의 `echo` 두 줄이었다), 발송 도중 worker를 죽인 테스트도 없었다. 프로토콜은 구현돼 있고 그
계약은 실제 PostgreSQL에서 증명됐지만, 실제 전송과 장애 중단은 증명되지 않았다. 지금 등급이 말하는 것이 그것이다.
## Channels
## 채널
| Channel | Reference implementation | Grade | Strongest evidence the platform records by default |
| 채널 | 참조 구현 | 등급 | 플랫폼이 기본으로 기록하는 가장 강한 증거 |
|---|---|---|---|
| Email | SMTP, Amazon SES API | Contract implemented / runtime unqualified | Provider acceptance; recipient mail-server delivery, bounce and complaint when the provider publishes events |
| SMS | none shipped — adapter removed; the channel type stays in the application API (see `docs/capability-status.md` 제거된 코드) | Extension | Whatever the added provider adapter can prove |
| Mobile push (FCM, APNs) | none shipped — adapter removed; the channel type stays in the application API (see `docs/capability-status.md` 제거된 코드) | Extension | Whatever the added provider adapter can prove |
| Web Push | none shipped — adapter removed; the channel type stays in the application API (see `docs/capability-status.md` 제거된 코드) | Extension | Whatever the added provider adapter can prove |
| In-app inbox | Own database | Optional stable | `PERSISTED`, `SEEN`, `READ` |
| Webhook | none shipped — adapter removed; the channel type stays in the application API (see `docs/capability-status.md` 제거된 코드) | Extension | Whatever the receiving HTTP contract states |
| Email | SMTP, Amazon SES API | Contract implemented / runtime unqualified | provider 수락. provider가 이벤트를 내면 수신 메일 서버 전달, bounce, complaint |
| SMS | 내보내지 않음 — 어댑터를 지웠고 채널 종류는 애플리케이션 API에 남아 있다(`docs/capability-status.md` 제거된 코드) | Extension | 더한 provider 어댑터가 증명할 수 있는 것 |
| 모바일 push(FCM, APNs) | 내보내지 않음 — 어댑터를 지웠고 채널 종류는 애플리케이션 API에 남아 있다(`docs/capability-status.md` 제거된 코드) | Extension | 더한 provider 어댑터가 증명할 수 있는 것 |
| Web Push | 내보내지 않음 — 어댑터를 지웠고 채널 종류는 애플리케이션 API에 남아 있다(`docs/capability-status.md` 제거된 코드) | Extension | 더한 provider 어댑터가 증명할 수 있는 것 |
| 앱 안 inbox | 자체 DB | Optional stable | `PERSISTED`, `SEEN`, `READ` |
| Webhook | 내보내지 않음 — 어댑터를 지웠고 채널 종류는 애플리케이션 API에 남아 있다(`docs/capability-status.md` 제거된 코드) | Extension | 받는 HTTP 계약이 말하는 것 |
## Shipped provider assembly reachability
## 내보내는 provider 조립이 닿는 범위
The grade above describes protocol/reliability evidence. It does **not** mean every reference
implementation is selectable in the default composition. Dispatch reachability is a separate axis:
위 등급은 프로토콜·신뢰성 증거를 말한다. 모든 참조 구현을 기본 조립에서 고를 수 있다는 뜻이 **아니다**. 발송이 닿는지는
따로 보는 축이다.
| Provider family | Dispatch assembler in shipped composition | Callback assembler | Current use |
| provider family | 내보내는 조립의 발송 assembler | 콜백 assembler | 지금 쓰임 |
|---|---|---|---|
| SMTP | **yes** | no | EMAIL dispatch reference family |
| SES | **yes** | **yes** | EMAIL dispatch + SNS callback ingestion; disabled reference profile ships in `config/module-defaults/notification.yml` (`composition:notification-platform`) |
| SMTP | **있음** | 없음 | EMAIL 발송 참조 family |
| SES | **있음** | **있음** | EMAIL 발송 + SNS 콜백 수집. 꺼진 참조 profile이 `config/module-defaults/notification.yml`(`composition:notification-platform`)에 들어 있다 |
APNs, FCM, Twilio, Web Push and Webhook adapters shipped as protocol code with no assembler and
were removed; `ProviderType` now lists only SES and SMTP, so such a profile fails binding as an
unknown type. An enabled dispatch profile with no assembler fails startup by profile/family; it never silently
assembles into an empty runtime. SMTP additionally names `spring.mail.host` when its shipped
assembler is absent because the relay was not configured.
APNs, FCM, Twilio, Web Push, Webhook 어댑터는 assembler 없이 프로토콜 코드로만 들어 있다가 지워졌다. 이제
`ProviderType`에는 SES와 SMTP만 있으므로 그런 profile은 모르는 종류로 바인딩에서 실패한다. assembler가 없는 켜진 발송
profile은 profile·family 이름을 대며 기동에 실패한다. 빈 런타임으로 조용히 조립되는 일은 없다. SMTP는 relay가 설정되지
않아 내보내는 assembler가 없으면 `spring.mail.host`도 이름 댄다.
## What each grade requires
## 등급마다 필요한 것
| Grade | Requires |
| 등급 | 필요한 claim |
|---|---|
| Stable | durable, multi-worker-safe, callback-supported, recoverable, provider-wire-qualified |
| Contract implemented / runtime unqualified | durable, multi-worker-safe, callback-supported |
| Optional stable | durable |
| Extension | nothing; the receiving contract owns its own guarantees |
| Experimental | nothing; the grade is the warning |
| Extension | 없음. 받는 쪽 계약이 자기 보장을 가진다 |
| Experimental | 없음. 등급 자체가 경고다 |
`recoverable` is backed by two tests. `WorkerCrashRecoveryContractTest` walks the four phases a
dispatch passes through — claimed, attempt written, request started, body committed — and pins the
rows a dead worker leaves at each: a passed lease, and from the attempt insert on an unfinished
attempt carrying that phase's evidence. It writes those rows itself, so it checks recovery's input,
not recovery. `PostgreSqlNotificationBackgroundPassIntegrationTest` runs lease recovery and
reconciliation over rows the dispatcher's own factory wrote and asserts the outcome: requeued before
any attempt, reconciled after one (review 05-01, RR-03-07).
`recoverable`은 테스트 둘이 뒷받침한다. `WorkerCrashRecoveryContractTest`는 발송이 지나는 네 단계(claim됨, attempt 기록됨,
요청 시작됨, 본문 커밋됨)를 따라가며 단계마다 죽은 worker가 남기는 행을 고정한다. 지난 lease, 그리고 attempt insert부터는
그 단계의 증거를 가진 끝나지 않은 attempt다. 그 행을 테스트가 직접 쓰므로, 복구가 아니라 복구의 입력을 확인한다.
`PostgreSqlNotificationBackgroundPassIntegrationTest`는 dispatcher 자신의 factory가 쓴 행에 lease 복구와 맞추기를 돌리고
결과를 단언한다. attempt 전이면 다시 큐에 넣고, attempt 뒤면 맞춘다(review 05-01, RR-03-07).
The remaining unmet claim, and what would meet it:
남은 미충족 claim과 그것을 채울 것:
- **provider-wire-qualified** — a real provider sandbox call producing an immutable, uploaded
artifact with a correlation id. No request has ever left the process in CI.
- **provider-wire-qualified** — 실제 provider sandbox 호출로 correlation id가 있는 불변 산출물을 만들어 올린다. CI에서
프로세스 밖으로 요청이 나간 적이 한 번도 없다.
## Evidence levels
## 증거 수준
`NONE` → `PLATFORM_QUEUED` → `PROVIDER_ACCEPTED` → `NETWORK_OR_CARRIER_ACCEPTED` →
`DEVICE_DELIVERED` → `USER_AGENT_DISPLAYED` → `USER_READ`
| Provider signal | Highest evidence it may produce |
| provider 신호 | 그 신호가 낼 수 있는 가장 높은 증거 |
|---|---|
| Internal queue commit | `PLATFORM_QUEUED` |
| 내부 큐 커밋 | `PLATFORM_QUEUED` |
| SES `MessageId` | `PROVIDER_ACCEPTED` |
| SES `Delivery` | `NETWORK_OR_CARRIER_ACCEPTED` |
| In-app row commit | `PROVIDER_ACCEPTED` |
| In-app `seen` endpoint | `USER_AGENT_DISPLAYED` |
| In-app `read` endpoint, authenticated app receipt | `USER_READ` |
| 앱 안 행 커밋 | `PROVIDER_ACCEPTED` |
| 앱 안 `seen` 엔드포인트 | `USER_AGENT_DISPLAYED` |
| 앱 안 `read` 엔드포인트, 인증된 앱 수신 확인 | `USER_READ` |
Promotions the platform will not make, in code or in configuration:
플랫폼이 코드에서도 설정에서도 하지 않는 승격:
- A push or SMS acceptance, from any provider adapter a deployment adds, is not `DEVICE_DELIVERED`.
- A provider 2xx is not `DELIVERED`.
- An SES `MessageId` is not `DELIVERED`.
- An SMTP `250` is not inbox delivery.
- 배포가 더한 어느 provider 어댑터에서 온 것이든 push·SMS 수락은 `DEVICE_DELIVERED`가 아니다.
- provider의 2xx는 `DELIVERED`가 아니다.
- SES `MessageId`는 `DELIVERED`가 아니다.
- SMTP `250`은 받은편지함 도착이 아니다.
## Submission outcomes
## 제출 결과
`NOT_SUBMITTED`, `CONFIRMED_ACCEPTED`, `CONFIRMED_REJECTED`, `AMBIGUOUS`.
`AMBIGUOUS` is a first-class stored state, not an error path. It means the request body was committed
to the provider and the outcome could not be read. While an ambiguous attempt exists on a recipient
delivery, automatic retry and automatic cross-channel fallback are both blocked.
`AMBIGUOUS`는 오류 경로가 아니라 정식으로 저장되는 상태다. 요청 본문을 provider에 넘겼지만 결과를 읽지 못했다는 뜻이다.
수신자 전달에 모호한 attempt가 있는 동안에는 자동 재시도와 자동 채널 전환이 모두 막힌다.
## Not supported
## 지원하지 않는 것
The platform will not claim any of the following, because no channel above can support them:
위의 어떤 채널도 뒷받침할 수 없으므로 플랫폼은 다음 중 어떤 것도 주장하지 않는다.
- guaranteed delivery
- guaranteed read
- exactly-once human notification
- unconditional multi-provider failover after an unread response
- provider SDK types in the public API
- audience selection, campaign segmentation or jurisdiction rulings
- 전달 보장(guaranteed delivery)
- 읽음 보장(guaranteed read)
- 사람에게 가는 알림의 정확히 한 번(exactly-once) 전달
- 읽지 못한 응답 뒤의 조건 없는 다중 provider failover
- 공개 API의 provider SDK 타입
- 대상 선정, 캠페인 세분화, 관할 판정
## Target model
## 대상 모델
`FCM_FID` is the primary mobile push target. `FCM_REGISTRATION_TOKEN_LEGACY` and
`APNS_DEVICE_TOKEN` are separate types with separate lifecycles; they are never flattened into one
string field.
`FCM_FID`가 모바일 push의 기본 대상이다. `FCM_REGISTRATION_TOKEN_LEGACY`와 `APNS_DEVICE_TOKEN`은 수명 주기가 다른 별도
종류다. 하나의 문자열 칸으로 합치지 않는다.
+42 -46
View File
@@ -1,67 +1,63 @@
# Structured log field dictionary
# 구조화 로그 칸 사전
This file is the naming SSOT for structured fields emitted by application/bootstrap runtime code.
A new field should be added here before it becomes a new search/filter dimension.
이 파일은 application·bootstrap 런타임 코드가 내는 구조화 칸 이름의 정본이다. 새 칸은 새 검색·필터 기준이 되기 전에 여기에
먼저 더한다.
The message text is for humans. These fields are the stable machine-query surface.
메시지 문장은 사람을 위한 것이다. 이 칸들이 기계가 조회하는 안정된 표면이다.
## Startup and error classification
## 기동과 오류 분류
| Field | Meaning | Cardinality expectation |
| 칸 | 뜻 | 기대하는 cardinality |
|---|---|---|
| `startup.phase` | Startup phase such as env-validation, migration or adapter-check | bounded |
| `error.code` | Stable error-code registry value | bounded |
| `error.category` | Stable error category | bounded |
| `error.root_cause.class` | Root exception class for startup failure diagnosis | bounded by codebase/dependencies |
| `error.root_cause.message` | Root exception message | unbounded; diagnosis only, not metric/tag material |
| `startup.phase` | 기동 단계. `env-validation`, `migration`, `profile-check`, `adapter-enablement` | 상한 있음 |
| `error.code` | 안정된 오류 코드 registry 값 | 상한 있음 |
| `error.category` | 안정된 오류 분류 | 상한 있음 |
| `error.root_cause.class` | 기동 실패 진단용 근본 예외 클래스 | 코드베이스·의존성이 상한 |
| `error.root_cause.message` | 근본 예외 메시지 | 상한 없음. 진단에만 쓰고 메트릭·태그 재료가 아니다 |
Startup failures go through `StartupFailures`; callers do not construct their own startup error
classification.
기동 실패는 `StartupFailures`를 거친다. 호출자는 기동 오류 분류를 스스로 만들지 않는다.
## Runtime warning and retry classification
## 런타임 경고와 재시도 분류
| Field | Meaning | Cardinality expectation |
| 칸 | 뜻 | 기대하는 cardinality |
|---|---|---|
| `warning.kind` | Stable warning shape, for example `meter-unavailable`, `setting-fallback`, `scheduled-task-failed`, `lease-expired-before-close` | bounded |
| `capability` | Capability that emitted the runtime event, for example `fileserver`, `outbox`, `distributed-lock` | bounded |
| `operation` | Bounded operation name such as `cleanup` or `relay` | bounded |
| `retry.disposition` | What the runtime will do after the event, for example `next-run` or `next-tick` | bounded |
| `meter` | Meter name or bounded meter operation that could not be updated | bounded by metrics registry |
| `env.key` | Configuration key involved in a fallback | bounded by env registry |
| `setting.rejected` | Rejected setting value rendered for diagnosis | potentially unbounded; never metric/tag material |
| `setting.applied` | Fallback value actually applied | bounded where possible |
| `warning.kind` | 안정된 경고 모양. 예: `meter-unavailable`, `setting-fallback`, `scheduled-task-failed`, `lease-expired-before-close` | 상한 있음 |
| `capability` | 런타임 이벤트를 낸 capability. 예: `fileserver`, `outbox`, `distributed-lock` | 상한 있음 |
| `operation` | `cleanup`이나 `relay` 같은 상한 있는 operation 이름 | 상한 있음 |
| `retry.disposition` | 이벤트 뒤 런타임이 할 일. 예: `next-run`, `next-tick` | 상한 있음 |
| `meter` | 갱신하지 못한 meter 이름이나 상한 있는 meter 연산 | 메트릭 registry가 상한 |
| `env.key` | fallback에 관련된 설정 키 | env registry가 상한 |
| `setting.rejected` | 진단용으로 찍은, 거부된 설정 값 | 상한이 없을 수 있다. 메트릭·태그 재료가 절대 아니다 |
| `setting.applied` | 실제로 적용한 fallback 값 | 될 수 있으면 상한 있음 |
A retry disposition does not imply an `error.code`. Add an error code only when the failure is
actually classified by the error registry.
재시도 처리 방식이 `error.code`를 뜻하지는 않는다. 오류 코드는 그 실패를 오류 registry가 실제로 분류할 때만 더한다.
## Fileserver cleanup
## 파일 서버 정리
| Field | Meaning |
| 칸 | 뜻 |
|---|---|
| `cleanup.deleted` | Objects deleted in one bounded cleanup run |
| `cleanup.skipped_active_lease` | Items skipped because an active upload lease still owns them |
| `cleanup.skipped_state_changed` | Items skipped because state changed after queueing |
| `cleanup.failed` | Cleanup items that failed in the batch |
| `cleanup.reclaimed_bytes` | Bytes reclaimed in the batch |
| `cleanup.deleted` | 상한 있는 정리 실행 한 번에 지운 객체 |
| `cleanup.skipped_active_lease` | 살아 있는 upload lease가 아직 가져서 건너뛴 항목 |
| `cleanup.skipped_state_changed` | 대기열에 넣은 뒤 상태가 바뀌어 건너뛴 항목 |
| `cleanup.failed` | 그 묶음에서 실패한 정리 항목 |
| `cleanup.reclaimed_bytes` | 그 묶음에서 되찾은 바이트 |
These are numeric event fields. They are not identity fields.
이것들은 숫자 이벤트 칸이다. 신원 칸이 아니다.
## Background executor rejection
## background executor 거부
| Field | Meaning |
| 칸 | 뜻 |
|---|---|
| `executor_name` | Bounded executor identifier |
| `policy` | Rejection policy, currently `AbortPolicy` |
| `queue_size` | Queue size observed at rejection |
| `executor_name` | 상한 있는 executor 식별자 |
| `policy` | 거부 정책. 지금은 `AbortPolicy` |
| `queue_size` | 거부할 때 본 큐 크기 |
Executor rejection also carries `error.code=JOB_EXECUTOR_REJECTED` and its `error.category`.
executor 거부는 `error.code=JOB_EXECUTOR_REJECTED`와 그 `error.category`도 싣는다.
## Cardinality and sensitive identifiers
## cardinality와 민감한 식별자
Do not promote arbitrary identifiers to structured fields merely because they are useful in one
incident. Examples include distributed-lock keys, object keys, raw user identifiers, request
payloads and secret values.
한 장애에서 쓸모 있었다는 이유만으로 아무 식별자나 구조화 칸으로 올리지 않는다. 분산 락 키, 객체 키, 원본 사용자 식별자,
요청 payload, secret 값이 그 예다.
The distributed-lock lease-expiry warning intentionally keeps the lock key only in human-readable
message text and does not emit `lock.key`. If a future operational requirement needs a searchable
lock identity, define a bounded/pseudonymized contract first instead of adding the raw key.
분산 락 lease 만료 경고는 락 키를 사람이 읽는 메시지 문장에만 두고 `lock.key`를 내지 않는다. 일부러다. 앞으로 운영 요구가
검색할 수 있는 락 신원을 필요로 하면, 원본 키를 더하지 말고 먼저 상한 있거나 가명화한 계약을 정한다.
+18 -14
View File
@@ -4,31 +4,35 @@ category: INTERNAL
error_codes: [ADAPTER_DISABLED]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: ADAPTER_DISABLED (`runbook://adapter/adapter-disabled`)
## Symptoms
## 증상
- HTTP 500 with `error.code=ADAPTER_DISABLED`
- Code invoked an optional adapter (Kafka/Redis/Slack/Email) that is disabled in this deployment
- HTTP 500, `error.code=ADAPTER_DISABLED`.
- 이 배포에서 꺼져 있거나 묶이지 않은 선택 어댑터의 경로를 코드가 호출했다. 지금 템플릿에서 이 코드를 내는
곳은 알림 라우터(`RoutingNotifier`)다. 채널과 route에 묶인 provider가 없을 때 낸다.
## Diagnosis
## 진단
- Check adapter name in log (`adapter_name` field)
- Review deployment config — which optional adapters are enabled?
- ERROR 로그 `failure classified as ADAPTER_DISABLED (category=INTERNAL, retryable=false)`를 찾는다. 줄에 붙은
예외(`AdapterDisabledException`)의 메시지가 어댑터와 고칠 키를 알려 준다.
- 기본 메시지: `optional adapter '<이름>' is disabled (app.<domain>.<이름>.enabled=false) …`
- 알림 라우터: `no notification route bound for channel=… route='…' — set app.notification.routes.<channel>.<route>=<providerId>…`
- 배포 설정에서 어떤 선택 어댑터가 켜져 있는지 본다.
## Action
## 조치
- Enable the adapter in deployment configuration (env flag)
- Or update application logic to skip disabled-adapter paths
- 배포 설정에서 그 어댑터를 켠다(환경 변수 스위치). 알림이면 메시지가 가리키는 route를 묶고 그 provider를 켠다.
- 아니면 꺼진 어댑터의 경로를 건너뛰도록 애플리케이션 로직을 고친다.
## Escalation
## 에스컬레이션
- Escalate to deployment team if adapter should be enabled but isn't
- 켜져 있어야 할 어댑터가 꺼져 있으면 배포 담당 팀에 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+14 -14
View File
@@ -5,31 +5,31 @@ error_codes: [AUTH_AUDIENCE_MISMATCH]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: AUTH_AUDIENCE_MISMATCH (`runbook://auth/audience-mismatch`)
## Symptoms
## 증상
- HTTP 401 with `error.code=AUTH_AUDIENCE_MISMATCH`
- Token `aud` claim does not include this service's expected audience
- HTTP 401, `error.code=AUTH_AUDIENCE_MISMATCH`.
- 토큰의 `aud` 클레임에 이 서비스가 기대하는 audience가 없다.
## Diagnosis
## 진단
- Check token `aud` claim value
- Compare against configured `app.security.audience` (`APP_SECURITY_JWT_AUDIENCE`, comma-separated;
the token must name at least one)
- 토큰의 `aud` 클레임 값을 본다.
- 설정된 `app.security.audience`(`APP_SECURITY_JWT_AUDIENCE`, 쉼표로 구분)와 비교한다. 토큰은 그중 하나 이상을
담아야 한다.
## Action
## 조치
- Verify client is requesting tokens scoped to the correct audience
- Update audience configuration if service identifier changed
- 클라이언트가 맞는 audience로 토큰을 요청하는지 확인한다.
- 서비스 식별자가 바뀌었으면 audience 설정을 고친다.
## Escalation
## 에스컬레이션
- Escalate to auth-platform team if misconfiguration is system-wide
- 설정 오류가 시스템 전체에 걸쳐 있으면 인증 플랫폼 팀에 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [AUTH_CLAIM_MAPPING_FAILED]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: AUTH_CLAIM_MAPPING_FAILED (`runbook://auth/claim-mapping-failed`)
## Symptoms
## 증상
- HTTP 401 with `error.code=AUTH_CLAIM_MAPPING_FAILED`
- Token validated but required claims (sub, roles, tenant) missing or unexpected type
- HTTP 401, `error.code=AUTH_CLAIM_MAPPING_FAILED`.
- 토큰 검증은 통과했지만 필요한 클레임(sub, roles, tenant)이 없거나 타입이 다르다.
## Diagnosis
## 진단
- Inspect token payload claims via logs
- Check claim extractor configuration
- 로그에서 토큰 payload의 클레임을 본다.
- 클레임 추출 설정을 확인한다.
## Action
## 조치
- Verify IdP token template includes required claims
- Update claim mapping configuration if IdP schema changed
- IdP 토큰 템플릿에 필요한 클레임이 들어 있는지 확인한다.
- IdP 스키마가 바뀌었으면 클레임 매핑 설정을 고친다.
## Escalation
## 에스컬레이션
- Escalate to auth-platform team if IdP changed claim schema
- IdP가 클레임 스키마를 바꿨으면 인증 플랫폼 팀에 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [AUTH_ISSUER_MISMATCH]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: AUTH_ISSUER_MISMATCH (`runbook://auth/issuer-mismatch`)
## Symptoms
## 증상
- HTTP 401 with `error.code=AUTH_ISSUER_MISMATCH`
- Token `iss` claim does not match configured expected issuer
- HTTP 401, `error.code=AUTH_ISSUER_MISMATCH`.
- 토큰의 `iss` 클레임이 설정된 발급자와 다르다.
## Diagnosis
## 진단
- Compare token `iss` against `spring.security.oauth2.resourceserver.jwt.issuer-uri`
- Check if IdP environment changed
- 토큰의 `iss`를 `spring.security.oauth2.resourceserver.jwt.issuer-uri`와 비교한다.
- IdP 환경이 바뀌었는지 확인한다.
## Action
## 조치
- Update issuer config if IdP migrated
- Reject tokens from unexpected issuers
- IdP를 옮겼으면 issuer 설정을 고친다.
- 예상하지 않은 발급자의 토큰은 계속 거부한다.
## Escalation
## 에스컬레이션
- Escalate to platform-security if unexpected issuer detected
- 예상하지 않은 발급자를 찾으면 플랫폼 보안 팀에 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+15 -15
View File
@@ -5,32 +5,32 @@ error_codes: [AUTH_JWKS_UNAVAILABLE]
severity: P1
owner: oncall
last_updated: 2026-11-06
status: stub
status: 초안
---
# Runbook: AUTH_JWKS_UNAVAILABLE (`runbook://auth/jwks-unavailable`)
## Symptoms
## 증상
- HTTP 503 with `error.code=AUTH_JWKS_UNAVAILABLE`
- ERROR log line `security failure: code=AUTH_JWKS_UNAVAILABLE category=TRANSIENT_DEPENDENCY method=… path=…`
(logger `AuthErrorResponseWriter`)
- All authentication failing; JWKS refresh attempts failing
- HTTP 503, `error.code=AUTH_JWKS_UNAVAILABLE`.
- ERROR 로그 줄 `security failure: code=AUTH_JWKS_UNAVAILABLE category=TRANSIENT_DEPENDENCY method=… path=…`
(logger `AuthErrorResponseWriter`).
- 인증이 모두 실패하고, JWKS 새로 고침도 실패한다.
## Diagnosis
## 진단
- Check IdP JWKS endpoint health: `curl -sf https://<idp-host>/.well-known/jwks.json`
- Check network connectivity from app pods to IdP
- IdP의 JWKS 엔드포인트 상태를 본다: `curl -sf https://<idp-host>/.well-known/jwks.json`
- 앱 pod에서 IdP까지 네트워크가 닿는지 확인한다.
## Action
## 조치
- Enable cached JWKS fallback if available
- Coordinate with IdP team for restoration
- 캐시된 JWKS로 버틸 수단이 있으면 쓴다.
- IdP 팀과 복구를 맞춘다.
## Escalation
## 에스컬레이션
- P1 page: IdP team immediately if JWKS endpoint unreachable > 2 minutes
- P1 호출: JWKS 엔드포인트에 2분 넘게 닿지 않으면 IdP 팀을 바로 부른다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [AUTH_KID_UNKNOWN]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: AUTH_KID_UNKNOWN (`runbook://auth/kid-unknown`)
## Symptoms
## 증상
- HTTP 401 with `error.code=AUTH_KID_UNKNOWN`, `retryable=true`
- Token `kid` header not present in cached JWKS
- HTTP 401, `error.code=AUTH_KID_UNKNOWN`, `retryable=true`.
- 토큰 헤더의 `kid`가 캐시된 JWKS에 없다.
## Diagnosis
## 진단
- Check if IdP key rotation occurred recently
- Verify JWKS cache TTL and refresh timing
- 최근에 IdP 키 교체가 있었는지 확인한다.
- JWKS 캐시 TTL과 새로 고침 시점을 확인한다.
## Action
## 조치
- Force JWKS cache refresh
- Confirm new key is published in IdP JWKS endpoint
- JWKS 캐시를 강제로 새로 고친다.
- 새 키가 IdP JWKS 엔드포인트에 게시됐는지 확인한다.
## Escalation
## 에스컬레이션
- Escalate to IdP team if new kid not appearing in JWKS after 10 minutes
- 10분이 지나도 새 kid가 JWKS에 나타나지 않으면 IdP 팀에 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
@@ -4,33 +4,34 @@ category: INTERNAL
error_codes: [INTERNAL_AUTH_MISCONFIGURATION]
severity: P1
owner: oncall
last_updated: 2026-11-06
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: INTERNAL_AUTH_MISCONFIGURATION (`runbook://auth/public-path-misconfiguration`)
## Symptoms
## 증상
- HTTP 500 with `error.code=INTERNAL_AUTH_MISCONFIGURATION`
- ERROR log line `security failure: code=INTERNAL_AUTH_MISCONFIGURATION category=INTERNAL method=… path=…`
(logger `AuthErrorResponseWriter`)
- Security filter misconfiguration detected at runtime
- HTTP 500, `error.code=INTERNAL_AUTH_MISCONFIGURATION`.
- ERROR 로그 줄 `security failure: code=INTERNAL_AUTH_MISCONFIGURATION category=INTERNAL method=… path=…`
(logger `AuthErrorResponseWriter`).
- 실행 중에 보안 필터 설정 오류가 드러났다.
## Diagnosis
## 진단
- Check `verifyPublicPathSnapshot` output in CI
- Review recent changes to `SecurityConfig` or `application.yml` public path list
- CI의 `verifyPublicPathSnapshot` 결과를 본다.
- `SecurityConfig`와 공개 경로 목록(`config/security.yml`의 `public-paths`, `SECURITY_PUBLIC_PATHS`)의 최근
변경을 본다.
## Action
## 조치
- Revert misconfigured public path change
- Run `./gradlew verifyPublicPathSnapshot` to compare snapshot
- 잘못된 공개 경로 변경을 되돌린다.
- `src/`에서 `./gradlew verifyPublicPathSnapshot`을 돌려 스냅숏과 비교한다.
## Escalation
## 에스컬레이션
- P1 immediate: if auth bypass is possible due to misconfiguration
- P1 즉시: 설정 오류로 인증을 건너뛸 수 있으면.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+14 -14
View File
@@ -4,31 +4,31 @@ category: AUTH
error_codes: [AUTH_TOKEN_EXPIRED]
severity: P3
owner: oncall
last_updated: 2026-06-15
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: AUTH_TOKEN_EXPIRED (`runbook://auth/token-expired`)
## Symptoms
## 증상
- HTTP 401 with `error.code=AUTH_TOKEN_EXPIRED`
- Spike may indicate clock skew or long-lived token usage
- HTTP 401, `error.code=AUTH_TOKEN_EXPIRED`.
- 급증하면 시계 차이(clock skew)나 오래 사는 토큰을 의심한다.
## Diagnosis
## 진단
- Check `exp` claim vs server clock
- Check NTP sync on token-issuing host
- `exp` 클레임과 서버 시계를 비교한다.
- 토큰을 발급하는 호스트의 NTP 동기화를 확인한다.
## Action
## 조치
- Client must refresh tokens before expiry
- Verify clock skew tolerance is configured (default 60s)
- 클라이언트는 만료 전에 토큰을 새로 받아야 한다.
- 시계 차이 허용값을 확인한다. 이 템플릿의 JWT 검증기는 60초를 허용한다(`JwtDecoderConfig`).
## Escalation
## 에스컬레이션
- Escalate if spike is widespread or clock drift is confirmed
- 급증이 넓게 퍼졌거나 시계 어긋남이 확인되면 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+15 -15
View File
@@ -5,32 +5,32 @@ error_codes: [AUTH_TOKEN_INVALID_SIGNATURE]
severity: P1
owner: oncall
last_updated: 2026-11-06
status: stub
status: 초안
---
# Runbook: AUTH_TOKEN_INVALID_SIGNATURE (`runbook://auth/token-invalid-signature`)
## Symptoms
## 증상
- HTTP 401 with `error.code=AUTH_TOKEN_INVALID_SIGNATURE`
- WARN log line `security failure: code=AUTH_TOKEN_INVALID_SIGNATURE category=AUTH method=… path=…`
(logger `AuthErrorResponseWriter`). It is a WARN because the caller sent the token; search by
`code=`, not by level. A burst of these may indicate forged tokens or a wrong signing key
- HTTP 401, `error.code=AUTH_TOKEN_INVALID_SIGNATURE`.
- WARN 로그 줄 `security failure: code=AUTH_TOKEN_INVALID_SIGNATURE category=AUTH method=… path=…`
(logger `AuthErrorResponseWriter`). 토큰을 보낸 쪽이 호출자라서 WARN이다. 수준이 아니라 `code=`로 찾는다.
한꺼번에 몰리면 위조 토큰이나 잘못된 서명 키를 의심한다.
## Diagnosis
## 진단
- Check if JWKS endpoint returned a new key set
- Check for token forgery attempts in logs
- JWKS 엔드포인트가 새 키 묶음을 내놓았는지 확인한다.
- 로그에서 토큰 위조 시도를 찾는다.
## Action
## 조치
- Verify JWKS key IDs match token headers
- Alert security team if forgery suspected
- JWKS의 키 ID가 토큰 헤더와 맞는지 확인한다.
- 위조가 의심되면 보안 팀에 알린다.
## Escalation
## 에스컬레이션
- Immediate P1 escalation if forgery indicators present
- 위조 흔적이 있으면 바로 P1으로 올린다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [AUTH_TOKEN_MALFORMED, INVALID_TOKEN]
severity: P3
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: AUTH_TOKEN_MALFORMED (`runbook://auth/token-malformed`)
## Symptoms
## 증상
- HTTP 401 responses with `error.code=AUTH_TOKEN_MALFORMED`
- Token present but fails JWT parse (not 3-part, non-base64, etc.)
- HTTP 401 응답, `error.code=AUTH_TOKEN_MALFORMED`.
- 토큰은 있지만 JWT로 파싱되지 않는다(세 부분이 아님, base64가 아님 등).
## Diagnosis
## 진단
- Inspect raw Authorization header value in logs
- Check if token generation tooling has a bug
- 로그에서 Authorization 헤더 원문을 본다.
- 토큰을 만드는 도구에 버그가 있는지 확인한다.
## Action
## 조치
- Identify source of malformed tokens
- Fix or update client token generation
- 잘못된 토큰이 어디서 오는지 찾는다.
- 클라이언트의 토큰 생성을 고친다.
## Escalation
## 에스컬레이션
- Escalate if spike suggests infrastructure issue
- 급증이 인프라 문제를 가리키면 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [AUTH_TOKEN_MISSING, UNAUTHENTICATED]
severity: P3
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: AUTH_TOKEN_MISSING (`runbook://auth/token-missing`)
## Symptoms
## 증상
- HTTP 401 responses with `error.code=AUTH_TOKEN_MISSING`
- Client missing Authorization header or Bearer token
- HTTP 401 응답, `error.code=AUTH_TOKEN_MISSING`.
- 클라이언트가 Authorization 헤더나 Bearer 토큰을 보내지 않았다.
## Diagnosis
## 진단
- Check request logs for missing Authorization header
- Verify client SDK configuration
- 요청 로그에서 Authorization 헤더가 빠졌는지 본다.
- 클라이언트 SDK 설정을 확인한다.
## Action
## 조치
- Confirm API clients are sending Authorization header
- Check gateway/proxy configuration for header stripping
- API 클라이언트가 Authorization 헤더를 보내는지 확인한다.
- gateway·proxy가 헤더를 지우는지 설정을 확인한다.
## Escalation
## 에스컬레이션
- Escalate if widespread or affecting critical workflows
- 넓게 퍼졌거나 중요한 업무 흐름에 영향이 있으면 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+1 -1
View File
@@ -5,7 +5,7 @@ error_codes: [AUTH_TOKEN_EXPIRED, AUTH_KID_UNKNOWN, AUTH_JWKS_UNAVAILABLE, AUTH_
severity: P1
owner: oncall
last_updated: 2026-05-22
status: stub
status: 초안
---
# Runbook: JWT key rotation 시 인증 실패 spike
@@ -5,7 +5,7 @@ error_codes: [AUTHZ_INSUFFICIENT_PERMISSION, AUTHZ_TENANT_MISMATCH]
severity: P2
owner: oncall
last_updated: 2026-05-22
status: stub
status: 초안
---
# Runbook: cross-tenant 접근 시도 감지
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [AUTHZ_INSUFFICIENT_PERMISSION, FORBIDDEN]
severity: P3
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: AUTHZ_INSUFFICIENT_PERMISSION (`runbook://authz/insufficient-permission`)
## Symptoms
## 증상
- HTTP 403 with `error.code=AUTHZ_INSUFFICIENT_PERMISSION`
- Valid token but missing required role or permission
- HTTP 403, `error.code=AUTHZ_INSUFFICIENT_PERMISSION`.
- 토큰은 유효하지만 필요한 역할이나 권한이 없다.
## Diagnosis
## 진단
- Check user's assigned roles in IdP
- Review endpoint's required permission annotation
- IdP에서 사용자에게 준 역할을 확인한다.
- 엔드포인트가 요구하는 권한 애너테이션을 확인한다.
## Action
## 조치
- Grant correct role/permission to user
- Verify endpoint permission requirement is correct
- 사용자에게 맞는 역할·권한을 준다.
- 엔드포인트의 권한 요구가 맞는지 확인한다.
## Escalation
## 에스컬레이션
- Escalate to access-management team if bulk users affected
- 여러 사용자가 한꺼번에 영향을 받으면 접근 관리 팀에 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+16 -16
View File
@@ -4,33 +4,33 @@ category: AUTHZ
error_codes: [AUTHZ_TENANT_MISMATCH]
severity: P1
owner: oncall
last_updated: 2026-11-06
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: AUTHZ_TENANT_MISMATCH (`runbook://authz/tenant-mismatch`)
## Symptoms
## 증상
- HTTP 403 with `error.code=AUTHZ_TENANT_MISMATCH`
- The template does not emit this code; the service that decides cross-tenant access does. A 403
carrier is answered without a log line (`ServerFailureLog`), so that service logs
`code=AUTHZ_TENANT_MISMATCH` where it decides, if this runbook is to find the attempt
- HTTP 403, `error.code=AUTHZ_TENANT_MISMATCH`.
- 템플릿은 이 코드를 내지 않는다. 다른 테넌트 접근을 판단하는 서비스가 낸다. 403 carrier는 로그 줄 없이
응답하므로(`ServerFailureLog`), 이 runbook으로 시도를 찾으려면 그 서비스가 판단하는 자리에서
`code=AUTHZ_TENANT_MISMATCH`를 남겨야 한다.
## Diagnosis
## 진단
- Extract `traceId`, check `X-Tenant-Id` vs token tenant claim
- Determine if this is misconfigured client or intentional attack
- `traceId`를 뽑고, 요청의 테넌트 헤더(서비스가 정한 이름, 예: `X-Tenant-Id`)와 토큰의 테넌트 클레임을 비교한다.
- 클라이언트 설정 오류인지 의도한 공격인지 가린다.
## Action
## 조치
- Block repeat offenders at gateway level
- Alert security team for investigation
- 반복하는 호출자는 gateway에서 막는다.
- 보안 팀에 조사를 요청한다.
## Escalation
## 에스컬레이션
- P1 if confirmed malicious cross-tenant access attempt
- 악의적인 다른 테넌트 접근 시도로 확인되면 P1.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+15 -14
View File
@@ -4,31 +4,32 @@ category: TRANSIENT_DEPENDENCY
error_codes: [CACHE_STAMPEDE_LOCK_TIMEOUT]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: CACHE_STAMPEDE_LOCK_TIMEOUT (`runbook://cache/stampede-lock-timeout`)
## Symptoms
## 증상
- HTTP 503 with `error.code=CACHE_STAMPEDE_LOCK_TIMEOUT`
- Multiple concurrent cache misses on same key; lock contention
- HTTP 503, `error.code=CACHE_STAMPEDE_LOCK_TIMEOUT`.
- 같은 키에 캐시 miss가 동시에 몰리고 락 경합이 생긴다.
- 지금 템플릿은 이 코드를 내지 않는다. `docs/registries/error-codes.yaml`에 이 코드의 행이 없다. 이 runbook은 캐시가 이 코드를 내게 될 때를 위한 초안이다. Redis 장애는 [redis-capability-incident.md](redis-capability-incident.md)를 먼저 본다.
## Diagnosis
## 진단
- Check cache hit ratio metrics
- Identify cache keys with high miss rates
- 캐시 적중률 메트릭을 본다.
- miss 비율이 높은 캐시 키를 찾는다.
## Action
## 조치
- Verify stampede lock TTL is configured appropriately
- Pre-warm cache for high-traffic keys on startup
- 스탬피드 락 TTL이 알맞게 설정됐는지 확인한다.
- 트래픽이 많은 키는 기동할 때 캐시를 미리 채운다.
## Escalation
## 에스컬레이션
- Escalate if backend load spike accompanies stampede
- 스탬피드와 함께 백엔드 부하가 치솟으면 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+15 -14
View File
@@ -4,31 +4,32 @@ category: TRANSIENT_DEPENDENCY
error_codes: [CACHE_UNAVAILABLE]
severity: P1
owner: oncall
last_updated: 2026-06-15
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: CACHE_UNAVAILABLE (`runbook://cache/unavailable`)
## Symptoms
## 증상
- HTTP 503 with `error.code=CACHE_UNAVAILABLE`
- Redis connection errors in logs
- HTTP 503, `error.code=CACHE_UNAVAILABLE`.
- 로그에 Redis 연결 오류가 있다.
- 지금 템플릿은 이 코드를 내지 않는다. `docs/registries/error-codes.yaml`에 이 코드의 행이 없다. 이 runbook은 캐시가 이 코드를 내게 될 때를 위한 초안이다. Redis 장애는 [redis-capability-incident.md](redis-capability-incident.md)를 먼저 본다.
## Diagnosis
## 진단
- Check Redis cluster health
- Verify network connectivity from app to Redis
- Redis 클러스터 상태를 본다.
- 앱에서 Redis까지 네트워크가 닿는지 확인한다.
## Action
## 조치
- Check Redis sentinel/cluster status
- Enable cache degradation path if configured for optional caches
- Redis sentinel·클러스터 상태를 확인한다.
- 선택 캐시에 degraded 경로(캐시 없이 원본에서 읽기)가 설정돼 있으면 켠다.
## Escalation
## 에스컬레이션
- P1 if required cache is down and no degradation path exists
- 필수 캐시가 내려갔고 degraded 경로가 없으면 P1.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [DB_DEADLOCK]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: DB_DEADLOCK (`runbook://db/deadlock`)
## Symptoms
## 증상
- HTTP 409 with `error.code=DB_DEADLOCK`
- SQLState 40P01 in Postgres logs
- HTTP 409, `error.code=DB_DEADLOCK`.
- Postgres 로그에 SQLState 40P01이 있다.
## Diagnosis
## 진단
- Check `pg_locks` and `pg_stat_activity` during deadlock
- Identify conflicting transaction lock order
- 교착이 생길 때 `pg_locks`와 `pg_stat_activity`를 본다.
- 충돌하는 트랜잭션의 락 순서를 찾는다.
## Action
## 조치
- Client should retry (retryable=true)
- Fix lock ordering in code if recurring
- 클라이언트는 다시 시도한다(retryable=true).
- 반복되면 코드의 락 순서를 고친다.
## Escalation
## 에스컬레이션
- Escalate to DBA if deadlock rate is sustained > 1% of transactions
- 교착 비율이 트랜잭션의 1%를 넘는 상태가 이어지면 DBA에 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+16 -14
View File
@@ -4,31 +4,33 @@ category: TRANSIENT_DEPENDENCY
error_codes: [DB_IDLE_IN_TX_TIMEOUT]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: DB_IDLE_IN_TX_TIMEOUT (`runbook://db/idle-in-tx-timeout`)
## Symptoms
## 증상
- HTTP 503 with `error.code=DB_IDLE_IN_TX_TIMEOUT`
- SQLState 25P03; transaction held open too long without activity
- HTTP 503, `error.code=DB_IDLE_IN_TX_TIMEOUT`.
- SQLState 25P03. 트랜잭션이 아무 일 없이 너무 오래 열려 있었다.
## Diagnosis
## 진단
- Check `idle_in_transaction_session_timeout` Postgres setting
- Look for application-level long-running transaction holders
- Postgres의 `idle_in_transaction_session_timeout` 설정을 확인한다. 템플릿은 이 값을 설정하지 않는다.
DB나 역할에 걸린 값이다.
- 트랜잭션을 오래 쥐고 있는 애플리케이션 코드를 찾는다. 트랜잭션 안에서 외부 호출을 기다리는 코드가 흔한
원인이다.
## Action
## 조치
- Reduce transaction scope in application code
- Verify `spring.jpa.properties.hibernate.connection.timeout` is bounded
- 애플리케이션 코드에서 트랜잭션 범위를 줄인다.
- 트랜잭션 시간 상한(`app.persistence-jpa.transaction.write-timeout`·`read-timeout`)이 정해져 있는지 확인한다.
## Escalation
## 에스컬레이션
- Escalate to DBA if connection pool exhaustion results
- 그 결과로 커넥션 풀이 바닥나면 DBA에 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+16 -14
View File
@@ -4,31 +4,33 @@ category: TRANSIENT_DEPENDENCY
error_codes: [DB_QUERY_CANCELED]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: DB_QUERY_CANCELED (`runbook://db/query-canceled`)
## Symptoms
## 증상
- HTTP 503 with `error.code=DB_QUERY_CANCELED`
- SQLState 57014; query exceeds statement timeout
- HTTP 503, `error.code=DB_QUERY_CANCELED`.
- SQLState 57014. 쿼리가 문장 시간 상한을 넘었다.
## Diagnosis
## 진단
- Check `statement_timeout` in Postgres
- Identify slow queries in `pg_stat_statements`
- Postgres의 `statement_timeout`을 확인한다. 템플릿은 트랜잭션 시간 상한
(`app.persistence-jpa.transaction.write-timeout`·`read-timeout`)의 남은 시간을 문장마다 넘기므로, 그 상한을
넘긴 문장도 이 코드로 끝난다.
- `pg_stat_statements`에서 느린 쿼리를 찾는다.
## Action
## 조치
- Optimize slow query or add index
- Adjust statement timeout if query is legitimately long
- 느린 쿼리를 고치거나 인덱스를 더한다.
- 정말 오래 걸려야 하는 쿼리면 시간 상한을 조정한다.
## Escalation
## 에스컬레이션
- Escalate to DBA for query optimization if recurring
- 반복되면 쿼리 최적화를 DBA에 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [DB_SERIALIZATION_FAILURE]
severity: P3
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: DB_SERIALIZATION_FAILURE (`runbook://db/serialization-failure`)
## Symptoms
## 증상
- HTTP 409 with `error.code=DB_SERIALIZATION_FAILURE`
- SQLState 40001; high concurrent transaction contention
- HTTP 409, `error.code=DB_SERIALIZATION_FAILURE`.
- SQLState 40001. 동시 트랜잭션 경합이 심하다.
## Diagnosis
## 진단
- Check DB transaction isolation level
- Identify hot rows / hot tables under high concurrency
- DB 트랜잭션 격리 수준을 확인한다.
- 동시성이 높은 hot row·hot table을 찾는다.
## Action
## 조치
- Client should retry with exponential backoff (retryable=true)
- Optimize transaction scope if spike is sustained
- 클라이언트는 지수 백오프로 다시 시도한다(retryable=true).
- 급증이 이어지면 트랜잭션 범위를 줄인다.
## Escalation
## 에스컬레이션
- Escalate to DBA if sustained serialization failure rate > 5%
- 직렬화 실패 비율이 5%를 넘는 상태가 이어지면 DBA에 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [DB_UNAVAILABLE]
severity: P1
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: DB_UNAVAILABLE (`runbook://db/unavailable`)
## Symptoms
## 증상
- HTTP 503 with `error.code=DB_UNAVAILABLE`
- SQLState 08* connection errors in logs
- HTTP 503, `error.code=DB_UNAVAILABLE`.
- 로그에 SQLState 08* 연결 오류가 있다.
## Diagnosis
## 진단
- Check DB server health and connection pool exhaustion
- Review network connectivity from app pods to DB
- DB 서버 상태와 커넥션 풀 고갈을 확인한다.
- 앱 pod에서 DB까지 네트워크가 닿는지 확인한다.
## Action
## 조치
- Check DB primary health; failover to replica if available
- Drain connection pool and reconnect
- DB primary 상태를 확인한다. replica가 있으면 failover한다.
- 커넥션 풀을 비우고 다시 연결한다.
## Escalation
## 에스컬레이션
- P1: immediate if DB primary is down
- P1: DB primary가 내려갔으면 즉시.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [DEPENDENCY_4XX_CLIENT]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: DEPENDENCY_4XX_CLIENT (`runbook://dependency/4xx-client`)
## Symptoms
## 증상
- HTTP 502 with `error.code=DEPENDENCY_4XX_CLIENT`
- Upstream returned 401/403/400 — credential, scope, or request format issue
- HTTP 502, `error.code=DEPENDENCY_4XX_CLIENT`.
- 업스트림이 401·403·400을 돌려줬다. 자격 증명, scope, 요청 형식 문제다.
## Diagnosis
## 진단
- Check upstream response body in logs for error detail
- Verify API credentials and scopes are valid
- 로그에서 업스트림 응답 본문의 오류 내용을 본다.
- API 자격 증명과 scope가 유효한지 확인한다.
## Action
## 조치
- Rotate credentials if expired
- Fix request format if API contract changed
- 자격 증명이 만료됐으면 교체한다.
- API 계약이 바뀌었으면 요청 형식을 고친다.
## Escalation
## 에스컬레이션
- Escalate to upstream API owner if contract change is suspected
- 계약 변경이 의심되면 업스트림 API 소유자에게 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [DEPENDENCY_5XX_SERVER]
severity: P1
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: DEPENDENCY_5XX_SERVER (`runbook://dependency/5xx-server`)
## Symptoms
## 증상
- HTTP 502 with `error.code=DEPENDENCY_5XX_SERVER`
- Upstream returned 5xx; transient server-side failure
- HTTP 502, `error.code=DEPENDENCY_5XX_SERVER`.
- 업스트림이 5xx를 돌려줬다. 서버 쪽 일시 장애다.
## Diagnosis
## 진단
- Check `dependency_name` tag for which upstream is failing
- Review upstream service status page
- `dependency_name` 태그로 어느 업스트림이 실패하는지 본다.
- 업스트림 서비스의 상태 페이지를 본다.
## Action
## 조치
- Client should retry (retryable=true)
- Monitor upstream recovery
- 클라이언트는 다시 시도한다(retryable=true).
- 업스트림 회복을 지켜본다.
## Escalation
## 에스컬레이션
- P1 if critical upstream is in sustained 5xx state
- 중요한 업스트림이 5xx 상태로 계속 머물면 P1.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [DEPENDENCY_CIRCUIT_OPEN]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: DEPENDENCY_CIRCUIT_OPEN (`runbook://dependency/circuit-open`)
## Symptoms
## 증상
- HTTP 503 with `error.code=DEPENDENCY_CIRCUIT_OPEN`
- Circuit breaker (Resilience4j) in OPEN state for a dependency
- HTTP 503, `error.code=DEPENDENCY_CIRCUIT_OPEN`.
- 어떤 의존성의 circuit breaker(Resilience4j)가 OPEN 상태다.
## Diagnosis
## 진단
- Check Resilience4j circuit breaker metrics for the dependency
- Check upstream health; circuit opens after failure threshold breached
- 그 의존성의 Resilience4j circuit breaker 메트릭을 본다.
- 업스트림 상태를 확인한다. 실패가 임계를 넘으면 circuit이 열린다.
## Action
## 조치
- Wait for circuit half-open probe (automatic after wait duration)
- Resolve upstream issue to allow circuit to close
- circuit의 half-open 시험을 기다린다(대기 시간이 지나면 자동으로 한다).
- 업스트림 문제를 풀어 circuit이 닫히게 한다.
## Escalation
## 에스컬레이션
- P1 if circuit remains open > 5 minutes on a critical dependency
- 중요한 의존성의 circuit이 5분 넘게 열려 있으면 P1.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [DEPENDENCY_CONNECT_FAILED]
severity: P1
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: DEPENDENCY_CONNECT_FAILED (`runbook://dependency/connect-failed`)
## Symptoms
## 증상
- HTTP 503 with `error.code=DEPENDENCY_CONNECT_FAILED`
- TCP connection refused or network unreachable to upstream
- HTTP 503, `error.code=DEPENDENCY_CONNECT_FAILED`.
- 업스트림으로 TCP 연결이 거부됐거나 네트워크에 닿지 않는다.
## Diagnosis
## 진단
- Check `dependency_name` tag for which upstream is unreachable
- Verify network path and firewall rules
- `dependency_name` 태그로 어느 업스트림에 닿지 않는지 본다.
- 네트워크 경로와 방화벽 규칙을 확인한다.
## Action
## 조치
- Check upstream service availability
- Verify service discovery / DNS resolution
- 업스트림 서비스가 살아 있는지 확인한다.
- service discovery와 DNS 조회를 확인한다.
## Escalation
## 에스컬레이션
- P1 if upstream is a critical service dependency
- 업스트림이 중요한 서비스 의존성이면 P1.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [DEPENDENCY_DNS_FAILED]
severity: P1
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: DEPENDENCY_DNS_FAILED (`runbook://dependency/dns-failed`)
## Symptoms
## 증상
- HTTP 503 with `error.code=DEPENDENCY_DNS_FAILED`
- DNS resolution failure for upstream hostname
- HTTP 503, `error.code=DEPENDENCY_DNS_FAILED`.
- 업스트림 호스트 이름의 DNS 조회가 실패했다.
## Diagnosis
## 진단
- Test DNS resolution from app pod: `nslookup <upstream-host>`
- Check cluster DNS (CoreDNS) health
- 앱 pod에서 DNS 조회를 시험한다: `nslookup <upstream-host>`
- 클러스터 DNS(CoreDNS) 상태를 확인한다.
## Action
## 조치
- Verify upstream hostname configuration
- Check CoreDNS / cluster DNS health
- 업스트림 호스트 이름 설정을 확인한다.
- CoreDNS·클러스터 DNS 상태를 확인한다.
## Escalation
## 에스컬레이션
- P1 if cluster DNS is degraded
- 클러스터 DNS가 나빠졌으면 P1.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+15 -14
View File
@@ -4,31 +4,32 @@ category: TRANSIENT_DEPENDENCY
error_codes: [DEPENDENCY_TIMEOUT]
severity: P1
owner: oncall
last_updated: 2026-06-15
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: DEPENDENCY_TIMEOUT (`runbook://dependency/timeout`)
## Symptoms
## 증상
- HTTP 504 with `error.code=DEPENDENCY_TIMEOUT`
- Upstream service did not respond within configured timeout (default: global 10s)
- HTTP 504, `error.code=DEPENDENCY_TIMEOUT`.
- 업스트림 서비스가 설정된 시간 안에 답하지 않았다. 호출 전체의 상한은 HTTP 클라이언트 profile의
`timeout.total-call`이다(기본값은 `docs/httpclient/configuration-reference.md`).
## Diagnosis
## 진단
- Check `dependency_name` in log for which upstream is timing out
- Review upstream service latency metrics
- 로그의 `dependency_name`으로 어느 업스트림이 시간을 넘기는지 본다.
- 업스트림 서비스의 지연 메트릭을 본다.
## Action
## 조치
- Check upstream service health
- Verify timeout settings match SLA expectations
- 업스트림 서비스 상태를 확인한다.
- 시간 상한 설정이 SLA 기대와 맞는지 확인한다.
## Escalation
## 에스컬레이션
- P1 if critical upstream is timing out at scale
- 중요한 업스트림이 대규모로 시간을 넘기면 P1.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+1 -1
View File
@@ -5,7 +5,7 @@ error_codes: [DEPENDENCY_TIMEOUT, DEPENDENCY_CONNECT_FAILED, DEPENDENCY_DNS_FAIL
severity: P1
owner: oncall
last_updated: 2026-05-22
status: stub
status: 초안
---
# Runbook: 외부 의존성 unavailable
@@ -4,31 +4,33 @@ category: TRANSIENT_DEPENDENCY
error_codes: [DOWNLOAD_STREAMING_FAILURE]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: DOWNLOAD_STREAMING_FAILURE (`runbook://file/download-streaming-failure`)
## Symptoms
## 증상
- HTTP 503 with `error.code=DOWNLOAD_STREAMING_FAILURE`
- Streaming response truncated; backpressure or timeout (60s / 100MB limit)
- HTTP 503, `error.code=DOWNLOAD_STREAMING_FAILURE`.
- 스트리밍 응답이 잘렸다. backpressure나 시간 초과(60초 / 100MB 한도)다.
- 지금 템플릿은 이 코드를 내지 않는다. `docs/registries/error-codes.yaml`에 이 코드의 행이 없다. 파일 서버
다운로드 장애는 [`docs/fileserver/operations.md`](../fileserver/operations.md)를 먼저 본다.
## Diagnosis
## 진단
- Check streaming response timeout configuration
- Review download size vs 100MB limit
- 스트리밍 응답 시간 상한 설정을 확인한다.
- 다운로드 크기를 100MB 한도와 비교한다.
## Action
## 조치
- Verify storage backend is reachable
- Check for network congestion on download path
- 저장소 백엔드에 닿는지 확인한다.
- 다운로드 경로의 네트워크 혼잡을 확인한다.
## Escalation
## 에스컬레이션
- Escalate to infra if storage backend is degraded
- 저장소 백엔드가 나빠졌으면 인프라 팀에 넘긴다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+49 -55
View File
@@ -1,94 +1,88 @@
# Runbook: gRPC advanced capabilities
Scope: the `:grpc-advanced:*` family. Everything here is off by default and stays off until a
deployment names it. Nothing in this family ships in a runtime composition today.
범위: `:grpc-advanced:*` family. 여기 있는 것은 모두 기본으로 꺼져 있고, 배포가 이름을 대기 전까지 꺼진 채로
있다. 지금 이 family의 어떤 것도 런타임 조립에 들어가지 않는다.
Flags are `app.grpc.advanced.<capability>.enabled`. `GrpcAdvancedCapability` owns the list of
capability names; `GrpcAdvancedSupportMatrix` owns their current grades.
스위치는 `app.grpc.advanced.<capability>.enabled`다. capability 이름 목록과 기본 등급은
`GrpcAdvancedCapability`(`defaultGrade()`)가 가진다. 근거가 있는 배포는 `GrpcAdvancedFeatureFlags.withGrade`로
등급을 바꾼다.
---
## A capability refuses to start
## capability가 뜨기를 거부한다
`GrpcAdvancedModuleGuard` gives three different refusals, and the remedy differs:
`GrpcAdvancedModuleGuard`는 세 가지로 거부하고, 고치는 법이 다르다.
| Message contains | Meaning | Remedy |
| 메시지에 있는 말 | 뜻 | 고치는 법 |
| --- | --- | --- |
| "its feature flag is not set" | Nobody enabled it | Set the property named in the message |
| "tracked rather than implemented" | Grade is `WATCH` | Nothing to do here; the capability is not implemented |
| "uncharacterised failure modes" | Grade is `EXPERIMENTAL` and this is production | Record a production approval, or run it outside production |
| "its feature flag is not set" | 아무도 켜지 않았다 | 메시지가 이름 댄 속성을 설정한다 |
| "tracked rather than implemented" | 등급이 `WATCH`다 | 여기서 할 일은 없다. 그 capability는 구현되지 않았다 |
| "uncharacterised failure modes" | 등급이 `EXPERIMENTAL`이고 여기는 운영이다 | 운영 승인을 기록하거나, 운영 밖에서 돌린다 |
The refusal message always names the property key, so the first case is a configuration line rather
than a support question.
거부 메시지는 늘 속성 키를 이름 댄다. 그래서 첫 경우는 지원 문의가 아니라 설정 한 줄이다.
---
## xDS: the control plane went away
## xDS: control plane이 사라졌다
**What you are seeing.** The control plane is unreachable and clients are still routing.
**보이는 것.** control plane에 닿지 않는데 클라이언트는 아직 라우팅한다.
**What it means.** `GrpcXdsFailurePolicy` serves the last-known-good snapshot, up to its staleness
bound.
**뜻.** `GrpcXdsFailurePolicy`가 마지막으로 정상이던 snapshot을 오래됨 상한까지 내준다.
**What to do.**
**할 일.**
1. Check the snapshot's age. `SERVE_LAST_KNOWN_GOOD` is the healthy degraded state.
2. `STALE_BEYOND_BOUND` means the snapshot is older than the policy allows and is no longer trusted.
Beyond that bound, a decommissioned backend would otherwise keep receiving traffic indefinitely.
3. `NO_SNAPSHOT_YET` on a starting instance means it never reached the control plane. It fails after
the initial fetch timeout rather than starting with no routing.
1. snapshot의 나이를 본다. `SERVE_LAST_KNOWN_GOOD`는 정상적인 degraded 상태다.
2. `STALE_BEYOND_BOUND`는 snapshot이 정책이 허용하는 것보다 오래돼서 더는 믿지 않는다는 뜻이다. 그 상한이
없으면 내린 backend가 트래픽을 끝없이 받는다.
3. 뜨는 인스턴스의 `NO_SNAPSHOT_YET`은 control plane에 한 번도 닿지 못했다는 뜻이다. 라우팅 없이 뜨지 않고, 첫
fetch 시간 상한이 지나면 실패한다.
**Do not** add application-level retry policy while xDS is enabled. `GrpcXdsProfile` refuses an
`APPLICATION` retry owner, because retry defined in two places has a winner that depends on
resolution order rather than on a decision.
xDS가 켜진 동안 애플리케이션 수준의 재시도 정책을 **더하지 않는다**. `GrpcXdsProfile`이 `APPLICATION` 재시도
소유자를 거부한다. 두 곳에 정의한 재시도는 결정이 아니라 해석 순서가 이기는 쪽을 정하기 때문이다.
---
## gRPC-Web: a browser call hangs and then fails with no status
## gRPC-Web: 브라우저 호출이 멈췄다가 상태 없이 실패한다
**Almost always the proxy.** A gRPC status arrives as a trailer, and a browser cannot read a trailer
the proxy did not expose. Check that the proxy's CORS `expose_headers` includes `grpc-status` and
`grpc-message`; `GrpcWebProxyContract.violations` reports exactly this, and the reference
configuration in `envoy/envoy.yaml` shows it in place.
**거의 언제나 proxy다.** gRPC 상태는 trailer로 오고, 브라우저는 proxy가 노출하지 않은 trailer를 읽지 못한다.
proxy의 CORS `expose_headers`에 `grpc-status`와 `grpc-message`가 있는지 확인한다.
`GrpcWebProxyContract.violations`가 정확히 이것을 보고하고, 참조 설정
`src/platforms/grpc-advanced/grpc-advanced-compat/src/test/resources/envoy/envoy.yaml`에 그것이 들어 있다.
**If the method is client- or bidirectional-streaming**, it cannot work over gRPC-Web at all — a
browser has no way to send a stream of messages. `GrpcWebRpcSupport.require` refuses such a method.
**메서드가 client streaming이나 bidirectional streaming이면** gRPC-Web으로는 아예 되지 않는다. 브라우저는
메시지 stream을 보낼 방법이 없다. `GrpcWebRpcSupport.require`가 그런 메서드를 거부한다.
---
## Servlet: a transport setting appears to be ignored
## Servlet: 전송 설정이 무시되는 것 같다
It is ignored. The container owns the socket, so keepalive tuning, maximum connection age and
flow-control window tuning belong to it. This repository has no Servlet transport code that would
refuse them, so configure them on the container.
무시된다. 소켓은 컨테이너가 가지므로 keepalive 조정, 최대 연결 수명, flow-control window 조정은 컨테이너의
몫이다. 이 저장소에는 그것을 거부할 Servlet 전송 코드가 없으니 컨테이너에서 설정한다.
A Servlet run never substitutes for Netty certification.
Servlet 실행은 Netty 인증을 대신하지 않는다.
---
## Hedging: backend load doubled
## Hedging: backend 부하가 두 배가 됐다
**Expected, within a bound.** Hedging trades duplicate load for tail latency.
`GrpcHedgingResult` records both `duplicateBackendCalls` and `cancelledLoserAttempts`; a dashboard
showing only the latency improvement makes the trade look free.
**상한 안이면 예상한 일이다.** hedging은 중복 부하를 내고 꼬리 지연을 줄인다. `GrpcHedgingResult`는
`duplicateBackendCalls`와 `cancelledLoserAttempts`를 둘 다 기록한다. 지연 개선만 보여 주는 대시보드는 그 교환을
공짜처럼 보이게 한다.
**What to check.** `GrpcHedgingBudget` caps hedges as a fraction of completed calls. If duplicate
load is above that fraction, the budget is not being consumed — which means something is issuing
hedges outside the coordinator.
**확인할 것.** `GrpcHedgingBudget`은 hedge를 끝난 호출의 비율로 제한한다. 중복 부하가 그 비율을 넘으면 예산이
쓰이지 않고 있다는 뜻이다. coordinator 밖에서 무언가가 hedge를 보내고 있다.
**Hedging is refused** for anything but a read-only unary method. A hedged mutation runs twice by
design, and an idempotency key does not help: the second attempt duplicates a success in progress
rather than retrying a failure.
읽기 전용 unary 메서드가 아니면 **hedging을 거부한다**. hedge된 변경은 설계상 두 번 돈다. 멱등 키도 소용없다.
두 번째 시도는 실패를 다시 시도하는 것이 아니라 진행 중인 성공을 중복한다.
---
## Promoting a capability
## capability 승격
Promotion to `ADVANCED_STABLE` needs compatibility evidence, a security review, fault evidence,
performance evidence, an ADR, a runbook, a real-environment test and seven days of soak. A Stable
default needs thirty. Promotions are independent: promoting one capability changes no other's
grade. This is a review checklist; the in-code `GrpcAdvancedPromotionGate` that restated it was
removed (review 2026-09-24 S5-lead-4) because nothing but its own test called it.
`ADVANCED_STABLE`로 올리려면 호환성 증거, 보안 리뷰, 장애 증거, 성능 증거, ADR, runbook, 실제 환경 시험, 7일
soak이 필요하다. Stable 기본값은 30일이 필요하다. 승격은 서로 독립이다. 한 capability를 올려도 다른 것의 등급은
바뀌지 않는다. 이것은 리뷰 점검 목록이다. 이것을 코드로 다시 적은 `GrpcAdvancedPromotionGate`는 자기 테스트
말고는 부르는 곳이 없어 지웠다(리뷰 2026-09-24 S5-lead-4).
Before citing a suite as evidence, check that it ran against the real infrastructure it needs (proxy,
container, control plane or toolchain). A suite that ran without it passed and established nothing.
어떤 suite를 증거로 들기 전에, 그 suite가 필요한 실제 인프라(proxy, 컨테이너, control plane, toolchain)에 대고
돌았는지 확인한다. 인프라 없이 돈 suite는 통과했지만 아무것도 증명하지 않았다.
+101 -120
View File
@@ -1,179 +1,160 @@
# Runbook: gRPC platform operations
Scope: the `:grpc:*` family. All of it is build-only today — every leaf's `runtime_memberships` is
empty — so nothing here fires in production yet. It is written now because the states it covers are
the ones an on-call cannot work out from first principles at three in the morning, and shipping the
behaviour before the runbook means the first person to meet one is doing that.
범위: `:grpc:*` family. 지금은 모두 빌드만 된다. registry에서 이 family의 leaf는 모두 `"build": "optional-grpc"`
(주 빌드 밖, `-p platforms/optional-build`로 돈다)이고 어느 조립에도 들어가지 않으므로, 여기 있는 것은 아직 운영에서
일어나지 않는다. 그래도 지금 쓰는 이유가 있다. 여기서 다루는 상태는 당번이 새벽 세 시에 처음부터 따져서는 알아낼
수 없는 것들이고, runbook보다 동작을 먼저 내보내면 그것을 처음 만난 사람이 그 따지기를 하게 된다.
Configuration lives under `app.grpc.platform.*` and is bound by `GrpcPlatformProperties`.
The platform does not start unless `app.grpc.platform.enabled=true`.
설정은 `app.grpc.platform.*` 아래에 있고 `GrpcPlatformProperties`가 묶는다. 플랫폼은
`app.grpc.platform.enabled=true`가 아니면 뜨지 않는다.
---
## COMPLETION_UNKNOWN on a mutation
## 상태를 바꾸는 호출의 COMPLETION_UNKNOWN
**What you are seeing.** A client received `DEADLINE_EXCEEDED`, `UNAVAILABLE` or `INTERNAL` on a
state-changing call, and the response trailer `completion-outcome` reads `COMPLETION_UNKNOWN`.
**보이는 것.** 클라이언트가 상태를 바꾸는 호출에서 `DEADLINE_EXCEEDED`, `UNAVAILABLE`, `INTERNAL`을 받았고, 응답
trailer `completion-outcome`이 `COMPLETION_UNKNOWN`이다.
**What it means.** The server may have committed. This is not a failure and not a success; the status
code cannot distinguish them, which is why the outcome is carried separately.
**뜻.** 서버가 커밋했을 수 있다. 실패도 성공도 아니다. 상태 코드로는 둘을 가릴 수 없어서 결과를 따로 싣는다.
**What not to do.** Do not re-issue the call. Do not tell the caller it failed. Both are wrong half
the time, and which half is not knowable from the status.
**하지 말 것.** 호출을 다시 보내지 않는다. 호출자에게 실패했다고 말하지 않는다. 둘 다 절반은 틀리고, 어느 절반인지
상태 코드로는 알 수 없다.
**What to do.**
**할 일.**
1. Take the `error-execution-id` from the trailers. It is the only link between what the client saw
and what the server did.
2. If the method is `IDEMPOTENCY_KEY_REQUIRED`, query the operation ledger with the caller
fingerprint, the full method name and the caller's key. `GrpcOperationStatusQuery` returns one of
`IN_PROGRESS`, `COMMITTED`, `FAILED_TERMINAL`, `NOT_FOUND` or `UNKNOWN`.
3. `COMMITTED` means return the stored outcome reference, not a freshly computed answer — the resource
may have changed since, and a new answer would describe the state at reconciliation time rather
than the state the caller's own call produced.
4. `NOT_FOUND` means the operation never started and is safe to re-issue. `FAILED_TERMINAL` means the
same.
5. `UNKNOWN` means the ledger could not be consulted. Nothing may be concluded. The case is queued by
`GrpcCompletionReconciler` and retried later.
6. If the method is not keyed, there is no ledger row. Resolve it against the business resource, or
escalate to the service owner. This is the case the keyed profile exists to avoid.
1. trailer에서 `error-execution-id`를 꺼낸다. 클라이언트가 본 것과 서버가 한 것을 잇는 유일한 고리다.
2. 메서드가 `IDEMPOTENCY_KEY_REQUIRED`면 호출자 fingerprint, 전체 메서드 이름, 호출자의 키로 operation ledger를
조회한다. `GrpcOperationStatusQuery`는 `IN_PROGRESS`, `COMMITTED`, `FAILED_TERMINAL`, `NOT_FOUND`, `UNKNOWN`
중 하나를 돌려준다.
3. `COMMITTED`면 새로 계산한 답이 아니라 저장된 결과 참조를 돌려준다. 그 뒤에 자원이 바뀌었을 수 있고, 새 답은
호출자 자신의 호출이 만든 상태가 아니라 맞춰 보는 시점의 상태를 설명한다.
4. `NOT_FOUND`는 operation이 시작하지 않았다는 뜻이라 다시 보내도 안전하다. `FAILED_TERMINAL`도 같다.
5. `UNKNOWN`은 ledger를 조회하지 못했다는 뜻이다. 아무것도 결론 낼 수 없다. `GrpcCompletionReconciler`가 그
건을 대기열에 넣고 나중에 다시 시도한다.
6. 메서드에 키가 없으면 ledger 행이 없다. 업무 자원으로 맞춰 보거나 서비스 소유자에게 넘긴다. 키 있는 profile은
이 경우를 피하려고 있다.
7. `IN_PROGRESS` means a claim exists and has not finished. If its owner died, the claim is not
stuck forever: once it is older than the claim TTL (`app.grpc.platform.operation-ledger-claim-ttl`,
default 5m), the next retry of the same request takes it over and runs again,
and a later reconciler pass sees that attempt's `COMMITTED` or `FAILED_TERMINAL`. Until a retry
arrives, the case stays pending. The re-run is safe only when the ledger commit is recorded in the
mutation's own transaction; if this service commits them separately, check the business resource
before letting the retry through. An owner that was only slow cannot spoil the takeover: its claim
attempt (`claim_attempt`) is behind, so its late commit is refused and its late failure ignored.
A log line saying an operation "is no longer held by attempt N" is that refusal, not an outage.
7. `IN_PROGRESS`는 claim이 있고 끝나지 않았다는 뜻이다. 그 소유자가 죽었어도 claim이 영원히 묶이지는 않는다.
claim TTL(`app.grpc.platform.operation-ledger-claim-ttl`, 기본 5m)보다 오래되면, 같은 요청의 다음 재시도가
그것을 넘겨받아 다시 돌리고, 뒤의 reconciler 단계가 그 시도의 `COMMITTED`나 `FAILED_TERMINAL`을 본다.
재시도가 오기 전까지 그 건은 대기로 남는다. 다시 돌리는 것은 ledger 커밋이 변경 자신의 트랜잭션 안에서 기록될
때만 안전하다. 이 서비스가 둘을 따로 커밋하면 재시도를 들이기 전에 업무 자원을 확인한다. 느리기만 했던
소유자는 넘겨받기를 망치지 못한다. 그 claim 시도(`claim_attempt`)가 뒤처졌으므로 늦은 커밋은 거부되고 늦은
실패는 무시된다. operation이 "is no longer held by attempt N"이라는 로그 줄이 그 거부다. 장애가 아니다.
**Escalate when** the reconciler's pending list grows across passes. That means the ledger is
unreachable rather than slow. A case pending as `IN_PROGRESS` for longer than the claim TTL with no
retry arriving is a caller that gave up; it needs the business resource checked, not a ledger fix.
**넘길 때는** reconciler의 대기 목록이 단계를 거듭하며 커질 때다. ledger가 느린 게 아니라 닿지 않는다는 뜻이다.
claim TTL보다 오래 `IN_PROGRESS`로 대기 중인데 재시도가 오지 않는 건은 호출자가 포기한 것이다. ledger를 고칠 일이
아니라 업무 자원을 확인할 일이다.
---
## The operation ledger table keeps growing
## operation ledger 테이블이 계속 커진다
**What you are seeing.** `grpc_operation_ledger` grows without bound, or a retry of an old key runs
the mutation again instead of replaying.
**보이는 것.** `grpc_operation_ledger`가 끝없이 커지거나, 오래된 키의 재시도가 replay 대신 변경을 다시 돌린다.
**What it means.** Finished rows (`COMMITTED`, `FAILED_TERMINAL`) are deleted only when something
calls `GrpcOperationLedgerRetention.purgeExpired(now)`; the starter assembles that bean
(`app.grpc.platform.operation-ledger-enabled=true`) but does not schedule it. A growing table means
the service's scheduler is not calling it. A retry that re-ran after the retention
(`app.grpc.platform.operation-ledger-retention`, default 24h) is the trade the retention makes: its
record was purged, so it was a new operation.
**뜻.** 끝난 행(`COMMITTED`, `FAILED_TERMINAL`)은 누군가 `GrpcOperationLedgerRetention.purgeExpired(now)`를 불러야만
지워진다. starter는 그 bean을 조립하지만(`app.grpc.platform.operation-ledger-enabled=true`) 일정을 걸지는 않는다.
테이블이 커지면 서비스의 scheduler가 그것을 부르지 않는 것이다. 보존 기간
(`app.grpc.platform.operation-ledger-retention`, 기본 24h)이 지난 뒤 다시 돈 재시도는 보존 기간이 감수하는
교환이다. 기록이 지워졌으므로 새 operation이었다.
**What to do.**
**할 일.**
1. Check that the service schedules `purgeExpired`. Each call deletes in batches of 500 until a batch
comes back short, never touching `IN_PROGRESS` rows.
2. For a large backlog, call it repeatedly; each batch is a short transaction that skips rows another
transaction holds.
3. If retried keys re-run after the retention, raise the retention above the callers' retry window
rather than skipping the purge.
1. 서비스가 `purgeExpired`에 일정을 걸었는지 확인한다. 한 번 부르면 500행씩 지우다가 덜 찬 묶음이 나오면 멈추고,
`IN_PROGRESS` 행은 건드리지 않는다.
2. 밀린 양이 많으면 여러 번 부른다. 묶음마다 짧은 트랜잭션이고, 다른 트랜잭션이 쥔 행은 건너뛴다.
3. 다시 보낸 키가 보존 기간 뒤에 다시 돌면, purge를 건너뛰지 말고 보존 기간을 호출자의 재시도 창보다 길게 한다.
**Escalate when** old `IN_PROGRESS` rows accumulate. Those are not purged by design; each is an
abandoned claim no retry has taken over (see `IN_PROGRESS` above).
**넘길 때는** 오래된 `IN_PROGRESS` 행이 쌓일 때다. 그 행은 설계상 지워지지 않는다. 하나하나가 어느 재시도도
넘겨받지 않은 버려진 claim이다(위의 `IN_PROGRESS`).
---
## A stream ended with FULL_RESYNC_REQUIRED
## stream이 FULL_RESYNC_REQUIRED로 끝났다
**What you are seeing.** A client's resume was refused and it was told to resynchronise.
**보이는 것.** 클라이언트의 resume이 거부되고 다시 동기화하라는 답을 받았다.
**What it means.** The server can no longer replay from the client's cursor. Either the snapshot
version moved, or the cursor predates retained history.
**뜻.** 서버가 클라이언트의 cursor부터 더는 replay할 수 없다. snapshot 버전이 움직였거나, cursor가 보존된 이력보다
앞선다.
**What to do.** Nothing on the server. The client is expected to discard its position and start a new
stream from a fresh snapshot. A client that instead retries the same token will keep receiving the
same answer.
**할 일.** 서버에서는 없다. 클라이언트가 자기 위치를 버리고 새 snapshot에서 새 stream을 시작해야 한다. 대신 같은
token으로 다시 시도하는 클라이언트는 같은 답을 계속 받는다.
**Escalate when** it is happening to many clients at once. That usually means history retention was
reduced, or snapshots are rotating faster than clients reconnect.
**넘길 때는** 많은 클라이언트에 한꺼번에 일어날 때다. 보통 이력 보존이 줄었거나, 클라이언트가 다시 붙는 것보다
snapshot이 빨리 돈다는 뜻이다.
---
## A stream ended with SLOW_CONSUMER
## stream이 SLOW_CONSUMER로 끝났다
**What you are seeing.** Streams terminating with `SLOW_CONSUMER`, and
`grpc.stream.flow_control_stalls` rising.
**보이는 것.** stream이 `SLOW_CONSUMER`로 끝나고 `grpc.stream.flow_control_stalls`가 오른다.
**What it means.** The consumer could not keep up with the bounded queue. The stream was terminated
rather than silently dropping messages, because a client cannot detect drops — the sequence numbers
it sees are the ones it was sent.
**뜻.** 소비자가 상한 있는 큐를 따라가지 못했다. 메시지를 조용히 버리는 대신 stream을 끝냈다. 클라이언트는 버려진
것을 알아챌 수 없다. 클라이언트가 보는 순번은 보내진 것뿐이다.
**What to do.**
**할 일.**
1. Check whether the consumer is slow or the producer is fast. `grpc.stream.messages` against
`grpc.stream.lifetime` tells you the rate.
2. If the consumer is slow, the fix is on the consumer. Raising the queue bound moves the failure
later and makes it larger.
3. A resume is not available after this ending: the messages that overflowed the queue are gone, so
continuing from the last delivered sequence would silently skip them. The client resynchronises.
1. 소비자가 느린지 생산자가 빠른지 확인한다. `grpc.stream.messages`를 `grpc.stream.lifetime`과 견주면 속도가
나온다.
2. 소비자가 느리면 고칠 곳은 소비자다. 큐 상한을 올리면 실패가 뒤로 밀리고 커질 뿐이다.
3. 이렇게 끝난 뒤에는 resume을 쓸 수 없다. 큐를 넘친 메시지는 사라졌으므로, 마지막으로 전달한 순번부터 이어 가면
그것을 조용히 건너뛴다. 클라이언트는 다시 동기화한다.
---
## RESOURCE_EXHAUSTED under load
## 부하에서 RESOURCE_EXHAUSTED
**What you are seeing.** Calls refused with `RESOURCE_EXHAUSTED` and `GrpcAdmissionController`
reporting rejections.
**보이는 것.** 호출이 `RESOURCE_EXHAUSTED`로 거부되고 `GrpcAdmissionController`가 거부를 보고한다.
**What it means.** The server is at its concurrency and queue bounds and is shedding rather than
queueing. This is the designed behaviour: accepting work whose callers have already given up spends
capacity on nothing.
**뜻.** 서버가 동시성과 큐 상한에 닿아서 줄을 세우지 않고 덜어 낸다. 설계한 동작이다. 호출자가 이미 포기한 일을
받으면 아무것도 아닌 데 용량을 쓴다.
**What to do.**
**할 일.**
1. Read `grpc.rpc.duration` and `grpc.rpc.queue_wait` separately. Queue time rising with duration flat
means the bottleneck is admission, not the work.
2. Check which saturation counter is moving — executor, channel or flow control. They look identical
in a latency graph and have different fixes.
3. Raising `app.grpc.platform.executor-queue-capacity` defers the problem; it does not remove
it. `GrpcExecutorProfile` refuses a queue above ten thousand for that reason.
1. `grpc.rpc.duration`과 `grpc.rpc.queue_wait`를 따로 읽는다. duration은 그대로인데 큐 시간이 오르면 병목은 일이
아니라 admission이다.
2. 어느 포화 counter가 움직이는지 확인한다. executor, channel, flow control이다. 지연 그래프에서는 똑같이 보이지만
고치는 법이 다르다.
3. `app.grpc.platform.executor-queue-capacity`를 올리면 문제를 미룰 뿐 없애지 않는다. 그래서 `GrpcExecutorProfile`이
1만이 넘는 큐를 거부한다.
---
## A rollout is producing errors at every deploy
## 배포할 때마다 rollout이 오류를 낸다
**What you are seeing.** A burst of `UNAVAILABLE` or `CANCELLED` each time an instance goes away.
**보이는 것.** 인스턴스가 빠질 때마다 `UNAVAILABLE`이나 `CANCELLED`가 몰린다.
**What it means.** The drain sequence is not completing, or is running out of order.
**뜻.** drain 순서가 끝나지 않거나, 순서가 어긋나서 돈다.
**What to do.**
**할 일.**
1. `GrpcDrainResult` records what each drain achieved: completed and cancelled unary calls, signalled
and cancelled streams, and which phases ran. A drain that routinely force-cancels is the cause.
2. The order matters. Readiness flips first and nothing is refused during that window, because there
is a gap between an instance reporting unready and routing acting on it. Refusing during that gap
turns a clean rollout into a burst of errors at every deploy.
3. For long streams, check the Kubernetes profile's `streamReconnectBudget` and
`readinessDrainGrace`. A stream is pinned to one pod for its whole life, so every rollout ends it;
a profile with long streams and no reconnect budget has not decided what clients do next.
1. `GrpcDrainResult`가 각 drain이 해낸 것을 기록한다. 끝난 unary 호출과 취소된 unary 호출, 신호를 받은 stream과
취소된 stream, 돈 단계다. 늘 강제 취소하는 drain이 원인이다.
2. 순서가 중요하다. readiness가 먼저 뒤집히고, 그 사이에는 아무것도 거부하지 않는다. 인스턴스가 unready를 보고한
뒤 라우팅이 그것을 따르기까지 틈이 있기 때문이다. 그 틈에 거부하면 깨끗한 rollout이 배포마다 오류 묶음이 된다.
3. 긴 stream이면 Kubernetes profile의 `streamReconnectBudget`과 `readinessDrainGrace`를 확인한다. stream은 일생
내내 한 pod에 묶이므로 rollout마다 끝난다. 긴 stream이 있는데 다시 붙는 예산이 없는 profile은 클라이언트가 다음에
할 일을 정하지 않은 것이다.
---
## Verifying a deployment's configuration
## 배포의 설정 확인
`GrpcPlatformSnapshotService` produces a secret-free snapshot for a caller on the admin network
holding an admin role. Both gates are required.
`GrpcPlatformSnapshotService`는 관리 네트워크에 있고 관리 역할을 가진 호출자에게 secret 없는 snapshot을 만든다.
두 관문이 모두 필요하다.
`GrpcPlatformSnapshotService.driftAgainstRelease` compares a running snapshot with the release
manifest and reports schema version, method policy hash and per-channel profile differences. An
instance running a configuration the release did not ship is behind a whole class of incidents that
are otherwise diagnosed by reading logs.
`GrpcPlatformSnapshotService.driftAgainstRelease`는 실행 중인 snapshot을 릴리스 manifest와 비교해 스키마 버전,
메서드 정책 해시, channel별 profile 차이를 보고한다. 릴리스가 내보내지 않은 설정으로 도는 인스턴스는, 그렇지 않으면
로그를 읽어야만 진단되는 장애 한 부류의 원인이다.
The snapshot carries hashes and names only. A field whose name looks like a credential is refused at
construction rather than redacted.
snapshot에는 해시와 이름만 실린다. 자격 증명처럼 보이는 이름의 칸은 가리지 않고 만들 때 거부한다.
---
## Things that are deliberately off
## 일부러 꺼 둔 것
- **Reflection in production.** `GrpcReflectionMode.defaultFor` returns `DISABLED` for `STAGE` and
`PROD`. Reflection publishes the whole schema to anyone who can open a connection.
- **Every advanced capability.** See `docs/runbooks/grpc-advanced-capabilities.md`.
- **The platform itself.** `app.grpc.platform.enabled` defaults to false, and every `:grpc:*`
leaf is build-only in the registry.
- **운영의 reflection.** `GrpcReflectionMode.defaultFor`는 `STAGE`와 `PROD`에 `DISABLED`를 돌려준다. reflection은
연결을 열 수 있는 누구에게나 스키마 전체를 공개한다.
- **모든 advanced capability.** `docs/runbooks/grpc-advanced-capabilities.md`를 본다.
- **플랫폼 자체.** `app.grpc.platform.enabled`의 기본값은 false이고, registry에서 모든 `:grpc:*` leaf는
`"build": "optional-grpc"`라 기본 조립에 들어가지 않는다.
+95 -111
View File
@@ -4,68 +4,58 @@ category: TRANSIENT_DEPENDENCY
error_codes: [IDEMPOTENCY_UNAVAILABLE, IDEMPOTENCY_COMPLETION_UNKNOWN, IDEMPOTENCY_RECOVERY_REQUIRED]
severity: P2
owner: oncall
last_updated: 2026-11-05
status: active
last_updated: 2026-11-07
status: 운영
---
# Runbook: IDEMPOTENCY_UNAVAILABLE (`runbook://idempotency/unavailable`)
## Symptoms
## 증상
- HTTP 503 (`error.code=IDEMPOTENCY_UNAVAILABLE`, `retryable=true`) on endpoints that take an
`Idempotency-Key`; the same code on the gRPC `error-code` trailer (`UNAVAILABLE`).
- `IdempotencyExecutor` refused to run the action because the replay store (JPA or Redis, whichever
`app.idempotency` selects) did not answer. Nothing was executed: the refusal happens before the
action, so a client retry is safe.
- The same 503 when the store refused to start a claim whose processing lease had already run out
— the request spent longer than the lease between its claim and the start of its action (a
stalled process, a slow store call). The ERROR line, `failure classified as
IDEMPOTENCY_UNAVAILABLE (…)`, has the exception attached, and the exception's message reads `the
claim's processing lease ran out before the action started; nothing ran: <scope>` — in prod JSON
logs that is in `stack_trace`, not `message`. The store may be healthy.
Nothing ran here either, and the next request with the key takes the claim over and runs it.
- HTTP 503 `IDEMPOTENCY_COMPLETION_UNKNOWN` (`retryable=true`) is the same outage hitting after the
action ran: the store did not answer while the result was being recorded. When the use case called
the executor inside its write transaction, that transaction's database writes rolled back with the
exception; an action that committed a transaction of its own kept its writes, and anything outside
a transaction (an outbound call, a message) may have happened. This is not "nothing was executed".
Clients resend with the same key.
- HTTP 500 `IDEMPOTENCY_RECOVERY_REQUIRED` (`retryable=false`) means the opposite case: the store
cannot tell whether an earlier attempt's effect already happened. Two records produce it:
- `ABANDONED`: the action threw, or reported its effect unknown. Final until the record expires.
- `EXECUTING` past its processing lease (`APP_IDEMPOTENCY_PROCESSING_LEASE`, 30s): the attempt
crashed, or is still running longer than the lease. The executor never renews the lease, so a
slow but healthy request lands here too. The server never runs it again and does not touch the
record. If the attempt is still running and finishes, its result is recorded, the first request
gets its normal answer, and later requests with the key get that result replayed; a failure it
reports is recorded the same way. So this 500 can stop on its own (owner decision 2026-11-04).
This is the Redis store's case. The PostgreSQL store, called inside the use case's write
transaction as the template calls it, never shows another request an unfinished record: that
request waits for the first transaction to end, and gets the replay if it committed or a fresh
run if it rolled back (`docs/web/http-contract.md` §2).
- `Idempotency-Key`를 받는 엔드포인트에서 HTTP 503(`error.code=IDEMPOTENCY_UNAVAILABLE`, `retryable=true`).
gRPC는 `error-code` trailer에 같은 코드가 온다(`UNAVAILABLE`).
- replay 저장소(`app.idempotency`가 고른 JPA나 Redis)가 답하지 않아서 `IdempotencyExecutor`가 action 실행을
거절했다. 아무것도 실행되지 않았다. 거절은 action 전에 일어나므로 클라이언트가 다시 시도해도 안전하다.
- 처리 lease가 이미 끝난 claim을 저장소가 시작하지 않을 때도 같은 503이다. 요청이 claim과 action 시작 사이에
lease보다 오래 걸렸다(멈춘 프로세스, 느린 저장소 호출). ERROR 줄 `failure classified as
IDEMPOTENCY_UNAVAILABLE (…)`에 예외가 붙고, 예외 메시지는 `the claim's processing lease ran out before the
action started; nothing ran: <scope>`다. prod JSON 로그에서는 `message`가 아니라 `stack_trace`에 있다.
저장소는 멀쩡할 수 있다. 이때도 아무것도 실행되지 않았고, 그 키로 오는 다음 요청이 claim을 넘겨받아 실행한다.
- HTTP 503 `IDEMPOTENCY_COMPLETION_UNKNOWN`(`retryable=true`)은 같은 장애가 action이 실행된 뒤에 닥친 것이다.
결과를 기록하는 동안 저장소가 답하지 않았다. use case가 자기 쓰기 트랜잭션 안에서 executor를 불렀으면, 그
트랜잭션의 DB 쓰기는 예외와 함께 롤백됐다. 자기 트랜잭션을 따로 커밋한 action은 쓰기가 남았고, 트랜잭션 밖의
일(외부 호출, 메시지)은 일어났을 수 있다. 「아무것도 실행되지 않았다」가 아니다. 클라이언트는 같은 키로 다시
보낸다.
- HTTP 500 `IDEMPOTENCY_RECOVERY_REQUIRED`(`retryable=false`)는 반대 경우다. 앞선 시도의 효과가 이미 일어났는지
저장소가 가릴 수 없다. 두 기록이 이 코드를 낸다.
- `ABANDONED`: action이 예외를 던졌거나 효과를 모른다고 보고했다. 기록이 만료될 때까지 바뀌지 않는다.
- 처리 lease(`APP_IDEMPOTENCY_PROCESSING_LEASE`, 30s)가 지난 `EXECUTING`: 시도가 죽었거나, lease보다 오래 아직
돌고 있다. executor는 lease를 늘리지 않으므로 느리지만 멀쩡한 요청도 여기에 온다. 서버는 그 요청을 다시
실행하지 않고 기록도 건드리지 않는다. 시도가 아직 돌다가 끝나면 그 결과가 기록되고, 첫 요청은 보통의 응답을
받고, 그 키로 오는 뒤의 요청은 그 결과를 replay로 받는다. 시도가 보고한 실패도 같은 식으로 기록된다. 그래서
이 500은 저절로 멈출 수 있다(소유자 결정 2026-11-04).
이것은 Redis 저장소의 경우다. PostgreSQL 저장소는 템플릿이 부르는 대로 use case의 쓰기 트랜잭션 안에서
불리면, 끝나지 않은 기록을 다른 요청에 보이지 않는다. 그 요청은 첫 트랜잭션이 끝나기를 기다렸다가, 커밋됐으면
replay를, 롤백됐으면 새 실행을 받는다(`docs/web/http-contract.md` §2).
## Diagnosis
## 진단
- Check the health of the idempotency store the service uses (`/actuator/health` component of the
JPA datasource or Redis, depending on the selected provider).
- Look for connection-pool saturation or timeouts on that store in the same time window; the
executor reports saturation as unavailable rather than guessing.
- For `IDEMPOTENCY_RECOVERY_REQUIRED`, find the scope in the server's ERROR log of the failed request.
Every transport writes the same line, `failure classified as IDEMPOTENCY_RECOVERY_REQUIRED
(category=DATA_INTEGRITY, retryable=false)`, with the exception attached
(shared-contract `ServerFailureLog`), and adds its own correlation:
- web: no suffix; the line carries the request's `X-Request-Id` (MDC `request_id`).
- gRPC: ` (method=<service>/<method>)`; MDC `request_id` too when the service closed the call on
its callback thread.
- GraphQL: ` (executionId=<id>)`, the `executionId` the client got in the error's `extensions`.
- STOMP (`@MessageMapping`): no suffix; MDC `request_id` is the frame's.
- 서비스가 쓰는 멱등성 저장소의 상태를 본다(고른 provider에 따라 JPA datasource나 Redis의 `/actuator/health`
구성 요소).
- 같은 시간대에 그 저장소의 커넥션 풀 포화나 시간 초과를 찾는다. executor는 포화를 추측하지 않고 사용 불가로
보고한다.
- `IDEMPOTENCY_RECOVERY_REQUIRED`는 실패한 요청의 서버 ERROR 로그에서 scope를 찾는다. 모든 전송 계층이 같은 줄
`failure classified as IDEMPOTENCY_RECOVERY_REQUIRED (category=DATA_INTEGRITY, retryable=false)`에 예외를
붙여 쓰고(shared-contract `ServerFailureLog`), 자기 상관 정보를 덧붙인다.
- web: 덧붙이는 것이 없다. 줄에 요청의 `X-Request-Id`(MDC `request_id`)가 실린다.
- gRPC: ` (method=<service>/<method>)`. 서비스가 callback 스레드에서 호출을 닫았으면 MDC `request_id`도 있다.
- GraphQL: ` (executionId=<id>)`. 클라이언트가 오류의 `extensions`에서 받은 `executionId`다.
- STOMP(`@MessageMapping`): 덧붙이는 것이 없다. MDC `request_id`는 그 frame의 것이다.
The exception message ends with
`<operation code>::v<digest version>::<scope digest>`, for example
`claim requires reconciliation: CHARGE_CARD::v1::3f9a…` (64 hex characters). Then look at the
record in the store the service uses (`APP_IDEMPOTENCY_PROVIDER`). There is no tool for this; these
are the commands.
- Redis. The key, for example `prod:order:shared:idem:v1:d1:CHARGE_CARD:3f9a…`, is
예외 메시지는 `<operation code>::v<digest version>::<scope digest>`로 끝난다. 예:
`claim requires reconciliation: CHARGE_CARD::v1::3f9a…`(16진수 64자). 그다음 서비스가 쓰는 저장소
(`APP_IDEMPOTENCY_PROVIDER`)에서 기록을 본다. 이것을 해 주는 도구는 없다. 아래가 그 명령이다.
- Redis. 키는 예를 들어 `prod:order:shared:idem:v1:d1:CHARGE_CARD:3f9a…`이고, 모양은 다음과 같다.
<!-- runbook-redis: idempotency-record-key -->
```
@@ -77,11 +67,10 @@ status: active
PTTL <key>
```
`state` `ABANDONED` is final. `state` `EXECUTING` with a `leaseUntil` (lease end, epoch
milliseconds, server clock) earlier than the server's `TIME` (first value × 1000) is an attempt
past its lease that may still be running. `PTTL` is how long the record still lives, in
milliseconds.
- PostgreSQL, in the application's schema:
`state` `ABANDONED`는 바뀌지 않는다. `state` `EXECUTING`이면서 `leaseUntil`(lease 끝, epoch 밀리초, 서버
시계)이 서버의 `TIME`(첫 값 × 1000)보다 이르면, lease가 지났지만 아직 돌고 있을 수 있는 시도다. `PTTL`은
기록이 앞으로 살아 있을 시간(밀리초)이다.
- PostgreSQL. 애플리케이션의 스키마에서:
```sql
SELECT status, attempt, failure_disposition, last_transition_kind,
@@ -91,48 +80,44 @@ status: active
AND scope_hash = '<scope digest>';
```
`status` `ABANDONED` with `last_transition_kind` `FAIL_ABANDONED` means the action threw or
reported its effect unknown. `status` `EXECUTING` with `processing_lease_until` before
`clock_timestamp()` is an attempt past its lease that may still be running. (`ABANDONED` with
`EXPIRED_EXECUTION` is a lease that ran out under a version before 2026-11-04, which abandoned
such rows; it goes away when the row expires.) `expires_at` is when the reaper deletes the row.
`status` `ABANDONED`에 `last_transition_kind` `FAIL_ABANDONED`면 action이 예외를 던졌거나 효과를 모른다고
보고했다. `status` `EXECUTING`에 `processing_lease_until`이 `clock_timestamp()`보다 이르면, lease가 지났지만
아직 돌고 있을 수 있는 시도다. `expires_at`은 reaper가 행을 지우는 시각이다.
## Action
> 이력: `ABANDONED`에 `EXPIRED_EXECUTION`은 2026-11-04 전 버전에서 lease가 끝난 행이다. 그 버전은 그런 행을
> 버렸다. 행이 만료되면 사라진다.
- `IDEMPOTENCY_UNAVAILABLE`: restore the store; clients retry with the same key and backoff. When
the exception message says the claim's processing lease ran out before the action started, the
store is not the cause: find what held those requests between claim and start (thread dumps, GC
pauses, the store's latency in that window). Nothing to repair; the next same-key request runs.
- `IDEMPOTENCY_COMPLETION_UNKNOWN`: restore the store, then check the effects outside the
transaction for the failed requests (the ERROR log line names the code). A same-key resend replays
a result that was in fact recorded, gets `IDEMPOTENT_IN_FLIGHT` while the attempt's lease lasts,
and `IDEMPOTENCY_RECOVERY_REQUIRED` after it — handle that one as below.
- `IDEMPOTENCY_RECOVERY_REQUIRED`: do not ask the client to retry blindly. If the record is
`EXECUTING` past its lease, first wait for the attempt: look the record up again after the
longest time the action can take. It changes by itself when the attempt finishes — `COMPLETED`
(resends replay it, nothing to do), `ABANDONED`, or `FAILED_RETRYABLE` (the attempt proved it had
no effect, and the next request with the key runs it). A crashed attempt, or one whose request
already ended with `IDEMPOTENCY_COMPLETION_UNKNOWN`, never changes it; that record stays
`EXECUTING` until it expires. Business data checked while the attempt still runs can say "no
effect" a moment before the effect lands. Then confirm from business data (the order, the
payment, the downstream system) whether the effect exists. There is no way to complete the record
by hand — the stored response is the action's own result.
- The effect exists: tell the client it was applied. Leave the record; a resend with the key keeps
getting this 500 until the record expires (Redis `PTTL`, PostgreSQL `expires_at`).
- The effect does not exist: the client sends the request again under a new key. To let the same
key run again instead, delete the record — only while it is `ABANDONED`, because any other state
belongs to a request that may still be running or to a stored result. Do not delete an
`EXECUTING` record, even past its lease: if its attempt is still alive, its late result finds no
record (`ABSENT`) — the result is lost, the first request gets this 500 after its work took
effect, and the next request with the key runs the work a second time. Leave it to expire.
- Redis: check and delete in one step, as the account the service's registered scripts run as
(`APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE`, or the application account when it
is unset). Checking with `HMGET` and then sending `DEL` is two commands: a record that expires
between them and is claimed again by a new request is deleted while that request runs, and
the next request with the key runs the work a second time (re-review 2026-11-04 RR4-03-02).
The program below deletes the key only while its `state` is `ABANDONED`. The application
accounts are denied `EVAL` (`compose/redis/acl/README.md`), so load it and run it by the
digest `SCRIPT LOAD` prints, as the service runs its own scripts:
## 조치
- `IDEMPOTENCY_UNAVAILABLE`: 저장소를 되살린다. 클라이언트는 같은 키로 백오프하며 다시 시도한다. 예외 메시지가
action 시작 전에 claim의 처리 lease가 끝났다고 하면 저장소가 원인이 아니다. claim과 시작 사이에 그 요청들을
붙잡은 것을 찾는다(스레드 덤프, GC 멈춤, 그 시간대의 저장소 지연). 고칠 것은 없다. 같은 키의 다음 요청이
실행된다.
- `IDEMPOTENCY_COMPLETION_UNKNOWN`: 저장소를 되살린 뒤, 실패한 요청들의 트랜잭션 밖 효과를 확인한다(ERROR 로그
줄이 코드를 알려 준다). 같은 키로 다시 보내면, 실제로 기록된 결과는 replay로 받고, 시도의 lease가 남은 동안은
`IDEMPOTENT_IN_FLIGHT`를, 그 뒤에는 `IDEMPOTENCY_RECOVERY_REQUIRED`를 받는다. 마지막 것은 아래처럼 다룬다.
- `IDEMPOTENCY_RECOVERY_REQUIRED`: 클라이언트에게 그냥 다시 시도하라고 하지 않는다. 기록이 lease가 지난
`EXECUTING`이면 먼저 시도를 기다린다. action이 걸릴 수 있는 가장 긴 시간이 지난 뒤 기록을 다시 본다. 시도가
끝나면 기록은 저절로 바뀐다. `COMPLETED`(다시 보내면 replay된다, 할 일 없음), `ABANDONED`, `FAILED_RETRYABLE`
(시도가 효과가 없었음을 증명했고, 그 키의 다음 요청이 실행한다) 중 하나다. 죽은 시도, 또는 요청이 이미
`IDEMPOTENCY_COMPLETION_UNKNOWN`으로 끝난 시도는 기록을 바꾸지 않는다. 그 기록은 만료될 때까지 `EXECUTING`으로
남는다. 시도가 아직 도는 동안 확인한 업무 데이터는 효과가 들어가기 직전에 「효과 없음」으로 보일 수 있다.
그다음 업무 데이터(주문, 결제, 하위 시스템)로 효과가 있는지 확인한다. 기록을 손으로 완료할 방법은 없다. 저장된
응답은 action 자신의 결과다.
- 효과가 있다: 클라이언트에게 적용됐다고 알린다. 기록은 그대로 둔다. 그 키로 다시 보내면 기록이 만료될 때까지
(Redis `PTTL`, PostgreSQL `expires_at`) 이 500을 계속 받는다.
- 효과가 없다: 클라이언트가 새 키로 요청을 다시 보낸다. 같은 키로 다시 돌리게 하려면 기록을 지운다. 단
`ABANDONED`일 때만 지운다. 다른 상태는 아직 돌고 있을 수 있는 요청이나 저장된 결과의 것이다. `EXECUTING`
기록은 lease가 지났어도 지우지 않는다. 그 시도가 아직 살아 있으면 늦게 온 결과가 기록을 찾지 못하고
(`ABSENT`) 결과가 사라진다. 첫 요청은 일이 적용된 뒤에 이 500을 받고, 그 키의 다음 요청이 일을 한 번 더
한다. 만료되게 둔다.
- Redis: 확인과 삭제를 한 단계로, 서비스에 등록된 스크립트가 도는 계정으로 한다
(`APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE`, 비어 있으면 애플리케이션 계정). `HMGET`으로
확인하고 `DEL`을 보내면 명령이 둘이다. 그 사이에 만료되어 새 요청이 다시 claim한 기록은 그 요청이 도는
동안 지워지고, 그 키의 다음 요청이 일을 한 번 더 한다(2026-11-04 재확인 리뷰 RR4-03-02). 아래 프로그램은
`state`가 `ABANDONED`일 때만 키를 지운다. 애플리케이션 계정은 `EVAL`이 막혀 있으므로
(`compose/redis/acl/README.md`), 서비스가 자기 스크립트를 돌리는 것처럼 불러 올리고 `SCRIPT LOAD`가 찍은
digest로 돌린다.
<!-- runbook-redis: idempotency-delete-abandoned -->
```
@@ -140,11 +125,10 @@ status: active
EVALSHA <digest SCRIPT LOAD printed> 1 <key>
```
`1` deleted the record; the key is new. `0` deleted nothing: the record is no longer
`ABANDONED` (or is gone) — look again before doing anything else. `NOSCRIPT` means the node
that holds the key (a cluster) has not loaded the program: run `SCRIPT LOAD` on that node and
`EVALSHA` again; nothing was deleted. A record that is about to expire needs nothing; once it
is gone the key is new.
`1`이면 기록을 지웠고 키는 새것이다. `0`이면 아무것도 지우지 않았다. 기록이 더는 `ABANDONED`가 아니다
(또는 없다). 다른 일을 하기 전에 다시 본다. `NOSCRIPT`는 키를 가진 노드(클러스터)가 프로그램을 불러 올리지
않았다는 뜻이다. 그 노드에서 `SCRIPT LOAD`를 돌리고 `EVALSHA`를 다시 한다. 아무것도 지워지지 않았다. 곧
만료될 기록은 할 일이 없다. 사라지면 키는 새것이다.
- PostgreSQL:
```sql
@@ -154,12 +138,12 @@ status: active
AND status = 'ABANDONED';
```
Without either step the key is released when the record expires. A record whose attempt never
finished lives for the processing lease plus `APP_IDEMPOTENCY_TTL` from its claim; one the action
marked failed lives for `APP_IDEMPOTENCY_FAILURE_RETENTION` (not shorter than `APP_IDEMPOTENCY_TTL`)
from the failure (`docs/web/http-contract.md`, "서버가 기억하는 기간").
어느 단계도 하지 않으면 기록이 만료될 때 키가 풀린다. 시도가 끝나지 않은 기록은 claim부터 처리 lease에
`APP_IDEMPOTENCY_TTL`을 더한 만큼 산다. action이 실패로 표시한 기록은 실패부터
`APP_IDEMPOTENCY_FAILURE_RETENTION`(`APP_IDEMPOTENCY_TTL`보다 짧지 않다)만큼 산다
(`docs/web/http-contract.md` 「서버가 기억하는 기간」).
## Escalation
## 에스컬레이션
- P2 → P1 when the store stays unavailable for more than 10 minutes on a write path.
- Page the owner of the idempotency store (database or Redis on-call).
- 쓰기 경로에서 저장소가 10분 넘게 사용 불가로 남으면 P2 → P1.
- 멱등성 저장소 소유자(DB나 Redis 당번)를 부른다.
+1 -1
View File
@@ -5,7 +5,7 @@ error_codes: [INTERNAL_ERROR, INTERNAL_AUTH_MISCONFIGURATION, JVM_OOM]
severity: P1
owner: oncall
last_updated: 2026-05-22
status: stub
status: 초안
---
# Runbook: 5xx Internal error spike
+1 -1
View File
@@ -5,7 +5,7 @@ error_codes: [JOB_DEAD_LETTER]
severity: P1
owner: oncall
last_updated: 2026-06-13
status: stub
status: 초안
---
# Runbook: background job dead letter (`runbook://job/dead-letter`)
+1 -1
View File
@@ -5,7 +5,7 @@ error_codes: [JOB_EXECUTOR_REJECTED]
severity: P1
owner: oncall
last_updated: 2026-06-13
status: stub
status: 초안
---
# Runbook: async executor rejected (`runbook://job/executor-rejected`)
+1 -1
View File
@@ -5,7 +5,7 @@ error_codes: [JOB_TIMEOUT]
severity: P2
owner: oncall
last_updated: 2026-11-03
status: stub
status: 초안
---
# Runbook: background job timeout (`runbook://job/timeout`)
+32 -33
View File
@@ -5,34 +5,34 @@ error_codes: [LOCK_ACQUISITION_TIMEOUT]
severity: P2
owner: oncall
last_updated: 2026-11-07
status: stub
status: 초안
---
# Runbook: LOCK_ACQUISITION_TIMEOUT (`runbook://lock/acquisition-timeout`)
## Symptoms
## 증상
- HTTP 409 with `error.code=LOCK_ACQUISITION_TIMEOUT` and `Retry-After: 1`; GraphQL extension
`code=LOCK_ACQUISITION_TIMEOUT`, gRPC trailer `error-code: LOCK_ACQUISITION_TIMEOUT` (`ABORTED`), all
`retryable=true`.
- No server log line. A 4xx answer is not an incident, so no transport logs it, and the lock adapters
do not log a timeout either. The exception's message (lock key, wait time) reaches no log and no
client, so which lock timed out is recorded nowhere. Read the metric and the lock table below.
- Before 2026-11-07 the template answered this as 500 `INTERNAL_ERROR` with an "unhandled exception"
ERROR line (the exception was not an `ApiErrorCarrier`). A service on an older template sees that
instead.
- Distributed lock wait exceeded configured timeout; high contention on a resource
- HTTP 409, `error.code=LOCK_ACQUISITION_TIMEOUT`, `Retry-After: 1`. GraphQL은 extension
`code=LOCK_ACQUISITION_TIMEOUT`, gRPC는 trailer `error-code: LOCK_ACQUISITION_TIMEOUT`(`ABORTED`)이고, 모두
`retryable=true`다.
- 서버 로그 줄이 없다. 4xx 응답은 장애가 아니라서 어느 전송 계층도 로그를 남기지 않고, 락 어댑터도 시간 초과를
로그에 쓰지 않는다. 예외 메시지(락 키, 대기 시간)는 어느 로그에도 클라이언트에도 닿지 않으므로 어느 락이
시간을 넘겼는지는 어디에도 기록되지 않는다. 아래의 메트릭과 락 테이블을 읽는다.
- 분산 락 대기가 설정된 시간 상한을 넘었다. 한 자원에 경합이 심하다.
## Diagnosis
> 이력: 2026-11-07 전의 템플릿은 이 경우를 500 `INTERNAL_ERROR`와 "unhandled exception" ERROR 줄로
> 응답했다(예외가 `ApiErrorCarrier`가 아니었다). 옛 템플릿을 쓰는 서비스에서는 그것이 보인다.
1. Contention rate. With `APP_MULTI_INSTANCE_ENABLED=true` the JDBC lock is metered: compare
`lock.acquisition{outcome="timeout"}` with `lock.acquisition{outcome="acquired"}`. The counter has
no lock name and no wait time — a key is never a metric tag (`docs/registries/metrics.yaml`). The
in-process lock (`APP_MULTI_INSTANCE_ENABLED=false`, the default) has no metric and keeps nothing in
the database; the steps below apply only to the JDBC lock.
2. Who holds locks now. `INT_LOCK` has one row per held lock. `CLIENT_ID` is the holding instance's
lock repository id, and the times are UTC. A row whose `EXPIRED_AFTER` has passed is a dead lease:
the next acquisition of that key takes it over. The oldest live rows are the long holders.
## 진단
1. 경합 비율. `APP_MULTI_INSTANCE_ENABLED=true`이면 JDBC 락에 메트릭이 붙는다.
`lock.acquisition{outcome="timeout"}`을 `lock.acquisition{outcome="acquired"}`와 비교한다. 이 counter에는
락 이름도 대기 시간도 없다. 키는 메트릭 태그가 되지 않는다(`docs/registries/metrics.yaml`). 프로세스 안 락
(`APP_MULTI_INSTANCE_ENABLED=false`, 기본값)은 메트릭이 없고 DB에 아무것도 남기지 않는다. 아래 단계는 JDBC
락에만 해당한다.
2. 지금 누가 락을 쥐고 있나. `INT_LOCK`에는 쥔 락마다 한 행이 있다. `CLIENT_ID`는 쥔 인스턴스의 락 저장소 id이고,
시각은 UTC다. `EXPIRED_AFTER`가 지난 행은 죽은 lease다. 그 키를 다음에 잡는 쪽이 넘겨받는다. 가장 오래된
살아 있는 행이 오래 쥔 쪽이다.
<!-- runbook-sql: lock-holders -->
```sql
@@ -41,10 +41,9 @@ FROM int_lock
ORDER BY created_date;
```
3. The holder of one lock whose key you know from the code (for example `orders/42`). `LOCK_KEY` is
not the key: Spring Integration stores the key's name-based UUID (`UUID.nameUUIDFromBytes` of the
key's UTF-8 bytes), so a key cannot be read back from the table. This computes the UUID from the
key and finds its row:
3. 코드에서 키를 아는 락 하나(예: `orders/42`)를 누가 쥐고 있나. `LOCK_KEY`는 키 자체가 아니다. Spring
Integration은 키의 이름 기반 UUID(키의 UTF-8 바이트에 `UUID.nameUUIDFromBytes`)를 저장하므로 테이블에서 키를
거꾸로 읽을 수 없다. 아래 쿼리는 키에서 UUID를 계산해 그 행을 찾는다.
<!-- runbook-sql: lock-holder-of-key -->
```sql
@@ -56,18 +55,18 @@ WHERE lock_key = (
FROM md5('<lock_key>') AS h);
```
`:adapter:outbound:persistence-jpa:postgresqlDistributedLockIntegrationTest` runs both blocks, read
from this file, against real PostgreSQL while locks are held.
`:adapter:outbound:persistence-jpa:postgresqlDistributedLockIntegrationTest`가 두 블록을 이 파일에서 읽어,
락을 쥔 상태의 실제 PostgreSQL에 돌린다.
## Action
## 조치
- Client should retry with backoff (retryable=true)
- Optimize critical section holding time if lock contention is systemic
- 클라이언트는 백오프하며 다시 시도한다(retryable=true).
- 락 경합이 구조적이면 임계 구역을 쥐는 시간을 줄인다.
## Escalation
## 에스컬레이션
- Escalate if lock holder appears stuck (potential deadlock in distributed lock)
- 락 보유자가 멈춘 것으로 보이면 넘긴다(분산 락의 교착 가능성).
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+16 -14
View File
@@ -4,31 +4,33 @@ category: AUTHZ
error_codes: [ACTUATOR_FORBIDDEN]
severity: P2
owner: oncall
last_updated: 2026-06-15
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: ACTUATOR_FORBIDDEN (`runbook://management/actuator-forbidden`)
## Symptoms
## 증상
- HTTP 403 with `error.code=ACTUATOR_FORBIDDEN`
- Attempt to access restricted actuator endpoint (env/configprops/heapdump/shutdown)
- HTTP 403, `error.code=ACTUATOR_FORBIDDEN`.
- 제한된 actuator 엔드포인트(env·configprops·heapdump·shutdown)에 접근하려 했다.
## Diagnosis
## 진단
- Identify which actuator endpoint was accessed
- Check caller identity (internal tooling vs external)
- 어느 actuator 엔드포인트에 접근했는지 찾는다.
- 호출자가 누구인지(내부 도구인지 외부인지) 확인한다.
## Action
## 조치
- Verify management port is not exposed externally
- For heapdump/threaddump: follow break-glass runbook procedure
- management 포트가 밖으로 노출되지 않았는지 확인한다.
- heapdump·threaddump는 노출 목록에서 빠져 있다(`config/observability.yml`의
`management.endpoints.web.exposure.exclude`). 꼭 필요하면 운영 조직의 break-glass 절차를 따른다. 이 저장소에는
그 절차 문서가 없다.
## Escalation
## 에스컬레이션
- P1 if forbidden actuator access appears to be external attack
- 금지된 actuator 접근이 외부 공격으로 보이면 P1.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+94 -113
View File
@@ -5,27 +5,25 @@ error_codes: [MIGRATION_FAILED]
severity: P1
owner: oncall
last_updated: 2026-11-07
status: active
status: 운영
---
# Runbook: MIGRATION_FAILED (`runbook://migration/failed`)
## Symptoms
## 증상
- Container exits with code 70 (migration failure exit)
- Structured log with `error.code=MIGRATION_FAILED`, `startup.phase=migration`
- App refuses to start (fail-fast)
- JPA capability adapter refuses activation because its
`capability_schema_registry.lifecycle_state` is not `ACTIVE`
- 컨테이너가 코드 70으로 끝난다(마이그레이션 실패 종료).
- 구조화 로그 `error.code=MIGRATION_FAILED`, `startup.phase=migration`.
- 앱이 뜨기를 거부한다(fail-fast).
- JPA capability 어댑터가 활성화를 거부한다. 그 `capability_schema_registry.lifecycle_state`가 `ACTIVE`가 아니다.
## Diagnosis
## 진단
1. Stop rollout and keep the failed revision out of readiness. Do not route traffic to a partially
migrated instance.
2. Identify the exact stream from `src/adapter/outbound/persistence-jpa/release/readiness-cards.yaml`. Each stream has an
independent `location` and `history-table`; do not infer ownership from a broad
`classpath:db/migration` scan.
3. From a privileged migration session, capture the stream state before changing anything:
1. rollout을 멈추고, 실패한 revision을 readiness 밖에 둔다. 마이그레이션이 반쯤 된 인스턴스로 트래픽을 보내지
않는다.
2. `src/adapter/outbound/persistence-jpa/release/readiness-cards.yaml`에서 정확한 stream을 찾는다. stream마다
`location`과 `history-table`이 따로 있다. 넓은 `classpath:db/migration` 스캔으로 소유를 짐작하지 않는다.
3. 권한 있는 마이그레이션 세션에서, 무엇이든 바꾸기 전에 stream 상태를 남긴다.
```sql
select installed_rank, version, description, success
@@ -37,15 +35,14 @@ status: active
where capability_id = '<card-id>';
```
4. Check whether any owned relation was created without a successful history entry. Compare only
against the owned tables in the reviewed migration; do not drop unrelated relations.
5. Classify the failure:
- lock/statement timeout: remove the blocker or reduce rollout concurrency, then rerun. A
migration that locks a table already in use gives up after its own `SET LOCAL lock_timeout`
(5 s; SQLState `55P03` `lock_not_available`) and rolls back whole, so the history ends one
version below it. The blocker is a transaction that touched the table and is still open —
often an idle-in-transaction session. Find it by the lock it holds on that table (`<table>`
is the table the failing statement locks; for a `REFERENCES`, also the table it references):
4. 성공한 이력 행 없이 만들어진 소유 relation이 있는지 확인한다. 검토한 마이그레이션의 소유 테이블과만
비교한다. 상관없는 relation은 지우지 않는다.
5. 실패를 분류한다(Classify the failure).
- 락·문장 시간 초과: 막는 쪽을 없애거나 rollout 동시성을 줄이고 다시 돌린다. 이미 쓰는 테이블을 잠그는
마이그레이션은 자기 `SET LOCAL lock_timeout`(5 s, SQLState `55P03` `lock_not_available`)이 지나면 포기하고
통째로 롤백한다. 그래서 이력은 그 버전 바로 아래에서 끝난다. 막는 쪽은 그 테이블을 건드린 뒤 아직 열려 있는
트랜잭션이다. 흔히 idle-in-transaction 세션이다. 그 테이블에 쥔 락으로 찾는다(`<table>`은 실패한 문장이
잠그는 테이블이다. `REFERENCES`면 참조하는 테이블도 본다).
```sql
SELECT DISTINCT a.pid, a.state, a.xact_start, a.query
@@ -54,74 +51,65 @@ status: active
ORDER BY a.xact_start;
```
`query` is only that session's last statement, not the one that touched the table, so do not
look for the table name in it. Listing every long transaction instead names unrelated ones
(reports, batches) beside the blocker. End the blocker, then rerun
(`docs/jpa/migration-guide.md` "Bound the lock wait");
- SQL/data precondition: create a new forward migration that makes the precondition explicit;
a duplicate outbox order key stopping V21 (`ux_outbox_event_aggregate_order`) is the known
case — clean it up with `outbox-dead-letter.md` §8 and rerun, the migration stays as it is;
- checksum mismatch: compare the deployed artifact with the already applied script before
considering repair;
- a concurrent index migration failed (`CREATE [UNIQUE] INDEX CONCURRENTLY`, `DROP INDEX
CONCURRENTLY` or `REINDEX … CONCURRENTLY` that Flyway ran outside a transaction): a duplicate
value for a unique index, a deadlock, `statement_timeout` or a statement cancelled while it
waited for an open transaction. Outside a transaction nothing rolled back: the migration left
an invalid index and a history row with `success = false` for that version, and every later
deploy fails validation ("Detected failed migration to version …") until the row is gone.
Dropping the index alone does not clear it. Follow "Recover a failed concurrent index
migration" below;
- connection/TLS failure: fix transport or credentials without changing Flyway history.
`query`는 그 세션의 마지막 문장일 뿐 테이블을 건드린 문장이 아니므로, 거기서 테이블 이름을 찾지 않는다.
대신 긴 트랜잭션을 모두 나열하면 막는 쪽 옆에 상관없는 것(리포트, 배치)도 나온다. 막는 쪽을 끝낸 뒤 다시
돌린다(`docs/jpa/migration-guide.md` "Bound the lock wait").
- SQL·데이터 전제 조건: 전제 조건을 드러내는 새 forward 마이그레이션을 만든다. 중복된 outbox 순서 키가
V21(`ux_outbox_event_aggregate_order`)을 막는 것이 알려진 경우다. `outbox-dead-letter.md` §8로 정리하고 다시
돌린다. 마이그레이션은 그대로 둔다.
- checksum 불일치: repair를 생각하기 전에 배포한 산출물과 이미 적용된 스크립트를 비교한다.
- 동시 인덱스 마이그레이션 실패(Flyway가 트랜잭션 밖에서 돌린 `CREATE [UNIQUE] INDEX CONCURRENTLY`,
`DROP INDEX CONCURRENTLY`, `REINDEX … CONCURRENTLY`): unique 인덱스의 중복 값, 교착, `statement_timeout`,
또는 열린 트랜잭션을 기다리다 취소된 문장이다. 트랜잭션 밖이라 아무것도 롤백되지 않았다. 마이그레이션은
무효 인덱스와, 그 버전의 `success = false` 이력 행을 남겼다. 그 행이 사라질 때까지 뒤의 배포는 모두 검증에서
실패한다("Detected failed migration to version …"). 인덱스만 지워서는 풀리지 않는다. 아래 「실패한 동시
인덱스 마이그레이션 복구」를 따른다.
- 연결·TLS 실패: Flyway 이력을 바꾸지 않고 전송이나 자격 증명을 고친다.
## Action
## 조치
1. Prefer forward recovery. Fix the environmental blocker or add a new immutable migration, then
rerun the same owned stream with its exact history table.
2. For an optional stream that never installed successfully, keep the capability marker absent and
the runtime adapter disabled until migration succeeds.
3. After a successful migration, validate:
- the history contains only successful expected versions;
- `core_epoch` and `feature_revision` match the readiness registry;
- the marker is `INSTALLED_INACTIVE`;
- owned objects and constraints exist.
4. Change the marker to `ACTIVE` only after the compatible application revision is deployed and its
readiness check succeeds. Disabling or rolling back application code changes the marker to
`INSTALLED_INACTIVE`; it does not drop history or owned data.
5. Re-run the readiness lanes before promoting (every card's scenarios, no skips):
1. forward 복구를 먼저 쓴다. 환경 쪽 막힘을 고치거나 바뀌지 않는 새 마이그레이션을 더한 뒤, 같은 소유 stream을
그 정확한 이력 테이블로 다시 돌린다.
2. 한 번도 성공적으로 설치되지 않은 선택 stream은 마이그레이션이 성공할 때까지 capability 표시를 두지 않고 런타임
어댑터를 꺼 둔다.
3. 마이그레이션이 성공하면 확인한다.
- 이력에 기대한 버전의 성공 행만 있다.
- `core_epoch`와 `feature_revision`이 readiness registry와 같다.
- 표시가 `INSTALLED_INACTIVE`다.
- 소유 객체와 제약이 있다.
4. 맞는 애플리케이션 revision이 배포되고 그 readiness 검사가 성공한 뒤에만 표시를 `ACTIVE`로 바꾼다.
애플리케이션 코드를 끄거나 되돌리면 표시가 `INSTALLED_INACTIVE`로 바뀐다. 이력이나 소유 데이터는 지우지 않는다.
5. 승격 전에 readiness lane을 다시 돌린다(모든 card의 시나리오, 건너뜀 없음).
```bash
cd src
./gradlew :adapter:outbound:persistence-jpa:integrationTestLaneCheck --console=plain
```
6. Record the failed revision, stream/history table, root cause, recovery migration, elapsed time
and verification artifact in the incident.
6. 실패한 revision, stream·이력 테이블, 근본 원인, 복구 마이그레이션, 걸린 시간, 검증 산출물을 장애 기록에 남긴다.
Do not:
하지 않을 것:
- edit an already applied migration;
- delete or rewrite Flyway history to make validation green. The one exception is the failed row
of a failed concurrent index migration, deleted as "Recover a failed concurrent index migration"
below says — that row and nothing else;
- run `flyway repair` before checksum provenance is proven and reviewed;
- use `clean`, destructive rollback, or schema-wide restore as the first response;
- mark a capability `ACTIVE` before its migration and adapter readiness succeed.
- 이미 적용된 마이그레이션을 고친다.
- 검증을 통과시키려고 Flyway 이력을 지우거나 다시 쓴다. 예외는 하나다. 실패한 동시 인덱스 마이그레이션의 실패
행을 아래 「실패한 동시 인덱스 마이그레이션 복구」대로 지운다. 그 행 말고는 아무것도 지우지 않는다.
- checksum의 출처가 증명되고 검토되기 전에 `flyway repair`를 돌린다.
- 첫 대응으로 `clean`, 파괴적 롤백, 스키마 전체 복원을 쓴다.
- 마이그레이션과 어댑터 readiness가 성공하기 전에 capability를 `ACTIVE`로 표시한다.
If commit outcome was indeterminate during the failure, reconcile by the application
`OperationId`/idempotency reference before retrying business work. Never blind-retry a commit whose
result is unknown.
장애 중에 커밋 결과를 알 수 없었으면, 업무 작업을 다시 하기 전에 애플리케이션의 `OperationId`·멱등성 참조로
맞춘다. 결과를 모르는 커밋을 그냥 다시 시도하지 않는다.
## Recover a failed concurrent index migration
## 실패한 동시 인덱스 마이그레이션 복구 (Recover a failed concurrent index migration)
The one case where this runbook changes Flyway history (owner decision, 2026-11-06). It applies to a
migration that holds a single concurrent index statement which Flyway ran outside a transaction —
with the `executeInTransaction=false` the guide asks for, or on its own for `CREATE`/`DROP INDEX
CONCURRENTLY` (`docs/jpa/migration-guide.md` "Concurrent index builds") — and whose row for this
version in the stream's history table says `success = false`. A migration that mixed other
statements in has already committed them: reconstruct that state with the database owner instead.
이 runbook이 Flyway 이력을 바꾸는 유일한 경우다(소유자 결정, 2026-11-06). Flyway가 트랜잭션 밖에서 돌린 동시
인덱스 문장 하나만 담은 마이그레이션에 쓴다. 가이드가 요구하는 `executeInTransaction=false`로 돌렸거나,
`CREATE`/`DROP INDEX CONCURRENTLY`라서 Flyway가 알아서 그렇게 돌린 경우다(`docs/jpa/migration-guide.md`
"Concurrent index builds"). 그리고 stream 이력 테이블의 이 버전 행이 `success = false`여야 한다. 다른 문장을 섞은
마이그레이션은 그 문장을 이미 커밋했다. 그 상태는 DB 소유자와 함께 다시 맞춘다.
1. Confirm no build is still running. An index that is still being built looks invalid in the
catalog too, and dropping it races the build. This query returns no rows when none is:
1. 아직 도는 빌드가 없는지 확인한다. 아직 만드는 중인 인덱스도 카탈로그에서는 무효로 보이고, 그것을 지우면
빌드와 경합한다. 도는 빌드가 없으면 이 쿼리는 행을 돌려주지 않는다.
<!-- runbook-sql: failed-concurrent-index-builds -->
```sql
@@ -130,29 +118,26 @@ FROM pg_stat_progress_create_index
WHERE datname = current_database();
```
2. Remove the cause. For a unique index, clean up the duplicate rows with the data owner (a forward
fix, never by editing the migration). For a deadlock, a timeout or a cancelled statement, end or
wait out the transaction that held it: a build or a rebuild waits for every transaction older
than itself, a drop for every transaction that holds a lock on its table. Do this before step 3,
whose `DROP INDEX CONCURRENTLY` waits for the same transactions.
3. Drop the invalid index a failed build or rebuild left: the index a `CREATE [UNIQUE] INDEX
CONCURRENTLY` names, or the copy a `REINDEX … CONCURRENTLY` made, named after the index with
`_ccnew` (or `_ccold`) on the end (`docs/jpa/runbooks.md` "An invalid index exists" lists them).
Run it on its own, not inside `BEGIN`: `CONCURRENTLY` refuses a transaction block.
**Skip this step when the failed statement is `DROP INDEX CONCURRENTLY`.** The invalid index it
left is the index the migration drops, and the deploy in step 5 runs the same statement, which
drops it. Dropped by hand first, that statement fails with `42704` ("index … does not exist")
and leaves a new failed row.
2. 원인을 없앤다. unique 인덱스면 데이터 소유자와 중복 행을 정리한다(forward 수정이다. 마이그레이션을 고치지
않는다). 교착, 시간 초과, 취소된 문장이면 그것을 쥔 트랜잭션을 끝내거나 끝나기를 기다린다. 빌드와 재빌드는
자기보다 오래된 트랜잭션을 모두 기다리고, 삭제는 그 테이블에 락을 쥔 트랜잭션을 모두 기다린다. 3단계 전에
한다. 3단계의 `DROP INDEX CONCURRENTLY`도 같은 트랜잭션을 기다린다.
3. 실패한 빌드나 재빌드가 남긴 무효 인덱스를 지운다. `CREATE [UNIQUE] INDEX CONCURRENTLY`가 이름 붙인 인덱스,
또는 `REINDEX … CONCURRENTLY`가 만든 사본이다. 사본은 인덱스 이름 끝에 `_ccnew`(또는 `_ccold`)가 붙는다
(`docs/jpa/runbooks.md` "An invalid index exists"가 그 목록을 준다). `BEGIN` 안이 아니라 따로 돌린다.
`CONCURRENTLY`는 트랜잭션 블록을 거부한다.
**실패한 문장이 `DROP INDEX CONCURRENTLY`면 이 단계를 건너뛴다.** 그것이 남긴 무효 인덱스는 마이그레이션이
지우는 인덱스이고, 5단계의 배포가 같은 문장을 돌려 그것을 지운다. 먼저 손으로 지우면 그 문장이 `42704`
("index … does not exist")로 실패하고 새 실패 행을 남긴다.
<!-- runbook-sql: failed-concurrent-index-drop -->
```sql
DROP INDEX CONCURRENTLY IF EXISTS <invalid_index>;
```
4. Delete that version's failed row from the stream's history table, and nothing else. `<version>`
is the `version` column of the failed row as the Diagnosis query shows it (`22.1` for
`V22_1__…`). It must delete exactly one row; if it deletes none, this is not the failure this
section is for, so classify it again.
4. stream 이력 테이블에서 그 버전의 실패 행을 지운다. 그 밖에는 아무것도 지우지 않는다. `<version>`은 진단
쿼리가 보여 주는 실패 행의 `version` 칸이다(`V22_1__…`이면 `22.1`). 정확히 한 행을 지워야 한다. 한 행도 지우지
않으면 이 절이 다루는 실패가 아니므로 다시 분류한다.
<!-- runbook-sql: failed-concurrent-index-history-row -->
```sql
@@ -160,28 +145,24 @@ DELETE FROM <owned_history_table>
WHERE version = '<version>' AND NOT success;
```
5. Deploy again. Flyway runs the same migration from the start: it builds the index, rebuilds it,
or drops the index the failed drop left.
5. 다시 배포한다. Flyway가 같은 마이그레이션을 처음부터 돌린다. 인덱스를 만들거나, 다시 만들거나, 실패한
삭제가 남긴 인덱스를 지운다.
The failed row is the record of a version that never applied, so deleting it leaves the order and
the checksum of every applied version as they were. Do not use `flyway repair` for this: it also
rewrites the checksums and descriptions of the remaining rows to match the scripts on disk, which
removes the evidence a checksum mismatch carries. `:adapter:outbound:persistence-jpa:postgresqlConcurrentIndexMigrationIntegrationTest`
runs the three SQL blocks above, read from this file, against real PostgreSQL for each statement
this section covers: a unique build that fails on a duplicate, and a rebuild and a drop cancelled
while they wait for an open transaction. Steps 1–4 run in order, step 3 for the build and the
rebuild only, and the next deploy applies the version with no invalid index left and the earlier
version's checksum unchanged.
실패 행은 한 번도 적용되지 않은 버전의 기록이다. 그래서 지워도 적용된 모든 버전의 순서와 checksum은 그대로다.
이 일에 `flyway repair`를 쓰지 않는다. repair는 남은 행의 checksum과 description도 디스크의 스크립트에 맞춰 다시
쓰므로, checksum 불일치가 담은 증거를 지운다.
`:adapter:outbound:persistence-jpa:postgresqlConcurrentIndexMigrationIntegrationTest`가 위의 SQL 블록 셋을 이
파일에서 읽어, 이 절이 다루는 문장마다 실제 PostgreSQL에 돌린다. 중복으로 실패하는 unique 빌드, 열린 트랜잭션을
기다리다 취소된 재빌드와 삭제다. 1~4단계를 차례로 돌리고(3단계는 빌드와 재빌드만), 다음 배포가 무효 인덱스 없이
그 버전을 적용하며 앞 버전의 checksum은 바뀌지 않는다.
## Escalation
## 에스컬레이션
- P1 immediate: the required application revision cannot become ready.
- Escalate to the database owner before Flyway history repair, destructive DDL, point-in-time
recovery, or primary failover.
- R3 restore/PITR and failover rehearsal requires a target-like backup topology; local
Testcontainers evidence is not a substitute.
- P1 즉시: 필요한 애플리케이션 revision이 ready가 되지 못한다.
- Flyway 이력 repair, 파괴적 DDL, 시점 복구(PITR), primary failover 전에 DB 소유자에게 넘긴다.
- R3 복원·PITR과 failover 예행연습에는 대상과 비슷한 백업 구성이 필요하다. 로컬 Testcontainers 증거로 대신하지
않는다.
---
This runbook is forward-only. The reviewed migration artifact and the readiness lanes' JUnit
results from CI are the audit sources.
이 runbook은 forward 방향만 다룬다. 감사 근거는 검토한 마이그레이션 산출물과 CI의 readiness lane JUnit 결과다.
+1 -1
View File
@@ -5,7 +5,7 @@ error_codes: [OUTBOX_DEAD_LETTER]
severity: P1
owner: oncall
last_updated: 2026-11-04
status: stub
status: 초안
---
# Runbook: outbox dead letter (`runbook://outbox/dead-letter`)
+1 -1
View File
@@ -5,7 +5,7 @@ error_codes: [OUTBOX_PUBLISH_FAILED]
severity: P2
owner: oncall
last_updated: 2026-11-04
status: stub
status: 초안
---
# Runbook: outbox publish 일시 실패 (`runbook://outbox/publish-failed`)
+1 -1
View File
@@ -5,7 +5,7 @@ error_codes: [RATE_LIMIT_EXCEEDED, IDEMPOTENT_IN_FLIGHT]
severity: P3
owner: oncall
last_updated: 2026-05-22
status: stub
status: 초안
---
# Runbook: Rate limit 초과 spike
+1 -1
View File
@@ -5,7 +5,7 @@ error_codes: []
severity: P1
owner: oncall
last_updated: 2026-07-29
status: active
status: 운영
---
# Runbook: Redis capability incident (`runbook://redis/capability-incident`)
+18 -16
View File
@@ -4,33 +4,35 @@ category: INTERNAL
error_codes: [JVM_OOM]
severity: P1
owner: oncall
last_updated: 2026-06-15
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: JVM_OOM (`runbook://runtime/jvm-oom`)
## Symptoms
## 증상
- Container exits with code 137 (ExitOnOutOfMemoryError triggered)
- Structured log entry with `error.code=JVM_OOM` before exit
- 컨테이너가 코드 137로 끝난다(`-XX:+ExitOnOutOfMemoryError`가 동작함).
- 앱은 끝나기 전에 `error.code=JVM_OOM` 로그를 남기지 않는다. 이 코드를 로그에 쓰는 코드가 없다. JVM이
stderr에 `OutOfMemoryError`를 남기고 바로 끝난다.
## Diagnosis
## 진단
- Check heap dump if `-XX:HeapDumpOnOutOfMemoryError` is configured
- Review memory usage trends before crash
- Check for memory leaks: large cache growth, unbounded lists, session accumulation
- 힙 덤프를 본다. 이미지의 `JAVA_TOOL_OPTIONS`가 `-XX:+HeapDumpOnOutOfMemoryError`와
`-XX:HeapDumpPath=/var/tmp/heap`을 켠다(`src/Dockerfile`).
- 죽기 전 메모리 사용 추세를 본다.
- 메모리 누수를 찾는다: 커지기만 하는 캐시, 상한 없는 목록, 쌓이는 세션.
## Action
## 조치
- Restart container immediately (k8s will auto-restart with liveness probe)
- If recurring: increase heap `-Xmx` or fix memory leak
- 컨테이너를 바로 다시 띄운다(k8s는 liveness probe로 알아서 다시 띄운다).
- 반복되면 힙(`-Xmx`, 이미지는 `-XX:MaxRAMPercentage`)을 늘리거나 누수를 고친다.
## Escalation
## 에스컬레이션
- P1: immediate if multiple pods crashing simultaneously
- Page SRE / infra team for heap analysis
- P1: 여러 pod가 동시에 죽으면 즉시.
- 힙 분석은 SRE·인프라 팀을 부른다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+14 -14
View File
@@ -5,31 +5,31 @@ error_codes: [PROFILE_MISMATCH]
severity: P1
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: PROFILE_MISMATCH (`runbook://startup/profile-mismatch`)
## Symptoms
## 증상
- Container exits with code 71 (profile mismatch exit)
- Structured log with `error.code=PROFILE_MISMATCH`, `startup.phase=profile-check`
- Production profile active with local-only settings enabled
- 컨테이너가 코드 71로 끝난다(프로파일 불일치 종료).
- 구조화 로그 `error.code=PROFILE_MISMATCH`, `startup.phase=profile-check`.
- 운영 프로파일이 켜져 있는데 로컬 전용 설정이 켜져 있다.
## Diagnosis
## 진단
- Check active Spring profiles (`spring.profiles.active`)
- Identify which local-only setting is incorrectly enabled in prod profile
- 켜진 Spring 프로파일(`spring.profiles.active`)을 확인한다.
- 운영 프로파일에서 잘못 켜진 로컬 전용 설정을 찾는다.
## Action
## 조치
- Remove local-only setting from production deployment config
- Ensure prod profile does not inherit local/dev profile settings
- 운영 배포 설정에서 로컬 전용 설정을 지운다.
- 운영 프로파일이 local·dev 프로파일 설정을 물려받지 않게 한다.
## Escalation
## 에스컬레이션
- P1: security risk if local settings expose debug endpoints in production
- P1: 로컬 설정이 운영에서 디버그 엔드포인트를 열면 보안 위험이다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
@@ -4,31 +4,31 @@ category: INTERNAL
error_codes: [REQUIRED_ADAPTER_DISABLED]
severity: P1
owner: oncall
last_updated: 2026-06-15
status: stub
last_updated: 2026-11-07
status: 초안
---
# Runbook: REQUIRED_ADAPTER_DISABLED (`runbook://startup/required-adapter-disabled`)
## Symptoms
## 증상
- Container exits with code 72 (required adapter disabled exit)
- Structured log with `error.code=REQUIRED_ADAPTER_DISABLED`, `startup.phase=adapter-check`
- 컨테이너가 코드 72로 끝난다(필수 어댑터 비활성화 종료).
- 구조화 로그 `error.code=REQUIRED_ADAPTER_DISABLED`, `startup.phase=adapter-enablement`.
## Diagnosis
## 진단
- Identify which adapter is disabled but required
- Check adapter enable flags in environment config
- 필수인데 꺼진 어댑터를 찾는다.
- 환경 설정의 어댑터 스위치를 확인한다.
## Action
## 조치
- Enable required adapter in deployment configuration
- If adapter is intentionally disabled, update the required/optional designation
- 배포 설정에서 필수 어댑터를 켠다.
- 일부러 끈 어댑터면 필수·선택 지정을 고친다.
## Escalation
## 에스컬레이션
- P1: app cannot start; coordinate with deployment team
- P1: 앱이 뜨지 못한다. 배포 팀과 맞춘다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+13 -13
View File
@@ -5,30 +5,30 @@ error_codes: [STARTUP_VALIDATION_FAILED]
severity: P1
owner: oncall
last_updated: 2026-06-15
status: stub
status: 초안
---
# Runbook: STARTUP_VALIDATION_FAILED (`runbook://startup/validation-failed`)
## Symptoms
## 증상
- Container exits with code 78 (env validation failure exit)
- Structured log with `error.code=STARTUP_VALIDATION_FAILED`, `startup.phase=env-validation`
- 컨테이너가 코드 78로 끝난다(환경 변수 검증 실패 종료).
- 구조화 로그 `error.code=STARTUP_VALIDATION_FAILED`, `startup.phase=env-validation`.
## Diagnosis
## 진단
- Check which required env variable is missing or malformed
- Review container environment and secrets injection
- 빠졌거나 형식이 틀린 필수 환경 변수를 찾는다.
- 컨테이너 환경과 secret 주입을 확인한다.
## Action
## 조치
- Supply missing environment variables to deployment
- Verify secrets are correctly mounted / injected
- 빠진 환경 변수를 배포에 넣는다.
- secret이 제대로 마운트·주입됐는지 확인한다.
## Escalation
## 에스컬레이션
- P1: app cannot start; coordinate with deployment/secrets team
- P1: 앱이 뜨지 못한다. 배포·secret 담당 팀과 맞춘다.
---
> **Stub**: Phase D2 — author body after domain adoption. (feature-operational-runbook-contract D9)
> **초안**: 서비스가 도메인을 채운 뒤 본문을 쓴다.
+22 -23
View File
@@ -5,40 +5,39 @@ error_codes: [<ERROR_CODE_1>, <ERROR_CODE_2>]
severity: <P1|P2|P3>
owner: oncall
last_updated: <YYYY-MM-DD>
status: <stub|active>
status: <초안|운영>
---
# Runbook: <TITLE> (`runbook://<area>/<scenario>`)
## Symptoms
## 증상
- What observable signals trigger this runbook?
- Alert name, metric thresholds, log patterns
- 이 runbook을 펴게 하는 관측 신호는 무엇인가?
- alert 이름, 메트릭 임계값, 로그 패턴
## Diagnosis
## 진단
- Step-by-step diagnostic commands and queries
- Log queries (Loki/CloudWatch)
- Metric panels to check
- Trace investigation approach
- 차례로 따라 하는 진단 명령과 쿼리
- 로그 쿼리(Loki·CloudWatch)
- 볼 메트릭 패널
- trace 조사 방법
## Action
## 조치
- Immediate mitigation steps
- Configuration changes
- Manual intervention procedures
- 바로 하는 완화
- 설정 변경
- 손으로 하는 개입 절차
## Escalation
## 에스컬레이션
- Conditions for severity upgrade (e.g., P2 → P1)
- Who to page and when
- Fallback procedures if on-call cannot resolve
- 심각도를 올리는 조건(예: P2 → P1)
- 언제 누구를 부르나
- 당번이 풀지 못할 때의 대안
---
> **Note**: This is the canonical runbook template.
> Copy this file, rename it to match the `runbook://area/scenario` pattern (→ `area-scenario.md`),
> fill in the frontmatter fields, replace section bodies with operational content,
> then set `status: active`. `LEGACY_STUB_DEBT` in `RunbookCoverageContractTest` is temporary
> containment for existing debt only; do not add a new stub there. Complete the runbook or adopt
> the future owned, expiring debt ledger.
> **안내**: 이 파일이 runbook의 기준 양식이다.
> 이 파일을 복사하고, `runbook://area/scenario` 꼴에 맞춰 이름을 바꾸고(→ `area-scenario.md`), 머리말 칸을 채우고,
> 절 본문을 운영 내용으로 바꾼 뒤 `status: 운영`으로 둔다. 본문을 아직 쓰지 못한 runbook은 `status: 초안`이다.
> `RunbookCoverageContractTest`의 `LEGACY_STUB_DEBT`는 이미 있는 초안만 잠시 담아 두는 목록이다. 새 초안을 거기에
> 더하지 않는다. runbook을 끝내거나, 앞으로 생길 소유자·기한 있는 부채 장부를 쓴다.
+19 -24
View File
@@ -1,32 +1,27 @@
# Fileserver vs Object Storage
# 파일 서버와 Object Storage
These capabilities overlap at the byte-storage level but own different serving boundaries. They are
not interchangeable providers for one port.
두 capability는 바이트 저장 수준에서 겹치지만 가진 서빙 경계가 다르다. port 하나의 바꿔 끼울 수 있는 provider가 아니다.
| Question | Fileserver HTTP platform | Object Storage |
| 질문 | 파일 서버 HTTP 플랫폼 | Object Storage |
|---|---|---|
| Who serves bytes to the client? | This application, through Fileserver HTTP routes | This application, streaming through the semantic transfer port (no direct/presigned transfer exists) |
| Primary application contract | Upload/download/lifecycle HTTP workflow and Fileserver application ports | Provider-neutral managed and staged object-storage ports |
| Storage semantics | Application-owned staging, verification, publication, range/conditional delivery, upload leases | Managed and staged object publication plus remote-store versioning semantics |
| Local filesystem role | Certified backing store for the application-owned Fileserver platform | `filesystem-local-dev` development/provider implementation |
| Remote S3-style semantics | Not its purpose | First-class capability |
| 누가 클라이언트에 바이트를 주나? | 이 애플리케이션이 파일 서버 HTTP route로 준다 | 이 애플리케이션이 의미 수준 transfer port로 stream한다(직접·presigned 전송은 없다) |
| 주된 애플리케이션 계약 | upload/download/lifecycle HTTP 흐름과 파일 서버 애플리케이션 port | provider 중립의 managed·staged object storage port |
| 저장 의미 | 애플리케이션이 가진 staging, 검증, 게시, range·조건부 전달, upload lease | managed·staged 객체 게시와 원격 저장소의 versioning 의미 |
| 로컬 파일 시스템의 역할 | 애플리케이션이 가진 파일 서버 플랫폼의 인증된 backing store | `filesystem-local-dev` 개발용 provider 구현 |
| 원격 S3 방식의 의미 | 목적이 아니다 | 일급 capability |
## Decision rule
## 고르는 규칙
Use **Fileserver** when the service itself owns upload/download HTTP behavior: authentication, range
and conditional requests, verification/quarantine, resumable upload state, lifecycle/admin routes,
and optional delegated serving such as X-Accel-Redirect.
서비스 자신이 upload/download HTTP 동작을 가질 때 **파일 서버**를 쓴다. 인증, range와 조건부 요청, 검증·격리, 이어 올리는
upload 상태, lifecycle·관리 route, X-Accel-Redirect 같은 선택적 위임 서빙이다.
Use **Object Storage** when the application needs an object-storage abstraction whose provider owns
the storage semantics, especially S3-compatible managed objects. Direct/presigned transfer and
multipart upload are not implemented: their unassembled code was removed (see
`docs/capability-status.md` 「제거된 코드」).
애플리케이션이 저장 의미를 provider가 가지는 object storage 추상, 특히 S3 호환 managed 객체가 필요할 때 **Object Storage**를
쓴다. 직접·presigned 전송과 multipart upload는 구현하지 않았다. 조립되지 않던 그 코드는 지웠다(`docs/capability-status.md`
「제거된 코드」).
Do not enable both as two independent sources of truth for the same logical object. If a product
needs both, one capability must own the logical object/control record and the other must be an
explicit transport/provider integration behind that owner; duplicating metadata, retention state, or
publication state across both is not a supported composition.
같은 논리 객체에 대해 둘을 서로 독립된 정본 둘로 켜지 않는다. 제품에 둘 다 필요하면 한 capability가 논리 객체·제어 기록을
가지고, 다른 하나는 그 소유자 뒤의 명시적 전송·provider 통합이어야 한다. 둘에 메타데이터, 보존 상태, 게시 상태를 겹쳐 두는 것은
지원하는 조립이 아니다.
Readiness remains independent: `docs/fileserver/support-matrix.md` certifies Fileserver behavior;
`docs/registries/object-storage-readiness.yaml` certifies Object Storage behavior. Evidence from one
does not upgrade the other.
readiness는 따로 남는다. `docs/fileserver/support-matrix.md`가 파일 서버 동작을, `docs/registries/object-storage-readiness.yaml`이
Object Storage 동작을 인증한다. 한쪽의 증거가 다른 쪽을 올려 주지 않는다.
-67
View File
@@ -5,8 +5,6 @@
# - 형식: <검사><탭><경로>[<탭><걸린 값>]. 「#」으로 시작하는 줄과 빈 줄은 읽지 않는다.
# 언어: 아직 한국어로 옮기지 않은 살아 있는 문서와 ADR. 다음 단계(살아 있는 문서 번역, ADR 번역)에서 지운다.
language docs/compatibility/grpc-advanced-support-matrix.md
language docs/compatibility/grpc-support-matrix.md
language docs/fileserver/configuration.md
language docs/fileserver/design-deviations.md
language docs/fileserver/http-contract.md
@@ -24,18 +22,6 @@ language docs/httpclient/retry-and-ambiguity.md
language docs/httpclient/security.md
language docs/httpclient/streaming.md
language docs/httpclient/support-matrix.md
language docs/jpa/batch-write-guide.md
language docs/jpa/entity-mapping-guide.md
language docs/jpa/experimental-promotion-checklist.md
language docs/jpa/experimental-support-matrix.md
language docs/jpa/migration-guide.md
language docs/jpa/observability.md
language docs/jpa/postgresql-extensions.md
language docs/jpa/query-fetch-guide.md
language docs/jpa/repository-adaptation.md
language docs/jpa/runbooks.md
language docs/jpa/support-matrix.md
language docs/jpa/transaction-guide.md
language docs/mongodb/advanced/encryption.md
language docs/mongodb/advanced/multi-tenancy.md
language docs/mongodb/advanced/sharding.md
@@ -50,60 +36,10 @@ language docs/mongodb/runbooks/unknown-commit.md
language docs/mongodb/schema-index-migration-guide.md
language docs/mongodb/security-observability.md
language docs/mongodb/support-matrix.md
language docs/notification/at-rest-threat-model.md
language docs/notification/callback-reconciliation.md
language docs/notification/configuration-reference.md
language docs/notification/delivery-evidence.md
language docs/notification/migration-guide.md
language docs/notification/module-mapping.md
language docs/notification/operations.md
language docs/notification/provider-runbooks.md
language docs/notification/security-privacy.md
language docs/notification/support-matrix.md
language docs/observability/log-fields.md
language docs/redis/command-policy.md
language docs/redis/operations.md
language docs/redis/support-matrix.md
language docs/redis/upgrade-guide.md
language docs/runbooks/adapter-adapter-disabled.md
language docs/runbooks/auth-audience-mismatch.md
language docs/runbooks/auth-claim-mapping-failed.md
language docs/runbooks/auth-issuer-mismatch.md
language docs/runbooks/auth-jwks-unavailable.md
language docs/runbooks/auth-kid-unknown.md
language docs/runbooks/auth-public-path-misconfiguration.md
language docs/runbooks/auth-token-expired.md
language docs/runbooks/auth-token-invalid-signature.md
language docs/runbooks/auth-token-malformed.md
language docs/runbooks/auth-token-missing.md
language docs/runbooks/authz-insufficient-permission.md
language docs/runbooks/authz-tenant-mismatch.md
language docs/runbooks/cache-stampede-lock-timeout.md
language docs/runbooks/cache-unavailable.md
language docs/runbooks/db-deadlock.md
language docs/runbooks/db-idle-in-tx-timeout.md
language docs/runbooks/db-query-canceled.md
language docs/runbooks/db-serialization-failure.md
language docs/runbooks/db-unavailable.md
language docs/runbooks/dependency-4xx-client.md
language docs/runbooks/dependency-5xx-server.md
language docs/runbooks/dependency-circuit-open.md
language docs/runbooks/dependency-connect-failed.md
language docs/runbooks/dependency-dns-failed.md
language docs/runbooks/dependency-timeout.md
language docs/runbooks/file-download-streaming-failure.md
language docs/runbooks/grpc-advanced-capabilities.md
language docs/runbooks/grpc-platform-operations.md
language docs/runbooks/idempotency-unavailable.md
language docs/runbooks/lock-acquisition-timeout.md
language docs/runbooks/management-actuator-forbidden.md
language docs/runbooks/migration-failed.md
language docs/runbooks/runtime-jvm-oom.md
language docs/runbooks/startup-profile-mismatch.md
language docs/runbooks/startup-required-adapter-disabled.md
language docs/runbooks/startup-validation-failed.md
language docs/runbooks/template.md
language docs/storage-capability-boundary.md
language docs/web/advanced-capabilities.md
language docs/web/openapi-32-compatibility.md
language docs/web/patch-contract.md
@@ -118,10 +54,7 @@ reference docs/mongodb/consumer-leaf-guide.md :adapter:outbound:persistence-note
reference docs/web/http-contract.md docs/architecture/backend-api-and-server-state-contract.md
# 숫자: 정본(src/gradle/libs.versions.toml, registry)이 정하는 값을 복사한 곳. 정본을 가리키게 고치면 지운다.
number docs/compatibility/grpc-support-matrix.md Spring Boot 4.0.8
number docs/httpclient/repository-adaptation.md 19 leaf
number docs/httpclient/repository-adaptation.md Spring Boot 4.0.8
number docs/jpa/repository-adaptation.md 19 leaf
number docs/jpa/repository-adaptation.md Spring Boot 4.0.8
number docs/mongodb/repository-adaptation.md 19 leaf
number docs/mongodb/repository-adaptation.md Spring Boot 4.0.8
@@ -55,6 +55,13 @@ final class NotificationEvidenceVerifier {
/** A contract may extend a base; a longer chain is not followed. */
private static final int MAX_SUPERCLASS_DEPTH = 3;
/**
* The header of the column a table assigns grades in. The support matrix is written in Korean
* (docs/README.md), so its grade column is headed 등급; a table whose grade column is the first one
* lists what each grade requires and assigns nothing.
*/
private static final String GRADE_COLUMN_HEADER = "등급";
private static final Pattern SUPERCLASS =
Pattern.compile("\\bclass\\s+\\w+\\s+extends\\s+(\\w+)");
private static final Pattern PACKAGE = Pattern.compile("(?m)^package\\s+([\\w.]+)\\s*;");
@@ -117,7 +124,7 @@ final class NotificationEvidenceVerifier {
}
if (!insideTable) {
insideTable = true;
gradeColumn = cells.indexOf("Grade");
gradeColumn = cells.indexOf(GRADE_COLUMN_HEADER);
if (gradeColumn > 0) {
gradeAssigningTables++;
} else {
@@ -182,7 +189,9 @@ final class NotificationEvidenceVerifier {
throw new IllegalStateException(
"notification evidence: "
+ matrixFile.getName()
+ " has no table that assigns a grade (a 'Grade' column that is not the first"
+ " has no table that assigns a grade (a '"
+ GRADE_COLUMN_HEADER
+ "' column that is not the first"
+ " column), so no claim in it was checked.");
}
if (!problems.isEmpty()) {
@@ -150,7 +150,7 @@ class NotificationEvidenceVerifierTest {
Files.writeString(
fixture.matrix(),
"""
| Channel | Grade |
| 채널 | 등급 |
| --- | --- |
| email | Experimental |
""");
@@ -174,7 +174,7 @@ class NotificationEvidenceVerifierTest {
Files.writeString(
fixture.matrix(),
"""
| Grade | Requires |
| 등급 | 필요한 claim |
| --- | --- |
| Stable | delivery |
""");
@@ -248,7 +248,7 @@ class NotificationEvidenceVerifierTest {
Files.writeString(
matrix,
"""
| Channel | Grade |
| 채널 | 등급 |
| --- | --- |
| email | Stable |
""");
@@ -42,14 +42,16 @@ class NotificationReleaseGateTest {
// The terms must appear, but only under the refusal heading. Asserting they are absent
// altogether would be the wrong test: a matrix that never mentions guaranteed delivery leaves
// the reader to assume it, which is exactly the assumption this document exists to remove.
int refusalHeading = text.indexOf("## Not supported");
int refusalHeading = text.indexOf("## 지원하지 않는 것");
assertThat(refusalHeading).as("the matrix must state what it refuses to claim").isPositive();
String claims = text.substring(0, refusalHeading);
String refusals = text.substring(refusalHeading);
assertThat(claims).doesNotContain("guaranteed delivery", "guaranteed read", "exactly-once");
assertThat(refusals).contains("guaranteed delivery", "guaranteed read", "exactly-once");
assertThat(claims)
.doesNotContain(
"전달 보장", "읽음 보장", "정확히 한 번", "guaranteed delivery", "guaranteed read", "exactly-once");
assertThat(refusals).contains("전달 보장", "읽음 보장", "정확히 한 번");
assertThat(text).contains("PROVIDER_ACCEPTED", "AMBIGUOUS", "FCM_FID");
}
@@ -57,7 +59,7 @@ class NotificationReleaseGateTest {
void theEvidenceDocumentStatesTheForbiddenPromotions() throws IOException {
String text = Files.readString(DOCS.resolve("support-matrix.md"));
assertThat(text).contains("is not `DEVICE_DELIVERED`");
assertThat(text).contains("is not `DELIVERED`");
assertThat(text).contains("`DEVICE_DELIVERED`가 아니다");
assertThat(text).contains("`DELIVERED`가 아니다");
}
}
@@ -46,7 +46,7 @@ class PoolLaneClaimTest {
private static final String REMOVED_FLAG = "performance." + "assertions." + "enabled";
@Test
@DisplayName("no file describing the pool lane mentions the flag that was removed")
@DisplayName("풀 lane을 설명하는 파일은 지운 스위치를 말하지 않는다")
void noFileMentionsTheRemovedFlag() {
for (String description : LANE_DESCRIPTIONS) {
assertThat(read(description))
@@ -56,7 +56,7 @@ class PoolLaneClaimTest {
}
@Test
@DisplayName("no file describing the pool lane claims a certification or a machine bound")
@DisplayName("풀 lane을 설명하는 파일은 인증이나 기계 상한을 주장하지 않는다")
void noFileClaimsACertificationOrAMachineBound() {
for (String description : LANE_DESCRIPTIONS) {
String text = read(description).toLowerCase(Locale.ROOT);
@@ -68,12 +68,15 @@ class PoolLaneClaimTest {
.as("%s describes the pool lane as certifying something it does not measure", description)
.doesNotContain("pool pressure certification")
.doesNotContain("machine-dependent bounds")
.doesNotContain("machine bounds");
.doesNotContain("machine bounds")
.doesNotContain("풀 압력 인증")
.doesNotContain("기계 상한")
.doesNotContain("기계에 따라 다른 상한");
}
}
@Test
@DisplayName("the nightly job runs the behaviour lane, under its behaviour name")
@DisplayName("nightly job은 동작 lane을 그 동작 이름으로 돌린다")
void theNightlyJobRunsTheBehaviourLane() {
String nightly = read(".github/workflows/jpa-nightly.yml");
@@ -28,7 +28,7 @@ class JpaDocumentationContractTest {
private final JpaReleaseManifest manifest = JpaReleaseManifest.loadFromRepository();
@Test
@DisplayName("the support matrix names the registry's provider baseline, not the target")
@DisplayName("지원 매트릭스는 목표가 아니라 registry의 provider 기준선을 이름 댄다")
void theSupportMatrixNamesTheRegistrysProviderBaseline() {
String matrix = read("docs/jpa/support-matrix.md");
@@ -42,7 +42,7 @@ class JpaDocumentationContractTest {
}
@Test
@DisplayName("every gate the registry declares is named in the support matrix")
@DisplayName("registry가 선언한 gate는 모두 지원 매트릭스에 이름이 있다")
void everyRegistryGateIsNamedInTheSupportMatrix() {
String matrix = read("docs/jpa/support-matrix.md");
@@ -52,7 +52,7 @@ class JpaDocumentationContractTest {
}
@Test
@DisplayName("the H2 passage separates measurement from guarantee")
@DisplayName("H2 단락은 측정과 보장을 가른다")
void theH2PassageSeparatesMeasurementFromGuarantee() {
String matrix = read("docs/jpa/support-matrix.md");
@@ -62,18 +62,18 @@ class JpaDocumentationContractTest {
assertThat(flowed)
.as("two documents disagreed about SKIP LOCKED because they answered different questions")
.contains("not a production guarantee")
.contains("PostgreSQL contract evidence");
.contains("운영 보장이 아니")
.contains("PostgreSQL 계약 증거");
}
@Test
@DisplayName("the boundary document states the gap it does not enforce")
@DisplayName("경계 문서는 강제하지 않는 빈틈을 밝힌다")
void theBoundaryDocumentStatesItsGap() {
String adaptation = read("docs/jpa/repository-adaptation.md");
assertThat(adaptation)
.as("a document may call a boundary enforced only where a test actually enforces it")
.contains("Known gap");
.contains("알려진 빈틈");
}
private static String read(String repositoryRelativePath) {
@@ -35,11 +35,16 @@ import org.yaml.snakeyaml.Yaml;
* <li><b>LINK RESOLUTION</b> — every non-null {@code runbook_link} resolves to an existing file
* under {@code docs/runbooks/}.
* <li><b>PLACEHOLDER/STUB SMOKE</b> — runbook body must not contain TODO/TBD/PLACEHOLDER/FIXME
* and frontmatter must not have {@code status: stub} — EXCEPT files on the {@code
* LEGACY_STUB_DEBT} below. Files outside this temporary debt set that are stub/placeholder
* FAIL.
* and frontmatter must not have the draft status {@code status: 초안} — EXCEPT files on the
* {@code LEGACY_STUB_DEBT} below. Files outside this temporary debt set that are
* draft/placeholder FAIL.
* </ol>
*
* <p>A runbook's {@code status} is one of the two words the runbook template ({@code
* docs/runbooks/template.md}) allows: {@code 초안} (draft) or {@code 운영} (in operation). Any other
* value fails, so a stub written with the retired {@code stub} spelling cannot pass as a finished
* runbook.
*
* <p>The registry and runbook directory are checked-in contract resources. Missing resources and
* every contract violation are hard failures.
*
@@ -54,7 +59,7 @@ class RunbookCoverageContractTest {
* (feature-operational-runbook-contract D9).
*
* <p>These are only the legacy stub runbooks seeded during Phase D1. This set must exactly match
* the current {@code status: stub} files. Do not add new debt here: complete the runbook or adopt
* the current {@code status: 초안} files. Do not add new debt here: complete the runbook or adopt
* the future owned, expiring debt ledger.
*/
private static final Set<String> LEGACY_STUB_DEBT =
@@ -105,6 +110,12 @@ class RunbookCoverageContractTest {
"startup-required-adapter-disabled.md",
"startup-validation-failed.md");
/** The draft status: the runbook's body is not written yet. */
private static final String DRAFT_STATUS = "초안";
/** Every status a runbook may declare: draft, or in operation. */
private static final Set<String> RUNBOOK_STATUSES = Set.of(DRAFT_STATUS, "운영");
/** Categories exempt from mandatory-runbook requirement (client-error only). */
private static final Set<String> EXEMPT_CATEGORIES =
Set.of("VALIDATION", "NOT_FOUND", "CONFLICT", "DATA_INTEGRITY");
@@ -232,7 +243,7 @@ class RunbookCoverageContractTest {
}
Path trackedRunbook =
repositoryResources.requireTrackedFileInside("docs/runbooks", filename);
if (extractFrontmatterStatus(Files.readString(trackedRunbook)).equals("stub")) {
if (extractFrontmatterStatus(Files.readString(trackedRunbook)).equals(DRAFT_STATUS)) {
currentStubRunbooks.add(filename);
}
}
@@ -241,7 +252,7 @@ class RunbookCoverageContractTest {
assertThat(LEGACY_STUB_DEBT)
.as(
"LEGACY_STUB_DEBT is temporary containment and must match every and only current "
+ "status=stub runbook; do not add new allowlist entries—complete the runbook "
+ "status=초안 runbook; do not add new allowlist entries—complete the runbook "
+ "or adopt the future owned, expiring debt ledger")
.containsExactlyInAnyOrderElementsOf(currentStubRunbooks);
}
@@ -264,15 +275,15 @@ class RunbookCoverageContractTest {
Path trackedRunbook =
repositoryResources.requireTrackedFileInside("docs/runbooks", filename);
String content = Files.readString(trackedRunbook);
// Check for status: stub in frontmatter
boolean hasStubStatus = extractFrontmatterStatus(content).equals("stub");
// Check for the draft status in frontmatter
boolean hasStubStatus = extractFrontmatterStatus(content).equals(DRAFT_STATUS);
// Check for placeholder body text
boolean hasPlaceholderBody = PLACEHOLDER_PATTERN.matcher(content).find();
if (hasStubStatus || hasPlaceholderBody) {
violations.add(
filename
+ ": "
+ (hasStubStatus ? "status=stub" : "")
+ (hasStubStatus ? "status=초안" : "")
+ (hasPlaceholderBody ? " body-contains-placeholder" : ""));
}
}
@@ -285,6 +296,34 @@ class RunbookCoverageContractTest {
.isEmpty();
}
@Test
void everyRunbookFrontmatterDeclaresDraftOrOperatingStatus() throws Exception {
// given
List<String> outsideVocabulary = new ArrayList<>();
// when
try (Stream<Path> files = Files.list(runbooksDir)) {
for (Path path : files.sorted().toList()) {
String filename = path.getFileName().toString();
if (!filename.endsWith(".md") || filename.equals("template.md")) {
continue;
}
Path trackedRunbook =
repositoryResources.requireTrackedFileInside("docs/runbooks", filename);
String content = Files.readString(trackedRunbook);
String status = extractFrontmatterStatus(content);
if (!extractFrontmatter(content).isEmpty() && !RUNBOOK_STATUSES.contains(status)) {
outsideVocabulary.add(filename + ": status=" + status);
}
}
}
// then
assertThat(outsideVocabulary)
.as("A runbook's frontmatter status must be one of %s", RUNBOOK_STATUSES)
.isEmpty();
}
@Test
void runbookCoverageRejectsFrontmatterFromSymlinkOutsideRunbooks(@TempDir Path tempDir)
throws Exception {