From f40c03c6d3b027240ecff68a36e9678a2f72437b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 03:00:21 +0900 Subject: [PATCH] =?UTF-8?q?fix:=203=EC=B0=A8=20=ED=99=95=EC=9D=B8=20?= =?UTF-8?q?=EB=A6=AC=EB=B7=B0=EC=9D=98=20Minor=2019=EA=B1=B4=EC=9D=84=20?= =?UTF-8?q?=EA=B3=A0=EC=B9=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 3차 수정의 확인 리뷰가 새 Important 없이 Minor 19건을 남겼다. 동작에 닿는 것이 셋이다. JDK read-idle watchdog이 공용 ForkJoinPool에서 돌아 그 풀이 바쁘면 300ms timeout이 6초 가까이 늦었다. 붙여 쓴 -x를 verifyStrictLaneStages가 읽지 않아 lane을 뺀 workflow가 통과했다. 사용자 전송이 중간 클래스를 거쳐 @SystemCaller bean을 부르면 ArchUnit 규칙을 지났다. 잠금 대기 검사기는 FK·trigger·REINDEX와 lock_timeout = 0을 못 봤고, 쿼터 보정 SQL은 코드와 다른 모양의 행을 넣었다. 방법: 영역별 4묶음이 맡은 Minor만 test-driven-development 절차로 고쳤다(재리뷰 README 12절). - watchdog은 전용 데몬 스레드 하나에서 돌고 스트림을 닫으면 작업을 취소한다. read당 비용은 그대로다(21–24ns). - 사용자 전송 → @SystemCaller는 직접·간접 의존 모두 거부한다. 리뷰가 권한 직접 의존 검사는 중간 클래스 하나로 다시 열려서 버렸다. - 검사기를 보강하면서 새로 걸린 이미 배포된 마이그레이션 5개는 내용을 바꾸지 않고 동결 목록에 더했다(main과 blob이 같다). - 비밀 목록 bean은 규칙보다 먼저 만들어 실제 클래스로 검사한다. 위험·한계: 회복 필요 예외 메시지 끝에 scope digest가 붙고 기동 실패 문구가 바뀌어, 문구 전체에 맞추던 로그 매처는 고쳐야 한다. 코드가 든 Redis 계정 참조의 fixture- 검사는 문서로만 막았다(코드로 막으려면 새 의존 edge가 필요하다). failure-retention ≥ replay-ttl 기동 검사는 넣지 않았다. -mx 같은 짧은 플래그 묶음과 graphql 전송 fixture는 남았다. spotbugsTestFixtures(게이트 밖)의 정규식 경고가 15건으로 늘었다. 검증: ci, 두 빌드의 verifyStrictLaneStages --dry-run, mainCheck, :integrationCheck, -p optional-platforms ci integrationCheck performanceCheck, :performanceCheck, :releaseCheck(-PgitRevision), verify-compose-profile-contracts(18 lane) 첫 실행 통과. watchdog은 공용 풀을 채운 상태에서 300ms 설정이 300ms에 끝나는 것을 쟀다. Refs: docs/reviews/2026-11-03-rereview/README.md 11·12절, round3/ --- docs/fileserver/operations.md | 8 +- docs/httpclient/configuration-reference.md | 10 +- docs/jpa/entity-mapping-guide.md | 5 +- docs/jpa/migration-guide.md | 39 +++-- docs/manual/04-persistence.md | 6 +- docs/manual/05-idempotency.md | 5 +- docs/manual/07-authorization.md | 36 ++++- docs/registries/env-keys.yaml | 4 + docs/reviews/2026-11-03-rereview/README.md | 30 ++++ docs/runbooks/idempotency-unavailable.md | 76 +++++++-- docs/runbooks/migration-failed.md | 17 +- docs/runbooks/outbox-dead-letter.md | 13 +- docs/upgrade/2026-11-maturity-review.md | 17 +- docs/web/http-contract.md | 14 +- infra/redis-sdk/acl/README.md | 8 +- src/.env.example | 1 + src/adapter/inbound/messaging/CLAUDE.md | 6 +- src/adapter/inbound/messaging/README.md | 10 +- .../redis/idempotency/IdempotencyScripts.java | 12 +- .../RedisIdempotencyStoreAdapter.java | 13 +- src/adapter/outbound/httpclient/README.md | 11 +- .../httpclient/jdk/ReadIdleInputStream.java | 66 +++++++- .../jdk/ReadIdleInputStreamTest.java | 87 ++++++++++- .../outbound/persistence-jpa/CLAUDE.md | 3 +- .../migration/MigrationLockWaitTest.java | 16 +- .../persistence/migration/MigrationTrees.java | 23 ++- .../arch/JpaArchitectureRulesTest.java | 49 ++++++ .../arch/entity/JoinTableChildEntity.java | 30 ++++ .../arch/entity/JoinTableParentEntity.java | 35 +++++ .../arch/entity/TwoOwnerCourseEntity.java | 28 ++++ .../arch/entity/TwoOwnerStudentEntity.java | 34 ++++ .../LockWaitMigrationInspectorTest.java | 86 +++++++++- .../VersionedMigrationFilesTest.java | 48 ++++++ .../arch/SingleSidedAssociationCondition.java | 92 +++++++++-- .../migration/LockWaitMigrationInspector.java | 147 +++++++++++++++--- .../migration/VersionedMigrationFiles.java | 47 ++++++ .../InMemorySemanticRedisCommands.java | 9 +- src/adapter/outbound/redis-sdk/README.md | 13 +- .../connection/RedisSdkComposition.java | 14 +- .../startup/RequiredProductionSecrets.java | 5 + .../support/startup/StartupRuleRunner.java | 29 +++- .../startup/StartupRuleRunnerTest.java | 67 +++++++- src/app-bootstrap/CLAUDE.md | 5 +- src/app-bootstrap/README.md | 6 +- .../ApplicationBoundaryArchitectureTest.java | 68 ++++++-- .../ArchRuleDiscoveryContractTest.java | 1 + .../ArchitectureViolationFixtureTest.java | 91 +++++++++++ ...ystemCallerHandlerRegistrationFixture.java | 18 +++ .../inbound/messaging/package-info.java | 4 +- .../jaxrs/JaxRsSystemCallerFixture.java | 24 +++ ...SystemCallerWithNestedEndpointFixture.java | 34 ++++ .../scheduler/SystemJobLauncherFixture.java | 20 +++ ...SystemCallerInvokingControllerFixture.java | 26 ++++ ...SystemCallerRelayingControllerFixture.java | 26 ++++ .../runtime/SecretSourceValidator.java | 11 +- src/application-core/CLAUDE.md | 20 ++- src/application-core/README.md | 3 +- .../idempotency/IdempotencyExecutor.java | 67 +++++--- .../IdempotencyRecoveryRequiredException.java | 6 +- .../application/security/SystemCaller.java | 14 +- .../application/security/SystemInvoked.java | 16 +- .../idempotency/IdempotencyExecutorTest.java | 50 ++++++ .../testkit/IdempotencyStoreContract.java | 23 +++ .../config/EnvContractVerifier.java | 114 ++++---------- .../buildlogic/config/MetadataScope.java | 11 -- .../buildlogic/config/VerifyEnvKeysTask.java | 37 +---- .../strictlane/WorkflowGradleInvocations.java | 24 ++- .../config/EnvContractVerifierTest.java | 130 +++++++++++++--- .../WorkflowGradleInvocationsTest.java | 34 ++++ src/composition/idempotency/README.md | 8 +- src/composition/service-runtime/README.md | 3 +- .../PermissionEnforcementGuard.java | 15 +- ...rpcOperationLedgerMigrationLockWaitIT.java | 26 +++- .../ledger/GrpcOperationLedgerMigrations.java | 57 +++++-- .../src/main/resources/application.yml | 4 +- .../SampleMigrationLockWaitTest.java | 18 +-- .../shared/error/OperationalError.java | 3 +- 77 files changed, 1876 insertions(+), 410 deletions(-) create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableChildEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableParentEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerCourseEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerStudentEntity.java create mode 100644 src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java create mode 100644 src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFiles.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/adapter/inbound/messaging/SystemCallerHandlerRegistrationFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/messaging/jaxrs/JaxRsSystemCallerFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/scheduler/SystemCallerWithNestedEndpointFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/scheduler/SystemJobLauncherFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemCallerInvokingControllerFixture.java create mode 100644 src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/adapter/inbound/web/controller/SystemCallerRelayingControllerFixture.java delete mode 100644 src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/MetadataScope.java diff --git a/docs/fileserver/operations.md b/docs/fileserver/operations.md index cc7a14b0..33fd2cfb 100644 --- a/docs/fileserver/operations.md +++ b/docs/fileserver/operations.md @@ -133,7 +133,8 @@ Never delete staging content to clear a backlog: an upload that is mid-flight wi with the bytes its files actually hold. The known cause is history: before the 2026-11 maturity review, `move` relocated a file without moving its quota. The bytes of every file moved before that fix are still booked on the namespace it left, and deleting such a file reclaims from the namespace -it now lives in, where the reclaim stops at zero and leaves the old booking behind. A derived +it now lives in: the reclaim draws down the bookings of that namespace's other files, newest first, +or stops at zero, and the old booking stays behind either way. A derived service that moved files across namespaces before taking the fix has this drift; one that never did should see none. @@ -169,7 +170,8 @@ fileserver's writes stopped. To correct a namespace, stop every fileserver write to it first — uploads, copy, move, delete, and the cleanup worker (`APP_FILESERVER_PLATFORM_CLEANUP_ENABLED=false`) — because the statement below recomputes from `fs_file` and a publish or reclaim that lands between its two steps would be lost. -It zeroes the namespace's committed rows and books the recomputed total as one row; the per-row +It zeroes the namespace's committed rows and books the recomputed total as one row, shaped the way a +publish leaves one (`COMMITTED`, `reserved_bytes` 0, the bytes in `committed_bytes`); the per-row split has no meaning once reclaims have drawn rows down, and enforcement only ever reads the sum. `RESERVED` rows (uploads in progress) are left alone. @@ -183,7 +185,7 @@ UPDATE fs_quota_reservation INSERT INTO fs_quota_reservation ( reservation_id, scope_type, scope_value, reserved_bytes, committed_bytes, expires_at, status, version, created_at, updated_at) -SELECT gen_random_uuid(), 'namespace', :'namespace', held, held, +SELECT gen_random_uuid(), 'namespace', :'namespace', 0, held, now(), 'COMMITTED', 0, now(), now() FROM (SELECT coalesce(sum(actual_size), 0) AS held FROM fs_file diff --git a/docs/httpclient/configuration-reference.md b/docs/httpclient/configuration-reference.md index 7172e5c2..c694fa9b 100644 --- a/docs/httpclient/configuration-reference.md +++ b/docs/httpclient/configuration-reference.md @@ -103,10 +103,12 @@ greater than zero (`TIMEOUT_NOT_POSITIVE`): both engines read zero as "wait fore `total-call` also bounds the setup of a streaming download — connect, send, and the wait for response headers. Once the stream is handed over, each gap of the body is bounded by `read-idle` instead, so a long download is not cut at an arbitrary total (design §15.3). This holds on both -transports. The JDK transport keeps its exchange-wide timeout off a streamed body and bounds each -read with its own `read-idle` timer, because the JDK client has no socket read timeout; before -review 2026-11-03 RR-04-03 every JDK download longer than `response-header` was cut mid-body. A body -failure after hand-over is thrown from `read` as `HttpBodyReadException` — an `IOException`, as +transports. The JDK transport keeps its exchange-wide timeout off a streamed body, and a per-stream +watchdog bounds each read's wait by `read-idle`, because the JDK client has no socket read timeout. +The watchdog wakes on one daemon thread of its own (`httpclient-jdk-read-idle`), not on the common +`ForkJoinPool`, so a service that fills that pool with blocking work does not delay it (re-review +2026-11-04 RR3-03-01). Before review 2026-11-03 RR-04-03 every JDK download longer than +`response-header` was cut mid-body. A body failure after hand-over is thrown from `read` as `HttpBodyReadException` — an `IOException`, as `InputStream` promises, so `catch (IOException)` still sees it — whose `failure()` is `HttpResponseTimeoutException` (a wait longer than `read-idle`) or `HttpResponseTruncatedException` (the connection ended early), stage `RESPONSE_BODY`, evidence `PARTIAL_RESPONSE` (re-review diff --git a/docs/jpa/entity-mapping-guide.md b/docs/jpa/entity-mapping-guide.md index 8c3b39d7..2a09c7d5 100644 --- a/docs/jpa/entity-mapping-guide.md +++ b/docs/jpa/entity-mapping-guide.md @@ -85,7 +85,10 @@ reason those are ID references. 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). That last check also refuses two entities that each hold their own foreign key to the +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 diff --git a/docs/jpa/migration-guide.md b/docs/jpa/migration-guide.md index d79e63c8..04de288c 100644 --- a/docs/jpa/migration-guide.md +++ b/docs/jpa/migration-guide.md @@ -45,20 +45,33 @@ rolls it back whole, the database stays on the version before it and the new rel start: a failed deploy instead of an outage. Deploy again when the transaction has ended. `LOCAL`, because a plain `SET` outlives the migration on the pooled connection Flyway borrowed and -changes every statement that later runs on it. A statement on a table the same migration created a -moment earlier waits for nothing and needs no bound. +changes every statement that later runs on it. The value is not zero: `lock_timeout = 0` (or +`DEFAULT`, or a later `RESET`) is no bound at all. A migration with `executeInTransaction=false` +cannot use it — `SET LOCAL` outside a transaction only warns — so a statement that locks a table +goes into a migration that runs in one. A statement on a table the same migration created a moment +earlier waits for nothing and needs no bound; `CREATE TABLE IF NOT EXISTS` does not count, because +the table may already be there. -Enforced, not remembered: `LockWaitMigrationInspector` (persistence-jpa testkit) reads a script -and names every statement that locks an existing table before the bound. `MigrationLockWaitTest` -runs it over every tree this leaf's database runs, `SampleMigrationLockWaitTest` over the sample's -stream; a service stream copies the latter with its own directory. 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`) and the gRPC ledger's -`GrpcOperationLedgerMigrationLockWaitIT` show on real PostgreSQL that a bounded migration gives up -within the bound while another transaction holds the table, and leaves the version below it. The -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). +Enforced, not remembered: `LockWaitMigrationInspector` (persistence-jpa testkit) reads a script — +and the `.sql.conf` beside it — and names the statements from its list that lock an existing table +with no bound in force: `ALTER TABLE`, `LOCK TABLE`, `TRUNCATE`, `DROP TABLE`; `CREATE INDEX`, +`DROP INDEX`, `REINDEX` and `REFRESH MATERIALIZED VIEW` without `CONCURRENTLY`, `CLUSTER`, `VACUUM +FULL`; `REFERENCES` on the table it references, in a new table as much as in an `ALTER TABLE` (a +foreign key locks its parent against writes while it is added); `CREATE TRIGGER` and `DROP TRIGGER` +on their table; `UPDATE` and `DELETE`. It reads text, so a statement outside the list is not +checked. `MigrationLockWaitTest` runs it over every tree this leaf's database runs, +`SampleMigrationLockWaitTest` over the sample's stream; a service stream copies the latter with its +own directory. Both find the migrations the way Flyway does, decimal versions (`V22_1__`) included +(`VersionedMigrationFiles`, testkit). The migrations released before the rule wait unbounded and +stay that way (they are applied, and applied files are never edited); the test lists them and +refuses any new one. `PostgreSqlMigrationLockWaitIntegrationTest` +(`postgresqlMigrationLockWaitIntegrationTest`) shows on real PostgreSQL that a bounded migration +gives up within the bound while another transaction holds the table, and leaves the version below +it. The gRPC ledger's tree lives in the optional build, which cannot reach the testkit: its +`GrpcOperationLedgerMigrationLockWaitIT` runs every ledger migration after V001, read from the tree, +against a held ledger instead, so its next migration is checked on real PostgreSQL. The rule came +from V21 having the bound and V22, in the same commit, not having it (re-review 2026-11-03 round 2, +RR-02-09; round 3, RR3-02-01, RR3-02-03, RR3-02-04). ## Concurrent index builds diff --git a/docs/manual/04-persistence.md b/docs/manual/04-persistence.md index ec7e99dd..663319ce 100644 --- a/docs/manual/04-persistence.md +++ b/docs/manual/04-persistence.md @@ -128,8 +128,10 @@ capability 스트림 db/migration/jpa/ 각자 histor (리뷰 README 13.2, 09-02). - 기존 데이터가 새 제약을 어기면 마이그레이션이 이유를 남기고 멈추게 쓴다(`V8_1`의 `DO $$` 블록). 조용히 지우지 않는다. -- 운영 중인 테이블을 잠그는 문장(`ALTER TABLE`, `CONCURRENTLY` 없는 `CREATE INDEX`, `UPDATE`·`DELETE`)이 있으면 - 그 앞에 `SET LOCAL lock_timeout = '5s';`를 둔다(`V8_1`, `V22`). 상한이 없으면 그 테이블을 건드린 열린 +- 운영 중인 테이블을 잠그는 문장(`ALTER TABLE`, `CONCURRENTLY` 없는 `CREATE INDEX`, `UPDATE`·`DELETE`, 기존 + 테이블을 가리키는 `REFERENCES`, trigger 만들기·지우기 등 — 전체 목록은 `docs/jpa/migration-guide.md`)이 있으면 + 그 앞에 `SET LOCAL lock_timeout = '5s';`를 둔다(`V8_1`, `V22`). 값은 0이 아니어야 하고, + `executeInTransaction=false` 마이그레이션에서는 `SET LOCAL`이 효과가 없으니 잠그는 문장을 거기 두지 않는다. 상한이 없으면 그 테이블을 건드린 열린 트랜잭션 하나(`ALTER TABLE`이면 읽기만 한 것도) 뒤에서 마이그레이션이 끝없이 기다리고, 그동안 뒤에 온 그 테이블의 쓰기(`ALTER TABLE`이면 읽기까지)가 모두 마이그레이션 뒤에 줄을 선다. 상한이 있으면 5초 뒤 실패·롤백되고 새 버전이 뜨지 않을 뿐이다. 자기 스트림에도 `SampleMigrationLockWaitTest`처럼 `LockWaitMigrationInspector`(persistence-jpa testkit) 검사를 둔다 diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md index 0effa752..629ea091 100644 --- a/docs/manual/05-idempotency.md +++ b/docs/manual/05-idempotency.md @@ -57,7 +57,10 @@ DB 커밋 중 연결 끊김 ───────────────── 같은 키 재전송은 작업을 다시 돌리지 않는다. 첫 시도가 실행을 시작한 뒤 processing lease(기본 30s)가 지나면 두 저장소 모두 그 기록을 넘겨주지 않고 500 `IDEMPOTENCY_RECOVERY_REQUIRED`로 답한다. 넘겨받는 것은 실행 전 claim과 재시도 가능한 실패뿐이다. 기록은 lease + `replay-ttl` 동안 남고, `replay-ttl`이 lease보다 -짧으면 기동이 실패한다(`IdempotencyStoreContract`, 재리뷰 2026-11-04 RR-01-11·RR-03-11). +짧으면 기동이 실패한다(`IdempotencyStoreContract`, 재리뷰 2026-11-04 RR-01-11·RR-03-11). 작업이 실패로 +끝나 executor가 포기나 재시도 가능으로 표시한 기록은 표시한 때부터 `failure-retention`(기본 24h) 동안 +남는다. 이 값은 검사하지 않으므로 `replay-ttl` 이상으로 둔다. 짧으면 효과 불명으로 포기한 기록이 먼저 +사라져 같은 키 재전송이 작업을 다시 돌린다(RR3-03-02). 409를 `retryable=true`로 바꾼 이유(리뷰 02-01 결정): 같은 키 재전송은 서버가 안전하게 판정하므로 다시 보내는 것이 맞고, 새 키로 보내면 서버가 막지 못한다. 짝 프론트 분류기도 이 표를 따른다. diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index a6b8443a..0c1104fd 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -72,22 +72,45 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re ```text 사용자 요청 ─▶ web·GraphQL·gRPC·WebSocket ──✗──▶ @SystemInvoked 유스케이스 (빌드 실패) +사용자 요청 ─▶ web·GraphQL·gRPC·WebSocket ──✗──▶ @SystemCaller (빌드 실패, 중간 클래스를 거쳐도) 시스템 ─▶ 스케줄러(조립 모듈이 new로 넘김) ─────▶ @SystemInvoked 유스케이스 시스템 ─▶ 메시지 handler(@SystemCaller, 직접 new) ─▶ @SystemInvoked 유스케이스 +시스템 ─▶ 예약 작업(@SystemCaller, 직접 new) ──────▶ @SystemInvoked 유스케이스 어디서든 ─▶ @SystemInvoked 유스케이스를 bean으로 등록 ──✗ (기동 실패) ``` - 사용자 전송: 사용자가 보낸 요청이 들어오는 inbound adapter다(web·GraphQL·gRPC·WebSocket). - 시스템 호출자: broker 전달이나 시간(tick)이 깨우는 코드다. 사용자 요청은 여기로 들어오지 않는다. +시스템 호출자가 `@SystemInvoked` 유스케이스를 얻는 길은 아래 셋뿐이다. 이 표가 정본이고, 다른 문서는 이 +절을 가리킨다. + +| 경로 | 어디에 두나 | 유스케이스는 누가 만드나 | +| --- | --- | --- | +| 조립 모듈의 스케줄러 | `composition:*` leaf. 예: outbox relay(`src/composition/outbox-relay`) | 조립 모듈의 `@Bean` 메서드가 `new`로 만들어 스케줄러에 넘긴다 | +| 메시지 handler | `adapter:inbound:messaging` leaf, 또는 서비스 leaf의 `..adapter.inbound.messaging..` 패키지 | handler 생성자가 port를 받아 `new`로 만든다. handler에 `@SystemCaller`. 작업 순서는 09장 「소비」 4단계 | +| 예약 작업 | 서비스 자기 leaf의 `..adapter.inbound.scheduler..` 패키지. 등록된 scheduler leaf는 없다 | 작업 클래스 생성자가 port를 받아 `new`로 만든다. 작업 클래스에 `@SystemCaller`. 모양은 메시지 handler와 같고, 깨우는 것이 `@Scheduled` 메서드다 | + +예약 작업은 controller와 같은 leaf에 놓이기 쉽다. 그때 "지금 실행" endpoint가 작업 bean을 주입받아 부르면 +권한 검사 없는 쓰기를 사용자가 부르게 된다. 아래 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`가 이것을 +빌드에서 막는다. 사용자도 같은 일을 시켜야 하면 `@RequiresPermission`을 단 사용자용 유스케이스를 따로 +만든다(아래 D4 문단). + | 규칙 | 무엇을 막나 | 어디 | | --- | --- | --- | | bean 금지 | `@SystemInvoked` 유스케이스가 bean이면 기동 실패. 호출자가 `new`로 만들어 혼자 들고 있는 것만 허용한다 | `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java` | -| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | -| 표시 검사 | `@SystemCaller`는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·GraphQL·STOMP mapping·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) | +| 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스와 그 안에 중첩된 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | +| 표시 검사 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·JAX-RS·GraphQL·STOMP mapping·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) | +| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 사용자 전송 패키지에 있거나 사용자 전송 타입에 의존하는 클래스다. 그래서 handler를 bean으로 등록하는 `@Configuration`은 걸리지 않는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) | -규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 그래서 나중에 새 전송이 생겨도 따로 -고치지 않아도 막힌다. 메시지 소비자의 작업 순서는 09장 「소비」 4단계다. +규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 이 성질은 **패키지** 쪽에서만 온다. +패키지는 허용 목록이라, 나중에 새 전송 패키지가 생겨도 따로 고치지 않아도 막힌다. 사용자 전송 **타입** +쪽은 나열 목록이다(`ARE_USER_TRANSPORT_TYPES`). 시스템 패키지 안에 놓인 endpoint를 알아보는 데 쓰는 +목록이라, 목록에 없는 전송 라이브러리로 만든 endpoint는 전송으로 보이지 않는다. 새 전송 라이브러리를 +들이면 그 패키지를 이 목록에 더한다. + +이 규칙들은 클래스 의존만 본다. 실행 중에 bean을 찾는 코드(`getBean`, `ObjectProvider`)는 의존이 아니라서 +잡지 못한다. D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표시를 쓰지 않는다. 사용자가 부르는 쓰기라면 권한을 선언하고 역할에 매핑한다. 같은 쓰기를 사용자도 시스템도 부르면 유스케이스를 둘로 나눈다 @@ -102,7 +125,8 @@ web이 빠진 조립(gRPC 전용·배치 전용)에는 `@RequiresPermission`을 ## 지금 이해하면 되는 것 - 쓰기 = `@RequiresPermission` + non-final + bean + 역할 매핑. -- 시스템만 부르는 쓰기 = `@SystemInvoked` + bean 아님 + 사용자 전송에서 안 닿음. 부르는 쪽은 스케줄러 - 조립이나 `@SystemCaller` 메시지 handler뿐이다. +- 시스템만 부르는 쓰기 = `@SystemInvoked` + bean 아님 + 사용자 전송에서 안 닿음. 부르는 쪽은 셋뿐이다: + 조립 모듈의 스케줄러, `@SystemCaller` 메시지 handler, `@SystemCaller` 예약 작업. 사용자 전송은 + `@SystemCaller`에도 닿지 못한다. - 객체 판정은 유스케이스 안, 남의 것은 404. - 역할은 자기 client 것만 읽는다. diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 85391be2..130556ce 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -1681,6 +1681,10 @@ env_keys: required_test: redis-idempotency-contract:processing-lease-bounded - name: APP_IDEMPOTENCY_FAILURE_RETENTION + # app.capabilities.idempotency.failure-retention: how long a record the executor marked failed + # (abandoned with an unknown effect, or retryable without one) stays, from the marking. Not + # compared with APP_IDEMPOTENCY_TTL at startup; keep it at least that long, or an abandoned + # record goes first and a same-key resend runs the work again (re-review 2026-11-04 RR3-03-02). type: duration default: 24h allowed_values: null diff --git a/docs/reviews/2026-11-03-rereview/README.md b/docs/reviews/2026-11-03-rereview/README.md index 55545e28..17946aae 100644 --- a/docs/reviews/2026-11-03-rereview/README.md +++ b/docs/reviews/2026-11-03-rereview/README.md @@ -208,3 +208,33 @@ Minor 19건 중 동작에 닿는 것: ### 11.1 결정 리뷰 반복은 여기서 멈춘다. Minor 19건은 사용자 지시("남은 부분 전부 진행")에 따라 마지막 정리 라운드(r6)로 고친다. r6의 멈춤 기준: 전체 게이트 통과 + r6 diff 확인 리뷰 1회에서 Important가 나오면 그것만 고치고, Minor는 남은 것으로 기록하고 더 돌지 않는다. + +## 12. 마지막 정리 라운드 r6 (Minor 19건, 2026-11-04) + +11.1절 결정대로 3차 확인 리뷰의 Minor 19건을 영역 묶음 4개가 `339cf8fd`에서 `test-driven-development` 절차로 고쳤다. 맡은 Minor 밖은 고치지 않고 보고만 하게 했다. + +| 묶음 | 발견 | 상태 | 검증 (에이전트) | 처리 내용 | 결정·남은 것 | +|---|---|---|---|---|---| +| r6-a core·inbound | RR3-01-01~04 | 완료 | application-core·service-runtime·inbound messaging·app-bootstrap check(systemTest 포함), architectureTest 208, architectureCheck, 실 PG16 | RR3-01-01 `@SystemCaller` 안의 중첩 클래스도 검사, 새 규칙 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(사용자 전송 → `@SystemCaller`를 직접·중간 클래스 경유 모두 거부, RED 3). RR3-01-02 전송 타입 목록에 `jakarta.ws.rs..`·`graphql..`(RED JAX-RS)와 "목록 방식" 문서. RR3-01-03 쿼터 보정 SQL이 COMMITTED 행 `reserved_bytes`를 0으로(RED 실 PG). RR3-01-04 scheduler·handler·예약 작업 세 경로를 매뉴얼 07장 표로 정본화하고 Javadoc·README·가드 문구를 맞춤 | 새 규칙은 직접 의존이 아니라 이어지는 의존 전체를 본다(중간 클래스 하나로 다시 열리지 않게, 실행 5.7초). 남음: `graphql..` 항목은 fixture 없음(graphql-java가 architectureTest classpath에 없다) | +| r6-b persistence·messaging | RR3-02-01~05 | 완료 | persistence-jpa check 611, sample check 339, `-p optional-platforms` grpc ledger check·integrationTest 46, `postgresqlMigrationLockWaitIntegrationTest` 5/5, outbox runbook lane, documentContractTest 62, architectureCheck | RR3-02-01 검사기가 `REFERENCES`·trigger·비동시 `REINDEX`·`REFRESH MATERIALIZED VIEW`·`CLUSTER`·`VACUUM FULL`을 잡고, `lock_timeout` 0·`DEFAULT`·`RESET`과 비트랜잭션(`.sql.conf executeInTransaction=false`) `SET LOCAL`을 상한으로 치지 않음(RED 19). 새로 걸린 배포 파일 5개는 내용 그대로 동결 목록에(main과 blob 같음). RR3-02-02 원인 세션을 `pg_locks`로 찾는 runbook 조회(실 PG). RR3-02-03 버전 판정을 testkit `VersionedMigrationFiles` 하나로(RED `V22_1`·`V22.2`). RR3-02-04 grpc ledger IT가 tree 전체 검사(RED). RR3-02-05 연관 규칙 메시지(RED 2) | grpc는 optional 빌드라 testkit을 못 써 실 PG IT로 검사(버전 정규식 한 벌 더). 남음: `spotbugsTestFixtures`(게이트 밖) ReDoS 경고 8→15 | +| r6-c outbound·멱등성 | RR3-03-01~05 | 완료 | 6개 leaf check, architectureCheck, verifyEnvKeys, redisContainerContractTest 59/59, PG 멱등성 계약 20/20, httpclient 성능 5·장애 주입 4, documentContractTest 62, repositoryContractTest 69 | RR3-03-01 watchdog을 전용 데몬 스레드(`httpclient-jdk-read-idle`)로, close 시 작업 취소(RED 공용 풀 포화 시 300ms 설정이 5,995ms → 수정 후 300ms, read당 비용 21–24ns 그대로). RR3-03-02 `failure-retention` 수명 문서. RR3-03-03 회복 필요 예외 메시지 끝에 scope digest(RED 3), runbook에 Redis·PG 기록 조회와 ABANDONED만 지우는 절차(실 Redis 7.4·PG 16). RR3-03-04 옛 표현. RR3-03-05 INSPECT가 `leaseUntil`을 돌려줌(RED 실 Redis) | `failure-retention ≥ replay-ttl` 기동 검사는 넣지 않음(지금 뜨는 설정을 깨지 않게, 문서만 — 소유자 판단). 본 것: gRPC는 carrier 실패를 로그에 남기지 않아 digest를 찾을 수 없다 | +| r6-d bootstrap·build | RR3-04-01~05 | 완료(RR3-04-03은 문서) | `-p build-logic check`, support·redis-sdk·sample·app-bootstrap check, verifyEnvKeys, 두 빌드 verifyStrictLaneStages, systemTest 11, documentContractTest 62, `SampleDemoProfilesStartupSystemTest` 3 | RR3-04-01 규칙을 돌리기 전에 비밀 목록 bean을 만들어 실제 클래스를 검사(모든 프로필, RED). RR3-04-02 붙여 쓴 `-x`·`-p`(RED). RR3-04-03 코드가 든 Redis 계정 참조는 조립하는 쪽이 `static RequiredProductionSecrets` bean을 두는 방법을 문서로. RR3-04-04 "선언된 property" 계산을 classpath 기준 하나로(RED). RR3-04-05 주석 | RR3-04-03 코드 수정은 redis-sdk에 새 의존 edge가 필요하거나 G-7c 결정을 되돌려야 해서 하지 않음. 남음: `-mx` 같은 짧은 플래그 묶음은 읽지 않음, 바뀐 기동 실패 문구에 맞추던 로그 매처 | + +합칠 때 오케스트레이터: 업그레이드 안내 B-14·B-15(r6-d)와 B-16(r6-a)을 손으로 합쳤고, r6-c가 남긴 동작 변경 두 줄(JDK watchdog 스레드, 회복 필요 메시지의 scope digest·INSPECT `leaseUntil`)을 5절에 더했다. + +### 12.1 게이트 (2026-11-04, 합친 메인 작업 트리, 공유 잠금) + +첫 실행에서 모두 통과했다. + +| 게이트 | 결과 | 시간 | 실행 직전 부하(1분) | +|---|---|---|---| +| `ci` | rc=0 | 6분 22초 | 2.31 | +| `verifyStrictLaneStages --dry-run` (주 빌드 / `-p optional-platforms`) | rc=0 / rc=0 | 11초 / 3초 | 16.09 / 14.51 | +| `mainCheck` | rc=0 | 3분 10초 | 13.90 | +| `:integrationCheck` | rc=0 | 14분 27초 | 10.98 | +| `-p optional-platforms ci integrationCheck performanceCheck` | rc=0 | 1분 | 2.32 | +| `:performanceCheck` | rc=0 | 22초 | 9.95 | +| `:releaseCheck -PgitRevision=` | rc=0 | 3초 | 7.81 | +| `scripts/verify-compose-profile-contracts.sh` | rc=0, 18 lane | — | 8.31 | + +다음: 이 커밋만 보는 확인 리뷰 1회. Important가 나오면 그것만 고치고, Minor는 남은 것으로 기록한다(11.1절). diff --git a/docs/runbooks/idempotency-unavailable.md b/docs/runbooks/idempotency-unavailable.md index 423a05cc..cf32d735 100644 --- a/docs/runbooks/idempotency-unavailable.md +++ b/docs/runbooks/idempotency-unavailable.md @@ -4,7 +4,7 @@ category: TRANSIENT_DEPENDENCY error_codes: [IDEMPOTENCY_UNAVAILABLE, IDEMPOTENCY_COMPLETION_UNKNOWN, IDEMPOTENCY_RECOVERY_REQUIRED] severity: P2 owner: oncall -last_updated: 2026-11-03 +last_updated: 2026-11-04 status: active --- @@ -18,11 +18,18 @@ status: active `app.idempotency` selects) did not answer. Nothing was executed: the refusal happens before the action, so a client retry is safe. - 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. Effects in the action's - own transaction rolled back; anything else it did (an outbound call, a message) may have happened. - This is not "nothing was executed". Clients resend with the same key. + 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 external effect already happened. + cannot tell whether an earlier attempt's effect already happened. The usual cause: an attempt + started and its processing lease (`APP_IDEMPOTENCY_PROCESSING_LEASE`, 30s) ran out before it + recorded a result — it crashed, or ran longer than the lease. The next request with the key marks + the record abandoned and every later one gets this 500; the server never runs it again, and a late + result from the first attempt is not recorded either. An action that threw, or reported its effect + unknown, is abandoned the same way. ## Diagnosis @@ -30,8 +37,37 @@ status: active 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 digest in the server log line of the failed - request and inspect that record's state in the store. +- For `IDEMPOTENCY_RECOVERY_REQUIRED`, find the scope in the server's ERROR log of the failed request + (the web adapter logs `failure classified as IDEMPOTENCY_RECOVERY_REQUIRED` with the exception, + under the request's `X-Request-Id`). The exception message ends with + `::v::`, 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 is + `:::idem:v1:d::`, + for example `prod:order:shared:idem:v1:d1:CHARGE_CARD:3f9a…`. + + ``` + HMGET state attempt leaseUntil + PTTL + ``` + + `state` `ABANDONED` is the recovery-required record. `leaseUntil` is the lease end in epoch + milliseconds (server clock); `PTTL` is how long the record still lives, in milliseconds. + - PostgreSQL, in the application's schema: + + ```sql + SELECT status, attempt, failure_disposition, last_transition_kind, + processing_lease_until, expires_at, updated_at + FROM idempotency_record + WHERE record_version = 2 + AND scope_hash = ''; + ``` + + `last_transition_kind` `EXPIRED_EXECUTION` means the lease ran out (the first attempt may still + have finished its work); `FAIL_ABANDONED` means the action threw or reported its effect unknown. + `expires_at` is when the reaper deletes the row. ## Action @@ -40,9 +76,29 @@ status: active 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. Confirm whether the - downstream effect of the earlier attempt exists, then complete or release the record so the next - request with that key replays or re-executes deterministically. +- `IDEMPOTENCY_RECOVERY_REQUIRED`: do not ask the client to retry blindly. Confirm from business data + (the order, the payment, the downstream system) whether the earlier attempt's 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 in progress or a stored result: + - Redis: check `HMGET state` is `ABANDONED` and `PTTL ` has minutes left, then + `DEL `. A record that is about to expire needs nothing; once it is gone the key is new. + - PostgreSQL: + + ```sql + DELETE FROM idempotency_record + WHERE record_version = 2 + AND scope_hash = '' + AND status = 'ABANDONED'; + ``` + + Without either step the key is released when the record expires. That record lives for the + processing lease plus `APP_IDEMPOTENCY_TTL` from its claim when its lease ran out, and for + `APP_IDEMPOTENCY_FAILURE_RETENTION` from the failure when the action failed + (`docs/web/http-contract.md`, "서버가 기억하는 기간"). ## Escalation diff --git a/docs/runbooks/migration-failed.md b/docs/runbooks/migration-failed.md index 4a1c5c32..a2988d75 100644 --- a/docs/runbooks/migration-failed.md +++ b/docs/runbooks/migration-failed.md @@ -44,9 +44,20 @@ status: active 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: `SELECT pid, state, xact_start, query FROM - pg_stat_activity WHERE xact_start < now() - interval '5 seconds' ORDER BY xact_start;`. End - it, then rerun (`docs/jpa/migration-guide.md` "Bound the lock wait"); + often an idle-in-transaction session. Find it by the lock it holds on that table (`` + is the table the failing statement locks; for a `REFERENCES`, also the table it references): + + ```sql + SELECT DISTINCT a.pid, a.state, a.xact_start, a.query + FROM pg_locks l JOIN pg_stat_activity a USING (pid) + WHERE l.relation = '
'::regclass AND l.granted AND a.pid <> pg_backend_pid() + 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; diff --git a/docs/runbooks/outbox-dead-letter.md b/docs/runbooks/outbox-dead-letter.md index 1ccd6d13..0e6b4375 100644 --- a/docs/runbooks/outbox-dead-letter.md +++ b/docs/runbooks/outbox-dead-letter.md @@ -129,8 +129,17 @@ V20(`deferred_attempt_count`)과 V22(`last_failure_code`)도 같은 상한을 둘 다 `ALTER TABLE outbox_event`라 가장 강한 잠금(ACCESS EXCLUSIVE)을 건다. 이 잠금은 읽기와도 충돌하므로, `outbox_event`를 읽기만 한 트랜잭션 하나(운영자가 `BEGIN` 안에서 조회하고 둔 psql 세션 포함)가 열려 있어도 기다린다. 5초 안에 못 잡으면 그 마이그레이션이 실패·롤백되고 DB는 한 버전 아래(V19 또는 V21)에 남으며 새 버전은 -기동하지 않는다(`MIGRATION_FAILED`, exit 70). 열린 트랜잭션을 찾아 끝낸 뒤 다시 배포한다 — -`SELECT pid, state, xact_start, query FROM pg_stat_activity WHERE xact_start < now() - interval '5 seconds' ORDER BY xact_start;` +기동하지 않는다(`MIGRATION_FAILED`, exit 70). `outbox_event`에 잠금을 쥔 열린 트랜잭션을 찾아 끝낸 뒤 다시 배포한다. + +```sql +SELECT DISTINCT a.pid, a.state, a.xact_start, a.query +FROM pg_locks l JOIN pg_stat_activity a USING (pid) +WHERE l.relation = 'outbox_event'::regclass AND l.granted AND a.pid <> pg_backend_pid() +ORDER BY a.xact_start; +``` + +`query`는 그 세션의 마지막 문장일 뿐이다. `outbox_event`를 읽은 뒤 다른 문장을 실행한 세션이면 표 이름이 보이지 +않으니 `query`로 원인을 고르지 않는다. 오래 열린 트랜잭션을 모두 보는 조회는 보고·배치 같은 무관한 트랜잭션까지 낸다. rolling 배포 중 아직 옛 버전인 인스턴스가 벽시계 번호로 쓴 행은 floor보다 크다. 새 버전의 counter는 그 aggregate의 가장 큰 행 번호보다 작아지지 않으므로 그 행 뒤에 번호를 준다. 서로 커밋되지 않은 채 diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index 995b634a..1a6f5cbc 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -22,7 +22,7 @@ | 1 | JWT 모드면 `APP_SECURITY_JWT_AUDIENCE`에 이 서비스의 client id를 쉼표로 넣는다 | 기동 실패 `APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required` | JWT 모드(기본값) 전부 | | 2 | dev·prod 환경 변수의 `APP_FLYWAY_ENABLED` 값을 확인한다 | `false`가 남아 있으면 이제 정말로 마이그레이션이 안 돈다 | persistence-jpa 선택 | | 3 | prod 비밀값(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/`이 가리키는 변수)이 `fixture-`로 시작하지 않게 한다 | prod 기동 실패(exit 78) | prod 배포 전부 | -| 4 | 직접 만든 `StartupRule`·`RequiredProductionSecrets` bean을 `static @Bean`, 의존성 없이 바꾸고, 그 클래스에서 `@Value`·`@Autowired` 멤버와 `@ConfigurationProperties`를 뺀다 | 기동 실패 `startup rule '<이름>' created [...]` 또는 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one`(exit 78) | 자기 rule이 있는 서비스 | +| 4 | 직접 만든 `StartupRule`·`RequiredProductionSecrets` bean을 `static @Bean`, 의존성 없이 바꾸고, 그 클래스에서 `@Value`·`@Autowired` 멤버와 `@ConfigurationProperties`를 뺀다 | 기동 실패 `startup rule or secret list '<이름>' created [...]` 또는 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one`(exit 78) | 자기 rule이 있는 서비스 | | 5 | 직접 구현한 outbox·발행·알림·파일 서버 포트를 새 시그니처로 고친다(3.1절) | 컴파일 오류 | 해당 포트를 구현·호출하는 서비스 | | 6 | `dev.caskeleton.application.outbound.*` import를 `application.secret.*`·`application.objectstorage.content.CallBudget`으로 바꾼다 | 컴파일 오류 | 해당 타입을 쓰는 서비스 | | 7 | 이벤트 id를 소문자 UUIDv7로 만들고 `IntegrationEventDraft`는 `IntegrationEventDrafts.draft(...)`로만 만든다 | 쓰기 요청이 `IllegalArgumentException`으로 실패, architectureTest 실패 | 통합 이벤트를 내는 서비스 | @@ -66,9 +66,9 @@ |---|---|---|---|---| | B-12 | JWT 모드에서 `APP_SECURITY_JWT_AUDIENCE` 필수(빈 값 거부, `${...}`가 안 풀린 값도 없는 값으로 봄). 토큰 `aud`가 목록 중 하나를 담아야 통과. `resource_access` role은 audience에 적은 client 것만 읽는다(realm role은 그대로) | 기동 실패 `APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required`(exit 코드 확인 못 함). `.env.example`이 `APP_SECURITY_JWT_AUDIENCE=`(빈 값)를 싣고 있다. 다른 client의 role에 기대던 권한이 사라짐 | client id를 쉼표로 넣는다. 다른 client role로 권한을 받던 사용자가 있는지 IdP에서 확인 | `34565130`(필수·role), `1400dc15`(안 풀린 `${...}`) · `src/adapter/inbound/web/.../auth/JwtDecoderConfig.java`, `.../JwtToAuthenticatedPrincipalConverter.java`, `.../settings/SecuritySettings.java` | | B-13 | `app.security.*` strict 바인딩: 접두어 아래 오타 키, 또는 설정·placeholder 어디에도 쓰이지 않는 `APP_SECURITY_*` 환경 변수가 기동을 막는다 | 기동 실패(메시지는 `StrictSettingsBinder`가 키 이름을 담아 냄, 정확한 문구 확인 못 함) | 쓰지 않는 `APP_SECURITY_*` 변수를 지운다 | `5786126c` · `SecuritySettings.bind`, `src/adapter/outbound/support/.../StrictSettingsBinder.java` | -| B-14 | prod 프로필에서 `fixture-`로 시작하는 비밀값을 거부(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/` 참조 대상. `HOSTNAME`·앱 이름 같은 비밀 아닌 값은 보지 않는다 — RR2-04-01). Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로 | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` | -| B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다. 두 타입의 클래스는 `@Value`·`@Autowired`·`@Inject`·`@Resource` 멤버, `@PostConstruct`·`@PreDestroy`, `@ConfigurationProperties`를 가질 수 없다(post-processor보다 먼저 만들어져 비어 있게 된다, RR2-04-03) | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule '<이름>' created [] while creating it ... Declare the rule with a static @Bean method ...`, 위 멤버가 있으면 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one: [...]`(둘 다 exit 78, 후자는 모든 프로필) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 값은 `violations(Environment)`가 받는 `Environment`에서 읽는다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` | -| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르면 architectureTest 실패 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 호출자(scheduler 등)에 넘기거나, 메시지 handler면 handler에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다(매뉴얼 09장 「소비」 4단계). `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd` · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` | +| B-14 | prod 프로필에서 `fixture-`로 시작하는 비밀값을 거부(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/` 참조 대상. `HOSTNAME`·앱 이름 같은 비밀 아닌 값은 보지 않는다 — RR2-04-01). Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로. Redis SDK admin 계정(`RedisAccountContribution`)을 조립했다면 그 변수를 `static` `RequiredProductionSecrets` bean으로도 낸다(코드에 든 참조는 검사가 보지 않는다, RR3-04-03, `src/adapter/outbound/redis-sdk/README.md`) | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` | +| B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다. 두 타입의 클래스는 `@Value`·`@Autowired`·`@Inject`·`@Resource` 멤버, `@PostConstruct`·`@PreDestroy`, `@ConfigurationProperties`를 가질 수 없다(post-processor보다 먼저 만들어져 비어 있게 된다, RR2-04-03) | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule or secret list '<이름>' created [] while creating it ... Declare the rule with a static @Bean method ...`, 위 멤버가 있으면 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one: [...]`(둘 다 exit 78, 둘 다 모든 프로필. runner가 rule과 비밀 목록을 프로필과 무관하게 먼저 만들어, 인터페이스 타입 `@Bean`이 돌려준 실제 클래스까지 본다, RR3-04-01) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 값은 `violations(Environment)`가 받는 `Environment`에서 읽는다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` | +| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르거나, 사용자 전송(controller 등)이 `@SystemCaller` bean을 직접·중간 클래스를 거쳐 부르면 architectureTest 실패 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 스케줄러에 넘기거나, 메시지 handler·예약 작업이면 그 클래스에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다. 예약 작업은 서비스 leaf의 `..adapter.inbound.scheduler..` 패키지에 둔다. 세 경로와 두는 곳은 매뉴얼 07장 「시스템이 부르는 쓰기」(handler 작업 순서는 09장 「소비」 4단계). "지금 실행" endpoint가 필요하면 `@RequiresPermission` 유스케이스를 따로 만든다. `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd` · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` | | B-17 | `IntegrationEventDraft`: `eventId`·`causationId`는 소문자 UUIDv7만. ArchUnit `INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`: `new IntegrationEventDraft<>(...)` 금지, `IntegrationEventDrafts.draft(...)`만 | 이벤트를 만드는 쓰기 요청이 `IllegalArgumentException: eventId must be a canonical lower-case UUIDv7...`로 실패. architectureTest 실패 | event id를 UUIDv7로 만든다(예: sample `UuidOutboxEventIdFactory`가 `UuidCreator.getTimeOrderedEpochPlus1()`). draft는 헬퍼로 만든다. tenant가 없는 이벤트는 `IntegrationEventDrafts.SINGLE_TENANT_SCOPE`(`global`) | `1400dc15`, `bbe944bd` · `src/application-core/.../messaging/event/IntegrationEventDraft.java`, `IntegrationEventDrafts.java` | | B-18 | `MessageHandler.schemaVersions()`(vendored `messaging-core-api`, default `{v1}`): 소비자 decode 목록을 handler 선언으로 만든다. 같은 (메시지 타입, 버전)에 다른 payload class를 선언하면 실패 | 컴파일은 된다. v1이 아닌 메시지는 `SCHEMA_VERSION_NOT_REGISTERED`로 거부. 발행 등록(`MessageContracts`)과 class가 다르면 기동 실패 `MESSAGING_CONTRACT_CONFLICT` | v2 이상을 읽는 handler는 `schemaVersions()`를 override한다. 소비 타입을 `MessageContracts`에 따로 등록하던 코드는 지운다 | `5786126c` · `src/messaging/messaging-core-api/.../delivery/MessageHandler.java`, `messaging-spring-boot-starter/.../MessageContracts.java` | | B-19 | `APP_FLYWAY_ENABLED`가 모든 프로필에서 읽힌다. dev·prod 프로필 파일의 `spring.flyway.enabled: true`·`app.persistence.vendor` 고정값을 지우고 persistence-jpa `config/module-defaults`가 `${APP_FLYWAY_ENABLED:true}`를 싣는다 | dev·prod 환경에 `APP_FLYWAY_ENABLED=false`가 있으면 전에는 무시됐지만 이제 기동 때 마이그레이션이 안 돈다 | dev·prod 환경 값을 확인한다. 자기 `application-dev.yml`·`application-prod.yml`에 같은 고정값을 다시 넣지 않는다 | `5786126c` · `src/app-bootstrap/src/main/resources/application-{dev,prod}.yml`, `src/adapter/outbound/persistence-jpa/.../module-defaults/persistence-jpa.yml` | @@ -100,7 +100,7 @@ |---|---|---|---|---| | B-34 | 템플릿 패키지 규칙(ArchUnit): `FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`, `TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`. 템플릿 이름: application `usecase command query capability transaction security tenant observability secret messaging outbox idempotency operation lease lock cache realtime notification fileserver objectstorage`, domain `identifier stereotype` | 기능 패키지 이름이 이 목록과 겹치거나(예: `domain.lock`), 업무 코드를 템플릿 패키지(예: `application.usecase.*`)에 두고 기능 패키지를 import하면 `:app-bootstrap:architectureTest` 실패 | 기능 패키지 이름을 바꾸고, 업무 코드를 `dev.caskeleton.application.`로 옮긴다. 규칙 정본은 `src/application-core/CLAUDE.md` "Package ownership" | `5786126c` · `src/app-bootstrap/src/architectureTest/.../TemplatePackageOwnership.java` | | B-35 | JPA 규칙: 양방향 연관은 한쪽에서만 매핑(`mappedBy`), notification·fileserver 저장소 엔티티는 그 leaf 안에서만, `@Version` 엔티티의 bulk update는 version을 올려야 함 | 위반 엔티티·쿼리가 있으면 architectureTest 실패 | 매핑·쿼리를 고친다 | `34565130`, `1400dc15`, `bbe944bd` · `src/app-bootstrap/src/architectureTest/.../JpaProductionArchitectureTest.java` | -| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. 명령의 빌드는 `working-directory`(단계·job·workflow `defaults`)와 `-p`를 합친 디렉터리로 정하고, `workflow_dispatch`로만 시작하는 workflow의 명령은 세지 않으며, 축약한 `-x`도 Gradle처럼 맞춰 본다(RR2-04-04). `verifyEnvKeys`: lane 계약 json의 `APP_` 밖 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_`이거나 `secret://…/`가 가리키는 변수여야 하고, 레지스트리 `property:` 행은 그 property가 설정 metadata에 있어야 읽히는 것으로 친다(`@ConditionalOnProperty`로만 읽는 스위치는 `META-INF/additional-spring-configuration-metadata.json`에 선언, RR2-04-05). SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다. `working-directory: src` 없이 `./gradlew`를 부르는 자기 workflow 단계는 실행으로 세지 않는다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. 단계를 부르는 workflow 명령에 `working-directory`를 둔다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c` · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` | +| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. 명령의 빌드는 `working-directory`(단계·job·workflow `defaults`)와 `-p`를 합친 디렉터리로 정하고, `workflow_dispatch`로만 시작하는 workflow의 명령은 세지 않으며, 축약한 `-x`도 Gradle처럼 맞춰 본다(RR2-04-04). 붙여 쓴 `-x`·`-p`도 Gradle처럼 읽는다(RR3-04-02). `verifyEnvKeys`: lane 계약 json의 `APP_` 밖 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_`이거나 `secret://…/`가 가리키는 변수여야 하고, 레지스트리 `property:` 행은 그 property가 설정 metadata에 있어야 읽히는 것으로 친다(`@ConditionalOnProperty`로만 읽는 스위치는 `META-INF/additional-spring-configuration-metadata.json`에 선언, RR2-04-05). SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다. `working-directory: src` 없이 `./gradlew`를 부르는 자기 workflow 단계는 실행으로 세지 않는다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. 단계를 부르는 workflow 명령에 `working-directory`를 둔다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c` · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` | | B-37 | app-bootstrap 테스트 lane 분리: 저장소 파일을 읽는 테스트는 태그 `document-contract`(main 단계) 또는 `repository-contract`(`check`)여야 하고, 일반 `test` lane에는 `ca.repository.root`가 없다 | app-bootstrap에 둔 자기 테스트가 저장소 파일을 읽으면 `test`에서 실패 | 태그를 단다 | `1400dc15` · `src/app-bootstrap/build.gradle` | ### 3.5 모듈 registry·새 leaf @@ -132,6 +132,11 @@ `SET LOCAL lock_timeout = '5s'`를 둔다. 실패하면 SQLState `55P03`이고, 열린 트랜잭션을 끝낸 뒤 다시 배포한다 (`docs/runbooks/migration-failed.md` "Classify the failure"). 자기 스트림에도 같은 규칙과 검사 (`LockWaitMigrationInspector`, 예: `SampleMigrationLockWaitTest`)를 둔다(`docs/jpa/migration-guide.md` "Bound the lock wait"). + 검사기는 3차 확인 리뷰(RR3-02-01) 뒤로 기존 테이블을 가리키는 `REFERENCES`, trigger 만들기·지우기, `REINDEX` 등을 더 잡고, + `CREATE TABLE IF NOT EXISTS`를 "이 마이그레이션이 만든 테이블"로 세지 않으며, 0인 `lock_timeout`과 `executeInTransaction=false` + 파일의 `SET LOCAL`을 상한으로 세지 않는다. 자기 스트림의 이미 배포된 파일이 새로 걸리면 그 파일은 고치지 않고 규칙 이전 + 목록에 더한다(템플릿은 idempotency V1, notification V3, messaging V1003, postgresql V11·V12를 더했다). 파일 경로를 넘기는 + `unboundedLockingStatements(Path)`가 옆의 `.sql.conf`까지 읽으니, 복사한 검사는 문자열 대신 경로를 넘긴다. - **번호 충돌**: 템플릿이 이제 postgresql V20~V22, notification V11~V13, sample V8_1, grpc V002·V003을 쓴다. 파생 서비스가 같은 위치에 같은 번호를 두었다면 Flyway가 같은 버전 두 개로 실패한다. 자기 마이그레이션은 템플릿과 떨어진 번호대로 옮긴다 (이미 적용된 파일 이름을 바꾸면 checksum·history가 어긋나므로 운영 DB에 적용된 것이면 DB 담당과 정한다). @@ -212,6 +217,8 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | 로그 설정 | logback이 `APP_LOG_*` 대신 `app.logging.*`을 읽는다(환경 변수 이름은 그대로 매핑) | 프로필 yml의 `app.logging.*`이 이제 먹힌다 | `1400dc15` · `logback-spring.xml` | | local 프로필 | `server.port`가 `${APP_SERVER_PORT:8080}`을 읽는다. Flyway·`ddl-auto validate`·PostgreSQL vendor를 module-defaults에서 받는다 | local에서 `APP_SERVER_PORT`가 다른 값이면 포트가 바뀐다 | `1400dc15`, `5786126c` · `application-local.yml` | | deprecated | `APP_CACHE_REDIS_TTL_JITTER`는 아무것도 바인딩하지 않음(`removal_deadline: 2027-02-28`) | 값이 아무 효과 없다 | `1400dc15` · `env-keys.yaml` | +| HTTP client(JDK transport) | 스트리밍 응답의 read-idle 감시가 전용 데몬 스레드 하나(`httpclient-jdk-read-idle`)에서 돈다. 스트림마다 감시 작업 하나, 스트림을 닫으면 작업을 바로 취소 | 스레드 덤프에 그 스레드가 하나 보인다. 공용 `ForkJoinPool`이 바빠도 timeout이 설정값에 난다(전에는 늦게 났다). Apache transport(기본)는 영향 없음 | 3차 확인 리뷰 RR3-03-01 · `src/adapter/outbound/httpclient/.../jdk/ReadIdleInputStream.java` | +| 멱등성 | `IDEMPOTENCY_RECOVERY_REQUIRED`를 내는 예외 메시지 끝에 scope digest가 붙는다. Redis 기록 조회(INSPECT 스크립트)가 `leaseUntil`을 돌려줘 `processingLeaseUntil`이 실제 lease 끝이다(전에는 key TTL 끝, 즉 lease + replay TTL) | 예외 메시지 전체에 맞추던 로그 매처는 고친다. 회복 절차는 `docs/runbooks/idempotency-unavailable.md`(digest로 기록을 찾는다) | 3차 확인 리뷰 RR3-03-03·05 · `src/application-core/.../idempotency/IdempotencyRecoveryRequiredException.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java` | | sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` | ## 6. 따라오는 순서 diff --git a/docs/web/http-contract.md b/docs/web/http-contract.md index de18900b..50edc581 100644 --- a/docs/web/http-contract.md +++ b/docs/web/http-contract.md @@ -122,9 +122,19 @@ status는 코드 표(`HttpStatusErrorCodes`)에 있는 것만 그대로 나간 요청이 만나면 두 저장소(PostgreSQL·Redis) 모두 넘겨주지 않고 포기(abandoned)로 표시한다 — 그 뒤 첫 시도가 늦게 끝나도 결과는 기록되지 않고 그 요청도 500을 받는다. 새 키로 보내면 서버는 다른 요청으로 보고 막지 못한다 (재리뷰 2026-11-03 README 4절 결정 RR-02-03, 2026-11-04 9.1절 결정 RR-01-11). -- **서버가 기억하는 기간.** 완료된 응답은 완료부터 `replay-ttl`(기본 24h), 끝나지 않은 시도의 기록은 - claim부터 processing lease + `replay-ttl` 동안 남는다. 그 뒤 같은 키는 새 요청으로 실행된다. +- **서버가 기억하는 기간.** 위 판정은 기록이 남아 있는 동안만 선다. 기록이 사라지면 같은 키는 새 + 요청으로 실행된다. 기록의 수명은 시도가 어떻게 끝났는지로 갈린다. + - 완료된 응답: 완료부터 `replay-ttl`(`APP_IDEMPOTENCY_TTL`, 기본 24h). + - 끝나지 않은 시도: claim부터 processing lease + `replay-ttl`. lease가 지나 다음 요청이 포기로 표시한 + 기록도 이 수명을 그대로 쓴다. + - 실패로 표시된 시도: 작업이 예외를 던졌거나 효과 불명으로 끝나 포기(abandoned)된 시도, 효과 없이 + 재시도 가능으로 끝난 시도. 표시한 때부터 `failure-retention`(`APP_IDEMPOTENCY_FAILURE_RETENTION`, + 기본 24h). + `replay-ttl`이 `processing-lease`보다 짧으면 기동이 실패한다(재리뷰 2026-11-04 RR-03-11). + `failure-retention`은 `replay-ttl`과 비교하지 않는다. 더 짧게 두면 효과 불명으로 포기한 기록이 그만큼 + 먼저 사라지고, 그 뒤 같은 키 재전송은 작업을 다시 돌린다. 그래서 `replay-ttl` 이상으로 둔다 + (재리뷰 2026-11-04 RR3-03-02). ## 3. 헤더 diff --git a/infra/redis-sdk/acl/README.md b/infra/redis-sdk/acl/README.md index 6c20d498..cbbfd494 100644 --- a/infra/redis-sdk/acl/README.md +++ b/infra/redis-sdk/acl/README.md @@ -9,8 +9,12 @@ control of it (`CONFIG`, `MODULE`, every key). A deployment writes its own ACL f shape: the application accounts it actually uses, passwords from its secret store, and none of the lane-only accounts (review 2026-11-03 RR-07-04). The application enforces its half of that: under the `prod` runtime profile it refuses to start while a secret holds a value beginning with -`fixture-` (`SecretSourceValidator`): a key the secrets registry classifies `secret`, or the -variable a `secret://…/` credential reference names. A deployment that copied a lane's +`fixture-` (`SecretSourceValidator`): a key the secrets registry classifies `secret`, a variable a +module's `RequiredProductionSecrets` bean names, or the variable a `secret://…/` credential +reference in the environment names. A reference held in code — the typed SDK's admin account, +contributed as a `RedisAccountContribution` bean — is none of those: the composer names its variable +in a `RequiredProductionSecrets` bean too (`src/adapter/outbound/redis-sdk/README.md`), or the +`fixture-admin` password passes. A deployment that copied a lane's `APP_REDIS_AUTHENTICATION_*_REFERENCE` and `REDIS_LANE_*` values stops before it connects. Values that are not secrets — a pod's `HOSTNAME`, an application name — are not read, because `fixture-` is an ordinary word as well. diff --git a/src/.env.example b/src/.env.example index e1b49131..a15941b3 100644 --- a/src/.env.example +++ b/src/.env.example @@ -128,6 +128,7 @@ APP_IDEMPOTENCY_TTL=24h APP_IDEMPOTENCY_PROVIDER=disabled APP_IDEMPOTENCY_REDIS_NAMESPACE_ENVIRONMENT=local APP_IDEMPOTENCY_PROCESSING_LEASE=30s +# Failure retention: at most 30d. Not checked against APP_IDEMPOTENCY_TTL; keep it at least that long. APP_IDEMPOTENCY_FAILURE_RETENTION=24h APP_LEASE_PROVIDER=disabled APP_LEASE_REDIS_NAMESPACE_ENVIRONMENT=local diff --git a/src/adapter/inbound/messaging/CLAUDE.md b/src/adapter/inbound/messaging/CLAUDE.md index a13b56d8..2eaacaa0 100644 --- a/src/adapter/inbound/messaging/CLAUDE.md +++ b/src/adapter/inbound/messaging/CLAUDE.md @@ -11,8 +11,10 @@ - Boundaries: no business rule in a handler (HARD-STOP 4); no persistence entity or repository; no broker SDK type. Allowed edges come only from the registry entry. - A handler that calls a write use case is `@SystemCaller(reason = ...)` and constructs the - `@SystemInvoked` use case itself; the use case is never a bean (manual 09 「소비」 step 4, - `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`). + `@SystemInvoked` use case itself; the use case is never a bean, and no user transport calls the + handler (manual 09 「소비」 step 4, manual 07 「시스템이 부르는 쓰기」, + `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`, `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`, + `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`). - Tests: focused auto-configuration and inbox behavior tests; `./gradlew :adapter:inbound:messaging:check`. The real Kafka + PostgreSQL redelivery lane is `messagingInboxRedeliveryIntegrationTest` (`:integrationCheck`). diff --git a/src/adapter/inbound/messaging/README.md b/src/adapter/inbound/messaging/README.md index 3443f2a8..a457a018 100644 --- a/src/adapter/inbound/messaging/README.md +++ b/src/adapter/inbound/messaging/README.md @@ -103,8 +103,10 @@ PostgreSQL에서 같은 모양은 `InboxRedeliveryIntegrationTest`의 `Projectio `messaging-core-api`만 보는 anti-corruption 경계이고, 소비는 inbound 방향이다. - 고름(RR-01-12): handler가 `@SystemCaller`를 달고 `@SystemInvoked` use case를 직접 `new`로 만든다. 사용자 요청이 들어오는 전송(web·GraphQL·gRPC·WebSocket)만 그 use case에 닿지 못하고, 표시는 ArchUnit이 검사한다 - (`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`: messaging·scheduler inbound 패키지에만, 사용자 전송 - 타입에 의존하지 않음). 기동 가드는 바꾸지 않는다: `@SystemInvoked` bean은 예외 없이 실패다. + (`SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`: 표시한 클래스와 그 안에 중첩된 클래스는 messaging· + scheduler inbound 패키지에만, 사용자 전송 타입에 의존하지 않음). 사용자 전송이 handler bean을 주입받아 + 부르는 길은 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`가 막는다(RR3-01-01). 기동 가드는 바꾸지 않는다: + `@SystemInvoked` bean은 예외 없이 실패다. 규칙 전체는 매뉴얼 07장 「시스템이 부르는 쓰기」. - 버림: use case를 bean으로 두고 가드에 "handler만 주입받으면 허용" 예외 — 누가 주입받는지는 기동 때 확정되지 않는다(`ObjectProvider`, `getBean`, 나중에 추가된 bean). 예외 조건이 곧 우회 경로가 된다. - 버림: handler는 `CommandUseCase` 인터페이스만 받고 조립 모듈이 `new`로 넣기 — 소비자마다 composition @@ -113,7 +115,9 @@ PostgreSQL에서 같은 모양은 `InboxRedeliveryIntegrationTest`의 `Projectio - 버림: ArchUnit 대상에서 messaging 패키지를 통째로 빼기 — 클래스에 표시가 없어 의도가 안 보이고, 그 패키지의 아무 클래스(HTTP endpoint 포함)나 닿는다. - 버림: 사용자 전송 패키지만 나열해 금지 — 나중에 새 전송이 생기면 조용히 열린다. 규칙은 "닿아도 되는 - 쪽"을 적는다. + 쪽"을 적는다. 이 성질은 패키지 쪽에만 있다: 시스템 패키지 안에 놓인 endpoint를 알아보는 사용자 전송 + **타입**은 나열 목록이다(`ARE_USER_TRANSPORT_TYPES`, JAX-RS·graphql-java 포함). 새 전송 라이브러리를 + 들이면 그 목록에 더한다(RR3-01-02). - 버림: application-core에 소비 포트를 새로 만들어 platform `MessageHandler`로 감싸는 범용 bridge — payload 타입 매핑과 결과 매핑 규칙을 먼저 정해야 해서 이번 범위보다 크다. 지금은 handler가 직접 use case를 부른다. diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java index 7e47507c..43c967e3 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java @@ -243,7 +243,14 @@ public final class IdempotencyScripts { return {'APPLIED', attempt, rev, owner, '', ''} """; - /** Inspect: read the record without touching it. */ + /** + * Inspect: read the record without touching it. + * + *

The detail is {@code ownership|key PTTL|leaseUntil}. A completed record's replay deadline is + * its key's TTL; an in-progress record's lease is not, because its key lives for the lease plus + * {@code afterLease} — reading the lease off the TTL reported it a replay TTL too late (re-review + * 2026-11-04 RR3-03-05). + */ private static final String INSPECT = """ local state = redis.call('HGET', KEYS[1], 'state') @@ -268,7 +275,8 @@ public final class IdempotencyScripts { end return {state, attempt, rev, owner, redis.call('HGET', KEYS[1], 'resp') or '', - mine .. '|' .. tostring(redis.call('PTTL', KEYS[1]))} + mine .. '|' .. tostring(redis.call('PTTL', KEYS[1])) .. '|' + .. (redis.call('HGET', KEYS[1], 'leaseUntil') or '')} """; private final RegisteredLuaScript claim = new RegisteredLuaScript(CLAIM); diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java index c0bbb8c5..65249e1f 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java @@ -361,9 +361,16 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort if (reply.status() == ScriptStatus.FINGERPRINT_MISMATCH) { return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.FINGERPRINT_MISMATCH); } - String[] detail = reply.detail().split("\\|", 2); + String[] detail = reply.detail().split("\\|", 3); String ownership = detail[0]; long ttlMillis = detail.length > 1 ? parseLong(detail[1]) : 0; + // The lease the record carries, in server time as the claim reported it — not the key's TTL, + // which runs a replay TTL past the lease (RR3-03-05). + long leaseUntilMillis = detail.length > 2 ? parseLong(detail[2]) : 0; + Optional leaseUntil = + leaseUntilMillis > 0 + ? Optional.of(Instant.ofEpochMilli(leaseUntilMillis)) + : Optional.empty(); if ("OPERATION_CONFLICT".equals(ownership)) { return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.OPERATION_CONFLICT); } @@ -390,7 +397,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort ? new IdempotencyInspection( IdempotencyInspectionOutcome.CLAIMED_SAME_OPERATION, Optional.of(handle), - Optional.of(now.plusMillis(Math.max(1, ttlMillis))), + leaseUntil, Optional.empty(), Optional.empty()) : IdempotencyInspection.outcome(IdempotencyInspectionOutcome.IN_PROGRESS_OTHER); @@ -399,7 +406,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort ? new IdempotencyInspection( IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION, Optional.of(handle), - Optional.of(now.plusMillis(Math.max(1, ttlMillis))), + leaseUntil, Optional.empty(), Optional.empty()) : IdempotencyInspection.outcome(IdempotencyInspectionOutcome.IN_PROGRESS_OTHER); diff --git a/src/adapter/outbound/httpclient/README.md b/src/adapter/outbound/httpclient/README.md index f79afca1..bb5e72f4 100644 --- a/src/adapter/outbound/httpclient/README.md +++ b/src/adapter/outbound/httpclient/README.md @@ -42,11 +42,12 @@ no reactive (`WebClient`/Reactor Netty) surface; it was removed on 2026-09-25 (d left, the experimental Jetty HTTP/3 transport aborts the request, and the caller gets `HttpDeadlineExceededException`. A streaming download's setup (up to the response headers) runs inside the same deadline; after hand-over each body gap is bounded by `read-idle` and nothing else, - on both transports — the JDK transport arms its own per-read timer for this, because the JDK client - has no socket read timeout. A body that fails after hand-over throws `HttpBodyReadException`, an - `IOException` as `InputStream.read` promises, whose `failure()` is the same stable exception a - buffered call throws (`HttpResponseTimeoutException` for a stalled body, - `HttpResponseTruncatedException` for a cut one). + on both transports — on the JDK transport, which has no socket read timeout, a per-stream watchdog + on its own daemon thread (`httpclient-jdk-read-idle`) bounds each read's wait. A body that fails + after hand-over throws `HttpBodyReadException`, an `IOException` as `InputStream.read` promises, + whose `failure()` is the same stable exception a buffered call throws + (`HttpResponseTimeoutException` for a stalled body, `HttpResponseTruncatedException` for a cut + one). - **Evidence.** Each attempt reports `NOT_SENT`, `SENT_NO_RESPONSE`, `RESPONSE_RECEIVED`, or `PARTIAL_RESPONSE`. `NOT_SENT` is only claimed when a stage failure proves it. - **Retry.** Never from the HTTP method alone. Idempotency, body replayability, evidence, deadline, diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java index a836ec1d..36ffbdc2 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStream.java @@ -6,7 +6,9 @@ import java.io.InputStream; import java.net.SocketTimeoutException; import java.time.Duration; import java.util.Objects; -import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -31,6 +33,20 @@ import java.util.concurrent.atomic.AtomicBoolean; * it moves the queue off the shared scheduler but keeps a queue insertion and removal on every * read. * + *

The watchdog wakes on a thread of its own: one daemon thread, {@code + * httpclient-jdk-read-idle}, shared by every JDK stream and started with the first (re-review + * 2026-11-04 RR3-03-01). It used to wake through {@code CompletableFuture.delayedExecutor}, whose + * task runs on the common {@code ForkJoinPool}; a service that filled that pool with blocking work + * — {@code supplyAsync(blockingCall)} without an executor — held every timeout until a pool thread + * came free, and a 300 ms {@code read-idle} ended after 2.7 s. The wake is O(1), and the close it + * may do waits on no I/O — the JDK body marks itself closed, cancels its subscription and wakes the + * read — so both run on this thread, as the per-read timer before RR-03-13 closed on the JDK's + * delay thread. Rejected: {@code delayedExecutor(delay, unit, Runnable::run)}, which judges on the + * JDK's own delay thread — that thread fires every {@code CompletableFuture} timeout in the + * process, so a slow close there would delay them all, and it returns no handle to take a closed + * stream's wake off the queue. Closing the stream cancels its pending wake, so a closed stream is + * not kept reachable until its {@code read-idle} passes. + * *

{@link #skip} reads through this stream rather than delegating: the JDK body does not override * {@code skip}, so {@code InputStream.skip} ran many reads inside one guarded call and a long skip * over a steady body timed out as one long wait (re-review 2026-11-04 RR-03-12). @@ -53,10 +69,35 @@ final class ReadIdleInputStream extends FilterInputStream { private final AtomicBoolean idled = new AtomicBoolean(); private volatile long readStartedAt = NOT_READING; private volatile boolean closed; + private volatile ScheduledFuture pendingWake; + private final ScheduledExecutorService watchdogs; ReadIdleInputStream(InputStream delegate, Duration readIdle) { + this(delegate, readIdle, SharedWatchdogs.INSTANCE); + } + + /** The scheduler is a parameter so a test can see what a stream leaves queued on it. */ + ReadIdleInputStream(InputStream delegate, Duration readIdle, ScheduledExecutorService watchdogs) { super(Objects.requireNonNull(delegate, "body stream")); this.readIdleNanos = Objects.requireNonNull(readIdle, "read idle timeout").toNanos(); + this.watchdogs = Objects.requireNonNull(watchdogs, "watchdog scheduler"); + } + + /** + * A watchdog scheduler as every stream gets it: one daemon thread, and a cancelled wake leaves + * the queue at once instead of when it would have fired. + */ + static ScheduledThreadPoolExecutor newWatchdogs() { + ScheduledThreadPoolExecutor scheduler = + new ScheduledThreadPoolExecutor( + 1, + runnable -> { + Thread thread = new Thread(runnable, "httpclient-jdk-read-idle"); + thread.setDaemon(true); + return thread; + }); + scheduler.setRemoveOnCancelPolicy(true); + return scheduler; } @Override @@ -89,6 +130,7 @@ final class ReadIdleInputStream extends FilterInputStream { @Override public void close() throws IOException { closed = true; + cancelPendingWake(); super.close(); } @@ -113,7 +155,19 @@ final class ReadIdleInputStream extends FilterInputStream { /** Wakes the watchdog when a read that started at {@code started} reaches read-idle. */ private void watchFrom(long started) { long left = Math.max(0, readIdleNanos - (System.nanoTime() - started)); - CompletableFuture.delayedExecutor(left, TimeUnit.NANOSECONDS).execute(this::watch); + pendingWake = watchdogs.schedule(this::watch, left, TimeUnit.NANOSECONDS); + // A close between the watchdog's check and this schedule did not see the new wake; take it + // off here. Both sides write their own volatile before reading the other's. + if (closed) { + cancelPendingWake(); + } + } + + private void cancelPendingWake() { + ScheduledFuture wake = pendingWake; + if (wake != null) { + wake.cancel(false); + } } private void watch() { @@ -158,4 +212,12 @@ final class ReadIdleInputStream extends FilterInputStream { throw new SocketTimeoutException("no response body bytes within the read-idle timeout"); } } + + /** The scheduler every stream shares, started with the first stream that is read. */ + private static final class SharedWatchdogs { + + static final ScheduledExecutorService INSTANCE = newWatchdogs(); + + private SharedWatchdogs() {} + } } diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java index 6b70aa42..3f9ab53f 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/jdk/ReadIdleInputStreamTest.java @@ -8,6 +8,8 @@ import java.io.InputStream; import java.net.SocketTimeoutException; import java.time.Duration; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -15,12 +17,14 @@ import org.junit.jupiter.api.Test; /** * What the JDK transport's read-idle bound promises: each read that waits longer than {@code * read-idle} for the server ends the body, and nothing else does (re-review 2026-11-04 RR-03-12, - * RR-03-13). + * RR-03-13); the watchdog keeps that time whatever the common pool is doing, and leaves nothing + * scheduled for a stream that is closed or timed out (RR3-03-01). */ class ReadIdleInputStreamTest { private static final Duration READ_IDLE = Duration.ofMillis(300); private static final Duration GAP = Duration.ofMillis(20); + private static final Duration COMMON_POOL_HOLD = Duration.ofSeconds(3); @Test @DisplayName("데이터가 read-idle보다 짧은 간격으로 오면 read-idle보다 오래 걸리는 skip도 끝까지 건너뛴다") @@ -67,6 +71,79 @@ class ReadIdleInputStreamTest { assertThat(waited).isGreaterThanOrEqualTo(READ_IDLE).isLessThan(READ_IDLE.multipliedBy(3)); } + @Test + @DisplayName("공용 ForkJoinPool이 블로킹 작업으로 차 있어도 멈춘 read는 read-idle 무렵에 끝난다") + void aStalledReadTimesOutOnTimeWhileTheCommonPoolIsBlocked() throws Exception { + // given + // Every common-pool worker parks on a latch, which does not make the pool add a spare thread — + // what a service's supplyAsync(blockingCall) without an executor does. The hold is bounded so + // a watchdog that needs a pool worker still ends the read, late (re-review 2026-11-04 + // RR3-03-01: 300 ms read-idle timed out after 2,699 ms). + int workers = Math.max(1, ForkJoinPool.getCommonPoolParallelism()); + CountDownLatch occupied = new CountDownLatch(workers); + CountDownLatch release = new CountDownLatch(1); + for (int task = 0; task < workers * 2; task++) { + ForkJoinPool.commonPool() + .execute( + () -> { + occupied.countDown(); + awaitQuietly(release, COMMON_POOL_HOLD); + }); + } + assertThat(occupied.await(5, TimeUnit.SECONDS)).as("every common-pool worker is held").isTrue(); + InputStream body = new ReadIdleInputStream(new StalledStream(), READ_IDLE); + long started = System.nanoTime(); + try { + // when + Throwable failure = catchThrowable(body::read); + + // then + Duration waited = Duration.ofNanos(System.nanoTime() - started); + assertThat(failure).isInstanceOf(SocketTimeoutException.class); + assertThat(waited).isGreaterThanOrEqualTo(READ_IDLE).isLessThan(READ_IDLE.multipliedBy(3)); + } finally { + release.countDown(); + } + } + + @Test + @DisplayName("스트림을 닫으면 그 스트림의 watchdog 예약이 스케줄러에서 바로 빠진다") + void closingTheStreamTakesItsWatchdogOffTheScheduler() throws IOException { + // given + ScheduledThreadPoolExecutor watchdogs = ReadIdleInputStream.newWatchdogs(); + try { + InputStream body = new ReadIdleInputStream(new DrippingStream(1, GAP), READ_IDLE, watchdogs); + body.read(); + + // when + body.close(); + + // then + assertThat(watchdogs.getQueue()).isEmpty(); + } finally { + watchdogs.shutdownNow(); + } + } + + @Test + @DisplayName("read-idle로 끝난 스트림은 닫지 않아도 watchdog을 더 예약하지 않는다") + void aStreamThatTimedOutLeavesNoWatchdogBehind() { + // given + ScheduledThreadPoolExecutor watchdogs = ReadIdleInputStream.newWatchdogs(); + try { + InputStream body = new ReadIdleInputStream(new StalledStream(), READ_IDLE, watchdogs); + + // when + Throwable failure = catchThrowable(body::read); + + // then + assertThat(failure).isInstanceOf(SocketTimeoutException.class); + assertThat(watchdogs.getQueue()).isEmpty(); + } finally { + watchdogs.shutdownNow(); + } + } + @Test @DisplayName("호출자가 read 사이에 오래 머문 시간은 read-idle로 세지 않는다") void timeTheCallerSpendsBetweenReadsIsNotIdle() throws Exception { @@ -83,6 +160,14 @@ class ReadIdleInputStreamTest { } } + private static void awaitQuietly(CountDownLatch latch, Duration atMost) { + try { + latch.await(atMost.toNanos(), TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + } + /** Gives one byte per read, each after {@code gap}. */ private static final class DrippingStream extends InputStream { diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index 5e489322..3b68d487 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -95,7 +95,8 @@ not grow by wiring accident. - OSIV is false in every runtime profile; Flyway owns schema change and Hibernate only validates. - A migration that locks a table already in use starts with `SET LOCAL lock_timeout = '5s';` (`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest` refuses one - without it; its list of migrations released before the rule only ever shrinks. + without it. Its list of migrations released before the rule never takes a new migration; it + grows only when the inspector learns a statement and finds it in a file already on `main`. - Metric tags, exception messages, and logs carry no SQL parameters, entity ids, tenant ids, or PII. - Contracts run against real PostgreSQL. H2 never satisfies one. diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java index 5495c145..657e03e4 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationLockWaitTest.java @@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.testkit.migration.LockWaitMigrationInspector; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map; @@ -26,21 +25,30 @@ class MigrationLockWaitTest { * Migrations released before the rule, which wait without a bound and stay that way: they are * applied (on {@code main} when the rule came in), and an applied migration is never edited * ({@link AppliedMigrationImmutabilityTest}). Their waits are behind every database that ran - * them. Nothing is added here — a new migration bounds its wait. + * them. A new migration is never added here — it bounds its wait. The list grows only when the + * inspector learns a statement it did not know and finds it in a file released before the rule: + * {@code REFERENCES} on an existing table, and a {@code CREATE TABLE IF NOT EXISTS} that no + * longer exempts the statements after it (re-review 2026-11-03 round 3, RR3-02-01), added {@code + * jpa/idempotency/V1}, notification {@code V3}, {@code messaging/V1003} and {@code + * postgresql/V11} and {@code V12} — all five on {@code main} ({@code 01a8a2a7}), unchanged since. */ private static final Set RELEASED_BEFORE_THE_RULE = Set.of( "jpa/core/V2__widen_capability_schema_stream.sql", + "jpa/idempotency/V1__expand_owner_safe_v2.sql", "jpa/idempotency/V2__request_hash_varchar.sql", "postgresql/V5__int_lock_expired_after.sql", "postgresql/V9__widen_capability_schema_stream.sql", "postgresql/V10__idempotency_request_hash_varchar.sql", + "postgresql/V11__durable_operation.sql", + "postgresql/V12__live_event_log.sql", "postgresql/V13__outbox_canonical_transport_compatibility.sql", "postgresql/V14__validate_outbox_canonical_constraints.sql", "postgresql/V16__outbox_canonical_hash_columns_varchar.sql", "postgresql/V17__outbox_event_lease_fencing.sql", "postgresql/V18__outbox_event_unpublished_aggregate_order.sql", "postgresql/V19__outbox_event_canonical_only.sql", + "jpa/notification-platform/V3__notification_platform_inbox_admin.sql", "jpa/notification-platform/V4__notification_platform_alignment_and_activation.sql", "jpa/notification-platform/V5__notification_recipient_expiry.sql", "jpa/notification-platform/V6__notification_projection_facts.sql", @@ -52,6 +60,7 @@ class MigrationLockWaitTest { "jpa/fileserver/V4__fileserver_upload_terminal_state.sql", "jpa/fileserver/V5__fileserver_file_owner.sql", "messaging/V1002__messaging_outbox_lease_fencing.sql", + "messaging/V1003__messaging_admin_operation_journal.sql", "messaging/V1004__messaging_outbox_canonical_metadata.sql", "messaging/V1005__messaging_outbox_ordering_key_index.sql"); @@ -94,8 +103,7 @@ class MigrationLockWaitTest { throws IOException { Map> unbounded = new TreeMap<>(); for (Map.Entry migration : migrations.entrySet()) { - List statements = - inspector.unboundedLockingStatements(Files.readString(migration.getValue())); + List statements = inspector.unboundedLockingStatements(migration.getValue()); if (!statements.isEmpty()) { unbounded.put(migration.getKey(), statements); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java index 04727620..83cd9ab0 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java @@ -1,12 +1,11 @@ package dev.caskeleton.adapter.outbound.persistence.migration; +import dev.caskeleton.adapter.outbound.persistence.testkit.migration.VersionedMigrationFiles; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.TreeMap; -import java.util.stream.Stream; /** * The migration trees that run against the database this leaf owns, read the one way every @@ -46,22 +45,18 @@ final class MigrationTrees { private MigrationTrees() {} /** - * Every versioned migration, keyed by its path below its tree ({@code postgresql/V22__...sql}), - * the key {@code applied-migrations.sha256} uses. + * Every versioned migration ({@link VersionedMigrationFiles}, the definition the sample's check + * uses too), keyed by its path below its tree ({@code postgresql/V22__...sql}), the key {@code + * applied-migrations.sha256} uses. */ static Map versionedMigrations() throws IOException { Map migrations = new TreeMap<>(); for (Path root : ROOTS) { - try (Stream files = Files.walk(root)) { - for (Path file : - files - .filter(path -> path.getFileName().toString().matches("V\\d+__.+\\.sql")) - .toList()) { - String key = root.relativize(file).toString().replace('\\', '/'); - if (migrations.put(key, file) != null) { - throw new IllegalStateException( - key + " exists in two migration trees; the classpath would load one at random"); - } + for (Map.Entry migration : VersionedMigrationFiles.under(root).entrySet()) { + if (migrations.put(migration.getKey(), migration.getValue()) != null) { + throw new IllegalStateException( + migration.getKey() + + " exists in two migration trees; the classpath would load one at random"); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java index bc60ed6b..6454b138 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/JpaArchitectureRulesTest.java @@ -12,6 +12,8 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseMa import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.InverseOneToOneEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnChildEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinColumnParentEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinTableChildEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.JoinTableParentEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.MutualForeignKeyInvoiceEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.MutualForeignKeyOrderEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.NoDefaultConstructorEntity; @@ -19,6 +21,8 @@ import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OrderEnti import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningChildEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningManyToManyEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.OwningOneToOneEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.TwoOwnerCourseEntity; +import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.TwoOwnerStudentEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity.UnidirectionalCollectionEntity; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.BadOrderController; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.web.GoodOrderController; @@ -230,6 +234,51 @@ class JpaArchitectureRulesTest { .hasMessageNotContaining("two fields map one link"); } + @Test + @DisplayName("mappedBy를 잊어 컬렉션은 조인 테이블에, 반대쪽은 자기 외래 키 열에 링크를 두면 한 링크가 아니라 따로 저장된 두 사본으로 거부된다") + void aCollectionInAJoinTableAndAToOneInItsOwnColumnAreRefusedAsTwoStoredCopies() { + // given + var classes = + new ClassFileImporter() + .importClasses(JoinTableParentEntity.class, JoinTableChildEntity.class); + + // when + Throwable failure = + catchThrowable( + () -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)); + + // then + assertThat(failure) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("JoinTableParentEntity.children") + .hasMessageContaining("JoinTableChildEntity.parent") + .hasMessageContaining("the link is stored twice") + .hasMessageContaining("column parent_id") + .hasMessageNotContaining("two fields map one link"); + } + + @Test + @DisplayName("mappedBy 없는 두 @ManyToMany는 한 링크가 아니라 양쪽이 따로 저장하는 두 사본으로 거부된다") + void twoManyToManyCollectionsWithoutMappedByAreRefusedAsTwoStoredCopies() { + // given + var classes = + new ClassFileImporter() + .importClasses(TwoOwnerStudentEntity.class, TwoOwnerCourseEntity.class); + + // when + Throwable failure = + catchThrowable( + () -> JpaArchitectureRules.associationsAreMappedFromOneSideOnly().check(classes)); + + // then + assertThat(failure) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("TwoOwnerStudentEntity.courses") + .hasMessageContaining("TwoOwnerCourseEntity.students") + .hasMessageContaining("the link is stored twice") + .hasMessageNotContaining("two fields map one link"); + } + @Test @DisplayName("단방향 연관관계는 통과한다") void unidirectionalAssociationsPass() { diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableChildEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableChildEntity.java new file mode 100644 index 00000000..d43b51f1 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableChildEntity.java @@ -0,0 +1,30 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; + +/** Refused by the association rule: the other half of {@link JoinTableParentEntity}'s pair. */ +@Entity +public class JoinTableChildEntity { + + @Id private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "parent_id") + private JoinTableParentEntity parent; + + protected JoinTableChildEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The reference kept in this table's own column. */ + public JoinTableParentEntity parent() { + return parent; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableParentEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableParentEntity.java new file mode 100644 index 00000000..c5e81187 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/JoinTableParentEntity.java @@ -0,0 +1,35 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import java.util.ArrayList; +import java.util.List; + +/** + * Refused by the association rule: a pair without {@code mappedBy} that stores the link twice. + * + *

A {@code @OneToMany} without {@code @JoinColumn} keeps its links in a join table, and {@link + * JoinTableChildEntity#parent} keeps the same link in its own {@code parent_id} column — the shape + * forgetting {@code mappedBy} produces. Two copies stored apart, not one mapped twice (re-review + * round 3, RR3-02-05). + */ +@Entity +public class JoinTableParentEntity { + + @Id private Long id; + + @OneToMany private List children = new ArrayList<>(); + + protected JoinTableParentEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The collection kept in the join table. */ + public List children() { + return List.copyOf(children); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerCourseEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerCourseEntity.java new file mode 100644 index 00000000..914d714e --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerCourseEntity.java @@ -0,0 +1,28 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; +import java.util.HashSet; +import java.util.Set; + +/** Refused by the association rule: the other half of {@link TwoOwnerStudentEntity}'s pair. */ +@Entity +public class TwoOwnerCourseEntity { + + @Id private Long id; + + @ManyToMany private Set students = new HashSet<>(); + + protected TwoOwnerCourseEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The students, kept in this side's join table. */ + public Set students() { + return Set.copyOf(students); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerStudentEntity.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerStudentEntity.java new file mode 100644 index 00000000..12191854 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/entity/TwoOwnerStudentEntity.java @@ -0,0 +1,34 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.arch.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; +import java.util.HashSet; +import java.util.Set; + +/** + * Refused by the association rule: two {@code @ManyToMany} collections without {@code mappedBy}. + * + *

Both this collection and {@link TwoOwnerCourseEntity#students} own the link, each in its own + * join table by default. Two copies stored apart, not one mapped twice (re-review round 3, + * RR3-02-05). + */ +@Entity +public class TwoOwnerStudentEntity { + + @Id private Long id; + + @ManyToMany private Set courses = new HashSet<>(); + + protected TwoOwnerStudentEntity() {} + + /** The identifier. */ + public Long id() { + return id; + } + + /** The courses, kept in this side's join table. */ + public Set courses() { + return Set.copyOf(courses); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java index f0358905..5cfb63d1 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java @@ -2,9 +2,15 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.migration; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.InstanceOfAssertFactories.STRING; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -14,6 +20,9 @@ import org.junit.jupiter.params.provider.ValueSource; */ class LockWaitMigrationInspectorTest { + private static final String BOUNDED_ALTER = + "SET LOCAL lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;"; + private final LockWaitMigrationInspector inspector = new LockWaitMigrationInspector(); @ParameterizedTest @@ -26,7 +35,20 @@ class LockWaitMigrationInspectorTest { "UPDATE outbox_event SET status = 'FAILED';", "LOCK TABLE outbox_event IN SHARE MODE;", "ALTER TABLE outbox_event ADD COLUMN c INT;\nSET LOCAL lock_timeout = '5s';", - "SET lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;" + "SET lock_timeout = '5s';\nALTER TABLE outbox_event ADD COLUMN c INT;", + "CREATE TABLE outbox_note (id BIGINT, event_id UUID REFERENCES outbox_event (event_id));", + "CREATE TABLE poster_note (id BIGINT);\n" + + "ALTER TABLE poster_note ADD CONSTRAINT fk FOREIGN KEY (id) REFERENCES poster (id);", + "CREATE TRIGGER trg_outbox BEFORE UPDATE ON outbox_event FOR EACH ROW EXECUTE FUNCTION f();", + "CREATE OR REPLACE TRIGGER trg_outbox AFTER INSERT ON public.outbox_event" + + " FOR EACH ROW EXECUTE FUNCTION f();", + "DROP TRIGGER IF EXISTS trg_outbox ON outbox_event;", + "REINDEX TABLE outbox_event;", + "REINDEX INDEX ux_outbox_event_aggregate_order;", + "REFRESH MATERIALIZED VIEW outbox_summary;", + "CLUSTER outbox_event USING ix_outbox_event_status;", + "VACUUM FULL outbox_event;", + "CREATE TABLE IF NOT EXISTS ledger (id BIGINT);\nALTER TABLE ledger ADD c INT;" }) @DisplayName("이미 있는 테이블에 잠금을 거는 문장 앞에 SET LOCAL lock_timeout이 없으면 거부된다") void aLockOnAnExistingTableWithoutABoundBeforeItIsRefused(String sql) { @@ -50,8 +72,12 @@ class LockWaitMigrationInspectorTest { "-- bound first\nset local lock_timeout = '5s';\ndelete from notification_suppression;", "CREATE TABLE ledger (id BIGINT);\nCREATE INDEX ix_ledger ON ledger (id);\n" + "ALTER TABLE ledger ADD COLUMN c INT;", - "CREATE TABLE IF NOT EXISTS public.ledger (id BIGINT);\nALTER TABLE ledger ADD c INT;", "CREATE INDEX CONCURRENTLY ix_outbox ON outbox_event (status);", + "REINDEX TABLE CONCURRENTLY outbox_event;", + "CREATE TABLE parent (id BIGINT PRIMARY KEY);\n" + + "CREATE TABLE child (id BIGINT, parent_id BIGINT REFERENCES parent (id));", + "CREATE TABLE node (id BIGINT PRIMARY KEY, parent_id BIGINT REFERENCES node (id));", + "SET LOCAL lock_timeout TO 5000;\nDROP TRIGGER trg_outbox ON outbox_event;", "-- ALTER TABLE outbox_event ADD COLUMN c INT;\n/* DELETE FROM outbox_event; */\n" + "COMMENT ON TABLE outbox_event IS 'update outbox_event set status';", "CREATE TABLE poster_copy AS SELECT * FROM poster;" @@ -68,6 +94,62 @@ class LockWaitMigrationInspectorTest { assertThat(refused).isNull(); } + @ParameterizedTest + @ValueSource( + strings = { + "SET LOCAL lock_timeout = 0;\nALTER TABLE outbox_event ADD COLUMN c INT;", + "SET LOCAL lock_timeout = '0s';\nALTER TABLE outbox_event ADD COLUMN c INT;", + "SET LOCAL lock_timeout TO DEFAULT;\nALTER TABLE outbox_event ADD COLUMN c INT;", + "SET LOCAL lock_timeout = '5s';\nSET LOCAL lock_timeout = 0;\n" + + "ALTER TABLE outbox_event ADD COLUMN c INT;", + "SET LOCAL lock_timeout = '5s';\nRESET lock_timeout;\n" + + "ALTER TABLE outbox_event ADD COLUMN c INT;" + }) + @DisplayName("lock_timeout을 0이나 기본값으로 두거나 되돌린 뒤의 잠금은 상한이 없는 것으로 거부된다") + void aLockAfterATimeoutOfZeroOrALiftedBoundIsRefused(String sql) { + // given + MigrationResource migration = new MigrationResource("V99__change.sql", sql); + + // when + Throwable refused = catchThrowable(() -> inspector.requireBoundedLockWait(migration)); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("alter table outbox_event"); + } + + @Test + @DisplayName("executeInTransaction=false인 마이그레이션의 SET LOCAL lock_timeout은 상한으로 세지 않는다") + void setLocalInANonTransactionalMigrationIsNotABound(@TempDir Path stream) throws IOException { + // given + Path script = Files.writeString(stream.resolve("V99__change.sql"), BOUNDED_ALTER); + Files.writeString(stream.resolve("V99__change.sql.conf"), "executeInTransaction=false\n"); + + // when + List unbounded = inspector.unboundedLockingStatements(script); + + // then + assertThat(unbounded) + .singleElement(STRING) + .contains("alter table outbox_event") + .contains("executeInTransaction=false"); + } + + @Test + @DisplayName("설정 파일이 없는 마이그레이션 파일은 트랜잭션 안에서 돌아 SET LOCAL lock_timeout이 상한이 된다") + void setLocalInAMigrationFileWithoutConfigurationIsABound(@TempDir Path stream) + throws IOException { + // given + Path script = Files.writeString(stream.resolve("V99__change.sql"), BOUNDED_ALTER); + + // when + List unbounded = inspector.unboundedLockingStatements(script); + + // then + assertThat(unbounded).isEmpty(); + } + @Test @DisplayName("거부 메시지는 상한 없이 잠금을 기다리는 문장과 대상 테이블을 모두 말한다") void theRefusalNamesEveryUnboundedStatementAndItsTable() { diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java new file mode 100644 index 00000000..e38d3faa --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFilesTest.java @@ -0,0 +1,48 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.migration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Set; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * One definition of a versioned migration for every check that walks a tree (re-review 2026-11-03 + * round 3, RR3-02-03): the operating trees' checks once skipped {@code V22_1__} while the sample's + * counted it. + */ +class VersionedMigrationFilesTest { + + @Test + @DisplayName("소수 버전을 포함한 버전 마이그레이션만 하위 디렉터리까지 찾고 다른 파일은 뺀다") + void everyVersionedMigrationIncludingADecimalVersionIsFoundAndNothingElse(@TempDir Path tree) + throws IOException { + // given + Files.createDirectories(tree.resolve("postgresql")); + for (String file : + Set.of( + "postgresql/V22__outbox.sql", + "postgresql/V22_1__outbox_fix.sql", + "postgresql/V22.2__outbox_index.sql", + "postgresql/V22__outbox.sql.conf", + "postgresql/R__view.sql", + "postgresql/U22__undo.sql", + "README.md")) { + Files.writeString(tree.resolve(file), "SELECT 1;"); + } + + // when + Set found = VersionedMigrationFiles.under(tree).keySet(); + + // then + assertThat(found) + .containsExactlyInAnyOrder( + "postgresql/V22__outbox.sql", + "postgresql/V22_1__outbox_fix.sql", + "postgresql/V22.2__outbox_index.sql"); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java index 592d9d62..d841308c 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/arch/SingleSidedAssociationCondition.java @@ -10,6 +10,8 @@ import com.tngtech.archunit.core.domain.JavaType; import com.tngtech.archunit.lang.ArchCondition; import com.tngtech.archunit.lang.ConditionEvents; import com.tngtech.archunit.lang.SimpleConditionEvent; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; @@ -30,10 +32,12 @@ import java.util.stream.Stream; *

    *
  • With {@code mappedBy}: the inverse half says so. Only that half is reported, because the * foreign key belongs to the owning {@code @ManyToOne} either way. - *
  • Without it: both halves map the same join column, one of them usually {@code insertable = - * false, updatable = false} (Hibernate's {@code @JoinColumn} form). Neither half says it is - * the copy, so both are reported (review RR-03-04). Reading the attribute alone let this form - * pass. + *
  • Without it: neither half says it is the copy, so both are reported (review RR-03-04). + * Reading the attribute alone let this form pass. Either both halves map the same join + * column, one of them usually {@code insertable = false, updatable = false} (Hibernate's + * {@code @JoinColumn} form), or each stores the link on its own — a {@code @OneToMany} + * without {@code @JoinColumn} in a join table beside the to-one's column, two + * {@code @ManyToMany} in a join table each — and the report says which (RR3-02-05). *
* *

Two to-one links the other way round — {@code Order.@OneToOne latestInvoice} and {@code @@ -116,25 +120,48 @@ public final class SingleSidedAssociationCondition extends ArchCondition + *

  • Two to-one links are two foreign keys that reference each other's table. + *
  • A collection with {@code @JoinColumn} and a to-one on that same column (or one that does + * not name its column) map one link from both ends — Hibernate's {@code @JoinColumn} form. + *
  • Anything else stores the link twice: a {@code @OneToMany} without {@code @JoinColumn} + * keeps it in a join table while the to-one keeps it in its own column (the shape a + * forgotten {@code mappedBy} produces), two {@code @ManyToMany} each own a join table, and + * two differently named columns are two columns (re-review 2026-11-03 round 3, RR3-02-05). + * */ - private static String why(String own, String back) { - if (own.equals(inverseOf(back)) && !own.equals("OneToOne")) { + private static String why( + JavaClass ownType, + JavaMember ownMember, + Association own, + JavaClass backType, + JavaMember backMember, + Association back) { + if (!own.toMany() && !back.toMany()) { + return "each holds a foreign key to the other, so the two tables reference each other: neither" + + " row can be inserted or deleted first, and one key has to be nullable and written by a" + + " second UPDATE."; + } + Storage ownStorage = Storage.of(ownType, ownMember, own); + Storage backStorage = Storage.of(backType, backMember, back); + if (ownStorage.sameColumnAs(backStorage)) { return "two fields map one link, and the read-only one does not follow a change made through" + " the other."; } - return "each holds a foreign key to the other, so the two tables reference each other: neither" - + " row can be inserted or deleted first, and one key has to be nullable and written by a" - + " second UPDATE."; + return "the link is stored twice — in " + + ownStorage.where() + + " and in " + + backStorage.where() + + " — and each copy is written on its own, so the two drift apart."; } /** The annotation the other half of a pair carries. */ @@ -154,9 +181,48 @@ public final class SingleSidedAssociationCondition extends ArchCondition joinColumn = + member + .tryGetAnnotationOfType(JoinColumn.class.getName()) + .map(annotation -> String.valueOf(annotation.get("name").orElse(""))); + boolean joinTable = + association.annotation().equals("ManyToMany") + || member.isAnnotatedWith(JoinTable.class) + || (association.annotation().equals("OneToMany") && joinColumn.isEmpty()); + if (joinTable) { + return new Storage(true, "", name(owner, member) + "'s join table"); + } + String column = joinColumn.orElse(""); + return new Storage( + false, + column, + column.isEmpty() ? name(owner, member) + "'s foreign-key column" : "column " + column); + } + + /** Whether both halves name, or may default to, one foreign-key column. */ + boolean sameColumnAs(Storage other) { + return !joinTable + && !other.joinTable + && (column.isEmpty() || other.column.isEmpty() || column.equalsIgnoreCase(other.column)); + } + } + /** One association member: its annotation, its {@code mappedBy}, and the entity it points at. */ private record Association(String annotation, String mappedBy, JavaClass target) { + boolean toMany() { + return annotation.equals("OneToMany") || annotation.equals("ManyToMany"); + } + static Optional of(JavaMember member) { for (Class type : ASSOCIATIONS) { if (!member.isAnnotatedWith(type)) { diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java index b289dbc4..60ca7711 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java @@ -1,11 +1,16 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.migration; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.NavigableMap; import java.util.Objects; +import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -22,21 +27,44 @@ import java.util.regex.Pattern; * version before it — a failed deploy, not an outage. {@code LOCAL}, because a plain {@code SET} * outlives the migration on the pooled connection Flyway borrowed. * - *

    What counts as waiting for a lock: {@code ALTER TABLE}, {@code CREATE [UNIQUE] INDEX} and - * {@code DROP INDEX} without {@code CONCURRENTLY}, {@code LOCK TABLE}, {@code TRUNCATE}, {@code - * DROP TABLE}, and {@code UPDATE}/{@code DELETE} (they wait on the rows other transactions hold). A - * statement on a table this same migration created earlier waits for nothing and is left out. - * Comments and quoted literals are not read as statements. The check reads text, not a parse tree: - * it is a guard against the forgotten line, not a proof. + *

    The statements it looks for, each on the table named in it: + * + *

      + *
    • {@code ALTER TABLE}, {@code LOCK TABLE}, {@code TRUNCATE}, {@code DROP TABLE}; + *
    • {@code CREATE [UNIQUE] INDEX}, {@code DROP INDEX} and {@code REINDEX} without {@code + * CONCURRENTLY}, {@code REFRESH MATERIALIZED VIEW} without it, {@code CLUSTER}, {@code VACUUM + * FULL}; + *
    • {@code REFERENCES} — in a new table as much as in an {@code ALTER TABLE} — on the table it + * references: a foreign key locks its parent against writes while it is added; + *
    • {@code CREATE TRIGGER} and {@code DROP TRIGGER} on the table the trigger is on; + *
    • {@code UPDATE} and {@code DELETE}, which wait on the rows other transactions hold. + *
    + * + *

    A statement on a table this same migration created earlier waits for nothing and is left out; + * {@code CREATE TABLE IF NOT EXISTS} does not count as creating it, because the table may already + * be there. The bound in force at a statement is the last {@code lock_timeout} setting before it, + * and it counts only as {@code SET LOCAL} with a value that is not zero: {@code 0}, {@code DEFAULT} + * and {@code RESET} wait without end, a plain {@code SET} outlives the migration. A migration + * Flyway runs outside a transaction ({@code executeInTransaction=false} in its {@code .sql.conf}, + * read by {@link #unboundedLockingStatements(Path)}) has no bound at all: {@code SET LOCAL} there + * only warns. Comments and quoted literals are not read as statements. The check reads text, not a + * parse tree: it is a guard against the forgotten line for the statements above, not a proof that + * no other statement waits (re-review 2026-11-03 round 3, RR3-02-01). */ public final class LockWaitMigrationInspector { - private static final String NAME = - "((?:\"[^\"]+\"|[a-z_][a-z0-9_$]*)(?:\\.(?:\"[^\"]+\"|[a-z_][a-z0-9_$]*))?)"; + private static final String IDENTIFIER = "(?:\"[^\"]+\"|[a-z_][a-z0-9_$]*)"; + + /** A possibly qualified name the pattern does not capture: a trigger's own name. */ + private static final String OTHER_NAME = IDENTIFIER + "(?:\\." + IDENTIFIER + ")?"; + + /** A possibly qualified name, captured as group 1: the table the statement locks. */ + private static final String NAME = "(" + OTHER_NAME + ")"; private static final Pattern CREATED_TABLE = Pattern.compile( - "\\bcreate\\s+(?:(?:temp|temporary|unlogged)\\s+)?table\\s+(?:if\\s+not\\s+exists\\s+)?" + "\\bcreate\\s+(?:(?:temp|temporary|unlogged)\\s+)?(?:table|materialized\\s+view)\\s+" + + "(?!if\\s+not\\s+exists\\b)" + NAME); /** Each pattern's group 1, when it has one, is the table the statement locks. */ @@ -48,6 +76,28 @@ public final class LockWaitMigrationInspector { + "(?:[a-z0-9_$\"]+\\s+)??on\\s+(?:only\\s+)?" + NAME), Pattern.compile("\\bdrop\\s+index\\s+(?!concurrently\\b)"), + Pattern.compile( + "\\breindex\\s+(?:\\([^)]*\\)\\s+)?(?:(?:index|table)\\s+(?!concurrently\\b)" + + NAME + + "|(?:schema|database|system)\\b(?!\\s+concurrently\\b))"), + Pattern.compile("\\brefresh\\s+materialized\\s+view\\s+(?!concurrently\\b)" + NAME), + Pattern.compile( + "(? unboundedLockingStatements(String sql) { + return unboundedLockingStatements(sql, true); + } + + /** + * The same, for a migration file on disk: a {@code