Files
clean-architecture-backend-…/docs/testing/TESTING_STRATEGY.md
T
DongHyeonka bbe944bd3c fix!: 재리뷰가 찾은 결함과 색인에서 빠졌던 발견 5건을 고친다
문제: 성숙도 리뷰 수정을 다시 읽은 재리뷰(Critical 0, 회귀 0)가
Important 27건·Minor 41건을 찾았다. 수정이 새로 만든 결함이 많았다.
@SystemInvoked가 권한 규칙의 탈출구가 됐고, 데모 계정 거부가 정확히
prod일 때만 걸렸고, outbox 순서 번호가 업그레이드 때 뒤로 갔고,
GraphQL union 아래 복잡도가 0이었고, 서블릿 오류 응답이 success:true로
나갔고, 호출자 deadline이 breaker를 열었다. 원래 리뷰 색인이 06 영역
발견 5건(06-10~14)을 빠뜨려 그동안 처리되지 않았다.

방법: 영역별 7묶음이 test-driven-development 절차로 실패 테스트를
먼저 쓰고 고쳤다. 결정은 재리뷰 README 4절에 적었다: 순서 번호는 V21이
기록한 전역 floor부터, 데모 계정은 local·test·demo 허용 목록,
@SystemInvoked bean은 기동 실패, complete 단계 실패는
IDEMPOTENCY_COMPLETION_UNKNOWN(결과 불명), 캐시 조건부 쓰기는 별도
SCRIPT lane, strict lane 정책은 build cache 입력, 끝나지 않는 재시도
행은 원인 코드·지표·PARKED 절차. 레지스트리가 선언만 하고 아무 코드도
내보내지 않던 redis.capability.* 지표 6개는 빼고 runbook을 실제
지표(redis.lane.*) 기준으로 고쳤다.

위험·한계: V21을 V22 없이 직접 고쳤다(어느 배포에도 아직 없음). 이
브랜치의 V21을 적용한 개발 DB는 다시 만들어야 한다. 서블릿 오류
디스패치를 보안 체인이 허용한다. 발행·저장소 포트 시그니처가 바뀌어
파생 서비스 코드가 깨진다. prod에서 fixture-로 시작하는 설정값은
기동을 막는다. httpclient failure-injection lane의 main 단계 중복
실행은 이전 결정대로 남겼다. 실제 CI runner 실행은 확인하지 못했다.

검증: ci, mainCheck, :integrationCheck, -p optional-platforms ci
integrationCheck performanceCheck, :performanceCheck, :releaseCheck
(-PgitRevision), verify-compose-profile-contracts(18 lane) 통과.
첫 실행의 실패 2건(FindSecBugs 1, sample 동시 생성 테스트의 v4 event
id)은 고친 뒤 ci·integrationCheck·mainCheck를 다시 돌려 통과했다.

Refs: docs/reviews/2026-11-03-rereview/README.md 3·4·6·7절
BREAKING CHANGE: outbox 발행 포트와 저장소 포트 시그니처, 순서 번호
첫 값(V21 floor 다음), 샘플 데모 계정 프로필 허용 목록, 새 오류 코드
IDEMPOTENCY_COMPLETION_UNKNOWN, prod의 fixture- 값 거부, 기동 rule은
static·의존 없음이어야 한다.
2026-11-03 23:29:35 +09:00

362 lines
31 KiB
Markdown

# 테스트 전략 — TEST / INTEGRATION / SYSTEM / ARCHITECTURE / PERFORMANCE
- 기준 일자: 2026-09-18
- 상태: **활성 SSOT**
- 기계 기준: `build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/TestLaneCategory.java`
- 관련 리뷰: `docs/reviews/2026-09-07-app-bootstrap-module-code-review.md` BOOT-014~016
- 후속 결정: `docs/superpowers/specs/2026-09-16-verification-surface-reduction-design.md`
## 1. 공식 테스트 분류는 다섯 개뿐이다
이 저장소의 실행 taxonomy는 다음 다섯 개다.
| Category | 의미 | 외부 인프라 |
| --- | --- | --- |
| **TEST** | 빠르고 결정적인 로컬 검증. unit, slice, hermetic contract를 포함한다. | 원칙적으로 없음 |
| **INTEGRATION** | 실제 DB·브로커·스토리지·프로세스 등 외부 경계와의 통합을 검증한다. | 허용 |
| **SYSTEM** | 여러 모듈이 조립된 애플리케이션/런타임 동작과 클래스패스 형상을 검증한다. | 필요에 따라 허용 |
| **ARCHITECTURE** | 의존 방향, 패키지 경계, 금지 API, 테스트 taxonomy 같은 구조 규칙을 검증한다. | 없음 |
| **PERFORMANCE** | 지연, 처리량, 자원 사용과 회귀를 측정한다. | 실제에 가까운 환경 허용 |
`StrictTestLaneSpec`의 기본 category는 `TEST`이며,
`test()`, `integration()`, `system()`,
`architecture()`, `performance()`가 각각 위 다섯 값을 선택한다.
### 1.1 unit / slice / contract는 별도 category가 아니다
다음 용어는 **TEST 안에서 무엇을 검증하는지 설명하는 스타일**이다.
- unit: 한 클래스·함수·도메인 규칙
- slice: Spring MVC/JPA 등 한 프레임워크 계층의 좁은 조립
- contract: 외부 인프라 없이 검증 가능한 모듈/API/직렬화 약속
예를 들어 `@WebMvcTest`는 slice이지만 category는 TEST다.
JSON snapshot 검증은 contract이지만 hermetic하면 category는 TEST다.
새로운 `SLICE`나 `CONTRACT` category를 만들지 않는다.
### 1.2 qualification은 테스트 종류가 아니다
`qualification`은 **CI/release 검증 gate**다. 여섯 번째 테스트 category가 아니다.
현재 루트 `qualificationCheck`는 full system composition과 auxiliary-source style 검증을
묶는다. 특정 provider certification workflow나 leaf task 이름에 qualification이 들어갈 수도 있지만,
그 안에서 실행되는 테스트 자체는 다섯 category 중 하나로 분류한다.
즉 다음 두 질문을 분리한다.
1. 이 테스트는 무엇을 검증하는가? → 다섯 category 중 하나.
2. 언제/어떤 gate가 이 테스트를 실행하는가? → CI, qualification, release 정책.
## 2. Category와 source set은 같은 개념이 아니다
source set 이름으로 category를 추론하지 않는다.
- 일반적인 `src/test`는 TEST의 기본 실행 위치다.
- 별도 runtime/classpath가 필요한 테스트는 auxiliary source set을 사용할 수 있다.
- strict lane은 자신이 사용할 source set과 category를 **각각 명시**한다.
- `postgresqlIntegrationTest`처럼 이름에 integration이 들어가더라도, 기계 기준은
이름이 아니라 lane의 `integration()` 선언이다.
source set 목록은 계속 변하는 구현 세부사항이다. 이 문서에 전체 목록을 복제하지 않는다.
2026-09-16 verification-surface 축소에서 `verifyTestSourceSetRegistry`를 삭제했다.
Markdown 표와 Gradle source set을 대조하는 parser는 current-state를 또 하나의 build contract로
복제했기 때문이다. **이 verifier를 다시 만들지 않는다.**
## 3. 어디에 어떤 테스트를 두는가
| 대상 | Category | 기본 방식 |
| --- | --- | --- |
| 도메인 엔티티·값 객체 | TEST | 순수 단위 테스트 |
| Application use case | TEST | fake/stub port, 필요 최소 mock |
| startup validator / settings validation | TEST | `MockEnvironment` 또는 순수 객체 |
| Spring `@Configuration` 한 조각 | TEST | `ApplicationContextRunner` |
| MVC controller 한 slice | TEST | framework slice test |
| hermetic serialization/API snapshot | TEST | contract assertion |
| JPA repository + 실제 PostgreSQL | INTEGRATION | Testcontainers/real DB |
| Kafka/Rabbit/Redis/Mongo와 실제 프로토콜 통신 | INTEGRATION | real service/container |
| 전체 Boot composition, optional classpath 조합 | SYSTEM | full application/runtime graph |
| sample 제거/transport 포함 여부 등 전체 조립 결과 | SYSTEM | 별도 classpath/source set 가능 |
| ArchUnit, module dependency rule, forbidden API | ARCHITECTURE | static/bytecode structure |
| JMH, throughput/latency regression | PERFORMANCE | benchmark/performance lane |
### 3.1 TEST에서 금지하는 것
기본 TEST가 개발자의 로컬 루프를 무겁게 만들면 taxonomy가 무너진다.
- 실제 Docker/DB/broker를 요구하지 않는다.
- 외부 SaaS/network를 호출하지 않는다.
- 전체 애플리케이션 graph가 필요하지 않은데 `@SpringBootTest`를 사용하지 않는다.
- production 패키지와 무관한 `unit/`, `service/`,
`regression/` 같은 별도 분류 폴더를 만들지 않는다.
taxonomy 자체를 검증하기 위한 negative fixture는 예외다. 예를 들어 Testcontainers import를 일부러
가진 fixture는 실제 컨테이너를 실행하려는 테스트가 아니라 ARCHITECTURE 규칙의 입력이다.
## 4. 배치 원칙
테스트 코드는 가능한 한 production package를 그대로 mirror한다. 위치는 **대상 코드의 소유권**으로
찾을 수 있어야 한다.
별도 source set은 다음 중 하나가 실제로 달라질 때만 만든다.
- runtime/classpath
- 외부 인프라 요구
- JVM 옵션/환경
- 실행 비용과 스케줄
- 독립적인 strict-lane evidence가 필요한 경우
단순히 이름을 예쁘게 나누기 위해 source set을 만들지 않는다.
## 5. 공용 테스트 지원 코드
공유 fixture의 publish 표준은 Gradle `java-test-fixtures`다.
- **다른 source set 또는 다른 leaf가 소비해야 하는** fixture/fake/assertion/container helper는
`src/testFixtures/java`에 둔다.
- 다른 leaf는 `testFixtures(project(':...'))`로 명시적으로 소비한다.
- auxiliary lane이 fixture를 쓰면 그 lane의 classpath에 testFixtures를 명시적으로 연결한다.
- 반대로 한 source set 안에서만 쓰는 helper는 그 source set 안에 둔다. 사용처가 하나의 test
classpath뿐인데 `testFixturesJar`를 만들 이유는 없다.
- `TestUtil`, `CommonUtil`처럼 역할이 드러나지 않는 bucket을 만들지 않는다.
과거 `testkit` custom source set / `ca.testkit-publisher` 방식은
`java-test-fixtures`로 이관됐으며 다시 도입하지 않는다.
fixture는 **지원 코드**다. TEST/INTEGRATION/SYSTEM/ARCHITECTURE/PERFORMANCE 중 하나의 category를
추가하지 않는다.
## 6. Gradle 실행 계층
### leaf
- `:<leaf>:check`: 그 leaf의 compile, 일반 테스트와 로컬 quality 검증.
- `:<leaf>:testLaneCheck`: 그 leaf가 선언한 TEST category strict lanes.
- `:<leaf>:integrationTestLaneCheck`: INTEGRATION strict lanes.
- `:<leaf>:systemTestLaneCheck`: SYSTEM strict lanes.
- `:<leaf>:architectureTestLaneCheck`: ARCHITECTURE strict lanes.
- `:<leaf>:performanceTestLaneCheck`: PERFORMANCE strict lanes.
모든 leaf가 모든 category lane을 가질 필요는 없다.
### repository
- `integrationCheck`: production leaf들의 INTEGRATION lanes.
- `systemTestCheck`: production leaf들의 SYSTEM lanes.
- `architectureCheck`: repository architecture rules + ARCHITECTURE lanes.
- `qualificationCheck`: SYSTEM composition + auxiliary-source style gate.
- `ci`: leaf checks + architecture/quality/config contract + qualification.
- `releaseCheck`: `ci` + release-only provenance/archive/public-path checks.
`integrationCheck`는 현재 `ci`에 암묵적으로 포함되지 않는다.
여러 integration lane이 container runtime을 요구하므로 별도 workflow/main/nightly에서 실행할 수 있다.
PERFORMANCE는 기본 로컬 `check`에 붙이지 않는다. 명시적 benchmark/performance task나
scheduled workflow가 실행한다.
## 7. 새 테스트를 추가할 때 판단 순서
1. 실제 외부 인프라가 필요한가?
- yes → INTEGRATION 후보.
2. 여러 모듈의 실제 application graph/classpath 조합이 검증 대상인가?
- yes → SYSTEM 후보.
3. 코드 구조/의존 관계 자체가 검증 대상인가?
- yes → ARCHITECTURE.
4. 성능 수치가 검증 대상인가?
- yes → PERFORMANCE.
5. 모두 아니면 TEST.
그 다음에야 어떤 source set과 fixture가 필요한지 결정한다.
## 8. SSOT 역할 분리
- **기계 SSOT:** `TestLaneCategory` + `StrictTestLaneSpec`
- **사람 SSOT:** 이 문서
- **실행 graph:** 각 leaf의 strict lane 선언과 root lifecycle task
- **qualification/release 정책:** CI/workflow 및 qualification task
문서와 build.gradle의 전체 현재 상태를 다시 파싱해 서로 맞는지 검사하는 별도 verifier는 두지 않는다.
불변조건은 코드와 convention plugin이 강제하고, 이 문서는 분류 기준과 의도를 설명한다.
## 9. application-core 포트의 공유 계약 현황 (review 2026-11-01 01-05·TEST-F-1)
규칙(`AGENTS.md` 테스트 규칙): 포트마다 fake 하나를 포트 소유 leaf의 `testFixtures`에 두고, fake와
모든 adapter가 같은 추상 계약 테스트(`*Contract`)를 상속한다. 실제 adapter의 계약 테스트는 그
adapter leaf의 실 DB·Redis lane에서 돈다. fake가 실제와 다르게 동작하면 유스케이스 테스트가 거짓
녹색이 되기 때문이다.
아래는 application-core가 소유한 `*Port` 전부(2026-11-03 기준, `application-core/src/main`의
`public interface *Port`)와, `application-notification`이 소유하고 `persistence-notification`이 구현하는
저장소 포트 전부다(review 04-14, 표에 `(notification)`으로 표시). notification 포트의 계약은
`application-notification` testFixtures에 있고, 실제 구현 쪽은 persistence-jpa의 `postgresqlIntegrationTest`
source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌린다. fileserver 저장 포트는
9.3에 있다.
### 9.1 계약이 있는 포트
| 포트 | 계약(`application-core` testFixtures) | fake | 상속하는 실제 구현 테스트 (lane) |
| --- | --- | --- | --- |
| `TransactionPort` | `transaction.testkit.TransactionPortContract` + `TransactionProbe` | `DirectTransactionPort` | `SpringTransactionContractTest` — persistence-jpa, `JpaTransactionManager`, 실 PostgreSQL (`jpaPlatformContractTest`, 태그 `jpa-contract`) |
| `IdempotencyStorePort` | `idempotency.testkit.IdempotencyStoreContract` | `InMemoryIdempotencyStore` | `RedisIdempotencyStoreContractTest`(command fake, `test`) · `LiveRedisIdempotencyStoreContractTest`(실 Redis, `redisTopologyTest` standalone·cluster) · `PostgreSqlIdempotencyStoreContractTest`(실 PostgreSQL, `jpaPlatformContractTest`) |
| `SecretSourcePort` | `secret.testkit.SecretSourceContract` | `InMemorySecretSource` | `EnvironmentSecretSourceContractTest` — support (`test`) |
| `OutboxAppendPort` | `outbox.testkit.OutboxAppendContract` | `InMemoryOutboxStore(DirectTransactionPort)` | `PostgreSqlOutboxAppendTransactionalIntegrationTest` (`postgresqlOutboxAppendTransactionalIntegrationTest`) |
| `LiveEventReplayPort` | `realtime.testkit.LiveEventReplayContract` | `InMemoryLiveEventReplay` | `JpaLiveEventReplayContractTest` (`jpaPlatformContractTest`) |
| `AuthorizationPort` | `security.testkit.AuthorizationContract` | `InMemoryAuthorization` | `AuthorizationAdapterContractTest` — web (`test`) |
| `CorrelationIdPort` | `observability.testkit.CorrelationIdContract` | `FixedCorrelationId` | `MdcCorrelationIdPortAdapterContractTest` — web (`test`) |
| `CacheRegionPort` | `cache.testkit.CacheRegionContract` | `InMemoryCacheRegion` | `RedisCacheRegionContractTest`(`test`) · `LiveRedisCacheRegionContractTest`(`redisTopologyTest`) |
| `DistributedLeasePort` | `lease.testkit.DistributedLeaseContract` | `InMemoryDistributedLease` | `RedisDistributedLeaseContractTest` · `LiveRedisDistributedLeaseContractTest` |
| `DistributedLockPort` | `lock.testkit.DistributedLockContract` | `InMemoryDistributedLock` | `PostgreSqlDistributedLockIntegrationTest` (`postgresqlDistributedLockIntegrationTest`) |
| `DurableOperationStorePort` | `operation.testkit.DurableOperationStoreContract` | `InMemoryDurableOperationStore` | `JpaDurableOperationStoreContractTest` (`jpaPlatformContractTest`) |
| `IntegrationEventEncoderPort` | `messaging.event.testkit.IntegrationEventEncoderContract` | `FakeIntegrationEventEncoder` | `JsonIntegrationEventEncoderContractTest` — support (`test`) |
| `OutboxStorePort` (lease fencing) | `outbox.testkit.OutboxLeaseFencingContract` | `InMemoryOutboxStore` | `PostgreSqlOutboxConcurrentRelayIntegrationTest` |
| `OutboxAggregateSequencePort` | `outbox.testkit.OutboxAggregateSequenceContract` | `InMemoryOutboxAggregateSequences` | `PostgreSqlOutboxAggregateSequenceIntegrationTest` |
| `OutboxMessagePublishPort` | `outbox.testkit.OutboxMessagePublishContract` | `FakeOutboxMessagePublisher` (relay 테스트 4개도 이 fake를 쓴다) | `OutboxMessagePublishAdapterTest` — messaging (`test`) |
| `IntegrationEventPublishPort` | `messaging.event.testkit.IntegrationEventPublishContract` | `FakeIntegrationEventPublisher` | `PlatformIntegrationEventPublishAdapterTest` — messaging (`test`) |
| `PreferenceStorePort` (notification) | `policy.testkit.PreferenceStoreContract` | `InMemoryPreferenceStore` | `PostgreSqlPreferenceStoreContractTest` (`jpaPlatformContractTest`) |
| `SuppressionStorePort` (notification) | `policy.testkit.SuppressionStoreContract` | `InMemorySuppressionStore` | `PostgreSqlSuppressionStoreContractTest` (`jpaPlatformContractTest`) |
| `DeduplicationStorePort` (notification) | `policy.testkit.DeduplicationStoreContract` | `InMemoryDeduplicationStore` | `PostgreSqlDeduplicationStoreContractTest` (`jpaPlatformContractTest`) |
| `NotificationRequestStorePort` (notification) | `dispatch.testkit.NotificationRequestStoreContract` | `InMemoryNotificationRequestStore` | `PostgreSqlNotificationRequestStoreContractTest` (`jpaPlatformContractTest`) |
| `ReconciliationJobStorePort` (notification) | `dispatch.testkit.ReconciliationJobStoreContract` | `InMemoryReconciliationJobStore` | `PostgreSqlReconciliationJobStoreContractTest` (`jpaPlatformContractTest`) |
| `AdminOperationStorePort` (notification) | `admin.testkit.AdminOperationStoreContract` | `InMemoryAdminOperationStore` | `PostgreSqlAdminOperationStoreContractTest` (`jpaPlatformContractTest`) |
| `TemplateRegistry` (notification) | `template.testkit.TemplateRegistryContract` | `InMemoryTemplateRegistry` | `PostgreSqlTemplateRegistryContractTest` (`jpaPlatformContractTest`) |
| `RecipientLeaseStorePort` (notification) | `dispatch.testkit.RecipientLeaseStoreContract` | `InMemoryRecipientQueue` | `PostgreSqlRecipientLeaseStoreContractTest` (`jpaPlatformContractTest`, JPA `@Version` 경우만 PG 전용) |
| `RecipientDeliveryStorePort` (notification) | `dispatch.testkit.RecipientDeliveryStoreContract` | `InMemoryRecipientQueue` (lease 포트와 같은 fake — 같은 행) | `PostgreSqlRecipientDeliveryStoreContractTest` (`jpaPlatformContractTest`) |
| `DeliveryAttemptStorePort` (notification) | `dispatch.testkit.DeliveryAttemptStoreContract` | `InMemoryDeliveryAttemptStore` | `PostgreSqlDeliveryAttemptStoreContractTest` (`jpaPlatformContractTest`) |
| `DeliveryAttemptResolverPort` (notification) | `callback.testkit.DeliveryAttemptResolverContract` | `InMemoryDeliveryAttemptStore` (JPA처럼 attempt store가 구현) | `PostgreSqlDeliveryAttemptResolverContractTest` (`jpaPlatformContractTest`) |
| `DeliveryProjectionStorePort` (notification) | `callback.testkit.DeliveryProjectionStoreContract` | `InMemoryDeliveryAttemptStore` | `PostgreSqlDeliveryProjectionStoreContractTest` (`jpaPlatformContractTest`, `projection_version` 경우만 PG 전용) |
| `ProviderEventLedger` (notification) | `callback.testkit.ProviderEventLedgerContract` | `InMemoryProviderEventLedger` | `PostgreSqlProviderEventLedgerContractTest` (`jpaPlatformContractTest`) |
| `NotificationSideEffectPort` (notification) | `callback.testkit.NotificationSideEffectContract` | 없음 — 구현 `SuppressionSideEffect`가 application 규칙이라 fake 대신 그대로 쓴다 | `SuppressionSideEffectTest`(store fake 위) · `PostgreSqlNotificationSideEffectContractTest`(JPA store 위, `jpaPlatformContractTest`) |
| `ContactPointStorePort` (notification) | `dispatch.testkit.ContactPointStoreContract` | `InMemoryContactPointStore` | `PostgreSqlContactPointStoreContractTest` (`jpaPlatformContractTest`) |
계약을 실제 구현에 처음 적용할 때 드러난 차이와 처리:
- `DirectTransactionPort`는 예외가 나도 쓰기를 되돌리지 않았고, 참여한 안쪽 경계가 실패해도 바깥
커밋이 성공했고, `inRead` 안의 쓰기를 막지 않았다. 실 PostgreSQL의 `SpringTransaction`은 셋 다
반대다. fake가 롤백(`onRollback`), 참여 실패 시 바깥 커밋 실패, 읽기 전용 표시(`readOnly()`)를
갖게 고쳤다. `committed()`는 이제 실제로 커밋된 경계만 담는다(바깥이 롤백되면 안쪽도 빠진다).
- PostgreSQL 멱등성 store는 (1) 이전 revision의 핸들을 `OPERATION_CONFLICT`로, Redis·fake는
`NOT_OWNER`로 답했다. 핸들의 owner 튜플에는 revision이 들어가므로 `NOT_OWNER`로 맞췄다.
`OPERATION_CONFLICT`는 "같은 operation id가 다른 인자로 이미 적용됨" 한 뜻만 남는다. (2) 실행
전(CLAIMED) claim의 renew를 받아 줬고 Redis·fake는 거부했다. renew는 실행 중인 작업의 lease만
늘리도록 PostgreSQL을 맞췄다(호출자 없음 — 템플릿 안 동작 변화 없음). (3) release 뒤의 다음
claim을 `TakenOverClaimed`(attempt 2)로, Redis는 `Acquired`로 답한다. executor는 둘을 같게
처리하므로 계약은 "다음 claim이 scope를 가진다"만 요구한다.
- `OutboxAppendContract`는 static helper 두 개였고 JPA readiness 테스트만 불렀다. 추상 계약으로 바꿔
readiness 테스트가 상속한다(같은 두 케이스 + 트랜잭션 밖·읽기 전용·중복 eventId). 실 PostgreSQL에서
`inRead` 안의 append가 예외 없이 사라지는 것을 찾았다(실측: 예외 없음, 행 없음) — JPA 트랜잭션
매니저가 읽기 전용 세션을 flush하지 않아 저장 자체가 일어나지 않는다. `JpaOutboxStore.append`가 읽기·쓰기 트랜잭션을 요구하게
고쳤다. in-memory store는 `DirectTransactionPort`를 받으면 같은 규칙(트랜잭션 밖·읽기 전용 거부,
롤백 시 취소)으로 동작한다. 인자 없이 만들면 지금처럼 바로 쓴다(relay 테스트가 행을 미리 심는 용도).
- `IdempotencyStoreContract`의 시간 케이스(renew가 lease를 실제로 늘린다, review 05-02)는 시계를
가진 store(실 Redis, PostgreSQL)에서만 의미가 있다. 시계를 움직일 수 없는 store(in-memory fake,
command fake 위 Redis)는 `elapse`를 재정의하지 않고, 기본 `elapse`가 그 케이스를 abort해 보고서에
skipped로 남는다. 예전에는 no-op이라 시간이 흐르지 않은 채 통과했다(review 2026-11-03 RR-01-06).
PostgreSQL에서 renew가 lease를 늘리지 않게 바꾼 변이로 이 케이스가 실패함을 확인했다.
- `OutboxAggregateSequenceContract`는 포트 Javadoc의 세 약속 중 둘을 보지 않았다(RR-01-06). "쓰기
트랜잭션 밖 거부"와 "롤백된 번호는 다시 준다"를 넣었다. fake는 `DirectTransactionPort`를 받으면 같은
규칙으로 동작한다(인자 없이 만들면 예전처럼 트랜잭션을 보지 않는다 — sample 테스트가 쓰는 방식).
`CacheRegionContract`에는 2^53 위 revision 한 자리 차이 경우를 넣었다. fake가 revision을 double로
비교하게 바꾼 변이가 이제 실패한다(전에는 통과).
notification 계약 다섯 개(deduplication·request·reconciliation job·admin operation·template, 2026-11-03)는
PostgreSQL 쪽에만 있던 테스트를 계약으로 옮긴 것이다. `ReconciliationJobClaimContractTest`(8건)와
`AdminOperationClaimContractTest`(6건)는 지웠고 같은 경우가 포트 단위로 계약에 들어갔다 — 앞의 것은 SQL을
직접 돌렸고, 계약은 store를 거친다. 스키마 CHECK 제약 하나(`phase`)는 벤더 동작이라
`PostgreSqlAdminOperationStoreContractTest`에만 남겼다. 처음 적용할 때 fake와 실제가 다르게 답한 경우는
없었다. 유스케이스 테스트의 대역은 `PlatformFakes.RequestStore`·deduplication 람다·
`AdminOperationExecutorTest.FakeStore`를 이 fake들로 바꿨다. 아직 테스트 안에 남은 대역: admin
`NotificationAdminApplicationServiceTest.RecordingOperations`·`UnusedSuppressionStore`, reconciliation job
`ReconciliationJobWorkerTest`(notification adapter)의 stub — 호출 횟수를 세거나 "부르지 않는다"를 확인하는
용도라 fake로 바꾸면 단언을 다시 써야 한다.
notification 계약 여덟 개(recipient lease·recipient delivery·attempt·resolver·projection·ledger·side
effect·contact point, 2026-11-03 r3-J)로 9.2의 "다음 단계"가 끝났다. fake는 JPA 구현의 묶음을 따른다:
`InMemoryRecipientQueue` 하나가 lease·delivery 두 포트를 구현하고 행을 `InMemoryNotificationRequestStore`와
나눈다(claim이 lease·fence를 쓰고 fenced 쓰기가 그 값을 읽는다). `InMemoryDeliveryAttemptStore` 하나가 attempt·
resolver·projection 세 포트를 구현한다(`JpaDeliveryAttemptStore`와 같다). PG 쪽에서 SQL을 따로 돌리던
`RecipientClaimContractTest`·`LateEventBindingContractTest`·`ProjectionFactDurabilityContractTest`는 지웠고
같은 경우가 store를 거치는 계약으로 들어갔다. 벤더 동작 두 개(claim이 JPA `@Version`을 올림, projection
저장이 `projection_version`을 올림)는 PG 하위 클래스에만 남겼다. `EvidenceCertaintyContractTest`의 DB CHECK
경우와 `WorkerCrashRecoveryContractTest`의 여러 store 시나리오는 그대로 둔다.
처음 적용할 때 새 fake와 JPA store가 다르게 답한 경우는 없었다. 다르게 답한 것은 지운 대역들이었다:
`PlatformFakes.RecipientStore`는 `save`가 lease까지 덮어썼고(JPA는 lease를 쓰지 않는다) "superseded"를 테스트가
채운 집합으로 정했다. `PlatformFakes.AttemptStore`는 provider 요청 id를 평문으로 돌려줬고 snapshot을 행과 무관한
map에서 꺼냈다. 연락처 람다는 지문 조회에서 테넌트를 보지 않았다. 원장·resolver·projection stub은 저장한
이벤트를 하나도 보여 주지 않았다. 이 대역들(`PlatformFakes.RecipientStore`·`AttemptStore`,
`NotificationDispatchServiceTest`·`LeaseRecoveryServiceTest`·`DispatchOutcomeRecorderTest`의 기록용 store,
`ProviderEventLateMatchTest`·`CallbackIngestionAtomicityTest`의 원장 stub, 연락처 대역 4곳, 테스트 조립 도우미의
no-op 원장·resolver·projection)은 모두 위 fake로 바꿨다. 조립 도우미는 이제 no-op이 아니라서
`NotificationPlatformNoops`를 `PlatformCollaborators`로 이름을 바꿨다.
`NotificationSideEffectPort`의 유일한 구현 `JpaNotificationSideEffect`는 표를 하나도 쓰지 않는 규칙(hard
bounce→INVALID, complaint→SUPPRESSED, 사유별 억제)이었다. persistence에 두면 유스케이스 테스트는 no-op이나 규칙의
두 번째 복사본만 쓸 수 있어서 application의 `dispatch.SuppressionSideEffect`로 옮겼고(`callback`은 `dispatch`에 의존할 수 없어 연락처 포트를 가진 쪽에 둔다) 조립은
`composition:notification-platform`이 한다. 계약은 같은 클래스를 store fake 위와 JPA store 위에서 돌린다.
계약이 실제로 결함을 잡는지는 변이로 확인했다. fake마다 결함 하나를 넣으면 해당 계약이 실패한다:
`DirectTransactionPort`가 중첩 `inRootWrite`를 거부하지 않음(3건 실패), `InMemoryAuthorization`이 권한
없는 호출을 통과시킴(3건), `InMemoryLiveEventReplay`가 만료 이벤트를 걸러내지 않음(1건),
`InMemoryOutboxStore`가 롤백 때 append를 취소하지 않음(1건), `InMemorySecretSource`가 공백 값을 돌려줌
(1건), PostgreSQL 멱등성 store의 renew가 lease를 늘리지 않음(시간 케이스 1건). notification:
reconciliation job fake가 fence를 보지 않음(2건), admin operation fake가 다른 명령을 충돌로 보지 않음(1건),
deduplication fake가 window를 무시함(1건), request fake가 `findById`에서 테넌트를 보지 않음(1건),
r3-J: queue가 fence를 보지 않음(같은 worker 이름 재claim 1건), queue가 만료된 작업을 claim함(1건), queue의
`save`가 lease를 덮어씀(2건), attempt store가 완료 attempt의 요청 id를 평문으로 남김(1건), resolver가 profile을
보지 않음(1건), projection이 나중 저장에서 읽음 사실을 지움(1건), 원장이 이미 묶인 이벤트를 다시 묶음(1건),
원장이 PENDING이 아닌 상태를 다시 바꿈(1건), 연락처 fake가 지문 조회에서 테넌트를 보지 않음(1건),
`SuppressionSideEffect`가 complaint를 INVALID로 기록함(1건). relay
use case가 결과 조회 대신 예외만 보는 `publish`를 부르게 바꾸면 relay 테스트 7건이 실패한다.
### 9.3 application-fileserver 저장 포트 (review 2026-11-03 RR-01-04·RR-07-06)
`persistence-fileserver`가 구현하는 포트 9개와 소유자 규칙 포트. 계약은 `application-fileserver`
testFixtures(`dev.caskeleton.application.fileserver.testkit`)에 있고, 실제 구현 쪽은 persistence-jpa의
`postgresqlIntegrationTest` source set(`readiness` 패키지, 공용 기동 `FileserverPostgreSqlStack`)에서 태그
`jpa-contract`로 `jpaPlatformContractTest` lane이 돌린다. 시간이 걸린 경우는 stack이 움직이는 시계로 본다.
| 포트 | 계약 | fake | 상속하는 실제 구현 테스트 |
| --- | --- | --- | --- |
| `FileMetadataPort` | `FileMetadataPortContract` | `InMemoryFileMetadataStore` | `PostgreSqlFileserverMetadataStoreIntegrationTest` (`postgresqlFileserverMetadataIntegrationTest`) |
| `CleanupQueuePort` | `CleanupQueuePortContract` | `InMemoryCleanupQueue` | `PostgreSqlFileserverReclamationIntegrationTest` (`postgresqlFileserverReclamationIntegrationTest`) |
| `FileQuotaPort`·`QuotaCommitPort`·`QuotaReclaimPort` | `FileQuotaLedgerContract` — 세 포트가 한 장부라 한 계약 | `FakeFileQuotaService`(장부) + `FakeQuotaCommitGateway`·`RecordingQuotaReclaimGateway`(같은 장부에 쓴다) | `PostgreSqlFileQuotaLedgerContractTest` |
| `UploadSessionPort` | `UploadSessionPortContract` | `InMemoryUploadSessionStore` | `PostgreSqlUploadSessionContractTest` |
| `StagingUploadLocatorPort` | `StagingUploadLocatorPortContract` | `InMemoryUploadSessionStore`(같은 세션) | `PostgreSqlStagingUploadLocatorContractTest` |
| `RecoveryQueuePort` | `RecoveryQueuePortContract` | `InMemoryRecoveryQueue` | `PostgreSqlRecoveryQueueContractTest` |
| `ContentReferenceLedgerPort` | `ContentReferenceLedgerPortContract` | `InMemoryFileMetadataStore`(같은 레코드) | `PostgreSqlContentReferenceLedgerContractTest` |
| `FileAccessPolicyPort` | `FileAccessPolicyPortContract` — 규칙 정본은 `FileAccessSubject.owns` | `FakeFileAccessPolicy` | `RoleBasedFileAccessPolicyContractTest` — fileserver adapter (`test`) |
계약을 처음 적용할 때 fake가 실제와 다르게 답한 경우와 처리(모두 fake를 실제에 맞췄다):
- 쿼터: fake에 시계가 없어 만료된 예약도 사용량에 셌고, 해제한 예약의 확정·연장을 조용히 받았다. 확정·
회수 fake는 기록만 하고 장부를 바꾸지 않았다. 이제 한 장부에 시계가 있고 JPA와 같은 조건으로 거절한다.
만료됐지만 해제되지 않은 예약의 확정은 JPA SQL이 받으므로(쓴 바이트는 사용량이다) 계약도 받는다 —
`JpaFileQuota` Javadoc의 "만료된 예약은 확정할 수 없다"는 SQL과 달라 고쳤다.
- 업로드 세션: fake가 기한이 지난 업로드에 lease를 줬고, lease가 만료된 writer의 offset 확정을 받았고,
`findExpired`를 기한 순이 아니라 넣은 순서로 줬다.
- 복구 큐: fake가 한도 0을 거절하지 않았다.
- 소유자 규칙: fake와 실제 정책이 같은 규칙을 따로 썼다(principal·tenant 비교 두 벌). 정본
`FileAccessSubject.owns` 하나를 둘 다 부른다. fake 규칙에서 tenant 비교를 빼는 변이가 계약 2건으로 잡힌다.
### 9.2 계약이 없는 포트 (의도)
| 포트 | 실제 구현 | fake | 계약이 없는 이유 | 다음 단계 |
| --- | --- | --- | --- | --- |
| `UserPrincipalPseudonymizerPort` | identifier `HmacUserPrincipalPseudonymizer` | 없음 — 의도 | 결정적 순수 함수라 테스트가 실제 구현을 그대로 쓴다. fake는 두 번째 복사본이 된다. 출력은 `HmacUserPrincipalPseudonymizerVectorTest`가 고정한다 | 해당 없음 |
| `OutboxRelayFailureReportPort` | messaging `Slf4jOutboxRelayFailureReportAdapter` | 테스트마다 기록용 | 진단 출력 포트라 호출자가 기대는 동작이 "던지지 않는다" 하나뿐이다 | 해당 없음 |
| `NotificationServingStatePort` (notification) | `JdbcNotificationServingState` | 없음 — 의도 | 여러 표에 걸친 집계 읽기다. `FILTER`·`EXTRACT(EPOCH …)`·lease 조건이 답이라 fake는 쿼리를 다시 쓰는 복사본이 된다. `ServingStateContractTest`가 실 PostgreSQL에서 고정한다 | 해당 없음 |
| `ConsentStorePort`·`NotificationInbox` (notification) | `JpaPolicyStores.Consents`·`JpaNotificationInbox` | 없음 — 의도 | 이 포트를 fake로 쓰는 유스케이스 테스트가 없다. 소비자 없는 fake는 두 번째 복사본이 된다(결정 2026-11-03, README 15절). inbox의 `@Version` 동작은 `InboxBulkReadVersionContractTest`가 실 PG에서 본다 | 해당 없음 — fake가 필요한 소비자 테스트가 생기면 계약과 함께 만든다 |
application-core 안에서 `TransactionPort`를 구현하는 것은 이제 `DirectTransactionPort` 하나다(테스트
전용 구현 5개를 바꿨다). 롤백을 흉내 내던 `SubmitDurableOperationUseCaseTest.RollbackAwareTransactions`
대신 `InMemoryDurableOperationStore`·`InMemoryOutboxStore`가 `DirectTransactionPort`를 받아 롤백 때 자기
쓰기를 되돌린다. application-notification 테스트도 `DirectTransactionPort`를 쓴다. 아직 따로 있는 것:
application-fileserver testFixtures의 `DirectTransactions`(composition fileserver
`FileserverAssemblyFixture`가 쓴다).
relay 테스트(`PublishPendingOutboxEventsUseCaseTest`·`OutcomeAwareRelayTest`·`TransientPublishFailureRelayTest`·
`StoppingRelayReleasesItsClaimsTest`)는 각자 만든 publish 대역 대신 `FakeOutboxMessagePublisher`를 쓴다.
fake는 event별 답(`answering(eventId, outcome)`), 예외(`throwing`), 발행 중 일어나는 일(`whenPublishing` —
시계 이동, 정지 요청)을 받는다. `OutboxPublishOutcomeTest`의 람다 하나는 대역이 아니라 포트의 default
메서드 자체가 시험 대상이라 남겼다.