fix!: r9 확인 리뷰가 찾은 결함 25건을 고친다

문제: r9 커밋(45d2a478)을 영역 4개로 다시 리뷰해 결함 25건을 찾았다
(Important 2, Minor 23, round6/01~04). Important 둘: r9가 @Configuration을
사용자 전송에서 통째로 빼서 설정 안의 RouterFunction·DataFetcher가
@SystemCaller를 불러도 잡히지 않는 회귀, 그리고 가이드대로 만든
CREATE INDEX CONCURRENTLY 마이그레이션이 Flyway 기본 트랜잭션 잠금과 서로
기다려 끝나지 않는 것(이전부터). 그 밖에 시작을 거절당한 같은 attempt가
기록 만료까지 503을 받는 것, gRPC 취소 판정과 raw status 설명의 로그 유출,
STOMP의 IAE ERROR 기록, 아무것도 잡지 못하던 shared-contract 패키지 규칙,
workflow 판독기의 거짓 통과 모양(-v·조건부 exit·Windows 기본 셸·요청형
trigger 등).

방법: 영역별 4묶음이 실패 테스트를 먼저 확인하고 고쳤다(재리뷰 README 17절).
- 설정과 그 중첩 클래스는 요청 처리기 타입에 의존하면 사용자 전송으로 센다.
- Flyway PostgreSQL 잠금을 세션 수준으로(transactional-lock=false), 직접
  만드는 Flyway는 FlywaySchemaPolicy 하나로. 버린 대안: CIC를 마이그레이션에서
  금지하고 운영 절차로.
- 같은 attempt로 다시 claim하면 lease가 지난 claim을 넘겨받는다. 옛 revision의
  늦은 시작이 ALREADY를 받아 이중 실행되던 것도 막았다.
- 네 전송이 IAE를 ServerFailureLog의 같은 WARN 한 줄로 남긴다.
- workflow 판독기가 세지 않는 이유를 셋으로 나누고 문서 5곳을 같은 말로.

위험·한계: Flyway 세션 잠금은 transaction-mode PgBouncer 뒤에서 깨진다
(Hikari 직접 연결 전제, 가이드에 적음). 배포 마이그레이션 도구도 같은 값을
써야 한다(업그레이드 안내). 같은 attempt를 두 호출이 동시에 쓰는 것은
저장소가 가려내지 않는다(호출자 계약으로 문서화).

검증: 묶음별 RED·GREEN은 로컬(노트북 빌드 금지 지시 전)에서, 지시 뒤에
바뀐 01 A5 fixture의 RED와 02 늦은 시작 revision 검사의 RED, 03 동시 인덱스
검사기 GREEN은 desktop에서 확인했다. 합친 트리를 desktop에서 돌려 모두 첫
실행 통과: :ci :verifyDependencyLocks --warning-mode=fail, sample check,
두 빌드 verifyStrictLaneStages --dry-run, :mainCheck, :integrationCheck,
-p optional-platforms ci integrationCheck performanceCheck, :performanceCheck,
:releaseCheck, compose 18 lane, -p build-logic check javadoc(README 17.2절).

Refs: docs/reviews/2026-11-03-rereview/README.md 17절
BREAKING CHANGE: Flyway PostgreSQL 잠금이 세션 수준이 되어 배포 도구에도
flyway.postgresql.transactional.lock=false가 필요하다. GraphQL·gRPC가 IAE를
WARN 한 줄로 남긴다. shared-contract 패키지 규칙이 실제로 검사한다.
This commit is contained in:
DongHyeonka
2026-11-05 21:26:50 +09:00
parent 45d2a478b8
commit 6e992970ca
97 changed files with 5152 additions and 934 deletions
+15 -6
View File
@@ -82,13 +82,22 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어
`releaseCheck`, optional-platforms 빌드: `-p optional-platforms`로 부르는 `ci`·`integrationCheck`·
`performanceCheck`·`releaseCheck`) 중 하나에 들어 있는지, 그리고 workflow의 접힌(`>`) run 블록이 빈
줄 때문에 옵션을 별개 명령으로 떼어 내지 않는지 검사한다. 두 빌드가 각자 검사를 돌린다. `-x`로 뺀
lane(Gradle처럼 축약 이름도 맞춰 본다), `continue-on-error` 아래 명령, 상태 함수(`always()`·`success()`·
`!cancelled()`)가 아닌 `if:` 아래 명령, `workflow_dispatch`로만 시작하는 workflow의 명령은 실행으로 세지
않는다. 실패해도 단계를 실패시키지 못하는 명령(`|| true`, pipefail 없는 파이프 왼쪽, `!`, `&`,
`if`·`while` 조건과 복합 명령·함수·명령 치환 안, `set +e` 뒤, 스크립트 마지막이 아닌 `&&` 목록)과
Gradle이 거부하는 명령줄(`-mx`)도 세지 않는다. 명령이 어느 빌드를 실행하는지는 `working-directory`에서
lane(Gradle처럼 축약 이름도 맞춰 본다)은 덮이지 않는다. Gradle이 작업을 돌리지 않는 명령(`--dry-run`·
`-m`·`-v`·`--help`·`--status`·`--stop`·`--foreground`, 묶음 `-qm`·`-qv` 포함)과 Gradle이 거부하는
짧은 옵션 묶음(`-mx`), 다른 빌드를 실행하는 명령은 세지 않는다. 그 밖에 세지 않는 명령은 이유가 셋이다.
(1) 실패해도 단계가 실패하지 않을 수 있다: `|| exit <0 아닌 값>` 밖의 `||`(`|| true` 등), pipefail 없는
파이프 왼쪽, `!`, `&`, `if`·`while` 조건, 스크립트 마지막이 아닌 `&&` 목록의 앞쪽, `set +e` 뒤,
`exit 0` 하는 `EXIT`·`ERR` trap 뒤, `continue-on-error`. (2) 돌지 않을 수 있다: `||` 뒤, 마지막이 아닌
`&&` 목록의 뒤쪽, `if`·`while`·`for`·`case`·함수 본문 안, 최상위 `exit`·`exec`·`set -n` 뒤, 조건부이거나
부른 함수 안의 `exit 0`(인자 없는 `exit`, 값을 모르는 `exit` 포함)·`exec`·`set -n` 뒤, 상태
함수(`always()`·`success()`·`!cancelled()`)가 아닌 `if:` 아래, 요청으로만
시작하는 workflow(`workflow_dispatch`·`repository_dispatch`·`issue_comment` 등), 세는 job이 부르지 않는
`workflow_call` 재사용 workflow, 조건부이거나 `continue-on-error`인 job을 `needs`로 기다리는 job.
(3) 실패하면 단계도 실패하지만 검사가 읽지 않는다: `|| exit 1`, `{ }`·`( )`·`$( )`·`bash -c` 안, 다른
명령의 인자인 `gradlew`, 따라갈 수 없는 `cd`(`cd "$VAR"`·`cd -`·`pushd`·조건부·서브셸 등) 뒤,
`bash`·`sh`가 아닌 `shell:`, Windows일 수 있는 runner의 기본 셸(`pwsh`). 실패 메시지는 명령마다 이유를
적고 단계 명령을 혼자 한 줄로 두라고 안내한다. 명령이 어느 빌드를 실행하는지는 `working-directory`에서
시작해 같은 셸이 그 앞에서 확실히 실행한 `cd <상대 경로>`를 따라간 뒤 `-p`를 합친 디렉터리로 정한다.
따라갈 수 없는 `cd`(`cd "$VAR"`·`cd -`·`pushd`·조건부·서브셸 등) 뒤의 명령은 추측하지 않고 세지 않는다.
작업 파일의 소유 leaf는 registry의 `source_path`로 판단하고 가장 가까운 `src/**/CLAUDE.md`를
함께 읽는다. focused test는 registry의 `gradle_path`에서
+15 -7
View File
@@ -40,13 +40,21 @@ If this summary drifts from `AGENTS.md`, `AGENTS.md` wins and this summary must
`releaseCheck` and the named repository-wide gates). `verifyStrictLaneStages --dry-run` (pull
request; the main build and, as `-p optional-platforms`, the optional build each run their own)
fails when a non-`explicitOnly` strict lane is in no stage a workflow executes — a lane the
command removes with `-x` (abbreviations matched as Gradle does), a command under
`continue-on-error` or a non-status `if:`, a command whose failure cannot fail its step
(`|| true`, a pipe without pipefail, an `if` condition, …), a command line Gradle rejects, and a
`workflow_dispatch`-only workflow do not count;
the build a command runs is its `working-directory`, then the `cd <relative path>` the same shell
surely ran before it, joined with `-p` (a `cd` it cannot follow is not guessed: the command does
not count) — or a folded workflow `run:` block splits an option off its command.
command removes with `-x` (abbreviations matched as Gradle does) is not covered; a command after
which Gradle runs no task (`--dry-run`, `-v`, `--help`, `--status`, `--stop`, …, bundles such as
`-qm` included), a short-option bundle Gradle rejects (`-mx`) and a command for another build do
not count, nor does one that does not gate for one of three reasons: (1) its failure may not fail
its step (an `||` other than `|| exit <non-zero>`, a pipe without pipefail, an `if` condition,
after `set +e` or an `exit 0` trap, `continue-on-error`, …); (2) it may not run (inside
`if`/`for`/`case` or a function, after a top-level or conditional `exit 0`, `exec` or `set -n`,
under a non-status `if:`, in a workflow only a request starts or a `workflow_call` one no counted
job calls, in a job that `needs` a conditional job, …); (3) the check does not read it although
its failure would fail the step (`|| exit 1`, inside `{ }`, `( )`, `$( )` or `bash -c`, after a
`cd` it cannot follow, a `shell:` other than bash or sh, a runner that may be Windows with its
`pwsh` default, …) — the failure names each command's reason and says to put the stage command
on a line of its own; the build a command runs is its `working-directory`, then the
`cd <relative path>` the same shell surely ran before it, joined with `-p` — or a folded workflow
`run:` block splits an option off its command.
Commit policy is `human-only`: agents do not stage, commit, amend, or push implementation changes.
+44 -9
View File
@@ -12,6 +12,24 @@ Design §31-§32. Flyway owns the schema; Hibernate only validates.
Migrating from inside the application in production means every instance of a rolling deploy races
to apply the same script, and the loser's failure is indistinguishable from a real one.
Whoever runs the migration holds Flyway's PostgreSQL migration lock for the session, not in a
transaction: `flyway.postgresql.transactional.lock=false`. Flyway's default (`true`) keeps a
transaction open until the whole run ends, and a concurrent index build waits for every transaction
older than itself, Flyway's own included — the deploy stops with no error and no time limit
("Concurrent index builds" below). The template sets it for every Flyway it runs: the module
defaults (`config/module-defaults/persistence-jpa.yml`, `spring.flyway.postgresql.transactional-lock:
false`) for the one Spring Boot builds at startup, and `FlywaySchemaPolicy.configure()` for every
stream it builds itself — a service's own stream starts from it too, and `JpaProductionArchitectureTest`
refuses production code that calls `Flyway.configure()` directly. The deployment-owned migration of
staging and prod is outside this repository: give its tool the same value
(`FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK=false`, or the key above in its configuration file).
A session lock assumes the connection Flyway takes stays its own for the whole run, which the
template's direct Hikari connection gives. Behind a pooler in transaction mode (PgBouncer
`pool_mode = transaction`) the unlock can reach another server connection and release nothing, and
the next migration waits for a lock that a pooled connection still holds. Run migrations over a
direct connection or a session-mode pool.
`ddl-auto` is `validate` or `none`. Never `update`: it never drops or narrows anything, so it
produces a schema that is neither the old one nor the one the migrations describe — silently, on
whichever instance started first.
@@ -84,30 +102,47 @@ stay that way (they are applied, and applied files are never edited); the test l
refuses any new one. `PostgreSqlMigrationLockWaitIntegrationTest`
(`postgresqlMigrationLockWaitIntegrationTest`) shows on real PostgreSQL that a bounded migration
gives up within the bound while another transaction holds the table, and leaves the version below
it; it also holds the inspector's copy of Flyway's list to Flyway itself (the statements it names
are exactly those Flyway refuses next to a `SET LOCAL`), and shows a `VACUUM FULL` run under
`mixed=true` waiting out a reader despite its `SET LOCAL`. The gRPC ledger's tree lives in the
it; it also compares the inspector's copy of Flyway's list with Flyway itself for the statements it
lists (each is named by the inspector exactly when Flyway refuses it next to a `SET LOCAL`), and
shows a `VACUUM FULL` run under `mixed=true` waiting out a reader despite its `SET LOCAL`. A
statement a Flyway upgrade adds to the list is outside that comparison; `LockWaitMigrationInspectorTest`
pins Flyway's own patterns (`PostgreSQLParser`), so such an upgrade fails the pull request's `ci`
until the copy follows. The gRPC ledger's tree lives in the
optional build, which cannot depend on the testkit: its `GrpcOperationLedgerMigrationLockWaitIT`
runs every ledger migration after V001, read from the tree, against a held ledger instead, so its
next migration is checked on real PostgreSQL. It finds and orders that tree with the testkit's own
`VersionedMigrationFiles`, which the ledger's `build.gradle` copies into its integration-test sources
at build time (`sharedMigrationFileSources`), so both builds read one definition. The rule came from
V21 having the bound and V22, in the same commit, not having it (re-review 2026-11-03 round 2,
RR-02-09; round 3, RR3-02-01, RR3-02-03, RR3-02-04; round 4, RR4-02-01).
RR-02-09; round 3, RR3-02-01, RR3-02-03, RR3-02-04; round 4, RR4-02-01; round 6, RR6-03-02,
RR6-03-03).
## Concurrent index builds
`CREATE INDEX CONCURRENTLY` cannot run inside a transaction block, and Flyway wraps migrations in
one by default. Flyway recognizes `CREATE`/`DROP INDEX CONCURRENTLY` and runs such a script outside
the transaction on its own (above), but not `REINDEX … CONCURRENTLY`; write the companion
configuration for every concurrent statement anyway, so the file says what it needs and no reader
has to know Flyway's list:
`CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY` and `REINDEX … CONCURRENTLY` cannot run
inside a transaction block. Flyway recognizes `CREATE`/`DROP INDEX CONCURRENTLY` and runs such a
script outside a transaction on its own (above), but not `REINDEX … CONCURRENTLY`, which it runs in
the transaction for PostgreSQL to refuse. Write the companion configuration for every concurrent
statement anyway, so the file says what it needs and no reader has to know Flyway's list:
```conf
# V42__order_index.sql.conf
executeInTransaction=false
```
Outside a transaction, `CREATE INDEX CONCURRENTLY` and `REINDEX … CONCURRENTLY` still wait until
every transaction older than them has ended. Under Flyway's default lock that includes the
transaction Flyway itself keeps open, and Flyway waits for the build in turn: the deploy never ends,
and the table's other DDL and autovacuum queue behind the build meanwhile. The template's Flyway
holds its lock for the session instead ("Who may change the schema"), so the build waits only for
other transactions; a deployment tool left on Flyway's default stops on the first such migration.
`DROP INDEX CONCURRENTLY` does not wait that way. `PostgreSqlConcurrentIndexMigrationIntegrationTest`
(`postgresqlConcurrentIndexMigrationIntegrationTest`) applies both builds as a second deploy, with
the Flyway Spring Boot builds from the module defaults and with `FlywaySchemaPolicy.configure()`,
on real PostgreSQL. The other transactions still count: a long one an operator or a report keeps
open holds the build, and a file run outside a transaction cannot bound that wait with `SET LOCAL`.
Look for old transactions (`pg_stat_activity.xact_start`) before deploying one.
The testkit's `ConcurrentIndexMigrationInspector` checks a script for this in a migration test
(nothing checks it at startup), and additionally requires the migration to contain nothing else. A failed concurrent build leaves an invalid index behind;
recovering is a single `DROP INDEX` when the migration did nothing else, and a manual reconstruction
+3
View File
@@ -119,6 +119,9 @@ capability 스트림 db/migration/jpa/<capability> 각자 histor
`SamplePostgreSqlPersistenceConfig.sampleMigrationStrategy`
(`src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfig.java`)와
`NotificationSchemaStream`(persistence-notification). 그러면 번호가 템플릿 스트림과 독립이라 V1부터 쓴다.
자기 스트림의 Flyway는 `Flyway.configure()`가 아니라 `FlywaySchemaPolicy.configure()`(persistence-jpa)로
만든다. Flyway의 PostgreSQL 잠금을 세션에 두어야 `CREATE INDEX CONCURRENTLY` 마이그레이션이 끝나고,
직접 부르면 `:app-bootstrap:architectureTest`가 실패한다(`docs/jpa/migration-guide.md` "Who may change the schema").
- **예외**: 템플릿 운영 스트림(`db/migration/postgresql`)에 직접 넣으면 upstream이 다음에 쓸 번호와
겹친다. 어쩔 수 없으면 upstream이 쓰지 않을 큰 번호대를 정해 문서에 적는다.
- 이미 적용된 파일은 고치지 않는다. 고치면 체크섬 불일치로 기동이 멈추고, `repair`는 쓰지 않는다
+8 -2
View File
@@ -54,8 +54,11 @@ DB 커밋 중 연결 끊김 ─────────────────
| 500 `IDEMPOTENCY_RECOVERY_REQUIRED` | 이전 시도 효과를 증명 못함 | 자동 재시도 안 함. 같은 키 재전송은 안전(재생·실행·다시 500을 서버가 판정, 다시 돌리지 않음). 업무 데이터로 확인하고, 효과가 없다고 확인된 뒤에만 운영 절차에 따라 새 키 |
| 500 `DB_COMPLETION_UNKNOWN`, `retryable=false` | DB 커밋 중 연결 끊김. 커밋됐을 수도 있음 | 키 없이 재시도 금지. KEYED면 같은 키로 재전송하면 서버가 판정 |
같은 키 재전송은 작업을 다시 돌리지 않는다. 다만 첫 시도가 processing lease(기본 30s)보다 오래 걸릴 때
보이는 모습은 저장소마다 다르다(재리뷰 2026-11-04 RR5-01-05, 정본 `docs/web/http-contract.md` 2절).
같은 키 재전송이 무엇을 막는지는 저장소마다 다르다(재리뷰 2026-11-04 RR5-01-05, 라운드6 RR6-02-05, 정본
`docs/web/http-contract.md` 2절). Redis 저장소에서 같은 키 재전송은 효과가 있었을 수 있는 작업을 다시 돌리지
않는다. PostgreSQL 저장소를 템플릿처럼 쓰기 트랜잭션 하나로 쓰면 실패한 요청의 기록은 롤백되어 다음 같은 키
요청이 다시 실행한다. 그래서 트랜잭션 밖 효과는 따로 멱등하게 만든다. 첫 시도가 processing lease(기본 30s)보다
오래 걸릴 때 보이는 모습도 저장소마다 다르다.
- **Redis**: 첫 시도가 실행을 시작한 뒤 lease가 지나면 그 기록을 넘겨주지 않고 500
`IDEMPOTENCY_RECOVERY_REQUIRED`로 답한다. 넘겨받는 것은 실행 전 claim과 재시도 가능한 실패뿐이다. 이 답은
@@ -71,6 +74,9 @@ DB 커밋 중 연결 끊김 ─────────────────
claim의 lease가 작업 시작 전에 끝나면 두 저장소 모두 시작을 거절하고(`LEASE_EXPIRED`), executor는 작업을
돌리지 않은 채 503 `IDEMPOTENCY_UNAVAILABLE`로 답한다. 다음 같은 키 요청이 그 claim을 넘겨받아 실행한다.
`IdempotencyClaimAttempt`를 재시도 사이에 들고 있다가 같은 attempt로 다시 부르는 호출자도 넘겨받는다(라운드6
RR6-02-01. 전에는 같은 claim을 재생받아 시작을 다시 거절당해 기록이 사라질 때까지 503이었다). 같은 attempt를
두 호출이 동시에 쓰면 서버가 가려내지 못하므로, 재시도는 앞 호출이 돌아온 뒤에 한다.
기록은 lease + `replay-ttl` 동안 남고, `replay-ttl`이 lease보다 짧으면 기동이 실패한다
(`IdempotencyStoreContract`, 재리뷰 2026-11-04 RR-01-11·RR-03-11). 작업이 실패로 끝나 executor가 포기나
재시도 가능으로 표시한 기록은 표시한 때부터 `failure-retention`(기본 24h) 동안 남는다(PostgreSQL을 트랜잭션
+12 -7
View File
@@ -102,14 +102,15 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re
| 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·JAX-RS·GraphQL·STOMP mapping·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) |
| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등)에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 사용자 전송 패키지에 있는 클래스, 또는 사용자 전송 타입에 의존하는 클래스 가운데 설정(`@Configuration`·`@AutoConfiguration`)이 아닌 것이다. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`·interceptor·controller bean을 함께 만들어도 걸리지 않는다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) |
| 프로젝트 밖 상위 타입 금지 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스(익명·지역 클래스 제외)는 프로젝트(`dev.caskeleton..`) 밖의 클래스·인터페이스를 상속·구현하지 않는다. `Runnable`은 누구나 의존하는 타입이라, endpoint가 작업을 `Runnable`로 주입받아도 위 규칙이 다른 사용과 구별하지 못하기 때문이다. 메시지 handler의 `MessageHandler<T>`는 프로젝트 타입이라 된다 | `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`(같은 파일) |
| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등)에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 셋이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`)과 그 안에 중첩된 클래스 가운데 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor` 등)에 의존하는 것. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. ③ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·controller bean을 함께 만들어도 걸리지 않지만, 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 직접 쓰면 걸린다. 요청 처리 코드는 handler를 등록하는 설정과 다른 클래스에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) |
| 프로젝트 밖 상위 타입 금지 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스(익명·지역 클래스와 예외 제외)는 프로젝트(`dev.caskeleton..`) 밖의 클래스·인터페이스를 상속·구현하지 않는다. `Runnable`은 누구나 의존하는 타입이라, endpoint가 작업을 `Runnable`로 주입받아도 위 규칙이 다른 사용과 구별하지 못하기 때문이다. 메시지 handler의 `MessageHandler<T>`는 프로젝트 타입이라 된다. record·enum은 언어가 붙이는 상위 타입(`Record`, `Enum`과 `Enum`이 구현하는 `Comparable`·`Serializable`·`Constable`)만은 가져도 된다. 그래서 handler 안의 파싱 결과 record, 결과 enum, 독(poison) 메시지 예외, record로 쓴 handler는 통과하고, `Runnable`을 구현한 record는 걸린다 | `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`(같은 파일) |
규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 이 성질은 **패키지** 쪽에서만 온다.
패키지는 허용 목록이라, 나중에 새 전송 패키지가 생겨도 따로 고치지 않아도 막힌다. 사용자 전송 **타입**
쪽은 나열 목록이다(`ARE_USER_TRANSPORT_TYPES`). 시스템 패키지 안에 놓인 endpoint를 알아보는 데 쓰는
목록이라, 목록에 없는 전송 라이브러리로 만든 endpoint는 전송으로 보이지 않는다. 새 전송 라이브러리를
들이면 그 패키지를 이 목록에 더한다.
들이면 그 패키지를 이 목록에 더한다. 설정 안의 요청 처리 코드를 알아보는 요청 처리기 타입
(`ARE_REQUEST_HANDLER_TYPES`)도 나열 목록이라, 새 전송 라이브러리의 handler 타입을 함께 더한다.
D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표시를 쓰지 않는다. 사용자가 부르는
쓰기라면 권한을 선언하고 역할에 매핑한다. 같은 쓰기를 사용자도 시스템도 부르면 유스케이스를 둘로 나눈다
@@ -122,7 +123,10 @@ D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표
- 이름이나 `Object`로 bean을 찾는 코드: `getBean("nightlyJob")`, `Map<String, Object>` 주입 뒤 reflection 호출.
- 설정이 사용자 전송에 작업을 감싼 함수를 넘기는 코드: `new RunNowController(job::run)`처럼 controller는
`Runnable`만 받는다. 의존은 설정 → 작업 쪽에만 있고, 설정은 사용자 전송이 아니다.
`Runnable`만 받는다. 의존은 설정 → 작업 쪽에만 있고, 요청 처리 코드를 직접 갖지 않은 설정은 사용자 전송이
아니다.
- 설정 안의 요청 처리 코드가 요청 처리기 타입 목록(`ARE_REQUEST_HANDLER_TYPES`)에 없는 타입으로 쓰인 경우.
목록 방식이라, 목록에 없는 endpoint 타입으로 설정 안에 쓴 endpoint는 사용자 전송으로 보이지 않는다.
이 길을 막는 것은 ArchUnit 규칙이 아니라 다음 셋이다.
@@ -131,9 +135,10 @@ D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표
- 의존 방향 게이트(`src/config/architecture/modules.json`): 등록된 leaf 가운데 `adapter:inbound:messaging`에
의존할 수 있는 것은 조립 루트(`app-bootstrap`)뿐이다. 다른 leaf의 사용자 전송은 handler 타입을 컴파일조차
못 한다. 예약 작업은 서비스 자기 leaf에 있어서 같은 leaf의 controller와 사이에는 이 게이트가 없다. 그래서
위 두 길은 사실상 controller와 작업이 같은 leaf에 있을 때, 또는 둘을 모두 보는 설정에서 생긴다.
- 리뷰: 설정에서 시스템 호출자를 함수로 감싸 다른 bean에 넘기거나, 사용자 전송이 bean을 이름으로 찾는 코드는
리뷰에서 거절한다. 사용자도 같은 일을 시켜야 하면 위 문단대로 사용자용 유스케이스를 따로 만든다.
위 길들은 사실상 controller와 작업이 같은 leaf에 있을 때, 또는 둘을 모두 보는 설정에서 생긴다.
- 리뷰: 설정에서 시스템 호출자를 함수로 감싸 다른 bean에 넘기거나, 사용자 전송이 bean을 이름으로 찾거나, 목록에
없는 타입으로 설정 안에 endpoint를 쓰는 코드는 리뷰에서 거절한다. 사용자도 같은 일을 시켜야 하면 위 문단대로
사용자용 유스케이스를 따로 만든다.
## web 없는 조립
@@ -591,8 +591,12 @@ compose 실제 기동은 묶음 에이전트가 lane별로 확인했다: local-f
## 17. 커밋 단위 계획
저장소 정책이 `human-only`라 커밋하지 않았다. 사람이 그대로 쓸 수 있는 커밋 자료를
`../clean-architecture-backend-template-commit-kit/`(repo 밖, 같은 상위 폴더)에 두었다.
저장소 정책이 `human-only`라 커밋하지 않았다. 사람이 그대로 쓸 수 있는 커밋 자료(패치 세 개와 메시지)를
repo 밖 `../clean-architecture-backend-template-commit-kit/`에 두었다.
2026-11-03 소유자 지시로 이 세 커밋을 브랜치 `refactor/maturity-review-2026-11`에 만들고 push했다:
`34565130`(1), `1400dc15`(2), `5786126c`(3). 2026-11-05에 패치 세 개를 `01a8a2a70`에 차례로 적용한
트리가 세 커밋의 트리와 각각 같음을 확인하고 자료 폴더를 지웠다. 아래는 그때의 계획 기록이다.
### 17.1 고른 단위와 이유
@@ -608,8 +612,7 @@ compose 실제 기동은 묶음 에이전트가 lane별로 확인했다: local-f
- 발견 하나씩 커밋하려면 라운드 사이에 손으로 합친 충돌(14.1·16.1절)을 커밋마다 다시 풀고 중간 트리마다 게이트를 다시 돌려야 한다. 그 중간 트리는 검증된 적이 없다. 검증된 경계에서만 나누는 쪽을 골랐다.
- 리뷰어는 커밋 diff 대신 이 README의 13·14·16절 표(발견별 RED·GREEN·결정)를 따라가며 본다.
### 17.2 쓰는 법
### 17.2 쓰는 법 (끝남)
`../clean-architecture-backend-template-commit-kit/README.md`를 본다. 요약: 스크립트가 별도 worktree에
새 브랜치를 만들고 패치 세 개를 차례로 적용해 커밋한다. 메인 작업 트리는 건드리지 않는다. 마지막에
브랜치 트리가 메인 작업 트리와 같은지 비교한다.
자료 폴더의 스크립트가 별도 worktree에 새 브랜치를 만들고 패치 세 개를 차례로 적용해 커밋하는 방식이었다.
위 세 커밋으로 끝났고 자료 폴더는 2026-11-05에 지웠다.
@@ -361,3 +361,20 @@ Minor 중 RR5-01-01(`IDEMPOTENCY_RECOVERY_REQUIRED`의 클라이언트 안내가
| `scripts/verify-compose-profile-contracts.sh` | rc=0, 18 lane | — | 18.44 |
`mainCheck`·`integrationCheck`는 16.1절 수정 전 트리에서 돌았다. 그 수정은 httpclient만 바꿔서 httpclient `check`·`testQualityCheck`·`httpClientFailureInjectionTest`·`httpClientPerformanceTest`를 따로 다시 돌렸다(통과).
## 17. r9 확인 리뷰 round6과 수정 r10 (2026-11-05)
`45d2a478`(r9)을 영역 4개로 나눠 리뷰했다(`round6/01~04`). 결함 25건(Important 2, Minor 23). 01의 RR6-01-07과 02의 RR6-02-03은 같은 runbook 문장이라 한 번 고쳤다. 영역 묶음 4개가 `45d2a478`에서 고쳤고, 고치다 새로 찾은 결함도 고쳤다.
| 묶음 | 리뷰 결과 | 처리 | 결정 |
|---|---|---|---|
| r10-01 core·inbound | Important 1(RR6-01-01 회귀), Minor 8 | 설정·그 중첩 클래스는 요청 처리기 타입에 의존하면 사용자 전송으로 센다(A1 `RouterFunction`·A2 `DataFetcher` 위반 fixture, A5 허용 fixture). `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`는 예외를 빼고 record·enum은 언어가 주는 상위 타입만 허용(`Runnable`을 구현한 record는 여전히 잡힘). gRPC는 `isCancelled()`일 때만 로그를 건너뛰고, 던진 raw status는 로그에 붙이지 않는다. `ServerFailureLog.refusedArgument`로 네 전송이 IAE를 같은 WARN 한 줄로 남긴다(GraphQL·gRPC 동작 변경). runbook 문구, GraphQL carrier 테스트. 이전부터의 `SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES`를 `dev.caskeleton.shared..` 대상·정확한 12개 목록으로 고치고 "KNOWN DEFECT" 주석을 지웠다(업그레이드 B-42) | 요청 처리기 타입 목록은 리뷰어 예보다 넓게(설정에 중첩된 `@RestController`도 잡힘) |
| r10-02 멱등성·outbound | Minor 5 | 같은 attempt로 다시 claim하면 lease가 지난 `CLAIMED`와 `FAILED_RETRYABLE`을 넘겨받는다(Redis·PG·command fake·in-memory fake). 새로 찾아 고친 것: 옛 revision을 든 늦은 시작이 Redis에서 `ALREADY`를 받아 이중 실행됨 → 기록 revision이 핸들 revision + 1일 때만 `ALREADY`. PG의 다른 핸들 시작 답을 Redis와 같게(`NOT_OWNER`/`NOT_CLAIMED`). 같은 attempt의 `FAILED_RETRYABLE`·`ABANDONED` 답이 저장소마다 달랐던 것, in-memory fake가 fingerprint 검사 전에 기록을 넘겨준 것. command fake 위 계약이 시계를 움직인다(skip 17 → 0), fixture에 key TTL, 계약과 겹친 adapter 손 사본 20건 삭제. 503 뜻을 web README·인계 표에, 매뉴얼 05 첫 문장을 저장소별로 | RR6-02-01은 (a)안: 문서와 503 `retryable`이 약속하는 동작에 코드를 맞춘다. 같은 attempt를 두 호출이 **동시에** 쓰는 것은 attempt 정의(한 번의 순차 송신·재시도) 밖이라 저장소가 가려내지 않는다 — 결함이 아니라 호출자 계약으로 Javadoc·매뉴얼 05에 적었다 |
| r10-03 persistence | Important 1(RR6-03-01, 이전부터), Minor 4 | Flyway PostgreSQL 잠금을 세션 수준으로: module-defaults `spring.flyway.postgresql.transactional-lock: false`, 직접 만드는 Flyway는 `FlywaySchemaPolicy.configure()` 하나로(messaging은 persistence-jpa에 의존할 수 없어 같은 값 사본 + 대조 테스트), 직접 `Flyway.configure()`를 부르면 실패하는 ArchUnit 규칙, 실 PG IT(옛 설정 30초 정지 4/4 → 1.2초). 검사기의 `E'…\'…'` 판독과 중첩 주석, `PostgreSQLParser` 트랜잭션 밖 패턴을 PR `ci`에서 고정, IT 대조 목록 +6, ledger Spotless에서 Sync 사본 제외, "Flyway는 늘 트랜잭션으로 감싼다" 설명 정정. 새로 찾아 고친 것: 동시 인덱스 검사기가 `UNIQUE`·`REINDEX (CONCURRENTLY)`를 못 찾음 | RR6-03-01은 session-level 잠금(Flyway가 이 문제로 둔 공식 옵션). 버린 대안: CIC를 마이그레이션에서 금지하고 운영 절차로(큰 테이블 인덱스 추가가 번거로워짐). 전제: Hikari 직접 연결 — transaction-mode PgBouncer 뒤에서는 세션 잠금이 깨진다(가이드에 적음) |
| r10-04 build-logic | Minor 6 | 작업 없이 끝나는 Gradle 옵션(`-v`·`--help`·`--status`·`--stop`·`--foreground`, 묶음 포함)을 세지 않는다. `GradleCommandLineTest`가 판독기 옵션 표를 실행 중인 Gradle `--help`와 대조(9.2.0으로 돌리면 `task-graph`로 실패). 조건부 `exit 0`·`exec`·`set -n`·함수 안 exit·EXIT/ERR trap 뒤 명령, Windows일 수 있는 `runs-on`의 기본 셸, 요청형 trigger만 있는 workflow, 세는 호출자가 없는 `workflow_call`, 조건부 job을 `needs`로 기다리는 job을 세지 않는다. 세지 않는 이유를 셋(실패를 막지 못함 / 돌지 않을 수 있음 / 판독기가 읽지 않음)으로 나눠 메시지와 문서 5곳에 같은 말로 | 이 repo workflow에서 세는 명령 48개는 수정 전후 같다 |
합칠 때: 네 묶음 모두 `45d2a478` 기준이고 충돌 없이 적용됐다(92파일). 업그레이드 안내의 새 행 번호는 겹치지 않는다.
### 17.1 검증 위치 변경
2026-11-05 소유자 지시: 노트북에서 Gradle·Docker를 돌리지 않는다. 지시 전에 각 묶음이 로컬에서 RED·GREEN과 leaf `check`를 돌렸고, 지시 뒤의 변경(01의 A5 fixture 재작성, 03의 동시 인덱스 검사기 GREEN)과 합친 트리 전체는 desktop(`~/workspace/clean-architecture-backend-template`)에서 git pull 뒤 검증한다. 결과는 17.2절.
@@ -0,0 +1,218 @@
# 01 core·inbound r9 리뷰 (2026-11-05)
> 대상: `c508b1ba..45d2a478`의 r9-a 묶음. RR4-01-01·02(`@SystemCaller` 규칙), `graphql..` fixture, 원래 리뷰 16.3절
> (템플릿 패키지 목록 두 벌), RR4-03-03(전송별 실패 로그).
## 범위
### pathspec
```
src/application-core src/shared-contract src/adapter/inbound src/grpc src/composition/service-runtime src/app-bootstrap
docs/manual/07-authorization.md docs/runbooks/idempotency-unavailable.md docs/upgrade/2026-11-maturity-review.md
```
`git diff --stat c508b1ba..45d2a478 -- <pathspec>`: 57개 파일, +1956 −187. 새 파일(`ServerFailureLog`, `StompHandlerFailureLog`,
`TemplatePackageOwnershipDocumentTest`, fixture 13개)은 HEAD 전체를 읽었다. 바뀐 클래스는 diff와 함께 주변 코드
(`GrpcServerRunner` 인터셉터 순서, `WebSocketCorrelationInterceptor`, `GraphQlExceptionResolver`, `GlobalExceptionHandler`
전체 분기)를 읽었다.
### 불러온 스킬과 적용한 기준
| 스킬 | 기준 | 본 것 |
|---|---|---|
| `superpowers:requesting-code-review` | 주장(README 16절 r9-a)과 구현이 맞는가, 테스트가 이름대로의 동작을 보는가, 심각도 보정, Declined to judge, 읽기 전용(별도 worktree). 하위 에이전트는 띄우지 않고 diff를 여러 번에 나눠 직접 봤다 | 항목마다 닫힘 여부, 새 테스트의 이름과 준비 상태가 맞는지(RR6-01-04·08), 결함마다 실행 증거 |
| `clean-architecture` | Dependency Rule, "Main(조립 설정)은 바깥의 plugin", Humble Object(경계 코드는 얇게) | 조립 설정을 사용자 전송에서 뺀 판단이 "설정은 요청을 받지 않는다"는 가정에 기대는데, Spring 함수형 endpoint는 설정 클래스 안에 요청 처리 코드를 둔다(RR6-01-01). 템플릿 패키지 목록의 정본과 복사본 |
| `security-and-hardening` | 권한 검사는 모든 요청 경로에서, 민감 정보는 로그에 남기지 않는다("Never log sensitive data"), 오류 상세는 서버 로그로만 | 권한 없는 쓰기로 가는 우회 경로(RR6-01-01). 전송별 로그가 SQL·입력값을 싣는지(RR6-01-05·06). 4xx를 사고로 남기는지 |
### 실행한 명령과 결과
모든 실행은 `git worktree add --detach <scratchpad>/rr6-01 45d2a478`에서 했다. Gradle은 공유 `heavy.lock`으로 감쌌다.
탐침 코드(fixture·테스트)와 결과 파일은 공유 노트 폴더 `rr6-01-probes/`에 그대로 두었다. 고칠 때 fixture로 옮겨 쓸 수 있다.
| 명령 | 결과 | 직전 부하(1분) |
|---|---|---|
| `./gradlew :app-bootstrap:architectureTest --tests …Rr6ProbeTest :app-bootstrap:documentContractTest --tests …Rr6TablePairProbeTest :adapter:inbound:grpc:test --tests …Rr6GrpcProbeTest :adapter:inbound:websocket:test --tests …Rr6StompProbeTest --continue` | 표 대조·gRPC·STOMP 탐침 실행됨. architectureTest 탐침은 내 코드의 Error Prone 경고로 컴파일 실패 | 4.72 |
| `./gradlew :app-bootstrap:architectureTest --tests …Rr6ProbeTest` | rc=0. 탐침 A1~A7 결과는 결함마다 | 4.94 |
| `./gradlew :app-bootstrap:architectureTest --tests …Rr6AllRulesProbeTest` | 첫 실행은 내 탐침이 빈 규칙의 AssertionError를 안 잡아 실패. 고친 뒤 rc=0: 정적 `@ArchTest` 규칙 89개를 함수형 endpoint 설정 두 개에 돌려 위반 0(7개는 대상 클래스 없음) | 4.26 / 2.74 |
| `./gradlew :app-bootstrap:architectureTest --tests …Rr6SharedProbeTest` | rc=0. `dev.caskeleton.shared.rr6bogus` 클래스에 `SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES` 위반 없음 | 2.39 |
탐침의 모양:
- A1·A2: `@Configuration`(사용자 전송 패키지 밖)이 `RouterFunction` 람다 / graphql-java `DataFetcher` 람다 안에서 `@SystemCaller` 작업을 부른다. 새 규칙과 `c508b1ba` 판정식(설정 제외 없음)을 같은 클래스에 돌렸다. A1c: 같은 route를 `@Component`에 두었다(통제군).
- A3·A7: `@SystemCaller` 안의 중첩 record·enum·예외, record로 쓴 `@SystemCaller`.
- A4: production 클래스 3,415개에서 사용자 전송 570개가 `MessageHandler`에 닿는지.
- A5: RR4-01-02 모양에서 익명 `WebMvcConfigurer`가 설정의 필드를 읽는다.
- A6: 프로젝트 추상 클래스가 `Runnable`을 구현하고 `@SystemCaller`가 그것을 상속한다.
- 표 대조 C0~C5: `TemplatePackageOwnershipDocumentTest`의 `root`를 임시 트리로 바꿔 표만 늘리기, 표에서 빼기(클래스에만 남김), 소유 leaf 바꾸기, 패키지 디렉터리 없애기, domain 표만 늘리기.
- gRPC: 실제 Netty 서버(127.0.0.1, 포트 0)에 `GrpcExceptionHandlingInterceptor`를 걸고 실제 클라이언트로 불렀다.
- STOMP: `StompHandlerFailureLogTest`와 같은 실제 `WebSocketAnnotationMethodMessageHandler`로 `@MessageMapping`이 `IllegalArgumentException`을 던지게 했다.
### 못 본 것
- 멱등성 저장소(store·Lua)와 그 계약 테스트 변경은 02 영역이라 판단하지 않았다. application-core의 executor·enum Javadoc 변경은 읽기만 했다.
- `src/grpc/grpc-operation-ledger-jpa` 변경(r9-c)은 03 영역이라 보지 않았다.
- r9 게이트(`ci`, `mainCheck` 등)는 다시 돌리지 않았다. 탐침은 `--tests`로 좁힌 실행뿐이다.
## 항목 재확인
| ID | 판정 | 근거 |
|---|---|---|
| RR4-01-01 (인터페이스·`Runnable` 주입을 못 봄, 문서가 반대로 적음) | 닫힘 | 대상 술어 `ApplicationBoundaryArchitectureTest.java:555-566`, 새 규칙 `:664-707`, fixture `SystemJobInterfaceInvokingControllerFixture`·`RunnableSystemJobFixture`·`IndirectlyRunnableSystemJobFixture`. 탐침 A6(상위 추상 클래스 경유 `Runnable`)도 잡힌다. 매뉴얼 07 `:118-131`이 못 보는 길(이름 조회, 설정이 넘기는 함수)을 바르게 적는다. 탐침 A4: production 사용자 전송은 `MessageHandler`에 닿지 않아 정석 handler 모양은 거짓 양성이 없다. 새 규칙의 거짓 양성은 RR6-01-03 |
| RR4-01-02 (웹 bean을 함께 만드는 설정의 거짓 양성) | 부분 | 두 모양(`WebMvcConfigurer`, controller bean)은 허용 fixture로 통과한다. 익명 configurer가 설정의 상태를 쓰면 아직 걸린다(RR6-01-02). 고친 방법(설정 통째로 제외)이 새 구멍을 냈다(RR6-01-01) |
| RR3-01-01 (사용자 전송 → `@SystemCaller` 금지, r6에서 닫힘) | 회귀 | 설정 안의 함수형 endpoint가 `@SystemCaller`를 불러도 더는 잡히지 않는다. `c508b1ba` 판정식은 잡았다(RR6-01-01) |
| `graphql..` fixture | 닫힘 | `GraphQlJavaSystemCallerFixture`(graphql 타입 하나만 씀), `ArchitectureViolationFixtureTest.aGraphQlJavaDataFetcherMarkedAsASystemCallerIsCaught`. `app-bootstrap/build.gradle:284` compileOnly, lockfile은 `architectureTestCompileClasspath` 표시만 늘었다 |
| 원래 리뷰 16.3 (템플릿 패키지 목록 두 벌) | 닫힘 | `TemplatePackageOwnershipDocumentTest`. 탐침 C1~C5가 표만·클래스만·소유 leaf·디렉터리 누락·domain 표를 모두 실패시켰고 C0은 통과했다. 목록에 없는 새 템플릿 패키지는 못 잡는다는 한계는 `src/application-core/CLAUDE.md:169-171`에 적혀 있다 |
| RR4-03-03 (gRPC가 회복 필요 실패를 로그에 안 남김) | 닫힘 | carrier 분기 `GrpcExceptionHandlingInterceptor.java:125-130`, 테스트 `aServerSideCarrierIsLoggedAtError…`. runbook `:50-56`에 전송별 상관 정보. gRPC MDC 주장은 인터셉터 순서(`GrpcServerRunner.java:117-133`, correlation이 exception 바깥)로 맞다 |
| r9-a가 새로 고친 것: gRPC `INTERNAL_ERROR` 무기록 | 부분 | 기록은 생겼다. 그러나 "클라이언트 취소" 판정이 틀리고(RR6-01-04), raw status 설명이 던진 경로로 로그에 남는다(RR6-01-05) |
| r9-a가 새로 고친 것: STOMP가 persistence SQL 원인을 로그에 씀 | 닫힘 | `StompHandlerFailureLog.java:31-35`, 실제 method handler 테스트. 다만 IAE를 ERROR로 남긴다(RR6-01-06) |
| web 로그 리팩터링 | 닫힘 | `GlobalExceptionHandler.java:171-183`. persistence(분류만, span 정리)·dependency·5xx·4xx 네 갈래가 전과 같다(E1, 분기 대조) |
## 결함
### RR6-01-01 · Important · 설정을 사용자 전송에서 통째로 빼서, 설정 안의 함수형 endpoint가 `@SystemCaller`를 불러도 잡히지 않는다 (회귀)
- **위치**: `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java:516-519`(설정 제외),
`:497-505`(Javadoc "Leaving it out opens nothing"), `docs/manual/07-authorization.md:105`, `:118-131`(「규칙이 못 보는 길」에 없음),
`docs/upgrade/2026-11-maturity-review.md` B-16.
- **무엇이 틀렸나**:
- r9는 `@Configuration`·`@AutoConfiguration` 클래스를 사용자 전송으로 세지 않는다. 근거는 "설정은 조립 루트지 요청이 들어오는 곳이 아니다"이다.
- Spring MVC 함수형 endpoint(`RouterFunction`)와 graphql-java `DataFetcher`는 요청 처리 코드를 람다로 쓴다. 람다 본문은 그 람다를 쓴 설정 클래스의 메서드로 컴파일된다. 그래서 그 설정 클래스가 곧 endpoint다.
- 탐침 A1: 사용자 전송 패키지 밖 `@Configuration`이 `POST /admin/nightly/run-now` route 람다에서 `@SystemCaller` 작업의 `run()`을 부른다. 새 규칙은 위반 0. `c508b1ba` 판정식은 위반 1. 같은 route를 `@Component`에 두면(A1c) 새 규칙도 위반 1.
- 탐침 A2: GraphQL `runNow` mutation의 `DataFetcher` 람다로 같은 모양. 새 규칙 위반 0, `c508b1ba` 판정식 위반 1.
- 다른 규칙도 막지 않는다. 정적 `@ArchTest` 규칙 89개를 두 설정에 돌려 위반이 0이었다.
- Javadoc은 "설정을 빼도 열리는 길이 없다. 설정이 만드는 controller는 자신이 검사받는다"고 적는다. 매뉴얼 07과 업그레이드 안내도 설정은 걸리지 않는다고만 적는다. 이 길은 「규칙이 못 보는 길」 목록에도 없다.
- **발생 조건·영향**:
- 조건: 파생 서비스가 "지금 실행" endpoint를 함수형으로 쓰고, 그 route 또는 fetcher를 작업과 같은 leaf의 설정 클래스(사용자 전송 패키지 밖)에 둔다. 매뉴얼 07 `:95`는 예약 작업이 controller와 같은 leaf에 놓이기 쉽다고 적는다. 함수형 endpoint는 Spring이 문서로 권하는 방식 가운데 하나다.
- 영향: 인증만 된 사용자 요청이 권한 검사 없는 `@SystemInvoked` 쓰기를 부른다. 빌드는 아무 신호도 내지 않는다. r6에서 막은 RR3-01-01과 같은 피해다.
- Important로 둔 이유: 이 커밋이 만든 회귀다. 문서 세 곳이 이 길이 닫혀 있다고 말한다. 조건은 RR3-01-01·RR4-01-01과 같은 "같은 leaf"라서 Critical·High는 아니다.
- **고치는 법**:
1. 설정 제외에 예외를 둔다. 설정이 요청 처리기를 만드는 타입에 직접 의존하면 사용자 전송으로 센다. 목록 예: `org.springframework.web.servlet.function..`, `org.springframework.web.reactive.function.server..`, `org.springframework.web.HttpRequestHandler`, `org.springframework.web.servlet.HandlerInterceptor`, `org.springframework.web.socket.WebSocketHandler`, `jakarta.servlet.Servlet`, `jakarta.servlet.Filter`, `graphql.schema.DataFetcher`, `org.springframework.graphql.execution.RuntimeWiringConfigurer`, `io.grpc.BindableService`, `io.grpc.ServerServiceDefinition`, `io.grpc.ServerCallHandler`. `WebMvcConfigurer`·`CorsRegistry` 같은 설정용 타입은 넣지 않는다(RR4-01-02 허용 fixture가 계속 통과해야 한다).
2. 위반 fixture 두 개를 더한다: A1(`RunNowRoutesConfiguration`)과 A2(`RunNowDataFetcherConfiguration`). 노트 폴더 `rr6-01-probes/`의 파일을 그대로 쓸 수 있다.
3. Javadoc `:497-505`, 매뉴얼 07 `:105`, 업그레이드 B-16을 "요청 처리기를 만들지 않는 설정"으로 고친다. 목록 방식이라 목록에 없는 endpoint 타입은 못 본다는 것을 「규칙이 못 보는 길」에 한 줄 더한다.
- **이번 커밋/이전부터**: 이번 커밋.
- **증거**: E2 — 탐침 A1·A2·A1c(`Rr6ProbeTest`), 규칙 89개(`Rr6AllRulesProbeTest`).
### RR6-01-02 · Minor · 설정 안의 익명 configurer가 설정의 필드를 쓰면 아직 "사용자 전송"으로 잡힌다 (RR4-01-02 일부 남음)
- **위치**: `ApplicationBoundaryArchitectureTest.java:507-523`, `docs/manual/07-authorization.md:105`
("같은 클래스에서 `WebMvcConfigurer`·interceptor·controller bean을 함께 만들어도 걸리지 않는다").
- **무엇이 틀렸나**:
- 제외는 설정 클래스 자신에만 적용된다. 그 안의 익명 클래스(`Config$1`)는 설정이 아니다.
- 익명 `WebMvcConfigurer`는 웹 타입에 의존하므로 사용자 전송이다. 설정의 필드를 읽으면 바깥 인스턴스(`this$0`)에 의존한다. 설정은 handler bean에 의존한다. 그래서 `Config$1 → Config → handler` 경로가 위반이 된다.
- 탐침 A5: 생성자에서 정한 `allowedOrigin` 필드를 `addCorsMappings`에서 읽는 익명 configurer와 handler bean을 한 설정에 두었다. 위반 1(`FeatureConfigWithAnonymousConfigurer$1 transitively depends on SystemCallerHandlerFixture`).
- 허용 fixture `SystemCallerBesideWebMvcRegistrationFixture`는 빈 익명 클래스라 바깥을 참조하지 않아 통과한다.
- **발생 조건·영향**: `WebMvcConfigurer`는 메서드가 여럿이라 람다로 못 쓰고 익명 클래스로 쓰는 것이 보통이다. 설정 값을 필드로 받아 쓰는 것도 흔하다. 빌드가 실패하고 메시지는 없는 경로를 말한다(실패 쪽으로 틀림). 매뉴얼은 걸리지 않는다고 적는다.
- **고치는 법**: 설정 안에 중첩된 클래스도 설정과 같이 취급한다. 단 RR6-01-01의 "요청 처리기를 만드는 타입" 예외는 똑같이 적용한다(익명 `HandlerInterceptor`·`Filter`는 계속 사용자 전송). 탐침 A5를 허용 fixture로 더한다.
- **이번 커밋/이전부터**: 이번 커밋(RR4-01-02 수정이 덜 끝남).
- **증거**: E2 — 탐침 A5.
### RR6-01-03 · Minor · `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`가 handler 안의 중첩 record·enum·예외와 record로 쓴 handler를 거부한다 (거짓 양성)
- **위치**: `ApplicationBoundaryArchitectureTest.java:664-707`(규칙과 조건), `:660-661`(익명·지역 클래스만 뺀 이유), `docs/manual/07-authorization.md:106`.
- **무엇이 틀렸나**:
- 규칙은 `@SystemCaller` 클래스와 그 안에 중첩된 모든 이름 있는 클래스에 "프로젝트 밖 상위 타입 금지"를 건다.
- 중첩 record는 `java.lang.Record`, 중첩 enum은 `java.lang.Enum`·`Comparable`·`Serializable`·`Constable`, 중첩 예외는 `RuntimeException`·`Throwable`·`Serializable`을 상위 타입으로 가진다. 모두 위반이다(탐침 A3, 세 건). record로 쓴 `@SystemCaller`도 위반이다(A7).
- 규칙이 익명·지역 클래스를 빼는 이유는 "그 타입의 bean이 없다"이다. record·enum·예외 값도 bean이 아니고, 아무 endpoint도 그것을 `Record`·`Enum`·`Throwable`로 주입받지 않는다. 같은 이유가 적용되는데 빠지지 않았다.
- 위반 메시지는 "endpoint가 그 타입으로 주입받으면 보이지 않는다"고 말한다. 이 경우에는 맞지 않는다.
- **발생 조건·영향**: handler 안에 파싱 결과 record, 결과 enum, 독(poison) 메시지 예외를 두는 것은 흔한 모양이다. 빌드가 실패하고 개발자는 그 타입을 밖으로 옮겨야 한다. 권한 구멍은 아니다(실패 쪽).
- **고치는 법**: 조건 대상에서 record·enum·`Throwable` 하위 클래스를 뺀다(`isRecord`/`isEnum`/`isAssignableTo(Throwable.class)`). 표시한 클래스 자신의 상위 클래스 `java.lang.Record`는 `Object`처럼 무시한다. A3·A7을 허용 fixture로 더한다. 매뉴얼 07 `:106`의 "(익명·지역 클래스 제외)"를 "(익명·지역 클래스와 record·enum·예외 제외)"로 고친다.
- **이번 커밋/이전부터**: 이번 커밋.
- **증거**: E2 — 탐침 A3·A7.
### RR6-01-04 · Minor · gRPC가 "클라이언트 취소"를 status 코드로 판정해, 서비스가 `CANCELLED`로 끝낸 살아 있는 호출의 `INTERNAL_ERROR`를 아무 데도 남기지 않는다
- **위치**: `src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcExceptionHandlingInterceptor.java:146-149`,
Javadoc `:41-43`, `src/adapter/inbound/grpc/README.md:158`, 업그레이드 안내 "서버 로그" 행("클라이언트 취소 제외"),
테스트 `GrpcExceptionHandlingInterceptorTest.java:227-240`과 `:336-338`(`isCancelled()`가 늘 `false`).
- **무엇이 틀렸나**:
- `logUnrecognised`는 `status.getCode() == CANCELLED`이면 남기지 않는다. 이 코드는 "이 호출의 클라이언트가 취소했다"가 아니라 "서비스가 넘긴 status가 CANCELLED다"를 뜻한다.
- 서비스가 하위 gRPC 호출에서 받은 `CANCELLED`(프록시의 RST_STREAM CANCEL 등)를 그대로 던지거나 `onError`로 넘기면, 클라이언트는 기다리는 중인데 `INTERNAL_ERROR`를 받고 로그는 한 줄도 없다.
- 탐침(실제 Netty): `ErrorsCancelled`(`onError(CANCELLED)`)와 `ThrowsCancelled`(`throw CANCELLED`) 둘 다 클라이언트는 `INTERNAL`, 로그 0줄. 서버 쪽 `isCancelled()`는 `false`였다. 진짜 클라이언트 취소(`Slow` + `future.cancel`)는 `isCancelled()`가 `true`, 로그 0줄.
- 테스트 `aCallTheClientCancelledIsNotLogged`는 서비스가 `close(CANCELLED)`를 부르고 `isCancelled()`가 `false`인 호출을 만든다. 이름은 클라이언트 취소인데 보는 것은 서비스가 낸 CANCELLED다. 이 결함을 고정하는 테스트다.
- **발생 조건·영향**: 이 커밋이 닫으려던 문제("`INTERNAL_ERROR` 실패를 아무 데도 남기지 않음")가 이 경로에 남는다. 운영자는 `INTERNAL_ERROR` 응답을 보고도 서버 로그에서 원인을 못 찾는다.
- **고치는 법**: `close()`에서 `delegate.isCancelled()`로 판정한다(호출 자체가 취소됐을 때만 남기지 않음). 테스트 둘로 나눈다: `CapturingServerCall.isCancelled()`가 `true`인 호출은 남기지 않고, `false`인 호출에서 서비스가 `CANCELLED`로 끝내면 `unhandled failure … (status=CANCELLED)`로 남긴다. Javadoc·README·업그레이드 문구를 "클라이언트가 취소한 호출"로 맞춘다.
- **이번 커밋/이전부터**: 이번 커밋.
- **증거**: E3 — 실제 Netty 서버·클라이언트 탐침(`Rr6GrpcProbeTest`).
### RR6-01-05 · Minor · gRPC 서비스가 raw status를 던지면 그 설명(입력값이 든)이 로그에 남는다 — 문서는 "남기지 않는다"고 적는다
- **위치**: `GrpcExceptionHandlingInterceptor.java:142-144`(`closeWithError`가 `withCause(exception)`), `:150-157`(cause를 예외로 붙임),
Javadoc `:40-41`, `src/adapter/inbound/grpc/README.md:157-158`("raw status만 있으면 description은 남기지 않는다(입력이 들 수 있다)").
- **무엇이 틀렸나**:
- 서비스가 `onError(Status.X.withDescription(d).asRuntimeException())`로 끝내면 status에 cause가 없어 코드만 남는다.
- 같은 status를 `throw`하면 인터셉터가 그 예외를 cause로 붙인다. `StatusRuntimeException`의 메시지는 `코드: 설명`이라서 설명이 예외 메시지로 로그에 남는다.
- 탐침(실제 Netty): `ThrowsRawStatus`는 `throwable: INVALID_ARGUMENT: no customer with email alice@example.com`. `ErrorsRawStatus`는 같은 설명이 로그에 없다.
- grpc-java에서 `throw Status.X.withDescription(...).asRuntimeException()`은 흔한 관용구다. 테스트 `aRawStatusWithoutACauseIsLoggedByItsCodeAlone`은 `close` 경로만 본다.
- **발생 조건·영향**: 서비스가 입력값을 설명에 넣고 던지면 개인정보가 ERROR 로그(prod JSON의 `stack_trace`)에 남는다. 마스킹 decorator는 비밀 형식(토큰·비밀번호)만 가린다. 문서 주장과 코드가 다르다. 이 로그 줄 자체가 이 커밋에서 생겼다.
- **고치는 법**: `logUnrecognised`에서 cause가 `StatusRuntimeException`·`StatusException`이면(즉 cause가 raw status 자신이면) 그것을 붙이지 않는다. 그 예외에 다시 cause가 있으면 그 cause만 붙인다. 테스트: handler가 설명에 입력값을 넣은 status를 던지면 로그 줄과 예외 어디에도 설명이 없다.
- **이번 커밋/이전부터**: 이번 커밋.
- **증거**: E3 — 실제 Netty 탐침(`ThrowsRawStatus` / `ErrorsRawStatus`).
### RR6-01-06 · Minor · STOMP `@MessageMapping`의 `IllegalArgumentException`을 ERROR로, 메시지(입력값)까지 남긴다 — 다른 전송은 모두 클라이언트 쪽 `BAD_PARAMETER`로 본다
- **위치**: `src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompHandlerFailureLog.java:31-38`,
Javadoc `:17-20`, `src/adapter/inbound/websocket/README.md:37-39`.
비교: `GlobalExceptionHandler.java:97`(web: WARN, 클래스 이름만), `GraphQlWireErrorMapper.java:115-121`·`:188-189`(GraphQL: `BAD_PARAMETER`, 남기지 않음),
`GrpcExceptionHandlingInterceptor.java:131-132`(gRPC: 남기지 않음), `SafeStompSubProtocolErrorHandler.java:52`(STOMP 프레임: `BAD_PARAMETER`),
`src/shared-contract/README.md:81`("`IllegalArgumentException`은 모든 전송에서 `BAD_PARAMETER`").
- **무엇이 틀렸나**:
- advice는 carrier가 아니면 모두 `unhandled failure in a STOMP message handler`로 ERROR에 예외를 붙여 남긴다. IAE도 여기로 간다.
- 탐침: `throw new IllegalArgumentException("unknown recipient alice@example.com")` → `ERROR … | throwable: java.lang.IllegalArgumentException: unknown recipient alice@example.com`.
- web은 이 경우 메시지를 일부러 빼고 클래스 이름만 WARN으로 남긴다. GraphQL·gRPC는 남기지 않는다. advice의 Javadoc은 "클라이언트 쪽 거절을 오류로 남기던 것"을 고쳤다고 적는다.
- **발생 조건·영향**: 잘못된 입력 하나마다 ERROR 줄과 스택이 생기고, 입력값(이메일 등)이 로그에 남는다. "모든 전송이 같은 줄"이라는 r9 주장과 다르다.
- **고치는 법**: advice가 IAE를 `BAD_PARAMETER`로 보고 `ServerFailureLog.of(failure, OperationalError.BAD_PARAMETER)`를 쓴다(결과: 남기지 않음). web의 WARN 한 줄까지 맞추려면 "IAE → `BAD_PARAMETER`" 줄을 `ServerFailureLog`에 두고 네 전송이 같이 쓴다. STOMP 테스트에 IAE 경우를 더한다.
- **이번 커밋/이전부터**: 이번 커밋(advice가 새로 생김). web의 WARN 줄과 GraphQL·gRPC의 무기록이 다른 것은 이전부터.
- **증거**: E2 — `Rr6StompProbeTest`(실제 STOMP method handler).
### RR6-01-07 · Minor · runbook이 lease 만료 시작 거절의 문구를 "ERROR 줄의 message"에 있다고 적는다 — 실제로는 붙은 예외의 메시지다
- **위치**: `docs/runbooks/idempotency-unavailable.md:21-23`("The ERROR line's message then reads `the claim's processing lease ran out …`"), `:101`("When the message says …").
- **무엇이 틀렸나**:
- 그 거절은 `IdempotencyUnavailableException`(503)이다. 로그 줄의 message는 `ServerFailureLog`가 정한 `failure classified as IDEMPOTENCY_UNAVAILABLE (category=…, retryable=true)`다.
- "the claim's processing lease ran out …" 문구는 붙은 예외의 메시지다. prod 로그는 `LogstashEncoder`(`src/app-bootstrap/src/main/resources/logback-spring.xml:87`)라서 이 문구는 `message`가 아니라 `stack_trace` 필드에 있다.
- 같은 runbook의 `IDEMPOTENCY_RECOVERY_REQUIRED` 설명(`:51-61`)은 "예외가 붙고, 예외 메시지 끝에 digest"라고 바르게 적는다.
- **발생 조건·영향**: 운영자가 `message` 필드로 검색하면 찾지 못한다. "저장소는 멀쩡하다"는 판단의 근거를 놓치고 저장소 장애를 쫓는다.
- **고치는 법**: `:21-23`을 "the line has the exception attached; its message reads …"로, `:101`을 "When the exception message says …"로 고친다.
- **이번 커밋/이전부터**: 이번 커밋.
- **증거**: E1 — `IdempotencyExecutor.java:198-201`, `ServerFailureLog.java:66-71`, `logback-spring.xml:87` 대조.
### RR6-01-08 · Minor · GraphQL 테스트 `aClientSideCarrierIsNotLogged`가 carrier가 아니라 `IllegalArgumentException`을 넣는다
- **위치**: `src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java:193-206`.
- **무엇이 틀렸나**: 이름은 "클라이언트 쪽 carrier는 남기지 않는다"인데 입력은 `new IllegalArgumentException("bad cursor")`다. `sharedCodeOf`의 carrier 분기(`failure instanceof ApiErrorCarrier`)가 아니라 IAE 분기를 지난다. 4xx carrier가 남지 않는다는 것은 이 테스트가 보지 않는다. gRPC·STOMP의 같은 이름 테스트는 실제 4xx carrier를 쓴다.
- **발생 조건·영향**: carrier 분기에서 로그 조건이 바뀌어도 이 테스트는 통과한다.
- **고치는 법**: 4xx carrier(예: 테스트 안의 작은 carrier에 `OperationalError.BAD_PARAMETER`, 또는 `IdempotencyInFlightException`)로 바꾼다. IAE 경우는 이름을 맞춘 별도 테스트로 남긴다.
- **이번 커밋/이전부터**: 이번 커밋.
- **증거**: E1 — 테스트 코드와 `GraphQlWireErrorMapper.java:184-190` 대조.
### RR6-01-09 · Minor · (이전부터) `SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES`는 shared-contract 안에서 아무것도 잡지 못한다 — 코드에 "KNOWN DEFECT"로 남아 있다
- **위치**: `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ForbiddenApiArchitectureTest.java:98-114`(주석 "KNOWN DEFECT, deliberately left as found"), `:52-72`(허용 목록), `:78-80`(접두어 비교).
- **무엇이 틀렸나**:
- 허용 목록에 모듈 뿌리 `dev.caskeleton.shared`가 있고 비교는 접두어다. 그래서 `dev.caskeleton.shared` 아래 모든 패키지가 허용된다.
- 탐침: `dev.caskeleton.shared.rr6bogus.BusinessRuleInShared`(업무 규칙 흉내)에 위반이 없다.
- 지금 shared-contract의 `digest`·`observability`·`ratelimit`·`retry`·`runtime` 패키지는 목록에 없는데도 통과한다. 목록이 이미 실제와 다르다는 뜻이다.
- 대상 술어 `..shared..`는 모듈과 무관한 `…tenancy.shared` 같은 패키지를 잡아 목록에 예외(`:65`)를 늘렸다. 주석이 스스로 두 잘못을 적고 고치기를 미뤘다. 이 리뷰 시리즈의 README·라운드 문서 어디에도 기록되지 않았다(`docs/reviews/2026-11-0*` grep 0건).
- **발생 조건·영향**: shared-contract에 업무 개념 패키지가 생겨도 빌드가 모른다. CLAUDE.md 표는 shared-contract를 "Skeleton-wide operational contracts"로 묶는다. 이 규칙이 그 경계의 유일한 패키지 검사다. 소유자 지시("남은 문제 0")와도 어긋난다.
- **고치는 법**: 대상을 `dev.caskeleton.shared..`로 좁힌다. 허용은 정확히 같은 패키지 또는 그 아래로 하되 뿌리는 뿌리 자체(`package-info`)만 허용한다. 지금 있는 패키지 중 계약인 것을 목록에 넣는다(`digest`·`observability`·`ratelimit`·`retry`·`runtime`은 shared-contract CLAUDE.md "Responsibility"에 근거가 있다). `…tenancy.shared` 예외는 지운다. 위반 fixture는 `TemplatePackageOwnership`처럼 뿌리를 매개변수로 받는 판정식으로 fixture 뿌리에서 증명한다(주석이 미룬 이유 "fixture가 규칙의 분석 범위에 들어간다"를 이 방법이 푼다).
- **이번 커밋/이전부터**: 이전부터(`1400dc15` 이전, 2026-08 wave0 baseline에 처음 기록).
- **증거**: E2 — `Rr6SharedProbeTest`. E1 — 허용 목록과 `src/shared-contract/src/main/java/dev/caskeleton/shared/` 디렉터리 대조.
## Declined to judge
- 감싼 carrier: web·GraphQL·STOMP는 맨 위 예외만 carrier로 보고, gRPC는 원인 사슬을 따라간다(`carrierOf`). 그래서 다른 예외에 감싼 `PersistenceFailureException`은 web·GraphQL·STOMP에서 "unhandled"로 SQL 원인과 함께 남고 gRPC에서는 분류만 남는다. 이전부터의 차이다. 템플릿 코드에서 carrier를 감싸 던지는 곳은 찾지 못했고(GraphQL은 Spring이 `CompletionException`을 벗긴다), 현실 조건을 세우지 못해 판단하지 않았다.
- `DependencyFailureException`과 그 밖의 5xx carrier는 모든 전송에서 원인 사슬째 남는다. web은 전부터 그랬고 이번에 다른 전송으로 넓어졌다. 의존 클라이언트 예외 메시지가 자격 증명·URL을 싣는지는 클라이언트마다 달라 판단하지 않았다(마스킹 decorator가 알려진 비밀 형식은 가린다).
- GraphQL은 실패한 필드마다 한 줄을 남긴다. 키 N개가 5xx batch 코드로 실패하면 ERROR 줄도 N개다. 필드 단위 오류 설계의 결과이고 양은 재지 않았다.
- `docs/upgrade/2026-11-maturity-review.md` B-34가 템플릿 패키지 이름을 다시 나열한다(세 번째 복사본). 그 릴리스 시점의 변경 기록이라 갈라진 복사본으로 보지 않았다.
- STOMP에서 payload 변환·검증 실패(`MessageConversionException`, `MethodArgumentNotValidException`)는 여전히 ERROR로 남는다. 전에도 Spring이 그렇게 남겼고, STOMP 프레임 매핑도 이것을 클라이언트 코드로 분류하지 않아 RR6-01-06에 넣지 않았다.
- RR6-01-01 고치는 법의 endpoint 타입 목록이 완전한지는 확인하지 않았다. 목록 방식의 한계는 기존 `ARE_USER_TRANSPORT_TYPES`와 같다.
- 규칙 89개 탐침은 정적 `@ArchTest` 필드만 돌렸다. 이 스위트들에 메서드형 `@ArchTest`는 없다(grep).
## 결론
- 결함 9건: Important 1, Minor 8. 이번 커밋 8건, 이전부터 1건(RR6-01-09).
- 회귀 1건: `@Configuration` 제외(RR4-01-02 수정)가 RR3-01-01이 막은 "사용자 요청 → 시스템 호출자" 길을 함수형 endpoint에 다시 열었다(RR6-01-01). 가장 먼저 고칠 것이다.
- 닫힘: RR4-01-01, `graphql..` fixture, 원래 리뷰 16.3(세 방향 모두 탐침으로 확인), RR4-03-03, STOMP SQL 원인 기록, web 로그 리팩터링.
- 부분: RR4-01-02(익명 configurer 거짓 양성, RR6-01-02), gRPC `INTERNAL_ERROR` 기록(RR6-01-04·05).
- 판정: With fixes.
@@ -0,0 +1,231 @@
# 02 멱등성·outbound r9 리뷰 (2026-11-05)
대상: 수정 커밋 `45d2a478`(Base `c508b1ba`)의 r9-b 묶음 — CLAIMED → 시작의 lease, RR5-01-02~05, RR5-03-01,
RR4-03-01·02·04 — 와 README 16.1절의 httpclient drain 스레드 수정. 결함 ID 접두어 `RR6-02-`.
## 범위
### pathspec
```
src/application-core/src/main/java/dev/caskeleton/application/idempotency src/application-core/src/testFixtures
src/application-core/src/test src/adapter/outbound/cache-redis
src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency
src/adapter/outbound/persistence-jpa/src/test src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest
src/adapter/outbound/httpclient src/adapter/outbound/redis-runtime src/composition/idempotency src/.env.example
docs/web/http-contract.md docs/manual/05-idempotency.md docs/runbooks/idempotency-unavailable.md
docs/registries/env-keys.yaml
```
`git diff c508b1ba..45d2a478 -- <pathspec>`: 33파일, +1445 −115. 의미가 바뀐 공개 설명을 따라가느라 pathspec 밖
파일도 읽었다: `src/adapter/inbound/web/README.md`, `docs/upgrade/2026-11-maturity-review.md`,
`src/shared-contract/.../ServerFailureLog.java`, `src/app-bootstrap/src/main/resources/logback-spring.xml`,
`infra/redis-sdk/acl/*`, `docs/registries/error-codes.yaml`.
### 불러온 스킬과 적용한 기준
| 스킬 | 적용한 기준 | 무엇을 봤나 |
| --- | --- | --- |
| `superpowers:requesting-code-review` | 리뷰어 템플릿: 이 커밋이 만든 결함과 "고쳤다"는 주장의 닫힘을 따로, 심각도별, file:line 근거 | 항목 재확인 표, 결함 5건 |
| `api-and-interface-design` | 멱등 키 절: 원자적 claim, 처리 중 중복에 대한 의도된 응답, 결과는 성공·실패·불명 셋, 실패 의미 일관성(값 하나에 뜻 하나), Hyrum's Law(관찰되는 동작 변화는 계약 변화) | `LEASE_EXPIRED`가 두 저장소에서 같은 순서·같은 경계로 판정되는지, executor의 503이 "실행 안 됨"과 맞는지, 같은 attempt 재시도의 결과(RR6-02-01), 새 enum 값의 공개 영향(B-41) |
| `performance-optimization` | 측정 전후, 회귀 장치가 실제로 회귀를 잡는가, 스레드·큐 비용 | watchdog 스레드의 유휴 종료가 read당 비용을 바꾸지 않는지(코드), 유휴 종료 직후 새 예약이 고립되지 않는지(JDK 탐침 4만 회), RR4-03-01 RED 단언이 기계와 무관한지 |
| `doubt-driven-development` | 주장마다 반증을 먼저 시도. 하위 에이전트 금지라 fresh-context 리뷰어 대신 스스로 반대 논증을 세웠다(성능 저하된 단독 모드). 비대화 맥락이라 cross-model 검토는 하지 않았다 | "두 저장소 판정이 같다", "runbook 삭제가 원자적이고 ACL과 맞다", "watchdog 경쟁이 안전하다", "공유 계약이 세 구현에서 돈다"를 각각 실 Redis·실 PG·JDK 탐침으로 반증 시도. 결함마다 반대 논증을 적었다 |
### 실행한 명령과 결과
모두 별도 worktree(`git worktree add --detach <scratchpad>/rr6-02/wt 45d2a478`)에서, Gradle·Docker는 공유 잠금
`flock …/heavy.lock`으로 감쌌다.
1. 실 Redis 7.4 + `infra/redis-sdk/acl/lane-fixture-accounts.acl`(부하 3.25). runbook의 두 줄을 파일에서 그대로
꺼내 `redis-cli`에 넣었다(`probe/runbook-redis.sh`). advanced 계정: `SCRIPT LOAD` 성공, `ABANDONED` 기록에
`EVALSHA` → `1`·키 삭제, `EXECUTING` 기록 → `0`·상태 유지, 없는 키 → `0`, `EVAL` → `NOPERM`, 스크립트 캐시를
비운 뒤 → `NOSCRIPT`·삭제 없음. application 계정: `SCRIPT LOAD`·`EVALSHA` 모두 `NOPERM`.
2. `:adapter:outbound:cache-redis:test --tests '*RedisIdempotencyStoreContractTest' --tests '*RedisIdempotencyStoreAdapterTest'`
— worktree에서 `RedisIdempotencyStoreContractTest`에 `elapse → commands.advance(duration)` 3줄을 넣은 탐침
(부하 3.84). 계약 31 통과·skip 0, adapter 34 통과. 탐침은 되돌렸다.
3. 원래 코드로 `:adapter:outbound:cache-redis:test --tests '*RedisIdempotencyStoreContractTest' :application-core:test --tests '*idempotency*' :adapter:outbound:httpclient:test --tests '*ReadIdleInputStreamTest' --tests '*ClientRuntimeRegistryTest'`
(부하 4.11) — 모두 통과. command fake 계약 31 중 17 skip, in-memory fake 계약 31 중 17 skip,
`IdempotencyExecutorTest` 17, `ReadIdleInputStreamTest` 10, `ClientRuntimeRegistryTest` 4.
4. `java StpeRace.java 200 20000`, `java StpeRace.java 50 20000` — watchdog과 같은 설정(core 1,
`allowCoreThreadTimeOut`, keep-alive 200µs/50µs)의 실행기에 worker가 유휴 종료하는 순간 근처로 예약을 4만 번
넣었다. 고립된 예약 0, 최대 대기 5 ms, 스레드가 없는 상태에서 시작한 회차 4,823/350.
5. 실 Redis 7.4에서 출하 `CLAIM`·`TRANSITION` 프로그램을 `SCRIPT LOAD`+`EVALSHA`(advanced 계정)로 실행
(`probe/retained.sh`, 부하 2.81): 같은 attempt가 lease 1s를 넘긴 뒤 재시도 3회 모두 `REPLAYED_ACQUIRE` →
`LEASE_EXPIRED`, 새 attempt는 `TAKEN_OVER 2`(RR6-02-01).
6. `:adapter:outbound:cache-redis:redisContainerContractTest :adapter:outbound:persistence-jpa:postgresqlIdempotencyIntegrationTest`
(부하 3.37, 잠금 대기 약 10분 뒤 1분 14초) — live Redis lane 72 통과·skip 0(그중 `LiveRedisIdempotencyStoreContractTest`
31, `LiveRedisIdempotencyRunbookTest` 2), PG 멱등성 통합 10 통과.
7. `:adapter:outbound:persistence-jpa:jpaPlatformContractTest --tests '*PostgreSqlIdempotencyStoreContractTest'`
(부하 3.58) — 31 통과·skip 0(33초).
8. executor + Redis adapter + command fake 탐침 테스트(`Rr602RetainedAttemptProbeTest`, 부하 2.37): 같은 attempt
재시도 3회와 1시간 뒤 모두 503 `IDEMPOTENCY_UNAVAILABLE`, 새 attempt는 작업을 한 번 실행. 탐침 파일은 지웠다.
9. `java F.java` — JDK 21.0.12의 `Thread`에 `inheritedAccessControlContext` 필드가 있음을 확인(Declined 참고).
### 못 본 것
- pathspec 안의 r9-c 파일(`PostgreSqlMigrationLockWaitIntegrationTest`, `LockWaitMigrationInspectorTest`,
`VersionedMigrationFilesTest`)은 영역 03(persistence) 몫이라 깊게 보지 않았다.
- `httpclient`의 `httpClientPerformanceTest`·`httpClientFailureInjectionTest`는 다시 돌리지 않았다.
- 16.1절의 RED 주장(옛 `ClientRuntimeRegistry`에서 새 테스트 실패)은 다시 돌리지 않았다. 옛 코드가 scheduler를
멈추기 전에 예외를 던지므로 결정적으로 실패한다(코드 읽기).
- Redis cluster에서 runbook의 `NOSCRIPT` 절차는 실행하지 않았다(standalone만).
- 짝 프론트 repo 문서는 보지 않았다.
## 항목 재확인
| ID | 판정 | 근거 |
| --- | --- | --- |
| README 15 남음 — CLAIMED → 시작에서 PG는 lease를 보고 Redis는 보지 않음 | 닫힘 | Redis `IdempotencyScripts.java:155-162`, PG `PostgreSqlIdempotencyStore.java:197-204`·`IdempotencyTransitionGateway.java:42`, fixture `InMemorySemanticRedisCommands.java:280-283`, 계약 `IdempotencyStoreContract.java:731-771`(실 PG·실 Redis 모두 통과, 명령 6·7), executor `IdempotencyExecutor.java:195-201`. 두 저장소 모두 서버 시계로 `now ≥ leaseUntil`이면 만료(claim과 같은 경계), 이미 적용된 시작의 재시도(`ALREADY`)는 lease보다 먼저 판정. 같은 attempt 재시도는 RR6-02-01 |
| RR5-01-02 renew·inspect 값의 뜻 | 닫힘 | `IdempotencyRenewOutcome.java:4-35`, PG `:240-246`, Redis `IdempotencyScripts.java:235-240`, fixture `:327-332`, 계약 `:709-727`(`LEASE_EXPIRED` + 빈 owner). `ABANDONED`는 Javadoc 유지(권고안 중 하나)와 executor 주석 `:171-175` |
| RR5-01-03 포트 Javadoc "마지막 보고" | 닫힘 | `IdempotencyStorePort.java:12-23`, 계약 `:381-405`. 저장소·문서에 "last report" 문구 남지 않음(grep) |
| RR5-01-04 늦은 실패 경로 | 닫힘 | 계약 `:617-685`(실 PG·실 Redis 통과), adapter `RedisIdempotencyStoreAdapterTest.java:410-445`. 두 fake 위 시간 케이스 skip은 RR6-02-02 |
| RR5-01-05 PG 기본 모양 | 닫힘 | `http-contract.md:123-141`, `manual/05-idempotency.md:59-70`, runbook `:40-43`, `PostgreSqlIdempotencyIntegrationTest`의 두 새 테스트(명령 6). 매뉴얼 첫 문장은 RR6-02-05 |
| RR5-03-01 `APP_IDEMPOTENCY_TTL` 상한 안내 | 닫힘 | `env-keys.yaml:1603-1616`, `module-defaults/idempotency.yml:15-19`, `composition/idempotency/README.md:48`·`:76`, `.env.example:124-125`. `IdempotencySettings`의 `<` 비교와 문서의 "이하"가 같다 |
| RR4-03-01 watchdog RED 테스트가 병렬도 1에서 무력 | 닫힘 | `ReadIdleInputStreamTest.java:114`(닫은 스레드 이름 단언 — 옛 코드는 공용 풀이나 `Thread-N`에서 닫는다) |
| RR4-03-02 Redis 삭제가 두 명령 | 닫힘 | runbook `:126-145`, `LiveRedisIdempotencyRunbookTest`(명령 6), 실 `redis-cli`로 블록 그대로 실행(명령 1). Lua 한 번이라 확인과 삭제 사이 틈이 없다. ACL: advanced 계정에 `script|load`·`evalsha`가 있고 `eval`이 없음과 맞다 |
| RR4-03-04 watchdog 스레드 수명 | 닫힘 | `ReadIdleInputStream.java:51-59`·`:101-134`, 테스트 `:160-243`. 유휴 종료 직후 예약 경쟁은 JDK `processWorkerExit`가 큐를 다시 보고 worker를 만든다 — 명령 4에서 고립 0 |
| README 16.1 drain 스레드 join·예외 순서 | 닫힘 | `ClientRuntimeRegistry.java:148-195`: 런타임 실패가 먼저, scheduler 정지 실패는 suppressed. `awaitTermination` 뒤 같은 마감 안에서 join. 테스트 `ClientRuntimeRegistryTest.java:63-83` |
## 결함
### RR6-02-01 · Minor · 시작을 `LEASE_EXPIRED`로 거절당한 attempt는 같은 attempt로 다시 보내도 영원히 503이다
- **위치**: `src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java:82-89`
(CLAIM이 같은 owner·operation을 lease보다 먼저 `REPLAYED_ACQUIRE`로 답함), `:155-162`(시작 거절),
`src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java:141-143`,
`src/application-core/.../idempotency/IdempotencyExecutor.java:142-143`·`:198-201`. 약속하는 문서:
`docs/web/http-contract.md:111`, `docs/manual/05-idempotency.md:72-73`, `src/application-core/README.md:274-275`.
- **무엇이 틀렸나**:
- 시작을 `LEASE_EXPIRED`로 거절당한 claim은 `CLAIMED`로 남는다.
- 같은 attempt(같은 owner token·operation id)로 다시 claim하면 CLAIM은 lease를 보기 전에 `REPLAYED_ACQUIRE`로
답한다. PG도 `sameClaimAttempt`가 만료 검사(`:147`)보다 앞이다.
- executor는 `ReplayedAcquire`를 `Acquired`처럼 시작으로 보낸다. 시작은 다시 `LEASE_EXPIRED`다.
- 그래서 그 attempt를 쥔 호출자는 기록이 사라질 때까지(lease + `replay-ttl`, 기본 약 24h) 매번 503을 받는다.
- 문서의 "다음 같은 키 요청이 그 claim을 넘겨받아 실행한다"는 새 attempt에만 맞다.
- **발생 조건·영향**:
- API는 attempt를 재시도 사이에 유지하라고 한다: `IdempotencyClaimAttempt` "Caller-retained identity for one
claim send/retry sequence", `IdempotencyExecutor#newAttempt` "retains across a lost response".
- 503은 `retryable=true`다. attempt를 유지하는 호출자(재시도 래퍼, 메시지 소비자)는 같은 attempt로 다시 보낸다.
- 템플릿 안의 호출자(`PublishPosterImageUseCase.java:106`)는 요청마다 새 attempt를 만들어 해당하지 않는다.
HTTP 재전송은 서버에서 새 attempt가 되어 HTTP 계약은 지켜진다.
- 중복 실행은 없다. 진행이 막힌다. 이 커밋 전에는 Redis가 그 claim을 시작해 실행했다.
- PG를 쓰기 트랜잭션 하나로 쓰면 503과 함께 기록이 롤백되어 해당하지 않는다. 호출마다 트랜잭션을 여는
모양에서는 같다.
- **고치는 법**(둘 중 하나를 정한다):
- (a) 두 저장소 claim에서 "lease가 지난 `CLAIMED`는 같은 attempt라도 넘겨받는다". Redis CLAIM의
`state == 'CLAIMED' and leaseOver` 분기를 `owner == ARGV[1]` 분기 앞으로, PG `claim`의 `:147` 검사를
`:141` 앞으로 옮긴다. 답은 `TakenOverClaimed`(attempt+1, 새 lease). command fake도 같게. 공유 계약에 "시작을
거절당한 attempt가 같은 attempt로 다시 claim하면 넘겨받아 시작한다" 케이스를 더한다. 주의: 같은 attempt의 멈춘
첫 호출이 나중에 시작을 보내면 Redis TRANSITION은 상태가 이미 `EXECUTING`일 때 revision을 보지 않고
`ALREADY`로 답한다(`:138-146`). 같은 attempt를 동시에 쓰는 이전부터의 위험(5차 리뷰 Declined)과 같은 것이다.
- (b) 동작을 두려면 `IdempotencyClaimAttempt`·`IdempotencyExecutor#newAttempt` Javadoc과 executor 메시지
(`:199-201`)에 "`LEASE_EXPIRED`로 거절된 attempt는 다시 쓰지 않고 새 attempt를 만든다"를 적는다. 문서 세 곳의
"다음 같은 키 요청"을 "다음 같은 키 요청(새 attempt)"으로 좁힌다. 공유 계약에 지금 동작을 고정하는 케이스를 둔다.
- **반대 논증**: attempt는 응답을 잃었을 때만 유지하고 명시적 거절 뒤에는 새로 만드는 것이 의도라면, 동작이 아니라
문서 누락이다. 그 의도는 어디에도 적혀 있지 않고, 503은 재시도하라고 말한다.
- **이번 커밋**. 가이드 심각도 Low · P3.
- **증거**: E3 — 실 Redis에서 출하 Lua(명령 5). E3 — executor까지 command fake 위에서(명령 8). PG는 E1(코드).
### RR6-02-02 · Minor · command fake 위 공유 계약이 시계를 움직일 수 있는데도 시간 케이스 17개를 skip한다
- **위치**: `src/application-core/src/testFixtures/.../testkit/IdempotencyStoreContract.java:64-69`(Javadoc),
`src/adapter/outbound/cache-redis/src/test/.../idempotency/RedisIdempotencyStoreContractTest.java:17-37`
(`elapse` override 없음), `src/adapter/outbound/redis-runtime/src/testFixtures/.../InMemorySemanticRedisCommands.java:44`
(`advance`), `RedisIdempotencyStoreAdapterTest.java:357-445`(손 사본).
- **무엇이 틀렸나**:
- 계약 Javadoc은 command fake 위 Redis store를 "시계를 움직일 수 없는 store"로 묶어 기본 `elapse`(abort)를 쓴다고 적는다.
- command fake는 `advance(Duration)`로 시계를 움직인다. adapter 테스트가 그것으로 시간 케이스를 손으로 다시 쓴다.
- 그래서 `RedisIdempotencyStoreContractTest`는 시간 케이스 17개를 skip한다. adapter 테스트는 그중 일부만 복사한다.
이 커밋이 사본을 4건 더 늘렸다(`:373-445`).
- 사본이 없는 시간 케이스(`aClaimMeetingAnExpiredExecutionLeavesTheRecordToItsHolder`,
`anExpiredExecutionsHolderCanStillReportAnUnknownEffect`, `aRenewedLeaseOutlivesItsFirstExpiry` 등)에서는
fixture의 Lua 사본이 단위 수준에서 검사되지 않는다.
- **발생 조건·영향**: fixture가 Lua와 갈라지면 단위 테스트가 못 잡는다. 실 Lua는 `redisContainerContractTest`가
잡으므로 운영 동작 피해는 없다. 잃는 것은 fixture를 쓰는 테스트의 신뢰도다.
- **고치는 법**: `RedisIdempotencyStoreContractTest`가 만든 `InMemorySemanticRedisCommands`를 필드로 두고
`elapse`에서 `commands.advance(duration)`을 부른다. 계약 Javadoc `:64-69`에서 command fake를 뺀다. 계약과 겹치는
adapter 손 사본은 지우거나 계약 케이스를 가리키게 한다. fixture는 멱등성 hash에 key TTL을 두지 않는다
(`InMemorySemanticRedisCommands.java:184-247`에 PEXPIRE 없음). 그래서 기록 수명 케이스
(`aLeaseLongerThanTheReplayTtlKeepsTheRecordForTheWholeLease` 등)는 기록이 영원히 남아서 통과한다. 그 케이스도
의미 있게 하려면 fixture CLAIM·TRANSITION·RENEW에 TTL을 둔다.
- **이전부터**(Javadoc 문장은 `5786126c`/`bbe944bd`). 이번 커밋이 손 사본을 늘렸다. 가이드 심각도 Low · P3.
- **증거**: E2 — `elapse` override 3줄을 넣은 탐침으로 31 통과·skip 0(명령 2). 원래 코드는 31 중 17 skip(명령 3).
### RR6-02-03 · Minor · runbook이 시작 거절 문장을 ERROR 줄의 "message"에서 찾으라고 한다
- **위치**: `docs/runbooks/idempotency-unavailable.md:20-24`, `:100-101`.
- **무엇이 틀렸나**:
- runbook은 "The ERROR line's message then reads `the claim's processing lease ran out before the action started; …`"라고 적는다.
- 실제 ERROR 줄의 메시지는 `failure classified as IDEMPOTENCY_UNAVAILABLE (category=TRANSIENT_DEPENDENCY, retryable=true)`다
(`ServerFailureLog.java` 5xx 분기). 그 문장은 줄에 붙은 예외의 메시지다.
- local·dev 밖 프로필의 로그는 `LogstashEncoder` JSON이다(`logback-spring.xml:84-100`). 예외는 `message`가 아니라
`stack_trace` 필드에 있다.
- 같은 runbook의 `IDEMPOTENCY_RECOVERY_REQUIRED` 항목(`:51-61`)은 "with the exception attached … The exception
message ends with"로 맞게 적는다.
- **발생 조건·영향**: 운영자가 로그 시스템에서 `message`로 이 문장을 찾으면 못 찾는다. 그러면 저장소 장애로 보고
저장소 담당을 부른다. 이 503을 저장소 장애와 가르는 것이 이 문단의 목적이다.
- **고치는 법**: `:22`를 "The ERROR line (`failure classified as IDEMPOTENCY_UNAVAILABLE …`) carries the exception,
whose message reads `…`; in JSON logs it is in `stack_trace`."로, `:100-101`의 "When the message says"를 "When the
attached exception's message says"로 고친다.
- **이번 커밋**. 가이드 심각도 Low · P3.
- **증거**: E1 — `ServerFailureLog.of`의 형식 문자열, logback 설정.
### RR6-02-04 · Minor · `IDEMPOTENCY_UNAVAILABLE`의 넓어진 뜻이 웹 어댑터 매핑 표와 프론트 인계 표에 없다
- **위치**: `src/adapter/inbound/web/README.md:243`, `docs/upgrade/2026-11-maturity-review.md:280`(7절 짝 프론트).
둘 다 pathspec 밖이다.
- **무엇이 틀렸나**:
- 이 커밋으로 503 `IDEMPOTENCY_UNAVAILABLE`은 "저장소가 응답하지 않음"과 "claim의 lease가 시작 전에 끝나 저장소가
시작을 거절함" 둘을 뜻한다.
- `http-contract.md:111`, `manual/05-idempotency.md:52`, runbook, `application-core/README.md:274-275`는 고쳤다.
- 위 두 곳은 여전히 "조정 저장소가 응답하지 않아 action 전에 거부", "실행 전 저장소 응답 없음"만 적는다.
- **발생 조건·영향**: 클라이언트 행동은 같다(같은 키로 나중에). 다만 매핑 표와 인계 표를 읽는 개발자는 이 503을
저장소 장애로만 읽는다. 갈라진 복사본이다.
- **고치는 법**: 두 행에 "또는 claim의 processing lease가 시작 전에 끝나 저장소가 시작을 거절함(실행 안 됨)"을 더한다.
- **이번 커밋**. 가이드 심각도 Low · P3.
- **증거**: E1 — `grep -rn IDEMPOTENCY_UNAVAILABLE`.
### RR6-02-05 · Minor · 매뉴얼 05의 첫 문장 "같은 키 재전송은 작업을 다시 돌리지 않는다"가 바로 아래 PostgreSQL 항목과 어긋난다
- **위치**: `docs/manual/05-idempotency.md:57-58`과 `:65-70`.
- **무엇이 틀렸나**:
- 문단 첫 문장은 "같은 키 재전송은 작업을 다시 돌리지 않는다"이고, 예외를 "첫 시도가 lease보다 오래 걸릴 때"로 좁힌다.
- 바로 아래 PostgreSQL 항목은 lease와 무관하게 "작업이 예외로 끝나면 실패 기록도 함께 롤백되어 다음 같은 키
요청이 다시 실행한다", "트랜잭션 밖 효과는 다음 요청에서 다시 일어날 수 있다"고 적는다.
- 그래서 첫 문장은 PostgreSQL 기본 모양에서 틀리다. `http-contract.md:119-122`는 같은 단언을 "이것은 Redis
저장소의 판정이다"로 좁혀 맞다.
- **발생 조건·영향**: 매뉴얼만 읽은 개발자가 PG provider에서 효과 불명 실패 뒤 같은 키 재전송도 막힌다고 믿는다.
그러면 트랜잭션 밖 효과(외부 호출, 메시지)를 따로 멱등하게 만들지 않는다.
- **고치는 법**: 첫 문장을 저장소별로 나눈다. 예: "Redis 저장소에서 같은 키 재전송은 효과가 있었을 수 있는 작업을
다시 돌리지 않는다. PostgreSQL 저장소를 쓰기 트랜잭션 하나로 쓰면 실패한 요청의 기록은 롤백되어 다음 같은 키
요청이 다시 실행한다(아래)."
- **이번 커밋**(PG 항목이 이 커밋에서 생겼다). 가이드 심각도 Low · P3.
- **증거**: E1. PG 동작 자체는 E3 — `aSameKeyClaimAfterTheFirstTransactionRolledBackItsAbandonedRecordRunsAfresh`(명령 6).
## Declined to judge
- **watchdog 스레드의 `inheritedAccessControlContext`**: JDK 21 `Thread`는 만드는 스레드의 스택에서
`AccessControlContext`를 잡는다(명령 9). 요청 스레드가 watchdog을 시작하면 그 스택의 ProtectionDomain(과 class
loader)이 스레드가 사는 동안 잡힌다. README의 "pins neither … a redeployed application's loader"보다 약간 넓다.
다만 스레드는 마지막 예약 뒤 60초 안에 끝나고, httpclient가 WAR 안에 있으면 같은 loader라 의미가 없다. httpclient를
공유 부모 loader에 두는 배포에서만 남는다. 템플릿은 실행 jar로 배포한다. 판단하지 않았다.
- **`ClientRuntimeRegistry.close()`의 interrupt 처리**: 닫는 스레드가 interrupt 상태면 `awaitTermination`이 바로
예외를 내고, close는 flag만 되살린 채 정상으로 돌아온다. 그때는 "스레드를 남기지 않는다"가 성립하지 않는다.
이전부터의 모양이고 Spring 종료 스레드는 보통 interrupt되지 않는다.
- **배포 중 섞인 버전**: 옛 인스턴스의 TRANSITION은 lease가 지난 claim을 시작하고 새 인스턴스는 거절한다. 배포
동안만이고 중복 실행은 없다.
- **`docs/registries/error-codes.yaml`의 `IDEMPOTENCY_UNAVAILABLE` `log_level: WARN`**: 전송은 5xx carrier를 ERROR로
남긴다(`ServerFailureLog`). 영역 밖이고 이전부터이며, `log_level`을 읽는 코드가 없어 규범인지 판단하지 않았다.
- **시작 호출의 operation id가 claim과 다를 때**: Redis는 `OPERATION_CONFLICT`, PG는 시작을 적용한다. 이전부터의
차이이고 executor는 항상 claim의 operation id를 넘긴다.
- **in-memory fake(application-core)가 lease를 모델링하지 않음**: 시간 케이스 17개 skip은 RR-01-06 결정의 설계다.
executor의 `LEASE_EXPIRED` → 503 매핑은 손 fake 단위 테스트(`IdempotencyExecutorTest`)와 위 탐침(명령 8)이 본다.
## 결론
- 고쳤다고 한 10개 항목은 모두 닫혔다. 회귀는 없다.
- 두 저장소의 `LEASE_EXPIRED` 판정은 같은 시계(서버), 같은 경계(`now ≥ leaseUntil`), 같은 순서(이미 적용된
시작의 재시도가 먼저)다. 공유 계약 31건이 실 PG·실 Redis에서 skip 없이 통과했다. executor의 503은 계약 문서와 맞다.
- runbook의 Redis 삭제는 Lua 한 번이라 원자적이고, 실 Redis에서 블록 그대로 advanced 계정으로 돈다.
- watchdog 유휴 종료 직후의 새 예약은 고립되지 않는다. drain 스레드 close는 join 마감과 예외 순서가 맞다.
- 결함 5건, 모두 Minor: 이번 커밋 4건(RR6-02-01·03·04·05), 이전부터 1건(RR6-02-02, 이번 커밋이 넓힘).
@@ -0,0 +1,194 @@
# 03 persistence r9 리뷰 (2026-11-05)
대상: 커밋 `45d2a478`(r9), Base `c508b1ba`. 리뷰어 1명이 직접 봤다(하위 에이전트 없음). 결함 ID는 `RR6-03-<순번>`이다.
## 범위
### pathspec
```
src/adapter/outbound/persistence-jpa src/sample-portfolio src/grpc/grpc-operation-ledger-jpa src/optional-platforms
docs/jpa docs/manual/04-persistence.md docs/upgrade/2026-11-maturity-review.md
```
`git diff c508b1ba..45d2a478 -- <pathspec>`의 15개 파일. persistence-jpa 안의 멱등성 store 변경(`IdempotencyTransitionGateway`, `PostgreSqlIdempotencyStore`, `PostgreSqlIdempotencyIntegrationTest`, README 멱등성 문단)은 02가 보므로 뺐다.
요구사항은 재리뷰 README 16절 r9-c 행이다. 항목은 RR4-02-01(`round4/review.md`), gRPC 버전 정규식 복사본(README 12절 r6-b), V21 주석(README 6절 r4-e 남음), r9-c가 새로 찾아 고친 가이드 오류 네 가지다.
판정에 필요해 함께 읽은 것:
- Flyway 11.14.1(lockfile 버전) `PostgreSQLParser`, `Parser`, `ParserSqlScript`, `SqlScriptMetadata`, `ConfigUtils` — Gradle 캐시의 jar를 scratchpad에서 디컴파일했다.
- `ConcurrentIndexMigrationInspector`, `PostgreSqlMigrationUpgradeContractTest`, `MigrationLockWaitTest`, `MigrationTrees`, `applied-migrations.sha256`.
- `persistence-jpa.yml`의 `spring.flyway` 절, 직접 `Flyway.configure()`를 부르는 main 코드 5곳.
- `.github/workflows/ci-quality-gates.yml`·`integration-main.yml`의 optional 빌드 job, `QualityConventionsPlugin`의 Spotless 설정.
- `docs/study/postgresql-jpa-walkthrough.ko.md` §8.2(pathspec 밖, 같은 주장이 있어서).
### 불러온 스킬과 적용한 기준
| 스킬 | 적용한 기준 | 본 것 |
| --- | --- | --- |
| `superpowers:requesting-code-review` | 리뷰어 템플릿: 계획(16절 r9-c) 대비 구현, 테스트가 진짜 동작을 보는가, 마이그레이션 전략, 문서 완결성, 심각도별 Issues, Declined to judge, 읽기 전용 checkout, 하위 에이전트 금지 | 네 항목이 정말 닫혔는지, 새 Flyway 대조 테스트가 주장하는 것을 실제로 지키는지 봤다. 이 문서 양식이 그 템플릿이다 |
| `jpa-patterns` | "Migrations: Flyway·Liquibase, Hibernate auto DDL 금지", "Testing Data Access: Testcontainers로 운영과 같게" | 가이드가 안내하는 마이그레이션 모양(CIC + `.sql.conf`)을 실제 Flyway·실 PostgreSQL로 끝까지 돌려 봤다(RR6-03-01). `ddl-auto: validate` 확인 |
| `supabase-postgres-best-practices` | `lock-short-transactions`(잠금을 짧게, 긴 트랜잭션 금지), `lock-advisory`(transaction-level과 session-level advisory lock의 차이), `query-*`의 인덱스 생성 | Flyway의 transaction-level advisory lock이 열어 둔 트랜잭션을 CIC가 기다리는 것(RR6-03-01), `lock_timeout` 상한 판정, E-문자열 escape(RR6-03-02) |
### 실행한 명령과 결과
모두 `scratchpad/rr6-03/wt`(detached `45d2a478` worktree)에서 공유 잠금(`flock …/heavy.lock`)으로 돌렸다. 괄호 안은 실행 직전 1분 부하다.
1. `./gradlew :adapter:outbound:persistence-jpa:test --tests '*LockWaitMigrationInspectorTest' --tests '*VersionedMigrationFilesTest' --tests '*MigrationLockWaitTest' --tests '*AppliedMigrationImmutabilityTest' --tests '*ConcurrentIndexMigrationInspectorTest' :sample-portfolio:test --tests '*SampleMigrationLockWaitTest'` (2.31) → rc=0. 71·3·2·2·4·1건, 실패 0.
2. `applied-migrations.sha256` 대조(python, LF 정규화, `MigrationTrees.ROOTS` 네 tree) → 파일 47, 고정 47, 빠짐·남음·불일치 0.
3. 검사기 오프라인 탐침: testFixtures 클래스로 `javac`·`java`, 입력 12개(E-문자열, 중첩 주석, dollar quote, `BEGIN ATOMIC`, 옛 `REINDEX VERBOSE` 등).
4. `./gradlew :adapter:outbound:persistence-jpa:postgresqlMigrationLockWaitIntegrationTest` (3.25) — worktree 사본에 탐침 9개를 더했다 → rc=0, 37/37(원래 28 + 탐침). 탐침 결과:
| 입력(앞에 `SET LOCAL lock_timeout = '5s';`) | Flyway mixed 거부 | 검사기 트랜잭션 밖 판정 | 일치 |
| --- | --- | --- | --- |
| `UPDATE probe SET note = E'it\'s'; VACUUM FULL probe` | 거부 | `[]` | **불일치** (RR6-03-02) |
| `/* outer /* inner */ VACUUM probe; */ SELECT 1` | 통과 | `[vacuum]` | 불일치(거부 쪽, Declined) |
| `REINDEX VERBOSE SCHEMA public` | 거부 | `[reindex verbose schema]` | 일치 |
| `CREATE INDEX CONCURRENTLY IF NOT EXISTS …` | 거부 | `[create index concurrently]` | 일치 |
| `VACUUM "public"."probe"` | 거부 | `[vacuum]` | 일치 |
| `CREATE TABLESPACE probe_ts LOCATION '/tmp'` | 거부 | `[create tablespace]` | 일치 |
| `ALTER TABLE probe DETACH PARTITION probe_p CONCURRENTLY` | 통과(PG 오류) | `[]` | 일치 |
| `CLUSTER` | 통과(PG 오류) | `[]` | 일치 |
그리고 SET LOCAL 없이 `INSERT … VALUES (1, E'it\'s'); ALTER TABLE probe ADD COLUMN c INT;`를 읽는 트랜잭션이 열린 채 Flyway로 적용했다 → 검사기 `[]`, Flyway는 15,018 ms 기다린 뒤 적용(상한 없음, RR6-03-02).
5. `./gradlew -p optional-platforms ci --dry-run` → ledger의 `sharedMigrationFileSources`, `spotlessJava`, `compileIntegrationTestJava`, `spotbugsIntegrationTest`가 `ci`에 있다. 정본이 깨지면 optional `ci`(PR마다 도는 job)에서 컴파일로 잡힌다.
6. `./gradlew -p optional-platforms :grpc:grpc-operation-ledger-jpa:compileIntegrationTestJava :grpc:grpc-operation-ledger-jpa:spotlessCheck :grpc:grpc-operation-ledger-jpa:spotbugsIntegrationTest` 두 번 (4.60) → 둘 다 rc=0, 두 번째는 네 태스크 모두 UP-TO-DATE.
7. 정본 `VersionedMigrationFiles`에 포맷이 틀린 메서드를 넣고 같은 명령 (4.35) → `sharedMigrationFileSources`·`compileIntegrationTestJava`가 다시 돌았다(정본을 따라온다). `spotlessJavaCheck`는 `build/generated/sources/sharedMigrationFiles/…/VersionedMigrationFiles.java`를 위반으로 댔다. 이어서 `-p optional-platforms :grpc:grpc-operation-ledger-jpa:spotlessApply` (4.77) → rc=0, 정본 diff 변화 없음 → `spotlessCheck` 다시 실패(RR6-03-04). 정본은 원래대로 되돌렸다.
8. `./gradlew -p optional-platforms :grpc:grpc-operation-ledger-jpa:integrationTest` (3.56) → rc=0, 46/46. lock-wait IT는 `inVersionOrder` 순서대로 V002·V003 두 건.
9. CIC 단독 마이그레이션 탐침(같은 IT lane, 4.11): `CREATE INDEX CONCURRENTLY ix_probe_note ON probe (note);` 하나만 든 V1을 Flyway 기본 설정으로 적용 → 10분 넘게 멈췄다. 컨테이너에서 `pg_stat_activity`·`pg_locks`를 보니 Flyway 연결(pid 62)이 `idle in transaction`으로 advisory `ExclusiveLock`을 들고 있고, CIC(pid 63)는 `Lock/virtualxid` `ShareLock`을 기다렸다(granted=f). `pg_terminate_backend(63)`로 끝냈다.
10. 두 번째 배포 탐침(같은 lane, 3.69): V1(테이블·인덱스)을 적용한 뒤 V2를 적용한다. 20초가 지나면 감시자가 `pg_cancel_backend`로 취소한다 → rc=0.
| V2 | `.sql.conf` | Flyway PostgreSQL 잠금 | 결과 |
| --- | --- | --- | --- |
| `CREATE INDEX CONCURRENTLY` | `executeInTransaction=false`(가이드 모양) | 기본(transactional) | **멈춤** → 20초에 취소, version 1 |
| `CREATE INDEX CONCURRENTLY` | 없음 | 기본 | **멈춤** |
| `CREATE INDEX CONCURRENTLY` | `executeInTransaction=false` | `flyway.postgresql.transactional.lock=false` | 20 ms에 적용, version 2 |
| `DROP INDEX CONCURRENTLY` | `executeInTransaction=false` | 기본 | 19 ms에 적용 |
| `REINDEX INDEX CONCURRENTLY` | `executeInTransaction=false` | 기본 | **멈춤** |
### 못 본 것
- IntelliJ 가져오기는 실행하지 않았다. Sync 방식의 IDE 영향은 정적 판단이다(Declined).
- staging·prod의 "deployment-owned migration" 도구가 저장소에 없다. RR6-03-01은 Flyway API·Spring Boot 기본값으로만 확인했다(Flyway CLI 기본값도 같다는 것은 E0).
- PostgreSQL 16.15 외 버전.
- 전체 `check`·`ci`·`mainCheck`·`integrationCheck`는 돌리지 않았다(총괄 게이트 몫). 위 좁힌 태스크만 돌렸다.
## 항목 재확인
| ID | 판정 | 근거 |
| --- | --- | --- |
| RR4-02-01 | 닫힘 | Flyway 11.14.1 `PostgreSQLParser#detectCanExecuteInTransaction`이 PG 12 이상에서 쓰는 정규식 6개와 `LockWaitMigrationInspector.java:154-161`이 같다(디컴파일 대조). 판정 규칙(`.sql.conf`가 있으면 그것, 없으면 문장 판정)은 `ParserSqlScript.executeInTransaction()`과 같다(`:243-247`). `VACUUM FULL` + `SET LOCAL`은 "cannot run in a transaction … keep it out of migrations"로 거부(`:275-280`, 명령 1). `REINDEX (CONCURRENTLY)`(`:82-83`), `GRANT … REFERENCES ON`(`:117`), `executeInTransaction=FALSE`(`:378-399`, Flyway `ConfigUtils.removeBoolean`과 같은 판정) 모두 고쳐졌다. 가이드 `docs/jpa/migration-guide.md:55-69`. 남은 lexer 빈틈은 이전부터의 RR6-03-02, 업그레이드 감시의 빈틈은 RR6-03-03 |
| gRPC 버전 정규식 복사본 | 닫힘 | `GrpcOperationLedgerMigrations.java:35-39`가 `VersionedMigrationFiles.inVersionOrder`를 쓰고 자체 정규식·`version()`이 지워졌다. `build.gradle:27-33` Sync. 정본을 바꾸면 optional 빌드가 따라오고(명령 7), 두 번째 실행은 UP-TO-DATE(명령 6), optional `ci`가 컴파일한다(명령 5). 새 `inVersionOrder`는 Flyway처럼 수로 비교하고 없는 자리를 0으로 보며 같은 버전을 거부한다(`VersionedMigrationFiles.java:54-98`, 테스트 2건). 부작용: RR6-03-04 |
| V21 주석 | 닫힘 | `V21__outbox_aggregate_sequence.sql:10`의 `JpaOutboxStore#nextSequence`가 있다(`JpaOutboxStore.java:133`). sha256 `applied-migrations.sha256:43`이 파일과 같다(명령 2) |
| 가이드 "CONCURRENTLY는 Flyway가 트랜잭션으로 감싼다" (r9-c가 새로 찾아 고침) | 부분 | 가이드 `:98-104`는 고쳤다. 같은 주장이 `ConcurrentIndexMigrationInspector.java:10-14`, `GrpcOperationLedgerMigrationLockWaitIT.java:32-33`, study 문서 `:1338-1344`에 남았다(RR6-03-05). 고친 문장이 안내하는 길(CIC·`REINDEX … CONCURRENTLY`를 자기 마이그레이션에)은 Flyway 기본 설정에서 멈춘다(RR6-03-01) |
| 동결 목록(`RELEASED_BEFORE_THE_RULE`) | 맞음 | `MigrationLockWaitTest.java:79-99`가 두 방향으로 통과(명령 1). 이번 커밋에서 목록·마이그레이션 파일 변경 없음. `SampleMigrationLockWaitTest`는 `isEqualTo(V8)`로 통과 |
| sha256 고정 목록 | 맞음 | 47/47 일치(명령 2), `AppliedMigrationImmutabilityTest` 2/2 |
## 결함
### RR6-03-01 · Important · CIC·`REINDEX … CONCURRENTLY` 마이그레이션은 Flyway 기본 설정에서 끝나지 않는다 — 가이드가 그 길을 안내한다
- **위치**:
- 안내: `docs/jpa/migration-guide.md:98-114`("Concurrent index builds": CIC 마이그레이션 + `executeInTransaction=false`), `:63-65`(r9: `REINDEX TABLE|INDEX CONCURRENTLY`는 `executeInTransaction=false`), `:101-104`(r9: 동반 설정을 늘 쓴다), `LockWaitMigrationInspector.java:286-290`(r9 메시지: "put create index concurrently in a migration of its own").
- 설정: `src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml:125-139`(`spring.flyway`에 `postgresql.transactional-lock` 없음). 직접 만드는 Flyway: `IdempotencySchemaStream.java:85`, `NotificationSchemaStream.java:58`, `MessagingInboxSchemaStream.java:77`, `SamplePostgreSqlPersistenceConfig.java:41`, `SchemaTenantMigrationOrchestrator.java:51`.
- **무엇이 틀렸나**:
- Flyway 11.14.1은 PostgreSQL에서 기본으로 transaction-level advisory lock을 쓴다.
- 그 잠금을 든 연결은 migrate가 끝날 때까지 트랜잭션을 열어 둔다(`idle in transaction`).
- `CREATE INDEX CONCURRENTLY`와 `REINDEX … CONCURRENTLY`는 먼저 시작한 트랜잭션이 모두 끝나기를 기다린다(virtualxid 대기).
- 그래서 CIC는 Flyway 자신의 잠금 트랜잭션을 기다리고, Flyway는 CIC를 기다린다. 둘 다 끝나지 않는다.
- 이 대기에는 상한이 없다. `executeInTransaction=false` 파일에는 `SET LOCAL lock_timeout`을 둘 수 없다.
- 명령 10: 가이드 모양 그대로(`.sql.conf` 포함) 두 번째 배포가 멈췄다. 같은 파일이 session-level 잠금(`flyway.postgresql.transactional.lock=false`)에서는 20 ms에 적용됐다. `DROP INDEX CONCURRENTLY`는 멈추지 않는다.
- **발생 조건·영향**:
- 가이드대로 운영 중인 큰 테이블에 CIC 마이그레이션으로 인덱스를 더하는 파생 서비스. 템플릿 자체에는 지금 그런 파일이 없다.
- dev·test(기동 때 migrate)에서는 앱 기동이 멈춘다. 배포 마이그레이션도 Flyway 기본값이면 배포가 끝나지 않는다.
- 그동안 CIC가 테이블에 `SHARE UPDATE EXCLUSIVE`를 들어 그 테이블의 다른 DDL·autovacuum이 막힌다. Flyway advisory lock 때문에 다른 인스턴스의 migrate도 줄을 선다.
- 실패가 아니라 멈춤이라 알람과 롤백이 늦다. 취소하면 INVALID 인덱스가 남는다.
- **테스트가 못 본 이유**: CIC 마이그레이션을 Flyway로 끝까지 돌린 테스트가 없다. `PostgreSqlMigrationUpgradeContractTest.java:72-81`은 CIC를 JDBC autocommit으로만 돌린다. r9의 IT는 CIC를 `SET LOCAL` 옆에 두어 Flyway가 파싱 단계에서 거부하는 것만 본다(`PostgreSqlMigrationLockWaitIntegrationTest.java:129-188`).
- **고치는 법** (하나를 고른다):
- (권장) Flyway의 PostgreSQL 잠금을 session-level로 바꾼다.
- module-defaults에 `spring.flyway.postgresql.transactional-lock: false`(Spring Boot 4.0.8 속성, 기본값 없음 → Flyway 기본 true).
- 직접 만드는 Flyway 5곳에 같은 값(`flyway.postgresql.transactional.lock=false`)을 공용 helper 하나로 넣는다.
- 가이드 "Who may change the schema"·"Concurrent index builds"에 배포 마이그레이션 도구도 같은 값을 써야 한다고 적는다.
- session-level advisory lock은 transaction-mode PgBouncer 뒤에서 깨진다. 템플릿은 Hikari 직접 연결이라는 전제를 같은 곳에 적는다.
- RED: 실 PG IT 하나. 템플릿 설정으로 만든 Flyway가 V1 적용 뒤 `.sql.conf`가 있는 CIC V2를 상한(예: 30초) 안에 적용하는지 본다. 지금 설정에서는 상한에 걸려 실패한다.
- (대안) CIC·`REINDEX … CONCURRENTLY`를 `VACUUM FULL`처럼 "마이그레이션에 두지 않고 운영 절차로" 한다. 검사기가 거부하고, 가이드 "Concurrent index builds"를 runbook 절차로 바꾸고, `ConcurrentIndexMigrationInspector`를 정리한다.
- **이번 커밋/이전부터**: 이전부터(가이드 "Concurrent index builds"). 이번 커밋이 같은 길을 더 안내했다(가이드 `:63-65`, `:101-104`, 검사기 메시지 `:286-290`).
- **증거**: E3 — 명령 9·10(`pg_stat_activity`·`pg_locks`로 대기 관계 확인). Flyway 잠금 동작은 E1(디컴파일한 `PostgreSQLParser`·Spring Boot `spring-configuration-metadata.json`의 `spring.flyway.postgresql.transactional-lock`).
### RR6-03-02 · Minor · `E'…\'…'` 문자열이 검사기의 문자열 판정을 어긋나게 해, 뒤의 잠금 문장과 트랜잭션 밖 문장을 못 본다
- **위치**: `LockWaitMigrationInspector.java:433-471`(`withoutCommentsAndLiterals`, `'` 처리 `:446-458`). `:370-372` `normalized`가 이 결과를 잠금 판정과 트랜잭션 밖 판정에 함께 쓴다.
- **무엇이 틀렸나**:
- PostgreSQL과 Flyway는 `E'it\'s'`의 `\'`를 문자열 안의 따옴표로 읽는다(Flyway `Parser.readToken`의 `E'` 분기).
- 검사기는 `''`만 escape로 읽는다. 그래서 `\'`에서 문자열을 닫는다.
- 그 뒤 `s'`의 따옴표가 새 문자열을 연다. 다음 따옴표까지(없으면 파일 끝까지)가 문자열로 지워진다.
- 명령 4: `INSERT INTO probe (id, note) VALUES (1, E'it\'s');` 다음 줄의 `ALTER TABLE probe ADD COLUMN c INT;`를 검사기는 못 봤다(`[]`). 실 PG에서 읽는 트랜잭션이 열린 채 Flyway로 적용하니 15,018 ms를 기다린 뒤 적용됐다.
- 같은 이유로 `UPDATE … E'it\'s'; VACUUM FULL probe;`를 검사기는 트랜잭션 안으로 판정했다. Flyway는 mixed로 거부했다.
- **발생 조건·영향**: 시드·데이터 마이그레이션이 E-문자열에 `\'`를 쓰고 그 뒤에 잠금 문장을 둔 파일. 검사기가 막으려는 상한 없는 잠금 대기가 그대로 통과한다. 모양이 드물어 Minor다.
- **고치는 법**: `'` 바로 앞 글자가 `e`/`E`이고 그 앞이 식별자 글자가 아니면 E-문자열로 읽어 `\` 다음 글자를 건너뛴다(`\\`, `\'`). RED: 위 두 입력을 `LockWaitMigrationInspectorTest`에 더한다. 두 번째 입력은 IT의 Flyway 대조 목록(`:129-153`)에도 더한다.
- **이번 커밋/이전부터**: 이전부터(RR3-02-01 때의 함수). 이번 커밋의 트랜잭션 밖 판정도 같은 출력을 써서 함께 틀린다.
- **증거**: E3 — 명령 3·4.
### RR6-03-03 · Minor · "Flyway를 올리면 IT가 실패한다"는 주장이 Flyway 목록에 문장이 더해지는 경우를 못 본다
- **위치**: `LockWaitMigrationInspector.java:151-152`, `PostgreSqlMigrationLockWaitIntegrationTest.java:45-50`·`:129-153`, `docs/jpa/migration-guide.md:87-88`.
- **무엇이 틀렸나**:
- Javadoc은 `postgresqlMigrationLockWaitIntegrationTest`가 목록을 Flyway에 묶어 두어 "목록을 바꾸는 Flyway 업그레이드는 거기서 실패한다"고 한다. 가이드도 "the statements it names are exactly those Flyway refuses"라고 한다.
- IT는 고정 문장 21개에서만 검사기와 Flyway를 대조한다. Flyway가 목록에 새 문장을 더하면, 그 문장이 21개 안에 없는 한 아무 테스트도 실패하지 않는다.
- 지금 목록의 일부도 대조에 없다: `CREATE`/`DROP TABLESPACE`, `CREATE`/`DROP SUBSCRIPTION`, `REINDEX SYSTEM`, 옛 문법 `REINDEX VERBOSE SCHEMA`. 명령 4로 TABLESPACE·`REINDEX VERBOSE`는 지금 일치함을 확인했다.
- 이 lane은 `integrationCheck`(main push)에서만 돈다. Flyway를 올리는 PR의 `ci`는 이 대조를 돌리지 않는다.
- **발생 조건·영향**: Flyway가 트랜잭션 밖 목록에 문장을 더하는 업그레이드. 그 문장과 `SET LOCAL`이 든 마이그레이션을 검사기가 통과시킨다. 기본 `mixed=false`에서는 배포 때 Flyway가 거부하고, `mixed=true`에서는 상한 없이 돈다. 검사기 사본이 조용히 Flyway와 갈라진다.
- **고치는 법**:
- persistence-jpa `test`(PR `ci`에서 도는 lane)에 테스트 하나를 둔다. `org.flywaydb.database.postgresql.PostgreSQLParser`의 static `Pattern` 필드를 reflection으로 읽어 `pattern()` 집합을 11.14.1 기준 값으로 고정한다. 다르면 "Flyway의 트랜잭션 밖 목록이 바뀌었다: `FLYWAY_OUTSIDE_A_TRANSACTION`과 IT 대조 목록을 갱신하라"로 실패한다. `flyway-database-postgresql`은 이미 testRuntimeClasspath에 있다(lockfile).
- IT 대조 목록에 위 네 대안을 더한다.
- Javadoc `:151-152`·가이드 `:87-88`을 실제로 지키는 범위로 고친다.
- **이번 커밋/이전부터**: 이번 커밋.
- **증거**: E1 — 디컴파일한 `PostgreSQLParser`와 IT 대조 목록 비교, lane 단계(`integration-main.yml`). E3 — 명령 4.
### RR6-03-04 · Minor · optional 빌드의 Spotless가 Sync로 가져온 사본을 검사하고, 안내한 `spotlessApply`는 아무것도 고치지 못한다
- **위치**: `src/grpc/grpc-operation-ledger-jpa/build.gradle:27-33`. Spotless 대상은 기본값이다(`src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java:46-51`, target 미지정 → 모든 source set).
- **무엇이 틀렸나**:
- Sync 출력이 integrationTest source set의 소스 폴더가 됐다. Spotless 기본 대상은 모든 source set이라 `build/generated/sources/sharedMigrationFiles/…/VersionedMigrationFiles.java`도 검사한다(명령 5의 `spotlessJava`가 Sync에 의존).
- 정본의 포맷이 틀리면 optional 빌드는 생성 사본 경로를 대며 `spotlessApply`를 하라고 한다.
- 명령 7: `-p optional-platforms …:spotlessApply`는 rc=0으로 끝났지만 생성 사본만 고쳤다. 정본은 그대로였다. 다음 Sync가 사본을 되돌려 `spotlessCheck`가 다시 실패했다.
- **발생 조건·영향**: 정본을 고치다 포맷을 어긴 개발자가 optional 빌드만 돌릴 때. 안내대로 해도 고쳐지지 않는다. 주 빌드의 persistence-jpa `spotlessCheck`가 같은 PR에서 정본 경로로 잡으므로 피해는 혼란과 이중 보고다.
- **고치는 법**: ledger `build.gradle`에서 Sync 출력을 Spotless 대상에서 뺀다(예: `spotless { java { targetExclude('build/generated/sources/sharedMigrationFiles/**') } }`). 정본의 포맷은 주 빌드가 맡는다고 그 옆 주석(`:19-26`)에 적는다. RED: 정본에 포맷 위반을 넣으면 지금은 optional `spotlessCheck`가 사본 경로로 실패한다. 고친 뒤에는 통과하고, 주 빌드의 persistence-jpa `spotlessCheck`만 정본 경로로 실패한다.
- **이번 커밋/이전부터**: 이번 커밋.
- **증거**: E2 — 명령 5·6·7.
### RR6-03-05 · Minor · "Flyway는 마이그레이션을 늘 트랜잭션으로 감싼다"는 설명이 가이드 밖 세 곳에 남았다
- **위치**: `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java:10-14`, `src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java:32-33`, `docs/study/postgresql-jpa-walkthrough.ko.md:1338-1344`(pathspec 밖).
- **무엇이 틀렸나**:
- r9-c는 가이드의 같은 오류만 고쳤다(가이드 `:55-63`, `:100-104`: Flyway는 CIC가 든 파일을 스스로 트랜잭션 밖에서 돌린다).
- testkit Javadoc과 study 문서는 아직 이렇게 말한다. "Flyway가 트랜잭션으로 감싸서 CIC 마이그레이션은 첫 배포에서 실패한다(좋은 경우)." "다른 문장과 섞이면 그것들은 커밋되고 인덱스만 안 된다(나쁜 경우)."
- Flyway 11.14.1에서 CIC만 든 파일은 트랜잭션 밖에서 돈다(그리고 RR6-03-01 때문에 멈춘다, 명령 9·10). 섞인 파일은 기본 `mixed=false`에서 아무것도 실행하기 전에 거부된다(명령 4). 두 설명이 모두 틀렸다.
- gRPC ledger IT Javadoc은 "마이그레이션을 Flyway가 돌리는 대로, 한 트랜잭션에서 돌린다"고 한다. Flyway가 트랜잭션 밖에서 돌릴 파일(CIC 등)은 IT가 다르게 돌린다. JDBC 트랜잭션 안에서 25001로 실패하고, 실패 메시지는 "SET LOCAL을 넣어라"라고 한다. 그 안내를 따르면 Flyway가 mixed로 거부한다.
- **발생 조건·영향**: 읽는 사람이 Flyway 동작을 잘못 배운다. 가이드와 testkit 설명이 서로 다르다. ledger에 CIC 마이그레이션을 더하는 사람은 따를 수 없는 안내를 받는다.
- **고치는 법**:
- 두 설명을 가이드 `:55-65`·`:98-104`와 같게 고친다(RR6-03-01에서 고른 방법을 반영한 뒤).
- ledger IT Javadoc은 이렇게 고친다. "지금 파일들(`SET LOCAL` + 트랜잭션 안 문장)은 Flyway도 한 트랜잭션에서 돌린다. Flyway가 트랜잭션 밖에서 돌릴 파일은 여기서 판정하지 못하니 이 테스트에 예외로 적는다." SQLState가 25001이면 실패 메시지에 같은 안내를 덧붙인다.
- **이번 커밋/이전부터**: 이전부터. r9-c가 가이드만 고치고 같은 주장의 다른 사본은 남겼다.
- **증거**: E1(세 문서·코드), E3(명령 4의 mixed 거부, 명령 10의 CIC 단독 배포).
## Declined to judge
- **검사기의 10단어 셈이 Flyway와 다르다.** 검사기는 괄호 안 단어와 식별자도 센다(`:317-355`). Flyway는 괄호 밖 키워드만 센다. 판정 단어가 문장의 첫 4개 키워드 안에 있고, 그 앞에 오는 괄호(`REINDEX` 옵션)는 많아야 6단어라 결과가 달라지는 입력이 없다. Javadoc `:294-296`의 "the way Flyway finds them"도 그래서 결함으로 올리지 않았다.
- **중첩 블록 주석.** `/* outer /* inner */ VACUUM probe; */`를 검사기는 트랜잭션 밖으로 판정했다(명령 4). PostgreSQL과 Flyway는 중첩을 센다. 거부 쪽 오판이고 실제 마이그레이션에서 보기 힘든 모양이다. 고친다면 RR6-03-02와 같은 함수다.
- **`.sql.conf`의 `executeInTransaction=true` + `SET LOCAL` + `VACUUM FULL`.** 검사기는 통과시킨다(`:243-248`). Javadoc `:61-63`은 `VACUUM FULL`을 늘 거부한다고 읽힌다. 그러나 PostgreSQL이 배포 때 25001로 거부해 잠금 대기가 생기지 않고, 이 조합을 쓸 이유가 없는 입력이다.
- **`REINDEX (CONCURRENTLY 'false')`.** 문자열 값이 `''`로 지워져 동시로 판정된다. PostgreSQL이 받는 값이지만 쓰는 사람을 상정하기 어렵다.
- **`.sql.conf`의 placeholder·환경 변수.** Flyway는 `${…}`를 치환하고 검사기는 `IllegalStateException`으로 실패한다(`:394-398`). 거부 쪽이다.
- **Sync 방식과 IDE.** 생성 폴더는 Gradle을 한 번 돌리기 전에는 없다. 생성 사본을 IDE에서 고치면 다음 Sync가 덮는다. 생성 소스의 일반적인 성질이고, IntelliJ 기본(Gradle에 빌드 위임)에서는 Sync가 먼저 돈다. 실행으로 확인하지 않았다.
- **persistence-jpa 디렉터리가 없는 파생 서비스.** ledger의 integrationTest가 컴파일되지 않는다. 문서화된 capability 제거는 `runtimeOnly` 줄을 지우는 것이지 디렉터리를 지우는 것이 아니다.
- **V002 주석 "Flyway runs each migration in a transaction"**(`V002__index_grpc_operation_ledger_finished_rows.sql:11`). RR6-03-05와 같은 오류다. 다만 적용된 마이그레이션이라 고치면 checksum이 바뀐다. 이 파일의 결론(빈 테이블이라 일반 인덱스)은 맞다. 고칠지는 소유자 판단이다.
- **`MessagingMigrationNamespaceTest`의 정규식 `V(\d+)__.+\.sql`.** 05 영역이다. 소수 버전을 실패시키는 쪽이라 조용히 빠지지 않는다.
- **Flyway `mixed=true`·전역 `executeInTransaction=false`를 쓰는 서비스.** 검사기 Javadoc `:63-65`와 가이드 `:62`에 가정으로 적혀 있다.
## 결론
결함 5건: Important 1건, Minor 4건. 이번 커밋 2건(RR6-03-03, RR6-03-04), 이전부터 3건(RR6-03-01, RR6-03-02, RR6-03-05). RR6-03-01은 이전부터지만 이번 커밋이 같은 길을 더 안내했다.
- r9-c가 맡은 세 항목(RR4-02-01, gRPC 버전 정규식 복사본, V21 주석)은 닫혔다. 검사기의 Flyway 목록은 11.14.1과 같다. 동결 목록과 sha256 목록도 맞다.
- r9-c가 새로 고친 가이드 오류는 부분 닫힘이다(RR6-03-05).
- 가장 큰 문제는 RR6-03-01이다. 가이드가 안내하는 CIC 마이그레이션이 Flyway 기본 설정에서 끝나지 않는다. 고치기 전에 소유자가 방법(session-level 잠금 또는 운영 절차로 이동)을 정해야 한다.
@@ -0,0 +1,169 @@
# 04 build-logic r9 리뷰 (2026-11-05)
> 대상: `c508b1ba..45d2a478`의 r9-d 묶음. 실패를 막지 못하는 workflow 명령, 실행되지 않는 줄의 `cd`, 실패 메시지,
> 짧은 플래그 묶음, httpclient 장애 주입 lane 중복 실행 제거.
## 범위
### pathspec
```
src/build-logic src/build.gradle src/adapter/outbound/httpclient/build.gradle .github AGENTS.md CLAUDE.md
src/README.md docs/upgrade/2026-11-maturity-review.md
```
`git diff c508b1ba..45d2a478 -- <pathspec>`: 11개 파일, +1985 −330. `.github`와 `src/build.gradle`은 이번 커밋에서 바뀌지 않았다. 새 `ShellScript.java`(1213줄)와 `WorkflowGradleInvocations.java`(778줄)는 diff가 아니라 HEAD 전체를 읽었다.
### 불러온 스킬과 적용한 기준
| 스킬 | 기준 | 본 것 |
|---|---|---|
| `superpowers:requesting-code-review` | 계획(README 16절 r9-d 주장)과 구현이 맞는가, 테스트가 실제 동작을 보는가, 심각도 보정, Declined to judge, 읽기 전용(별도 worktree) | r9-d 항목마다 닫힘 여부, 테스트가 주장하는 고정 범위(RR6-04-02), 결함마다 실행 증거 |
| `ci-cd-and-automation` | "No gate can be skipped", 레드 플래그 "CI failures ignored or silenced" | 검사가 단계를 실행으로 세는데 실제로는 돌지 않거나 실패가 삼켜지는 모양(거짓 통과). `mainCheck`에서 뺀 httpclient lane이 다른 단계에서 실제로 도는지 |
| `codebase-design` | 깊은 모듈, seam은 실제 adapter와 맞물려 검증되는가("One adapter means a hypothetical seam"), 인터페이스가 테스트 표면인가 | `ShellScript.commands(script, dir, options)` 인터페이스는 작고 `WorkflowGradleInvocations.read`로 테스트된다. 반면 Gradle 명령줄 판독은 Gradle 파서의 손 복사본인데 실행 중인 Gradle과 맞대는 계약 테스트가 두 모양뿐이다(RR6-04-02) |
### 실행한 명령과 결과
모든 실행은 `git worktree add --detach <scratchpad>/rr6-04/wt 45d2a478`에서 했다. Gradle은 공유 `heavy.lock`으로 감쌌다.
| 명령 | 결과 | 직전 부하(1분) |
|---|---|---|
| `./gradlew :mainCheck --dry-run` | rc=0, 계획에 `httpClientFailureInjectionTest` 0회 | 3.89 |
| `./gradlew :integrationCheck --dry-run` | rc=0, 계획에 `:adapter:outbound:httpclient:httpClientFailureInjectionTest` 1회 | 3.89 |
| `./gradlew :verifyStrictLaneStages --dry-run` / `-p optional-platforms …` | rc=0 / rc=0, 둘 다 "every strict lane is in an executed stage" | 3.79 |
| `./gradlew -p build-logic test --tests 'dev.caskeleton.buildlogic.strictlane.*'` | rc=0, 76개 통과, 실패·건너뜀 0 | 4.00 |
| Gradle 9.0.0·9.2.0·9.7.1 `gradle --help` | 옵션 표 대조: 9.0.0과 판독기 표가 정확히 같음. 9.2.0에 `--task-graph`, 9.7.1에 `--console-unicode`·`--develocity-url`·`--develocity-plugin-version`·`--non-interactive`·`--isolated-projects` 추가 | 3.80 |
| 임시 프로젝트(`ci` 태스크가 파일을 씀)에서 9.0.0·9.2.0 `gradle --no-daemon -q :ci --task-graph` | 9.0.0 rc=1(옵션 모름), 9.2.0 rc=0·작업 미실행 | 2.98 |
| 같은 프로젝트에서 9.0.0 `:ci -v`, `:ci --version`, `-v :ci`, `:ci --help`, `:ci -h`, `:ci --status`, `:ci -V` | `-V`만 작업 실행. 나머지 여섯은 rc=0·작업 미실행 | 5.20 |
| 판독기 probe: HEAD의 `ShellScript.java`·`WorkflowGradleInvocations.java`를 scratchpad로 꺼내 `javac`로 따로 컴파일하고 사례 workflow 12개를 읽힘 | 결과는 결함마다 적었다 | — |
| 같은 probe로 이 repo의 workflow 15개 | run 스크립트 104개 파싱 실패 0. 단계 명령 11개 모두 COUNTED | — |
| `c508b1ba`의 판독기와 HEAD 판독기를 같은 workflow 15개에 | 단계 명령 11개 판정 같음. 다른 것은 단계가 아닌 명령: task 단어 6개(`-P…=${{ matrix.x }}`가 한 단어로 읽힘)와 미집계 3개(`for`·명령 치환 안) | — |
| `bash -e`로 가짜 `gradlew`(호출을 기록하고 exit 1)를 부르는 스크립트 13개 | 결함마다 적었다 | — |
| GitHub 문서(workflow syntax의 shell 표·exit code 절·`needs` 절, container 문서) | 기본 셸: Linux·macOS `bash -e {0}`, `shell: bash`는 `bash --noprofile --norc -eo pipefail {0}`, Windows는 `pwsh`, container 안은 `sh` | — |
### 못 본 것
- 실제 GitHub runner 실행, pwsh 실행(이 환경에 pwsh가 없다).
- `--stop`: 같은 Gradle 버전의 다른 세션 데몬을 멈추므로 실행하지 않았다(Gradle `--help` 설명과 코드 경로로만 판단).
- `-p build-logic check` 전체와 javadoc: strictlane 테스트만 돌렸다.
- README 16절의 "run 스크립트 253개" 코퍼스: 이 repo의 104개만 다시 파싱했다.
## 항목 재확인
| ID | 판정 | 근거 |
|---|---|---|
| README 15절 남음: `\|\| true`, pipefail 없는 `\| tee`, `if ./gradlew ci; then` | 닫힘 | `ShellScript.java:953-998`. 테스트 `gradlewWhoseFailureIsHandledOrDroppedDoesNotCountAndSaysWhy`, `gradlewThatRunsOnlyUnderAConditionOrInALoopOrFunctionDoesNotCount`, TestKit `aStageCalledOnlyInShapesThatCannotFailTheStepFailsNamingWhy` |
| RR5-02-02 `&`, `false && cd src && ./gradlew ci` | 닫힘 | `ShellScript.java:566-570`, `:959-979`. 테스트 `gradlewInAnAndListCountsOnlyWhenTheListIsTheScriptsLastCommand`. `bash -e` probe(`false && ./gradlew :ci` / `echo done`)는 rc=0·호출 0이고 판독기는 세지 않는다 |
| RR5-02-01 heredoc·부르지 않은 함수·여러 줄 문자열·`\;` 뒤의 `cd` | 닫힘 | `ShellScript.java:290-303`(heredoc 본문), `:663-674`·`:784-791`(함수 정의), `:332-334`(여러 줄 문자열), `:318-323`(이스케이프). 테스트 `aCdTheShellDoesNotRunThereIsNotFollowed`, `aCdInAFunctionBodyIsNotFollowedAndTheCommandsAfterItDoNotCount` |
| RR5-02-03 다른 빌드로 읽힌 명령을 실패 메시지에 | 닫힘 | `StrictLaneStagesPlugin.java:200-220`, `WorkflowGradleInvocations.java:152-160`. TestKit `aStageCalledForAnotherBuildIsNamedWithThatBuildInTheFailure`(`scr`, `src/src`) |
| `-mx` 같은 짧은 플래그 묶음 | 닫힘 | `WorkflowGradleInvocations.java:696-760`. 값 옵션·플래그 표가 9.0.0 `--help`와 같다. 작업 없이 끝나는 플래그는 별도 결함 RR6-04-01 |
| "Gradle 9.0 파서 동작을 TestKit으로 고정" | 부분 | `StrictLaneStagesFunctionalTest.java:564-606`은 `-qm`·`-mx` 두 모양만 고정한다 → RR6-04-02 |
| `shell:` 기본값·`defaults.run.shell` | 부분 | Linux·macOS 기본과 `shell: bash`·`sh`, job·workflow `defaults.run.shell`은 맞게 읽는다(probe `10-defaults-shell`). Windows 기본 pwsh를 bash로 읽는다 → RR6-04-04 |
| httpclient 장애 주입 lane 두 번 실행 | 닫힘 | `src/adapter/outbound/httpclient/build.gradle:230-242`. `:mainCheck --dry-run` 0회, `:integrationCheck --dry-run` 1회. `.github/workflows/integration-main.yml:173-176`의 `integration-check`가 main push·nightly에 `:integrationCheck`를 돌리고 판독기가 COUNTED로 읽는다. 문서(`docs/upgrade/…:236`, `docs/capability-status.md:38`)도 같다 |
| 새로 찾아 고친 것(`$(( ))`, `help --task ci`, `${{ }}` 안 공백, `-x=b`) | 닫힘 | 테스트 `aScriptWithArithmeticIsReadAsShellAndItsLastGradlewCounts`, `bundledShortOptionsAreReadTheWayGradleReadsThem`. 실제 workflow 비교에서 `${{ }}`가 한 단어로 읽힌다 |
| "실제 workflow 판독 전후 같음" | 확인 | 단계 명령 11개 판정이 `c508b1ba`와 같다 |
## 결함
### RR6-04-01 · 작업을 실행하지 않고 끝나는 Gradle 옵션을 실행으로 센다
- 심각도: Minor (가이드 Low · P2)
- 위치: `src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java:73-83`(`GRADLE_FLAGS`), `:728-744`(묶음 안의 글자), `:752-759`(`m`·`dry-run`만 계획 전용으로 본다)
- 무엇이 틀렸나: Gradle 9.0은 `-v`·`--version`, `-h`·`-?`·`--help`, `--status`를 받으면 정보만 찍고 작업 없이 0으로 끝난다. `--stop`도 데몬을 멈추고 끝난다. 판독기는 이 옵션들을 값 없는 플래그로만 읽는다. 그래서 `./gradlew :ci -v`를 `:ci` 실행으로 센다.
- 발생 조건·영향: 다른 도구처럼 `-v`를 "자세히"로 알고 붙인 workflow 명령이 대표적이다. 그 step은 Gradle 버전만 찍고 초록으로 끝난다. `verifyStrictLaneStages`도 통과한다. 단계와 그 lane은 아무 데서도 돌지 않는다. `-qm`을 계획 전용으로 막은 것과 같은 종류인데 빠졌다.
- 고치는 법: 작업 없이 끝나는 옵션 목록(`v`, `version`, `h`, `?`, `help`, `status`, `stop`)을 따로 둔다. 이 옵션이 단독으로든 묶음 안(`-qv`)으로든 나오면 "Gradle은 `<옵션>`을 받으면 작업을 실행하지 않고 끝난다"는 이유로 세지 않는다. 단위 테스트에 `:ci -v`, `:ci --help`, `-qv :ci`, `:ci --status`를 더한다. TestKit에는 `runner(":ci", "-v")`가 작업을 실행하지 않는다는 것을 고정한다(`--stop`은 TestKit에서도 돌리지 않는다).
- 이번 커밋/이전부터: 이전부터. 이번 커밋이 판독을 "Gradle 9.0 파서대로"로 다시 쓰고 `-qm`만 계획 전용에 더하면서 남았다.
- 증거: E3. 임시 프로젝트에서 Gradle 9.0.0 `gradle --no-daemon -q :ci -v`·`:ci --version`·`-v :ci`·`:ci --help`·`:ci -h`·`:ci --status` → 모두 rc=0, 작업 미실행(`-V`는 실행). 판독기 probe(`cases/06-early-exit-flags.yml`, `-qv`·`--stop` 포함 6개) → 모두 `executes(:ci, src)=true`.
### RR6-04-02 · Gradle을 올려 옵션 표가 낡아도 잡는 테스트가 없다 — 9.2의 `--task-graph`가 그 예
- 심각도: Minor (Low · P2)
- 위치: `WorkflowGradleInvocations.java:60-83`(9.0 값 옵션·플래그 표), `:658-660`(Javadoc "pinned by `StrictLaneStagesFunctionalTest`"), `src/build-logic/README.md:19`("the reader follows Gradle 9.0's parser, probed in round 9"), `src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java:564-606`(고정한 것은 `-qm`·`-mx`뿐)
- 무엇이 틀렸나: 옵션 표는 9.0.0 `--help`와 정확히 같다. 하지만 표를 실행 중인 Gradle과 비교하는 테스트가 없다. TestKit 테스트는 build-logic을 돌리는 Gradle(wrapper)에서 돌지만 두 모양만 본다. Gradle 9.2.0은 `--task-graph`("Print task graph instead of executing tasks")를 더했다. 9.2.0에서 `gradle :ci --task-graph`는 rc=0이고 작업을 실행하지 않는다. 판독기는 이 옵션을 모르는 긴 옵션으로 넘기고 `:ci` 실행으로 센다.
- 발생 조건·영향: wrapper를 9.2 이상으로 올린 뒤 계획만 보려고 `./gradlew :integrationCheck --task-graph` 같은 step을 둔 경우다. 이 repo의 `configuration-cache` job이 `--dry-run`으로 하는 일과 같은 용도다. 검사는 통과하고 lane은 돌지 않는다. wrapper 변경 PR은 `build-logic.yml`(경로 `src/gradle/**`)을 돌리지만 지금 테스트는 그대로 통과한다. 9.7.1은 값 옵션 `--console-unicode`·`--develocity-url`·`--develocity-plugin-version`과 플래그 `--non-interactive`·`--isolated-projects`도 더했다.
- 고치는 법: TestKit 테스트 하나를 더한다. `runner("--help")` 출력에서 옵션 이름을 뽑아 `GRADLE_FLAGS ∪ GRADLE_VALUE_OPTIONS`(그리고 RR6-04-01의 작업 없이 끝나는 목록)과 같다고 단언한다. 그러면 Gradle을 올리는 PR이 새 옵션마다 "값을 받는가, 작업을 실행하는가"를 정해야 통과한다. Javadoc과 README의 "고정" 문장은 실제로 고정한 범위로 고친다.
- 이번 커밋/이전부터: 이번 커밋. 표와 "고정" 주장을 이번에 새로 뒀다.
- 증거: E3. Gradle 9.0.0·9.2.0·9.7.1 `--help`의 옵션 이름과 판독기 표 대조(9.0.0: 표에 없는 옵션 0, 표에만 있는 옵션 0). 임시 프로젝트에서 9.0.0 `:ci --task-graph` → rc=1 "Problem configuring task :ci from command line", 9.2.0 → rc=0, "Tasks graph for: :ci", 작업 미실행. 판독기 probe(`cases/03-task-graph.yml`) → `executes=true`.
### RR6-04-03 · 스크립트가 그 명령 앞에서 끝날 수 있는 모양 중 맨 위의 `exit`만 본다
- 심각도: Minor (Low · P2)
- 위치: `src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/ShellScript.java:943-948`(맨 위에 혼자 있는 `exit`만 `terminated`), `:21-29`(Javadoc "anything after ... a top-level exit"), `:1144-1174`(`setEffect`가 `-n`을 모름)
- 무엇이 틀렸나: 판독기는 뒤 명령이 아예 돌지 않는 경우를 맨 위의 무조건 `exit` 하나로만 안다. 아래 모양에서 bash는 `./gradlew :ci`를 돌리지 않거나 그 실패를 버리고 step을 초록으로 끝낸다. 판독기는 모두 실행으로 센다.
- `if git diff --quiet origin/main -- .; then echo "no source change"; exit 0; fi` 다음 줄의 `./gradlew :ci`
- `[ "$SKIP_CI" = true ] && exit 0` 다음 줄
- `skip() { echo skip; exit 0; }`를 부른 다음 줄
- `exec ./gradlew :help` 다음 줄(셸이 Gradle로 바뀌어 다음 줄은 돌지 않는다)
- `set -n` 다음 줄(명령을 읽기만 하고 실행하지 않는다)
- `trap 'exit 0' EXIT` 뒤의 `./gradlew :ci`(돌지만 실패해도 step이 0으로 끝난다)
- 왜 결함인가: 같은 판독기는 step의 `if:`가 상태 함수가 아니면 "매 실행이 아니다"라며 세지 않는다. 스크립트 안의 조건부 `exit 0`도 같은 일을 한다. "바뀐 것이 없으면 건너뛴다"는 CI에서 흔한 모양이다.
- 고치는 법:
1. 맨 위가 아닌 곳(복합 명령, `&&`·`\|\|` 목록, 함수 본문)의 `exit`가 `exit 0`, 인자 없는 `exit`, 리터럴이 아닌 값이면 그 뒤 명령을 "앞의 `<exit>`가 그 전에 스크립트를 끝낼 수 있다"로 세지 않는다. `exit 1`처럼 0이 아닌 리터럴은 step을 실패로 끝내므로 지금처럼 둔다(이 repo `main-check` 첫 step의 `if …; then …; exit 1; fi` 모양).
2. 맨 위의 `exec <명령>`은 `exit`처럼 그 뒤를 끝낸 것으로 본다.
3. `set -n`·`set -o noexec`도 그 뒤를 끝낸 것으로 본다.
4. `trap`의 `EXIT`·`ERR` 동작에 `exit`가 있으면 그 뒤 명령을 세지 않는다.
5. 모양마다 RED 단위 테스트를 둔다.
- 이번 커밋/이전부터: 이전부터. 이번 커밋이 `exit`를 다루면서 무조건 `exit`만 막았다.
- 증거: E3. `bash -e`에 가짜 `gradlew`(호출을 기록하고 exit 1): 조건부 exit 두 모양·함수 안 exit·`set -n` → rc=0, 호출 0. `exec` → 다음 줄 호출 없음. `trap 'exit 0' EXIT` → 호출됐지만 rc=0. 판독기 probe(`cases/02-conditional-exit.yml`, `cases/11-more-exit.yml`) → 6개 모두 `executes=true`.
### RR6-04-04 · Windows runner의 기본 셸을 `bash -e`로 읽는다
- 심각도: Minor (Low · P3)
- 위치: `WorkflowGradleInvocations.java:32-35`(Javadoc "GitHub's default `bash -e`"), `:94-99`(`SHELLS`의 `""` → `bash -e`), `:298-310`(`runs-on`을 보지 않음), `src/build-logic/README.md:19`("a step whose `shell:` is not the default, `bash` or `sh`"), `docs/upgrade/2026-11-maturity-review.md:107`(B-36 "`shell:`이 기본·`bash`·`sh`가 아닌 단계도 세지 않는다")
- 무엇이 틀렸나: GitHub 문서에서 `shell`이 없을 때 Linux·macOS의 기본은 `bash -e {0}`이고 Windows의 기본은 `pwsh`다. pwsh에서 GitHub는 `$ErrorActionPreference = 'stop'`을 앞에, `if ((Test-Path -LiteralPath variable:\LASTEXITCODE)) { exit $LASTEXITCODE }`를 뒤에 붙인다. 네이티브 명령(`gradlew.bat`)이 0이 아닌 코드로 끝나도 스크립트는 멈추지 않는다. step 결과는 마지막 네이티브 명령의 코드다. 판독기는 `runs-on`을 보지 않고 모든 기본 셸을 `bash -e`로 읽는다.
- 발생 조건·영향: 파생 서비스가 `runs-on: windows-latest`(또는 matrix에 windows가 있는) job에서 `./gradlew :ci` 다음 줄에 `git status` 같은 네이티브 명령을 둔 경우다. Gradle이 실패해도 step은 초록이고 검사도 통과한다. 이 repo의 job 62개는 모두 `ubuntu-latest`라 지금은 해당하지 않는다. `container:` job의 기본은 `sh -e`인데 `-e` 켜짐·pipefail 없음이 같아 판정은 바뀌지 않는다. 주석의 "기본 = bash -e"만 정확하지 않다.
- 고치는 법: job의 `runs-on`을 읽는다. `shell`이 없고 `runs-on`이 `ubuntu-`·`macos-` 리터럴이 아니면(Windows 라벨, `${{ }}` 식, 알 수 없는 self-hosted 라벨) "기본 셸이 Windows의 pwsh일 수 있다"로 세지 않는다. Javadoc·README·B-36에는 "Linux·macOS의 기본"과 container의 `sh -e`를 적는다. `runs-on: windows-latest` RED 단위 테스트를 둔다.
- 이번 커밋/이전부터: 이번 커밋. 셸 판독과 "기본 = `bash -e`" 주장을 이번에 새로 뒀다.
- 증거: E3(판독기 probe `cases/01-windows.yml` → `executes=true`) + E1(GitHub workflow syntax의 shell 표와 "Exit codes and error action preference" 절, container 문서의 "The default shell for `run` steps inside a container is `sh`"). pwsh 실행은 하지 않았다.
### RR6-04-05 · 문서와 실패 메시지가 세지 않는 이유를 사실과 반대로 적는다
- 심각도: Minor (Low · P3)
- 위치: `docs/upgrade/2026-11-maturity-review.md:107`(B-36 괄호 안의 `\|\| exit 1`, "`if`·`for`·`case`·함수·`$( )`·`bash -c` 안"), `src/build-logic/README.md:19`("`\|\| true` or any `\|\|`", "the condition or body of `if`/`while`/`for`/`case`", "a command line Gradle rejects (`-mx` …)"), `AGENTS.md:87-89`("복합 명령·함수·명령 치환 안", "Gradle이 거부하는 명령줄(`-mx`)"), `CLAUDE.md:44-46`, `StrictLaneStagesPlugin.java:153-156`(요약 문구), `ShellScript.java:967-970`(`|| exit 1`에 "its failure is handled")
- 무엇이 틀렸나:
- `./gradlew ci || exit 1`, `if [ -n "$RUN" ]; then ./gradlew ci; fi`, `{ ./gradlew ci; }`, `( ./gradlew ci )`의 Gradle 실패는 `bash -e`에서 step을 실패시킨다. README 16절 결정대로 이 모양을 세지 않는 것(거짓 실패 쪽)은 맞다. 그런데 문서 넷과 실패 메시지는 이유를 "실패해도 단계를 실패시키지 못한다(a command whose failure cannot fail its step)"로 적는다. 사실과 반대다.
- 문서는 "Gradle이 거부하는 명령줄은 세지 않는다"고 적는다. 구현은 짧은 옵션 묶음만 본다. `./gradlew :ci --task-graph`(9.0에서 거부, rc=1)나 `./gradlew :ci -x --dry-run`은 Gradle이 거부하지만 판독기는 센다. 매 실행 빨간 step이라 조용한 통과는 아니다. 문서가 구현보다 넓게 약속한다.
- 영향: 실패를 workflow annotation으로 남기려고 `./gradlew ci || { echo "::error::ci failed"; exit 1; }`를 쓴 파생 서비스는 "your command cannot fail its step"을 받는다. 개발자는 검사가 틀렸다고 보고 우회를 찾는다. 해야 할 일(명령을 혼자 한 줄로 둔다)은 메시지에 없다.
- 고치는 법: 세지 않는 이유를 셋으로 나눠 문서와 메시지에 같은 말로 적는다.
1. 실패를 막지 못함: `|| true`·`|| :`, pipefail 없는 파이프 왼쪽, `!`, `&`, `if`·`while` 조건, `set +e` 뒤, 마지막이 아닌 `&&` 목록.
2. 돌지 않을 수 있음: 복합 명령·함수 본문 안, 맨 위 `exit` 뒤(RR6-04-03), 상태 함수가 아닌 `if:`.
3. 판독기가 읽지 않음(실패하면 step도 실패하지만 세지 않는다, 거짓 실패 쪽): `|| exit 1`, `|| { …; exit 1; }`, 서브셸·`{ }`, `$( )`, `bash -c`.
`listReason`은 `||` 오른쪽이 0이 아닌 `exit`면 "이 모양은 읽지 않는다. 명령을 혼자 한 줄로 두라"고 말한다. "Gradle이 거부하는 명령줄"은 "Gradle이 거부하는 짧은 옵션 묶음(`-mx`)"으로 좁힌다. 요약 문구와 AGENTS.md·CLAUDE.md·README·B-36을 함께 고친다.
- 이번 커밋/이전부터: 이번 커밋.
- 증거: E3. `bash -e` probe: `./gradlew :ci || exit 1`, `if true; then ./gradlew :ci; fi`, `{ ./gradlew :ci; }`, `( ./gradlew :ci )` 각각 다음 줄에 `echo done` → 모두 rc=1(step 실패). 판독기 probe(`cases/12-gated-but-uncounted.yml`) → 미집계, 이유 "its failure is handled by the `|| { echo "::error::ci failed"; exit 1; }` after it". 문서는 E1 대조.
### RR6-04-06 · 사람이나 다른 workflow가 시작해야만 도는 workflow·job을 실행으로 센다
- 심각도: Minor (Low · P3)
- 위치: `WorkflowGradleInvocations.java:364-410`(`dispatchOnlyReason`은 trigger가 모두 `workflow_dispatch`일 때만), `:528-542`(`uncountedReason`은 step과 자기 job의 `if:`만 본다)
- 무엇이 틀렸나: "`workflow_dispatch`로만 시작하는 workflow는 묻지 않으면 아무것도 돌리지 않으므로 세지 않는다"(RR2-04-04)는 규칙이 같은 이유의 다른 모양을 보지 않는다. 아래는 모두 판독기가 실행으로 센다.
- `on: [workflow_dispatch, repository_dispatch]`, `on: issue_comment`(ChatOps `/test`): 외부 요청이 있어야 돈다.
- `on: workflow_call`만 있는 재사용 workflow: 부르는 workflow가 없거나 조건부로 부르면 돌지 않는다.
- `needs:`로 기다리는 job이 상태 함수가 아닌 `if:`로 건너뛰어지는 job. GitHub 문서: "If a job fails or is skipped, all jobs that need it are skipped unless the jobs use a conditional expression that causes the job to continue."
- 발생 조건·영향: 파생 서비스가 무거운 단계를 ChatOps나 재사용 workflow, 또는 조건부 job 뒤로 옮긴 경우다. 검사는 통과하고 단계는 요청이 있을 때만 돈다. 이 repo의 workflow에는 지금 이 모양이 없다.
- 고치는 법:
1. 시작 trigger가 모두 요청형(`workflow_dispatch`, `repository_dispatch`, `issue_comment` 등)이면 세지 않는다.
2. `workflow_call`만 있는 workflow는 직접 세지 않는다. `jobs.<id>.uses: ./.github/workflows/<file>`로 부르는 job의 trigger와 `if:`를 물려받아 센다. 부르는 곳이 없으면 세지 않는다.
3. job의 `needs:`를 따라가며 각 job의 `if:`에 같은 규칙을 적용한다. 자기 `if:`에 `always()`·`!cancelled()`가 있으면 거기서 끊는다.
4. 모양마다 RED 테스트를 둔다.
- 이번 커밋/이전부터: 이전부터.
- 증거: E3(판독기 probe `cases/04-workflow-call.yml`, `07-triggers.yml`, `08-issue-comment.yml`, `09-needs.yml` → 모두 `executes=true`) + E1(GitHub workflow syntax `jobs.<job_id>.needs` 절).
## Declined to judge
- 경로·브랜치 필터(`paths:`, `branches:`)가 있는 trigger: 그 workflow가 도는 이벤트에서는 단계가 실제로 돈다. 어떤 필터가 충분한지는 저장소 정책이라 판단하지 않았다.
- 설계상 거짓 실패 모양(`timeout ./gradlew …`, `set +e` / `./gradlew …` / `exit $status`, `|| exit 1`, 서브셸·`eval`·`source` 안의 `cd` 뒤): README 16절 결정이라 다시 올리지 않았다. 이유 문구만 RR6-04-05에 넣었다.
- `${{ }}` 값이 `--dry-run`이나 `|| true`로 펼쳐지는 경우: 실행 전에는 값을 알 수 없다.
- `CDPATH`·심볼릭 링크로 `cd`가 다른 곳으로 가는 경우: GitHub runner 기본 환경에는 `CDPATH`가 없다.
- composite action(`.github/actions/*/action.yml`) 안의 `run:`: 판독기가 읽지 않는다. 거짓 실패 쪽이라 결함으로 올리지 않았다.
- httpclient 문서(`docs/httpclient/support-matrix.md:61,65`, `docs/httpclient/release-checklist.md:12`): 장애 주입 lane 주기에 main push가 빠졌고, `spring62CompatibilityTest`는 없는 lane 이름이다(실제 이름 `spring62ApiSurfaceScan`, 2026-09-18 리뷰가 이미 적음). pathspec 밖 다른 영역 파일이라 판정하지 않았다. 총괄이 해당 영역으로 넘길 것.
- 실제 GitHub runner와 pwsh 동작: 이 환경에서 실행할 수 없다. RR6-04-04는 문서 근거다.
## 결론
Critical 0, Important 0, 회귀 0. 결함 6건, 모두 Minor다.
- 이번 커밋 3건: RR6-04-02(옵션 표를 Gradle 올림에서 지키는 테스트 없음), RR6-04-04(Windows 기본 셸), RR6-04-05(세지 않는 이유 문구).
- 이전부터 3건: RR6-04-01(작업 없이 끝나는 Gradle 옵션), RR6-04-03(조건부 `exit`·`exec`·`set -n`·`trap`), RR6-04-06(요청형 trigger·`workflow_call`·`needs`).
r9-d가 고쳤다고 한 항목(README 15 남음, RR5-02-01·02·03, `-mx`, 장애 주입 lane 중복)은 모두 닫혔다. 이 repo의 실제 workflow 판정은 `c508b1ba`와 같고 두 빌드의 `verifyStrictLaneStages --dry-run`이 통과한다. 남은 결함은 모두 파생 서비스가 쓸 수 있는 모양에서 검사가 거짓으로 통과하거나 이유를 틀리게 말하는 것이다.
+7 -5
View File
@@ -19,8 +19,10 @@ status: active
action, so a client retry is safe.
- The same 503 when the store refused to start a claim whose processing lease had already run out
— the request spent longer than the lease between its claim and the start of its action (a
stalled process, a slow store call). The ERROR line's message then reads `the claim's processing
lease ran out before the action started; nothing ran: <scope>`, and the store may be healthy.
stalled process, a slow store call). The ERROR line, `failure classified as
IDEMPOTENCY_UNAVAILABLE (…)`, has the exception attached, and the exception's message reads `the
claim's processing lease ran out before the action started; nothing ran: <scope>` — in prod JSON
logs that is in `stack_trace`, not `message`. The store may be healthy.
Nothing ran here either, and the next request with the key takes the claim over and runs it.
- HTTP 503 `IDEMPOTENCY_COMPLETION_UNKNOWN` (`retryable=true`) is the same outage hitting after the
action ran: the store did not answer while the result was being recorded. When the use case called
@@ -98,9 +100,9 @@ status: active
## Action
- `IDEMPOTENCY_UNAVAILABLE`: restore the store; clients retry with the same key and backoff. When
the message says the claim's processing lease ran out before the action started, the store is
not the cause: find what held those requests between claim and start (thread dumps, GC pauses,
the store's latency in that window). Nothing to repair; the next same-key request runs.
the exception message says the claim's processing lease ran out before the action started, the
store is not the cause: find what held those requests between claim and start (thread dumps, GC
pauses, the store's latency in that window). Nothing to repair; the next same-key request runs.
- `IDEMPOTENCY_COMPLETION_UNKNOWN`: restore the store, then check the effects outside the
transaction for the failed requests (the ERROR log line names the code). A same-key resend replays
a result that was in fact recorded, gets `IDEMPOTENT_IN_FLIGHT` while the attempt's lease lasts,
+34 -10
View File
@@ -1336,15 +1336,35 @@ startup 동작으로는 절대 아니다.
### 8.2 `ConcurrentIndexMigrationInspector`
PostgreSQL은 `CREATE INDEX CONCURRENTLY`를 트랜잭션 블록 안에서 아예 거부하고, Flyway는
기본적으로 마이그레이션을 트랜잭션으로 감싼다. **그래서 첫 배포에서 실패하는데, 그게 좋은
경우다.**
PostgreSQL은 `CREATE INDEX CONCURRENTLY`·`DROP INDEX CONCURRENTLY`·`REINDEX … CONCURRENTLY`를
트랜잭션 블록 안에서 거부한다. Flyway 11은 `CREATE`/`DROP INDEX CONCURRENTLY`가 든 파일을 **스스로
트랜잭션 밖에서** 돌린다. `REINDEX … CONCURRENTLY`는 모른다. 그 파일은 트랜잭션 안에서 돌고, 배포 때
PostgreSQL이 거부한다. 그래서 검사기는 동시 인덱스 문장이 있으면 `.sql.conf`에
`executeInTransaction=false`를 적으라고 요구한다. Flyway가 알아서 빼 주는 문장에도 적는다. 파일이
자기에게 필요한 것을 스스로 말하게 하려는 것이다.
> 나쁜 경우는 다른 statement와 섞인 마이그레이션이다: 그것들은 커밋되고, concurrent index는
> 안 되고, 스키마는 **history row가 반대로 말하는 채로 부분 마이그레이션 상태로 남는다.**
> 다른 문장과 섞인 파일은 Flyway가 기본값(`mixed=false`)에서 **아무것도 실행하기 전에 거부**한다.
> 부분 적용은 일어나지 않는다. 그래도 한 파일에 하나만 두는 이유는 아래 `requireIsolatedStatement`의
> 복구 때문이다.
검사 대상: `create index concurrently`, `drop index concurrently`, `reindex index concurrently`,
`reindex table concurrently`, `reindex concurrently`.
트랜잭션 밖에서도 동시 빌드는 **자기보다 먼저 시작한 트랜잭션이 모두 끝나기를 기다린다.**
```
Flyway 기본값: 잠금 트랜잭션(열린 채) ──기다림──▶ 마이그레이션 끝
▲ │
└──────── CIC가 기다림 ◀───────────┘ → 배포가 끝나지 않는다
```
- Flyway는 기본으로 마이그레이션 잠금(PostgreSQL advisory lock)을 트랜잭션 안에 두고, 실행 내내 그
트랜잭션을 열어 둔다.
- CIC는 그 트랜잭션도 기다린다. Flyway는 CIC가 끝나기를 기다린다. 오류도 시간 제한도 없다.
- 템플릿은 잠금을 세션에 둔다. Spring Boot의 Flyway는 module-defaults의
`spring.flyway.postgresql.transactional-lock: false`, 템플릿이 직접 만드는 Flyway는
`FlywaySchemaPolicy.configure()`로 받는다. 배포 마이그레이션 도구도 같은 값이어야 한다
(`docs/jpa/migration-guide.md` "Who may change the schema").
검사 대상: `CREATE [UNIQUE] INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `REINDEX … CONCURRENTLY`
(`REINDEX (CONCURRENTLY) TABLE` 같은 괄호 옵션 포함).
`requireIsolatedStatement`도 있다 — concurrent 빌드가 실패하면 invalid index가 남고, 그
복구는 마이그레이션이 다른 걸 아무것도 안 했으면 `DROP INDEX` 하나지만 뭔가 했으면 부분
@@ -1700,15 +1720,19 @@ inserted == 1 → Acquired
COMPLETED이고 replay_until 지남 → resetClaim → TakenOverClaimed
request_hash 불일치 → FingerprintMismatch
COMPLETED이고 replay_until 있음 → CompletedReplay(payload, replayUntil)
같은 claim attempt(token+operationId) → ReplayedAcquire
같은 token, 다른 operationId → OwnerOperationConflict
ABANDONED → RecoveryRequired
CLAIMED이고 lease 만료 → resetClaim → TakenOverClaimed
FAILED_RETRYABLE → resetClaim → TakenOverClaimed
같은 claim attempt(token+operationId) → ReplayedAcquire
같은 token, 다른 operationId → OwnerOperationConflict
EXECUTING이고 lease 만료 → RecoveryRequired (행은 그대로)
ABANDONED → RecoveryRequired
그 외 → InProgress(retryAfter, attempt)
```
넘겨받기 두 줄이 같은 attempt의 재생보다 앞이다. 시작을 거절당했거나 재시도 가능 실패로 끝난 attempt가
같은 attempt로 다시 오면 재생이 아니라 넘겨받기다. 재생하면 시작할 수 없는 claim을 돌려줘 기록이 사라질
때까지 막혔다(라운드6 RR6-02-01, Redis CLAIM도 같은 순서).
**만료된 `CLAIMED`만 takeover하고, 만료된 `EXECUTING`은 reconciliation을 요구하되 행은 바꾸지
않는다.** 실행이 시작된 뒤의 blind retry를 하지 않는다는 뜻이다. 행을 그대로 두는 이유는 주인이 아직
돌고 있을 수 있어서다. 주인이 늦게 끝나면 그 결과가 기록되고 다음 claim이 재생한다(2026-11-04 소유자
+8 -4
View File
@@ -248,10 +248,14 @@ source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌
고쳤다. in-memory store는 `DirectTransactionPort`를 받으면 같은 규칙(트랜잭션 밖·읽기 전용 거부,
롤백 시 취소)으로 동작한다. 인자 없이 만들면 지금처럼 바로 쓴다(relay 테스트가 행을 미리 심는 용도).
- `IdempotencyStoreContract`의 시간 케이스(renew가 lease를 실제로 늘린다, review 05-02)는 시계를
가진 store(실 Redis, PostgreSQL)에서만 의미가 있다. 시계를 움직일 수 없는 store(in-memory fake,
command fake 위 Redis)는 `elapse`를 재정의하지 않고, 기본 `elapse`가 그 케이스를 abort해 보고서에
skipped로 남는다. 예전에는 no-op이라 시간이 흐르지 않은 채 통과했다(review 2026-11-03 RR-01-06).
PostgreSQL에서 renew가 lease를 늘리지 않게 바꾼 변이로 이 케이스가 실패함을 확인했다.
가진 store(실 Redis, PostgreSQL, command fake 위 Redis)에서만 의미가 있다. command fake는
`advance`로 시계를 움직이고 멱등성 기록에 key TTL을 두므로 `RedisIdempotencyStoreContractTest`가
`elapse`를 재정의해 시간 케이스를 모두 돌린다(라운드6 RR6-02-02 — 전에는 skip했고 adapter 테스트가 일부를
손으로 복사했다). 시계를 움직일 수 없는 in-memory fake는 `elapse`를 재정의하지 않고, 기본 `elapse`가 그
케이스를 abort해 보고서에 skipped로 남는다. 예전에는 no-op이라 시간이 흐르지 않은 채 통과했다(review
2026-11-03 RR-01-06). PostgreSQL에서 renew가 lease를 늘리지 않게 바꾼 변이로 이 케이스가 실패함을
확인했다. command fake의 claim key TTL을 replay TTL만으로 줄이거나 renew의 TTL 연장을 빼는 변이로 기록 수명
케이스 3건이 실패함을 확인했다.
- `OutboxAggregateSequenceContract`는 포트 Javadoc의 세 약속 중 둘을 보지 않았다(RR-01-06). "쓰기
트랜잭션 밖 거부"와 "롤백된 번호는 다시 준다"를 넣었다. fake는 `DirectTransactionPort`를 받으면 같은
규칙으로 동작한다(인자 없이 만들면 예전처럼 트랜잭션을 보지 않는다 — sample 테스트가 쓰는 방식).
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -28,7 +28,7 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇
| `qualificationCheck` | 전체 기동(system) 레인과 보조 source set Checkstyle을 실행 |
| `integrationCheck` | 선언된 strict integration lane(sample 포함)을 실행. 대부분 container runtime이 필요. 입력이 필요한 lane(Redis topology: `-Predis.topology.mode`, AWS: 보호 자격 증명 env)은 입력이 없으면 빠지고 집계가 그 이유를 출력 |
| `performanceCheck` | 선언된 strict performance lane(부하·종료·pool·자원 상한)을 실행. 실서버·container가 필요. `integration-main.yml` `performance-check`가 main·nightly에 돌림 |
| `verifyStrictLaneStages` | `--dry-run` 전용. `explicitOnly`가 아닌 strict lane이 workflow가 실제 실행하는 단계(`ci`·`:sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나의 계획에 있는지, 각 단계를 workflow가 `--dry-run` 없이 실행하는지 검사. 실패해도 단계를 실패시키지 못하는 명령(`\|\| true`, pipefail 없는 파이프, `if` 조건 등)은 실행으로 세지 않는다. PR 게이트가 돌림 |
| `verifyStrictLaneStages` | `--dry-run` 전용. `explicitOnly`가 아닌 strict lane이 workflow가 실제 실행하는 단계(`ci`·`:sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나의 계획에 있는지, 각 단계를 workflow가 `--dry-run` 없이 실행하는지 검사. Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-v`·`--help` 등)과, 실패해도 단계가 실패하지 않을 수 있거나(`\|\| true`, pipefail 없는 파이프, `if` 조건 등) 돌지 않을 수 있거나(조건부 `exit 0` 뒤, 요청으로만 시작하는 workflow 등) 검사가 읽지 않는(`\|\| exit 1`, `{ }` 안 등) 명령은 실행으로 세지 않는다. 자세한 목록은 `build-logic/README.md`. PR 게이트가 돌림 |
| `ci` | PR 게이트: 모든 leaf `check`(API surface 검사 포함, 소유자 결정 20) + `architectureCheck` + `qualityCheck` |
| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + sample 전체 기동(`:sample-portfolio:systemTest`) + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) |
| `releaseCheck` | tag 전용 검사: `verifyReleaseProvenance` + `verifyPublicPathSnapshot`(`ci`를 다시 돌리지 않음) |
+2
View File
@@ -72,6 +72,8 @@ instrumentation, data fetcher resolver 세 곳이 같은 bean 을 받는다).
만** — 소유자 결정 25)가 모두 여기로 온다.
3. **등록된 application 매핑**(`GraphQlExceptionResolver`).
4. **`IllegalArgumentException`** → `BAD_PARAMETER`(`REQUEST`, `BAD_REQUEST`) — web·gRPC·STOMP 와 같다.
로그도 같은 WARN 한 줄 `request refused as BAD_PARAMETER by <예외 타입> (executionId=<id>)` 이고,
입력값이 들 수 있는 메시지는 남기지 않는다.
5. 나머지는 `INTERNAL_ERROR` 로 가려지고 같은 executionId 로 ERROR 로그 한 줄이 남는다.
- **client 문구**: shared-contract `ClientErrorMessages`(Category 별 한국어 문구 표 하나, 소유자
@@ -40,7 +40,9 @@ import org.springframework.graphql.execution.ErrorType;
* <p>A carrier is logged here, with {@link ServerFailureLog}'s line — the one the web and gRPC
* adapters write — plus the execution id the client received. A server-side code therefore leaves
* its detail in the log, such as the scope digest of an {@code IDEMPOTENCY_RECOVERY_REQUIRED}
* (review 2026-11-04 RR4-03-03); a persistence failure leaves its classification only.
* (review 2026-11-04 RR4-03-03); a persistence failure leaves its classification only. An unmapped
* {@link IllegalArgumentException} leaves the WARN line every transport writes for it, naming its
* type and never its message (review 2026-11-05 RR6-01-06).
*/
public final class GraphQlWireErrorMapper {
@@ -114,16 +116,29 @@ public final class GraphQlWireErrorMapper {
}
ApiErrorCode shared = sharedCodeOf(failure);
if (shared != null) {
ServerFailureLog.of(failure, shared)
.ifPresent(
line ->
LOG.error(
line.format(" (executionId={})"), line.arguments(context.executionId())));
logAnswer(failure, shared, context);
return fromApiError(shared, context);
}
return applicationMappings.resolve(failure, context);
}
/**
* Writes {@link ServerFailureLog}'s line for a failure answered with a shared code: a carrier's
* line at ERROR, or nothing for a client-side carrier; an unmapped {@link
* IllegalArgumentException} the WARN line naming its type, as on every transport.
*/
private static void logAnswer(
Throwable failure, ApiErrorCode shared, GraphQlErrorContext context) {
String suffix = " (executionId={})";
if (failure instanceof ApiErrorCarrier) {
ServerFailureLog.of(failure, shared)
.ifPresent(line -> LOG.error(line.format(suffix), line.arguments(context.executionId())));
} else if (failure instanceof IllegalArgumentException refused) {
ServerFailureLog line = ServerFailureLog.refusedArgument(refused);
LOG.warn(line.format(suffix), line.arguments(context.executionId()));
}
}
/**
* Maps a failure and renders it as the engine's error type.
*
@@ -9,6 +9,7 @@ import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyException;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException;
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
import dev.caskeleton.application.idempotency.IdempotencyRecoveryRequiredException;
import dev.caskeleton.shared.error.OperationalError;
import dev.caskeleton.shared.error.PersistenceFailureException;
@@ -193,16 +194,41 @@ class GraphQlWireErrorMapperTest {
void aClientSideCarrierIsNotLogged() {
// given
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
RuntimeException inFlight = IdempotencyInFlightException.forScopeDigest("digest");
// when
List<ILoggingEvent> logged =
loggedWhile(() -> mapper.map(inFlight, GraphQlErrorContext.of("exec-9")));
// then
assertThat(logged).isEmpty();
}
@org.junit.jupiter.api.Test
void anIllegalArgumentIsLoggedAtWarnByItsTypeWithoutItsMessage() {
// given
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
// when
List<ILoggingEvent> logged =
loggedWhile(
() ->
mapper.map(
new IllegalArgumentException("bad cursor"), GraphQlErrorContext.of("exec-9")));
new IllegalArgumentException("bad cursor for alice@example.com"),
GraphQlErrorContext.of("exec-9")));
// then
assertThat(logged).isEmpty();
assertThat(logged)
.singleElement()
.extracting(
ILoggingEvent::getLevel,
ILoggingEvent::getFormattedMessage,
ILoggingEvent::getThrowableProxy)
.containsExactly(
Level.WARN,
"request refused as BAD_PARAMETER by java.lang.IllegalArgumentException"
+ " (executionId=exec-9)",
null);
}
private static List<ILoggingEvent> loggedWhile(Runnable action) {
+8 -3
View File
@@ -153,10 +153,15 @@ handler throw, listener callback throw, `responseObserver.onError(...)`, raw
`INTERNAL_ERROR`로 폴백한다. 입력 trailers도 폐기한다.
- **서버 로그**: carrier는 web과 같은 줄(shared-contract `ServerFailureLog`)에 ` (method=<서비스/메서드>)`를
붙여 ERROR로 남긴다. persistence 실패는 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다.
그래서 `IDEMPOTENCY_RECOVERY_REQUIRED`도 web처럼 scope digest를 로그에 남긴다(재리뷰 RR4-03-03,
`docs/runbooks/idempotency-unavailable.md`). `IllegalArgumentException`은 다른 전송과 같은 WARN 한 줄
`request refused as BAD_PARAMETER by <예외 타입> (method=<서비스/메서드>)`만 남긴다(메시지 없음).
인식되지 않아 `INTERNAL_ERROR`로 답한 실패는 `unhandled failure on <method> answered as INTERNAL_ERROR
(status=<code>)`에 원인 예외를 붙인다. raw status만 있으면 description은 남기지 않는다(입력이 들 수
있다). 클라이언트가 취소한 호출(`CANCELLED`)은 남기지 않는다. 그래서 `IDEMPOTENCY_RECOVERY_REQUIRED`도
web처럼 scope digest를 로그에 남긴다(재리뷰 RR4-03-03, `docs/runbooks/idempotency-unavailable.md`).
(status=<code>)`에 원인 예외를 붙인다. raw status는 `onError`로 넘겼든 던졌든 description을 남기지 않는다
(입력이 들 수 있다). 던진 raw status는 그 예외 대신 status를 만들 때 준 원인만 붙인다(없으면 아무것도).
클라이언트가 취소한 호출(`ServerCall.isCancelled()`)은 남기지 않는다. 기다리는 클라이언트가 없기 때문이다.
서비스가 하위 호출의 `CANCELLED`를 그대로 넘겨 살아 있는 호출을 끝내면 다른 인식 못 한 실패처럼 남긴다
(재리뷰 RR6-01-04·05).
`Category → Status` 표(설계 스펙 Error Mapping SSOT):
@@ -11,6 +11,8 @@ import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import io.grpc.StatusException;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,10 +39,14 @@ import org.slf4j.LoggerFactory;
* {@link ServerFailureLog}'s line, the one the web and GraphQL adapters write, plus the method — so
* an {@code IDEMPOTENCY_RECOVERY_REQUIRED} answer leaves the scope digest the runbook looks the
* record up by ({@code docs/runbooks/idempotency-unavailable.md}, review 2026-11-04 RR4-03-03). An
* unrecognised failure answered as {@code INTERNAL_ERROR} is logged with its exception, or by its
* status code alone when the service closed with a raw status — its description may echo input. A
* call the client cancelled is not logged: nobody is waiting for the answer, and nothing failed on
* the server.
* {@link IllegalArgumentException} gets the WARN line every transport writes for it: its type,
* never its message. An unrecognised failure answered as {@code INTERNAL_ERROR} is logged with its
* exception, or by its status code alone when the service ended with a raw status — returned or
* thrown — since a status description may echo input; a raw status built with a cause has that
* cause attached (review 2026-11-05 RR6-01-05). It is not logged when the client cancelled the call
* ({@link ServerCall#isCancelled()}): nobody is waiting for the answer. A {@code CANCELLED} status
* the service itself ends a live call with — a downstream call's cancellation passed on — is an
* unrecognised failure like any other (RR6-01-04).
*/
public class GrpcExceptionHandlingInterceptor implements ServerInterceptor {
@@ -128,11 +134,15 @@ public class GrpcExceptionHandlingInterceptor implements ServerInterceptor {
code = ((ApiErrorCarrier) carrier).errorCode();
ServerFailureLog.of(carrier, code)
.ifPresent(line -> log.error(line.format(" (method={})"), line.arguments(method)));
} else if (status.getCause() instanceof IllegalArgumentException) {
} else if (status.getCause() instanceof IllegalArgumentException refused) {
code = OperationalError.BAD_PARAMETER;
ServerFailureLog line = ServerFailureLog.refusedArgument(refused);
log.warn(line.format(" (method={})"), line.arguments(method));
} else {
code = OperationalError.INTERNAL_ERROR;
logUnrecognised(method, status);
if (!delegate.isCancelled()) {
logUnrecognised(method, status);
}
}
super.close(statusMapper.statusFor(code), statusMapper.trailersFor(code));
}
@@ -144,9 +154,6 @@ public class GrpcExceptionHandlingInterceptor implements ServerInterceptor {
}
private static void logUnrecognised(String method, Status status) {
if (status.getCode() == Status.Code.CANCELLED) {
return;
}
// The cause, when there is one, is the last argument and so the logged exception; the raw
// description is never logged.
log.error(
@@ -154,7 +161,21 @@ public class GrpcExceptionHandlingInterceptor implements ServerInterceptor {
method,
OperationalError.INTERNAL_ERROR.code(),
status.getCode(),
status.getCause());
failureBehind(status.getCause()));
}
/**
* The exception to attach for an unrecognised failure. A thrown raw status reaches {@code close}
* as the status's own cause ({@link #closeWithError}), and its message is {@code "CODE:
* description"} — the description that may echo input. So a raw status is never attached: only
* the first cause behind it that is not one, if any (review 2026-11-05 RR6-01-05).
*/
private static Throwable failureBehind(Throwable cause) {
Throwable current = cause;
while (current instanceof StatusRuntimeException || current instanceof StatusException) {
current = current.getCause();
}
return current;
}
/** The first {@link ApiErrorCarrier} in the cause chain, or {@code null}. */
@@ -224,21 +224,107 @@ class GrpcExceptionHandlingInterceptorTest {
}
@Test
void aCallTheClientCancelledIsNotLogged() {
void aFailureOnACallTheClientCancelledIsNotLogged() {
// given
CapturingServerCall call = new CapturingServerCall();
CapturingServerCall cancelledCall = new CapturingServerCall(true);
// when
List<ILoggingEvent> logged =
loggedWhile(
() -> closeAfterThrowing(cancelledCall, new IllegalStateException("stream closed")));
// then
assertThat(logged).isEmpty();
}
@Test
void aCancelledStatusTheServiceClosesALiveCallWithIsLoggedAsUnhandled() {
// given: a downstream call was cancelled and the service relays its status
CapturingServerCall liveCall = new CapturingServerCall();
ServerCallHandler<String, String> handler =
(serverCall, headers) -> {
serverCall.close(Status.CANCELLED.withDescription("client cancelled"), new Metadata());
serverCall.close(Status.CANCELLED.withDescription("upstream reset"), new Metadata());
return new ServerCall.Listener<>() {};
};
// when
List<ILoggingEvent> logged =
loggedWhile(() -> interceptor.interceptCall(call, new Metadata(), handler));
loggedWhile(() -> interceptor.interceptCall(liveCall, new Metadata(), handler));
// then
assertThat(logged).isEmpty();
assertThat(logged)
.singleElement()
.extracting(
ILoggingEvent::getLevel,
ILoggingEvent::getFormattedMessage,
ILoggingEvent::getThrowableProxy)
.containsExactly(
Level.ERROR,
"unhandled failure on test.Fixture/Call answered as INTERNAL_ERROR (status=CANCELLED)",
null);
}
@Test
void aThrownRawStatusIsLoggedByItsCodeWithoutItsDescription() {
// given
RuntimeException rawStatus =
Status.INVALID_ARGUMENT
.withDescription("no customer with email alice@example.com")
.asRuntimeException();
// when
List<ILoggingEvent> logged = loggedWhile(() -> closeAfterThrowing(rawStatus));
// then
assertThat(logged)
.singleElement()
.extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getThrowableProxy)
.containsExactly(
"unhandled failure on test.Fixture/Call answered as INTERNAL_ERROR"
+ " (status=INVALID_ARGUMENT)",
null);
}
@Test
void aThrownRawStatusWithACauseIsLoggedWithTheCauseAlone() {
// given
RuntimeException rawStatus =
Status.INTERNAL
.withDescription("lookup for alice@example.com failed")
.withCause(new IllegalStateException("connection pool exhausted"))
.asRuntimeException();
// when
List<ILoggingEvent> logged = loggedWhile(() -> closeAfterThrowing(rawStatus));
// then
assertThat(logged)
.singleElement()
.extracting(
event -> event.getThrowableProxy().getClassName(),
event -> event.getThrowableProxy().getMessage())
.containsExactly(IllegalStateException.class.getName(), "connection pool exhausted");
}
@Test
void anIllegalArgumentIsLoggedAtWarnByItsTypeWithoutItsMessage() {
// when
List<ILoggingEvent> logged =
loggedWhile(
() -> closeAfterThrowing(new IllegalArgumentException("unknown recipient alice")));
// then
assertThat(logged)
.singleElement()
.extracting(
ILoggingEvent::getLevel,
ILoggingEvent::getFormattedMessage,
ILoggingEvent::getThrowableProxy)
.containsExactly(
Level.WARN,
"request refused as BAD_PARAMETER by java.lang.IllegalArgumentException"
+ " (method=test.Fixture/Call)",
null);
}
private static List<ILoggingEvent> loggedWhile(Runnable action) {
@@ -256,7 +342,11 @@ class GrpcExceptionHandlingInterceptorTest {
}
private CapturingServerCall closeAfterThrowing(RuntimeException thrown) {
CapturingServerCall call = new CapturingServerCall();
return closeAfterThrowing(new CapturingServerCall(), thrown);
}
private CapturingServerCall closeAfterThrowing(
CapturingServerCall call, RuntimeException thrown) {
ServerCallHandler<String, String> handler =
(serverCall, headers) ->
new ServerCall.Listener<>() {
@@ -292,7 +382,10 @@ class GrpcExceptionHandlingInterceptorTest {
}
}
/** Minimal {@link ServerCall} that records the {@code close(status, trailers)} arguments. */
/**
* Minimal {@link ServerCall} that records the {@code close(status, trailers)} arguments. It
* answers {@link #isCancelled()} as the transport would after the client cancelled, when told so.
*/
private static final class CapturingServerCall extends ServerCall<String, String> {
private static final MethodDescriptor.Marshaller<String> NO_WIRE =
new MethodDescriptor.Marshaller<>() {
@@ -314,9 +407,18 @@ class GrpcExceptionHandlingInterceptorTest {
.setResponseMarshaller(NO_WIRE)
.build();
private final boolean cancelled;
private Status status;
private Metadata trailers;
CapturingServerCall() {
this(false);
}
CapturingServerCall(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public void request(int numMessages) {}
@@ -334,7 +436,7 @@ class GrpcExceptionHandlingInterceptorTest {
@Override
public boolean isCancelled() {
return false;
return cancelled;
}
@Override
@@ -42,10 +42,15 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-autoconfigure'
// MessagingInboxSchemaStream applies the platform's inbox migration as a stream of its own.
implementation 'org.flywaydb:flyway-core'
// PostgreSQL support for that stream, which also reads the session-lock setting it passes. A
// service always had it through persistence-jpa; the stream now says so itself.
runtimeOnly 'org.flywaydb:flyway-database-postgresql'
implementation 'org.springframework:spring-jdbc'
implementation 'org.springframework:spring-tx'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// MessagingInboxSchemaStreamTest reads the PostgreSQL lock setting the stream hands Flyway.
testImplementation 'org.flywaydb:flyway-database-postgresql'
// The consume path a service runs (review 2026-11-03 RR-01-12): the permission guard every
// service takes from composition:service-runtime, the typed startup failure it raises, and the
// transaction port's fake. Test edges are outside the registry gate.
@@ -125,7 +125,7 @@ org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.eclipse.angus:angus-activation:2.0.3=integrationTestRuntimeClasspath
org.flywaydb:flyway-core:11.14.1=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.flywaydb:flyway-database-postgresql:11.14.1=integrationTestRuntimeClasspath
org.flywaydb:flyway-database-postgresql:11.14.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.glassfish.jaxb:jaxb-core:4.0.9=integrationTestRuntimeClasspath
org.glassfish.jaxb:jaxb-runtime:4.0.9=integrationTestRuntimeClasspath
org.glassfish.jaxb:txw2:4.0.9=integrationTestRuntimeClasspath
@@ -1,8 +1,10 @@
package dev.caskeleton.adapter.inbound.messaging;
import java.util.Map;
import java.util.Objects;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.configuration.FluentConfiguration;
import org.springframework.beans.factory.SmartInitializingSingleton;
/**
@@ -51,6 +53,11 @@ public final class MessagingInboxSchemaStream implements SmartInitializingSingle
*/
static final String LAST_INBOX_VERSION = "1199?";
/**
* Flyway's key for how it holds its PostgreSQL migration lock ({@code false}: for the session).
*/
private static final String TRANSACTIONAL_LOCK = "flyway.postgresql.transactional.lock";
private final DataSource dataSource;
/**
@@ -73,21 +80,33 @@ public final class MessagingInboxSchemaStream implements SmartInitializingSingle
* @return how many migrations were applied
*/
public int apply() {
Flyway flyway =
Flyway.configure()
.dataSource(dataSource)
.locations(LOCATION)
.table(HISTORY_TABLE)
.baselineVersion(BASELINE_VERSION)
.baselineDescription("messaging inbox range starts above the platform outbox range")
.target(LAST_INBOX_VERSION)
.outOfOrder(false)
.cleanDisabled(true)
.validateOnMigrate(true)
.load();
Flyway flyway = configuration().load();
if (flyway.info().applied().length == 0) {
flyway.baseline();
}
return flyway.migrate().migrationsExecuted;
}
/**
* The stream's Flyway settings.
*
* <p>Flyway's PostgreSQL migration lock is held for the session, as every other Flyway of the
* template holds it (persistence-jpa's {@code FlywaySchemaPolicy.configure()}): Flyway's default
* keeps a transaction open for the whole run, and a concurrent index build waits for it without
* end (re-review 2026-11-03 round 6, RR6-03-01). This leaf may not depend on persistence-jpa, so
* the setting is written here; {@code MessagingInboxSchemaStreamTest} holds it to the same value.
*/
FluentConfiguration configuration() {
return Flyway.configure()
.configuration(Map.of(TRANSACTIONAL_LOCK, "false"))
.dataSource(dataSource)
.locations(LOCATION)
.table(HISTORY_TABLE)
.baselineVersion(BASELINE_VERSION)
.baselineDescription("messaging inbox range starts above the platform outbox range")
.target(LAST_INBOX_VERSION)
.outOfOrder(false)
.cleanDisabled(true)
.validateOnMigrate(true);
}
}
@@ -0,0 +1,36 @@
package dev.caskeleton.adapter.inbound.messaging;
import static org.assertj.core.api.Assertions.assertThat;
import javax.sql.DataSource;
import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/**
* The inbox stream takes Flyway's PostgreSQL lock the way every other Flyway of the template does
* (re-review 2026-11-03 round 6, RR6-03-01).
*
* <p>Flyway's default holds that lock in a transaction it keeps open for the whole run, and a
* concurrent index build waits for every older transaction, Flyway's own included: the migration
* never ends. persistence-jpa's {@code FlywaySchemaPolicy.configure()} holds it for the session
* instead, and {@code FlywaySchemaPolicyTest} pins that value. This leaf may not depend on
* persistence-jpa ({@code modules.json}), so the stream keeps its own copy of the setting, and this
* test holds the copy to the same value.
*/
class MessagingInboxSchemaStreamTest {
@Test
void theInboxStreamHoldsFlywaysPostgreSqlLockForTheSessionLikeTheTemplatesOtherStreams() {
// given
MessagingInboxSchemaStream stream =
new MessagingInboxSchemaStream(Mockito.mock(DataSource.class));
// when
PostgreSQLConfigurationExtension postgresql =
stream.configuration().getConfigurationExtension(PostgreSQLConfigurationExtension.class);
// then
assertThat(postgresql.isTransactionalLock()).isFalse();
}
}
+1 -1
View File
@@ -240,7 +240,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
| `AccessDeniedException` | `SecurityErrorClassifier` 결정(예: `AUTHZ_INSUFFICIENT_PERMISSION`) | 분류기 결정 | 메서드-시큐리티 거부가 컨트롤러를 빠져나오면 여기 도달. 필터 계층 `EnvelopeAccessDeniedHandler` 와 **동일한 세분화 코드**를 내도록 무상태 classifier 에 위임 |
| `PreconditionFailedException` | `PRECONDITION_FAILED` | 412 | D15: `If-Match` 불일치 쓰기 = 낙관적 동시성 충돌 → 412 (raw 409/500 금지) |
| `PageValidationException` | `VALIDATION_FAILED` | 400 | D18/D20/D21: 계약 범위 밖 페이지/정렬/필터 파라미터. field + reasonCode 를 details 로 |
| `IdempotencyUnavailableException` | `IDEMPOTENCY_UNAVAILABLE` | 503 (retryable=true) | 조정 저장소가 응답하지 않아 action 전에 거부. carrier 분기 |
| `IdempotencyUnavailableException` | `IDEMPOTENCY_UNAVAILABLE` | 503 (retryable=true) | action 전에 거부 — 조정 저장소가 응답하지 않았거나, claim의 processing lease가 시작 전에 끝나 저장소가 시작을 거절했다(실행 안 됨, 저장소는 정상일 수 있다). 같은 키로 나중에 재전송하면 다음 요청이 그 claim을 넘겨받아 실행한다(`docs/web/http-contract.md` §2, 라운드6 RR6-02-04). carrier 분기 |
| `IdempotencyCompletionUnknownException` | `IDEMPOTENCY_COMPLETION_UNKNOWN` | 503 (retryable=true) | action 이 돈 뒤 결과 기록(complete) 중 저장소가 응답하지 않음. 결과 불명 — 같은 키로 재전송, 새 키 금지(`docs/web/http-contract.md` §2, 재리뷰 RR-02-03). carrier 분기 |
| `IdempotencyRecoveryRequiredException` | `IDEMPOTENCY_RECOVERY_REQUIRED` | 500 (retryable=false) | 이전 시도의 외부 효과 여부를 판단할 수 없음. carrier 분기 |
| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=true, `Retry-After: 2`) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 클라이언트 행동: 결과 불명. 같은 `Idempotency-Key`로 `Retry-After` 뒤 재전송. 새 키 금지(`docs/web/http-contract.md` §2). 진단정보(scope digest)는 클라이언트 미도달 |
@@ -84,17 +84,17 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
}
/**
* An {@link IllegalArgumentException} is read as "the request was wrong" and answered 400. One
* WARN line names the exception type, so a 400 that is really a misassembled server — code that
* should have thrown {@link IllegalStateException} — still leaves a trace. The message is not
* logged: it may echo request input.
* An {@link IllegalArgumentException} is read as "the request was wrong" and answered 400, with
* {@link ServerFailureLog#refusedArgument}'s WARN line — the exception type, never the message,
* which may echo request input. The GraphQL, gRPC and STOMP adapters write the same line.
*/
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Envelope<Void>> handleIllegalArgument(IllegalArgumentException ex) {
if (ex instanceof ApiErrorCarrier) {
return handleCarrier(ex);
}
log.warn("request refused as BAD_PARAMETER by {}", ex.getClass().getName());
ServerFailureLog line = ServerFailureLog.refusedArgument(ex);
log.warn(line.format(""), line.arguments());
return ErrorResponseFactory.envelope(OperationalError.BAD_PARAMETER, null);
}
@@ -85,6 +85,34 @@ class GlobalExceptionHandlerTest {
assertThat(response.getBody().error().message()).doesNotContain(secret);
}
@Test
void anIllegalArgumentIsLoggedAtWarnByItsTypeWithoutItsMessage() {
// given
ch.qos.logback.classic.Logger logger =
(ch.qos.logback.classic.Logger) LoggerFactory.getLogger(GlobalExceptionHandler.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
// when
try {
handler.handleIllegalArgument(new IllegalArgumentException("unknown recipient alice"));
} finally {
logger.detachAppender(appender);
appender.stop();
}
// then
assertThat(appender.list)
.singleElement()
.extracting(
event -> event.getLevel().toString(),
ILoggingEvent::getFormattedMessage,
ILoggingEvent::getThrowableProxy)
.containsExactly(
"WARN", "request refused as BAD_PARAMETER by java.lang.IllegalArgumentException", null);
}
@Test
void adapterDisabledMapsToAdapterDisabled500NotRetryable() {
// integration-adapter-templates Layer 3 / §Audit A2 — runtime fail-fast code,
+4 -2
View File
@@ -36,8 +36,10 @@
`WEBSOCKET_REQUEST_REJECTED`다.
- `@MessageMapping` 메서드의 실패는 inbound 채널 executor에서 끝나서 프레임이 나가지 않는다. 서버 로그는
`StompHandlerFailureLog`가 web·GraphQL·gRPC와 같은 줄로 남긴다(`ServerFailureLog`): persistence 실패는
분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. 그 밖의 예외는 예외와 함께 ERROR.
전에는 Spring이 예외 전체(persistence 실패의 SQL 원인 포함)를 ERROR로 남겼다.
분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. `IllegalArgumentException`은
`BAD_PARAMETER`로 보고 WARN 한 줄(`request refused as BAD_PARAMETER by <예외 타입>`)만 남긴다. 메시지는
입력값이 들 수 있어 남기지 않는다. 그 밖의 예외는 예외와 함께 ERROR. 전에는 Spring이 예외 전체
(persistence 실패의 SQL 원인 포함)를 ERROR로 남겼다.
- `LiveEventProjector<T>` bean이 정확히 하나 있는 `@DomainEvent` 타입만 broadcast한다. 도메인
객체를 그대로 직렬화하지 않고, projector가 만든 bounded `Map<String, String>`만 보낸다.
@@ -17,10 +17,12 @@ import org.springframework.web.bind.annotation.ControllerAdvice;
* exception and stops: a persistence failure's SQL cause — values, constraint names, credentials —
* went to the log, and a client-side refusal was logged as an error. With this advice a carrier
* gets {@link ServerFailureLog}'s line (a persistence failure its classification only, a
* client-side code nothing), and anything else is logged with its exception, as before. The request
* id is on MDC ({@link WebSocketCorrelationInterceptor}). The client is answered as before: a
* handler method that throws sends no frame. A feature's own {@code @MessageExceptionHandler} still
* takes precedence over this one.
* client-side code nothing); an {@link IllegalArgumentException} is the {@code BAD_PARAMETER} every
* transport makes of it and gets the WARN line naming its type, never its message, which may echo
* input (review 2026-11-05 RR6-01-06); anything else is logged with its exception, as before. The
* request id is on MDC ({@link WebSocketCorrelationInterceptor}). The client is answered as before:
* a handler method that throws sends no frame. A feature's own {@code @MessageExceptionHandler}
* still takes precedence over this one.
*/
@ControllerAdvice
class StompHandlerFailureLog {
@@ -34,6 +36,11 @@ class StompHandlerFailureLog {
.ifPresent(line -> log.error(line.format(""), line.arguments()));
return;
}
if (failure instanceof IllegalArgumentException refused) {
ServerFailureLog line = ServerFailureLog.refusedArgument(refused);
log.warn(line.format(""), line.arguments());
return;
}
log.error("unhandled failure in a STOMP message handler", failure);
}
}
@@ -78,6 +78,24 @@ class StompHandlerFailureLogTest {
assertThat(logged).isEmpty();
}
@Test
void anIllegalArgumentFromAMessageMappingIsLoggedAtWarnByItsTypeWithoutItsMessage() {
// when
List<ILoggingEvent> logged = loggedWhileHandling("/app/illegal-argument");
// then
assertThat(logged)
.singleElement()
.extracting(
ILoggingEvent::getLevel,
ILoggingEvent::getFormattedMessage,
ILoggingEvent::getThrowableProxy)
.containsExactly(
Level.WARN,
"request refused as BAD_PARAMETER by java.lang.IllegalArgumentException",
null);
}
@Test
void anUnrecognisedFailureFromAMessageMappingIsLoggedAtErrorWithTheFailure() {
// when
@@ -161,6 +179,11 @@ class StompHandlerFailureLogTest {
throw new CarrierException(OperationalError.BAD_PARAMETER, "bad input");
}
@MessageMapping("/illegal-argument")
void illegalArgument() {
throw new IllegalArgumentException("unknown recipient alice@example.com");
}
@MessageMapping("/unrecognised")
void unrecognised() {
throw new IllegalStateException("boom");
+12 -4
View File
@@ -277,14 +277,21 @@ revision) come from app-bootstrap `IdempotencySettings`. This leaf reads only `k
`renew` has its own program rather than the generic transition. Renewal keeps the record in
`EXECUTING`, and the transition answers "already in the target state" before it reads the revision
(that answer exists for a retry whose first reply was lost), so a renewal sent through it was always
`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. The renew program checks owner,
`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. For a start that answer is given only to
the handle the start was applied from — the record one revision past it — because the executor runs
the action on it: another handle of the same attempt (one from before a takeover, or the current one
a replayed claim returned) used to be told the start was applied and ran the action a second time;
it is now `NOT_OWNER` or `NOT_CLAIMED`, as in the PostgreSQL store (round6 RR6-02-01). The renew program checks owner,
operation, revision and state, then extends `leaseUntil` from Redis `TIME` and bumps the revision.
A lost renewal reply is recognised by what the renewal recorded — the revision it started from and
the lease it asked for: the same lease is `ALREADY_RENEWED_SAME_OPERATION` with the current handle,
a different lease is `OPERATION_CONFLICT`.
A lease that runs out is taken over only from a claim that never started or an attempt marked
retryable. A record still `EXECUTING` when its lease ran out has an unknown effect: the claim
retryable — by whoever claims next, the holder's own attempt included: the claim program checks for
a takeover before it replays a same-owner claim, so an attempt whose start was refused takes its
claim over when it claims again instead of being replayed the claim and refused until the record
expired (round6 RR6-02-01). A record still `EXECUTING` when its lease ran out has an unknown effect: the claim
program answers `RECOVERY_REQUIRED` and leaves the record as it is, because the holder may still be
running. The holder's late completion or failure goes through the transition program as it would
have inside the lease, and the next claim replays or retries it; only the lease is final — `RENEW`
@@ -355,8 +362,9 @@ Useful focused checks:
```
`redisContainerContractTest` runs the cache-region, lease and idempotency-store port contracts (the
ones the in-memory fakes pass; the idempotency contract's timed cases run only here, on the server's
own clock) and the live semantic-port tests against a Redis it starts itself, under the standalone
ones the in-memory fakes pass; the idempotency contract's timed cases run here on the server's own
clock, and in `test` over the command fake's clock, which proves the fixture's copies of the
programs rather than the programs) and the live semantic-port tests against a Redis it starts itself, under the standalone
topology's ACL file. It is in `integrationCheck` (integration-main.yml's `integration-check` job), and
only there: listing it in `mainCheck` as well ran it twice on every push to main. The image is
`config/testing/container-images.properties` `redis`.
@@ -32,15 +32,17 @@ public final class IdempotencyScripts {
* would return somebody else's response.
*
* <p>A lease that ran out is taken over only when nothing can have happened under it: a claim
* that never started, or an attempt its holder marked retryable. A record that was {@code
* EXECUTING} has an unknown effect, so it is answered {@code RECOVERY_REQUIRED} — running it
* again is the duplicate this store exists to prevent, and it is what a client resending after a
* result-unknown 503 was promised would not happen (re-review 2026-11-04 RR-01-11). The answer
* changes nothing: the holder may still be running, and its late completion or failure is
* recorded by {@link #TRANSITION} as it would have been inside the lease, after which this
* program replays or retries it (owner decision 2026-11-04 — the record used to be abandoned
* here, so a holder that outlived its lease lost its result). The PostgreSQL store answers the
* same; {@code IdempotencyStoreContract} holds both to it.
* that never started, or an attempt its holder marked retryable. Whoever claims next takes it
* over, the holder's own attempt included — that attempt retrying after its start was refused
* used to be replayed the claim it held, refused again, until the record expired (round6
* RR6-02-01). A record that was {@code EXECUTING} has an unknown effect, so it is answered {@code
* RECOVERY_REQUIRED} — running it again is the duplicate this store exists to prevent, and it is
* what a client resending after a result-unknown 503 was promised would not happen (re-review
* 2026-11-04 RR-01-11). The answer changes nothing: the holder may still be running, and its late
* completion or failure is recorded by {@link #TRANSITION} as it would have been inside the
* lease, after which this program replays or retries it (owner decision 2026-11-04 — the record
* used to be abandoned here, so a holder that outlived its lease lost its result). The PostgreSQL
* store answers the same; {@code IdempotencyStoreContract} holds both to it.
*
* <p>The key lives for the lease plus the replay TTL ({@code afterLease}), not for the replay TTL
* alone. With the replay TTL alone, a replay TTL shorter than the lease dropped the key while the
@@ -79,6 +81,21 @@ public final class IdempotencyScripts {
if state == 'ABANDONED' then
return {'RECOVERY_REQUIRED', attempt, rev, owner, '', ''}
end
local leaseUntil = tonumber(redis.call('HGET', KEYS[1], 'leaseUntil'))
local leaseOver = leaseUntil ~= nil and leaseUntil <= nowMillis
if state == 'FAILED_RETRYABLE' or (state == 'CLAIMED' and leaseOver) then
-- Nothing ran under the previous holder: they never started, or they marked the attempt
-- retryable. Taking over bumps the attempt so the new holder can tell it is not the first.
-- This comes before the same-owner replay below: the previous holder may be this very
-- attempt, retrying after a refused start or a retryable failure, and replaying it the
-- record it holds would hand back a claim that cannot start (round6 RR6-02-01).
redis.call('HSET', KEYS[1],
'state', 'CLAIMED', 'owner', ARGV[1], 'attempt', attempt + 1, 'rev', rev + 1,
'op', ARGV[2], 'leaseUntil', nowMillis + leaseMillis, 'afterLease', afterLease)
redis.call('PEXPIRE', KEYS[1], leaseMillis + afterLease)
return {'TAKEN_OVER', attempt + 1, rev + 1, ARGV[1], '',
tostring(nowMillis + leaseMillis)}
end
if owner == ARGV[1] then
if op ~= ARGV[2] then
return {'OWNER_OPERATION_CONFLICT', attempt, rev, owner, '', ''}
@@ -87,24 +104,12 @@ public final class IdempotencyScripts {
return {'REPLAYED_ACQUIRE', attempt, rev, owner, '',
redis.call('HGET', KEYS[1], 'leaseUntil')}
end
local leaseUntil = tonumber(redis.call('HGET', KEYS[1], 'leaseUntil'))
local leaseOver = leaseUntil ~= nil and leaseUntil <= nowMillis
if state == 'EXECUTING' and leaseOver then
-- The holder started and its lease ran out: whether the work took effect is unknown, so it
-- is never run again. The record is left as it is — owner, revision, key TTL — because the
-- holder may still finish and record its result.
return {'RECOVERY_REQUIRED', attempt, rev, owner, '', ''}
end
if state == 'FAILED_RETRYABLE' or (state == 'CLAIMED' and leaseOver) then
-- Nothing ran under the previous holder: they never started, or they marked the attempt
-- retryable. Taking over bumps the attempt so the new holder can tell it is not the first.
redis.call('HSET', KEYS[1],
'state', 'CLAIMED', 'owner', ARGV[1], 'attempt', attempt + 1, 'rev', rev + 1,
'op', ARGV[2], 'leaseUntil', nowMillis + leaseMillis, 'afterLease', afterLease)
redis.call('PEXPIRE', KEYS[1], leaseMillis + afterLease)
return {'TAKEN_OVER', attempt + 1, rev + 1, ARGV[1], '',
tostring(nowMillis + leaseMillis)}
end
return {'IN_PROGRESS', attempt, rev, owner, '', tostring(leaseUntil - nowMillis)}
""";
@@ -137,12 +142,24 @@ public final class IdempotencyScripts {
end
if state == ARGV[5] then
-- Already in the target state, under the same owner and the same operation: a retry whose
-- first reply was lost, not a second transition. This is checked BEFORE the revision,
-- deliberately. The caller's handle necessarily carries the pre-transition revision — they
-- never received the reply that would have replaced it — so a revision check first would
-- turn every lost reply into NOT_OWNER and make the idempotent call non-idempotent. The
-- owner and operation already prove the record was moved by this caller and nobody else.
return {'ALREADY', attempt, rev, owner, redis.call('HGET', KEYS[1], 'resp') or '', ''}
-- first reply was lost, not a second transition. This is checked BEFORE the revision check
-- below, deliberately. The caller's handle necessarily carries the pre-transition revision
-- — they never received the reply that would have replaced it — so that check first would
-- turn every lost reply into NOT_OWNER and make the idempotent call non-idempotent.
--
-- A start is the one transition whose ALREADY runs the action, so for a start the owner and
-- operation are not proof enough: the same attempt also holds a handle from before a
-- takeover, and the current handle a replayed claim returned after the start. Either one
-- presenting a start the record already shows was answered ALREADY, and the executor ran the
-- action a second time (round6 RR6-02-01). A start is confirmed only to the handle it was
-- applied from — the record one revision past it — and any other falls through to the
-- revision check: NOT_OWNER for a stale handle, WRONG_STATE for the current one. The
-- PostgreSQL store answers the same: its start replay digest covers the handle's attempt
-- and revision. A completion or failure already applied is still reported back to any
-- handle of its operation: nothing runs on that answer.
if ARGV[4] ~= 'CLAIMED' or rev == tonumber(ARGV[2]) + 1 then
return {'ALREADY', attempt, rev, owner, redis.call('HGET', KEYS[1], 'resp') or '', ''}
end
end
if rev ~= tonumber(ARGV[2]) then
-- Stale handle: somebody moved the record on after this owner read it, and the target
@@ -40,11 +40,13 @@ import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
/**
* The state machine that keeps a retried request from happening twice.
* What the Redis store does beyond the port's contract: how it reports the replies it gets, and how
* it fails.
*
* <p>Every assertion below is about a way a duplicate side effect could get through: a second
* worker taking a live claim, a stale handle completing over a new owner's work, a lost reply being
* treated as a fresh attempt, or an ambiguous failure being reported as a clean one.
* <p>The state machine itself — claims, takeovers, stale handles, late results, leases and record
* lifetimes — is {@code IdempotencyStoreContract}, which {@link RedisIdempotencyStoreContractTest}
* runs over the same command fake with its clock and {@code LiveRedisIdempotencyStoreContractTest}
* over a real server. Cases that only repeated it by hand are gone from here (round6 RR6-02-02).
*/
class RedisIdempotencyStoreAdapterTest {
@@ -55,9 +57,6 @@ class RedisIdempotencyStoreAdapterTest {
private static final RequestFingerprint FINGERPRINT = new RequestFingerprint("b".repeat(64));
private static final RequestFingerprint OTHER_FINGERPRINT =
new RequestFingerprint("c".repeat(64));
private static final OperationId OPERATION = new OperationId("operation-aaaaaaaaaa");
private static final OperationId OTHER_OPERATION = new OperationId("operation-bbbbbbbbbb");
@@ -98,13 +97,8 @@ class RedisIdempotencyStoreAdapterTest {
}
private IdempotencyClaimRequest claim(IdempotencyClaimAttempt attempt) {
return claim(attempt, FINGERPRINT);
}
private IdempotencyClaimRequest claim(
IdempotencyClaimAttempt attempt, RequestFingerprint fingerprint) {
return new IdempotencyClaimRequest(
SCOPE, fingerprint, attempt, Duration.ofSeconds(30), Duration.ofHours(24), "json-v2", 1);
SCOPE, FINGERPRINT, attempt, Duration.ofSeconds(30), Duration.ofHours(24), "json-v2", 1);
}
@Test
@@ -120,174 +114,40 @@ class RedisIdempotencyStoreAdapterTest {
}
@Test
@DisplayName("the same attempt re-claiming replays rather than acquiring twice")
void theSameAttemptReplays() {
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
store.claim(claim(attempt));
// A retry whose first reply was lost. Treating it as a fresh claim would let the same worker
// start the operation twice believing it had exclusive hold both times.
assertThat(store.claim(claim(attempt)))
.isInstanceOf(IdempotencyClaimOutcome.ReplayedAcquire.class);
}
@Test
@DisplayName("a different request under the same scope is a fingerprint mismatch, never a replay")
void aDifferentRequestIsAMismatch() {
store.claim(claim(store.newClaimAttempt(OPERATION)));
// Returning the first request's response here would hand one caller another caller's result.
assertThat(store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), OTHER_FINGERPRINT)))
.isInstanceOf(IdempotencyClaimOutcome.FingerprintMismatch.class);
}
@Test
@DisplayName("the full happy path claims, starts, completes, and then replays the result")
void theHappyPathCompletesAndReplays() {
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
IdempotencyOwner owner =
((IdempotencyClaimOutcome.Acquired) store.claim(claim(attempt))).owner();
var started = store.markExecutionStarted(owner, OPERATION);
assertThat(started.outcome()).isEqualTo(IdempotencyStartOutcome.STARTED);
IdempotencyOwner executing = started.owner().orElseThrow();
assertThat(executing.stateRevision()).isGreaterThan(owner.stateRevision());
assertThat(
store.complete(
executing, new StoredResponse("{\"ok\":true}"), Duration.ofHours(1), OPERATION))
.isEqualTo(IdempotencyCompleteOutcome.COMPLETED);
void aCompletedReplayIsReplayableForTheReplayTtlTheRecordHasLeft() {
// given
// The deadline is read off the key's TTL. The command fake used to report a fixed minute
// whatever the completion set, so no test saw the deadline the program reports.
IdempotencyOwner executing = executing();
store.complete(executing, new StoredResponse("{}"), Duration.ofHours(1), OPERATION);
gateway.advance(Duration.ofMinutes(10));
// when
IdempotencyClaimOutcome replay = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
assertThat(replay).isInstanceOf(IdempotencyClaimOutcome.CompletedReplay.class);
assertThat(((IdempotencyClaimOutcome.CompletedReplay) replay).response().payload())
.isEqualTo("{\"ok\":true}");
// then
assertThat(replay)
.isInstanceOfSatisfying(
IdempotencyClaimOutcome.CompletedReplay.class,
completed ->
assertThat(completed.replayUntil()).isEqualTo(T0.plus(Duration.ofMinutes(50))));
}
@Test
@DisplayName("a stale owner handle cannot complete over a newer revision")
void aStaleHandleCannotComplete() {
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
IdempotencyOwner stale =
((IdempotencyClaimOutcome.Acquired) store.claim(claim(attempt))).owner();
store.markExecutionStarted(stale, OPERATION);
// `stale` still carries the revision from before markExecutionStarted. Accepting it would mean
// a handle read at any past point could write over everything that happened since.
assertThat(store.complete(stale, new StoredResponse("{}"), Duration.ofHours(1), OPERATION))
.isEqualTo(IdempotencyCompleteOutcome.NOT_OWNER);
}
@Test
@DisplayName("completing twice with the same result is idempotent, with a different one is not")
void completingTwiceIsIdempotentOnlyForTheSameResult() {
IdempotencyOwner executing = executing();
store.complete(executing, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION);
assertThat(
store.complete(
executing, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION))
.isEqualTo(IdempotencyCompleteOutcome.ALREADY_COMPLETED_SAME_RESULT);
assertThat(
store.complete(
executing, new StoredResponse("{\"v\":2}"), Duration.ofHours(1), OPERATION))
.isEqualTo(IdempotencyCompleteOutcome.RESPONSE_CONFLICT);
}
@Test
@DisplayName("a retryable failure releases the operation for another attempt")
void aRetryableFailureAllowsAnotherAttempt() {
IdempotencyOwner executing = executing();
assertThat(
store.markFailed(
executing,
IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE,
Duration.ofHours(1),
OPERATION))
.isEqualTo(IdempotencyFailOutcome.MARKED_RETRYABLE);
IdempotencyClaimOutcome next = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
assertThat(next).isInstanceOf(IdempotencyClaimOutcome.TakenOverClaimed.class);
assertThat(((IdempotencyClaimOutcome.TakenOverClaimed) next).owner().attempt())
.as("the new holder can tell it is not the first attempt")
.isEqualTo(2);
}
@Test
@DisplayName("an abandoned operation is not retried, it requires recovery")
void anAbandonedOperationRequiresRecovery() {
IdempotencyOwner executing = executing();
assertThat(
store.markFailed(
executing,
IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED,
Duration.ofHours(1),
OPERATION))
.isEqualTo(IdempotencyFailOutcome.MARKED_ABANDONED);
// The effect may have happened. Handing the operation to another worker is precisely how it
// happens twice, so the next claim is told a human decision is needed.
assertThat(store.claim(claim(store.newClaimAttempt(OTHER_OPERATION))))
.isInstanceOf(IdempotencyClaimOutcome.RecoveryRequired.class);
}
@Test
@DisplayName("releasing before execution frees the scope")
void releasingBeforeExecutionFreesTheScope() {
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
void releasingBeforeExecutionDeletesTheRecordSoTheNextClaimAcquiresAfresh() {
// given
IdempotencyOwner owner =
((IdempotencyClaimOutcome.Acquired) store.claim(claim(attempt))).owner();
assertThat(store.releaseBeforeExecution(owner, OPERATION))
.isEqualTo(IdempotencyReleaseOutcome.RELEASED_BEFORE_EXECUTION);
assertThat(store.claim(claim(store.newClaimAttempt(OTHER_OPERATION))))
.isInstanceOf(IdempotencyClaimOutcome.Acquired.class);
}
@Test
@DisplayName("releasing after execution started is refused")
void releasingAfterStartIsRefused() {
IdempotencyOwner executing = executing();
// The work may already have had an effect; discarding the record would erase the only evidence
// that anybody had ever claimed it.
assertThat(store.releaseBeforeExecution(executing, OPERATION))
.isEqualTo(IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED);
}
@Test
@DisplayName("renew는 RENEWED와 함께 더 새 revision의 owner 핸들을 돌려준다")
void renewReturnsAHandleAtTheNewRevision() {
// given
IdempotencyOwner executing = executing();
((IdempotencyClaimOutcome.Acquired) store.claim(claim(store.newClaimAttempt(OPERATION))))
.owner();
store.releaseBeforeExecution(owner, OPERATION);
// when
var renewed = store.renew(executing, Duration.ofSeconds(30), OPERATION);
IdempotencyClaimOutcome next = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
// then
assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.RENEWED);
assertThat(renewed.owner().orElseThrow().stateRevision())
.isGreaterThan(executing.stateRevision());
}
@Test
@DisplayName("renew한 처리 lease는 원래 lease가 지난 뒤에도 다른 요청의 claim을 IN_PROGRESS로 막는다")
void aRenewedLeaseStillExcludesAnotherClaimPastTheOriginalExpiry() {
// given
IdempotencyOwner executing = executing();
gateway.advance(Duration.ofSeconds(20));
store.renew(executing, Duration.ofSeconds(30), OPERATION);
// 40 seconds after the claim: past the original 30-second lease, inside the renewed one.
gateway.advance(Duration.ofSeconds(20));
// when
IdempotencyClaimOutcome other = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
// then
// TAKEN_OVER here would hand a running operation to a second worker: the effect happens twice.
assertThat(other).isInstanceOf(IdempotencyClaimOutcome.InProgress.class);
// The contract lets a store keep the released record and count the next claim as a further
// attempt; this one deletes the key, so the next claim is a first claim.
assertThat(next).isInstanceOf(IdempotencyClaimOutcome.Acquired.class);
}
@Test
@@ -322,21 +182,6 @@ class RedisIdempotencyStoreAdapterTest {
assertThat(retried.outcome()).isEqualTo(IdempotencyRenewOutcome.OPERATION_CONFLICT);
}
@Test
@DisplayName("renew한 뒤 받은 핸들로 complete할 수 있다")
void theRenewedHandleCanComplete() {
// given
IdempotencyOwner renewed =
store.renew(executing(), Duration.ofSeconds(30), OPERATION).owner().orElseThrow();
// when
IdempotencyCompleteOutcome outcome =
store.complete(renewed, new StoredResponse("{}"), Duration.ofHours(1), OPERATION);
// then
assertThat(outcome).isEqualTo(IdempotencyCompleteOutcome.COMPLETED);
}
@Test
@DisplayName("실행을 시작하지 않은 claim은 renew할 수 없다")
void renewBeforeExecutionStartedIsNotInProgress() {
@@ -352,179 +197,6 @@ class RedisIdempotencyStoreAdapterTest {
assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.NOT_IN_PROGRESS);
}
@Test
@DisplayName("lease가 지나 다른 요청이 회복 필요로 판정한 실행은 주인이 renew로 lease를 되살릴 수 없다")
void anOwnerWhoseExecutionWasFoundExpiredCannotRenewItsLease() {
// given
IdempotencyOwner executing = executing();
gateway.advance(Duration.ofSeconds(60));
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
// when
var renewed = store.renew(executing, Duration.ofSeconds(30), OPERATION);
// then
// The holder still owns the record — it still completes it — so not NOT_OWNER (RR5-01-02).
assertThat(renewed.outcome()).isEqualTo(IdempotencyRenewOutcome.LEASE_EXPIRED);
}
@Test
@DisplayName("lease가 지난 실행 전 claim은 주인도 시작할 수 없다")
void aClaimWhoseLeaseRanOutBeforeItStartedIsNotStarted() {
// given
// The live contract proves the program; this proves the fixture's copy of TRANSITION refuses
// the late start as the program does (re-review 2026-11-04 README 15).
IdempotencyOwner claimed =
((IdempotencyClaimOutcome.Acquired) store.claim(claim(store.newClaimAttempt(OPERATION))))
.owner();
gateway.advance(Duration.ofSeconds(60));
// when
var started = store.markExecutionStarted(claimed, OPERATION);
// then
assertThat(started.outcome()).isEqualTo(IdempotencyStartOutcome.LEASE_EXPIRED);
}
@Test
@DisplayName("lease가 지나 시작을 거절당한 claim은 다음 claim이 attempt 2로 넘겨받는다")
void aClaimWhoseLateStartWasRefusedIsTakenOver() {
// given
IdempotencyOwner claimed =
((IdempotencyClaimOutcome.Acquired) store.claim(claim(store.newClaimAttempt(OPERATION))))
.owner();
gateway.advance(Duration.ofSeconds(60));
store.markExecutionStarted(claimed, OPERATION);
// when
IdempotencyClaimOutcome next = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
// then
assertThat(next)
.isInstanceOfSatisfying(
IdempotencyClaimOutcome.TakenOverClaimed.class,
takenOver -> assertThat(takenOver.owner().attempt()).isEqualTo(2));
}
@Test
@DisplayName("lease가 지난 실행의 주인이 늦게 보고한 재시도 가능 실패 뒤에는 다음 claim이 넘겨받는다")
void aLateRetryableFailureOfAnExpiredExecutionLetsTheNextClaimTakeOver() {
// given
// The late markFailed through the fixture's copy of TRANSITION, which no test reached
// (re-review 2026-11-04 RR5-01-04).
IdempotencyOwner late = executing();
gateway.advance(Duration.ofSeconds(60));
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
store.markFailed(
late, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), OPERATION);
// when
IdempotencyClaimOutcome next = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
// then
assertThat(next).isInstanceOf(IdempotencyClaimOutcome.TakenOverClaimed.class);
}
@Test
@DisplayName("lease가 지난 실행의 주인이 늦게 보고한 효과 불명 실패 뒤에도 다음 claim은 회복 필요를 받는다")
void aLateUnknownEffectOfAnExpiredExecutionKeepsTheNextClaimInRecovery() {
// given
IdempotencyOwner late = executing();
gateway.advance(Duration.ofSeconds(60));
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
store.markFailed(
late,
IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED,
Duration.ofHours(1),
OPERATION);
// when
IdempotencyClaimOutcome next = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
// then
assertThat(next).isInstanceOf(IdempotencyClaimOutcome.RecoveryRequired.class);
}
@Test
@DisplayName("lease가 지난 실행 중 기록은 넘겨주지 않고 회복 필요로 답한다")
void anExpiredExecutionIsAnsweredRecoveryRequiredNotTakenOver() {
// given
IdempotencyOwner executing = executing();
gateway.advance(Duration.ofSeconds(60));
// when
IdempotencyClaimOutcome next = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
// then
// TAKEN_OVER would run work whose effect is unknown a second time. The live contract proves
// the program; this proves the fixture's copy of it agrees.
assertThat(next)
.isInstanceOfSatisfying(
IdempotencyClaimOutcome.RecoveryRequired.class,
recovery -> assertThat(recovery.currentAttempt()).isEqualTo(executing.attempt()));
}
@Test
@DisplayName("lease가 지난 실행을 주인이 늦게 complete하면 기록되고 다음 claim은 그 결과를 재생한다")
void aLateCompletionOfAnExpiredExecutionIsRecordedAndReplayed() {
// given
// The live contract proves the programs; this proves the fixture's copy of CLAIM leaves the
// record to its holder as the program does (owner decision 2026-11-04).
IdempotencyOwner late = executing();
gateway.advance(Duration.ofSeconds(60));
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
store.complete(late, new StoredResponse("{\"late\":true}"), Duration.ofHours(1), OPERATION);
// when
IdempotencyClaimOutcome next = store.claim(claim(store.newClaimAttempt(OTHER_OPERATION)));
// then
assertThat(next)
.isInstanceOfSatisfying(
IdempotencyClaimOutcome.CompletedReplay.class,
replay -> assertThat(replay.response().payload()).isEqualTo("{\"late\":true}"));
}
@Test
@DisplayName("lease가 지난 남의 실행을 inspect하면 회복 필요(ABANDONED)로 보고한다")
void inspectingAnotherHoldersExpiredExecutionReportsAbandoned() {
// given
executing();
gateway.advance(Duration.ofSeconds(60));
// when
var inspection =
store.inspect(
new IdempotencyInspectionRequest(
SCOPE, FINGERPRINT, store.newClaimAttempt(OTHER_OPERATION)));
// then
assertThat(inspection.outcome()).isEqualTo(IdempotencyInspectionOutcome.ABANDONED);
}
@Test
@DisplayName("an expired claim that never started can be taken over, and the attempt increments")
void anExpiredLeaseIsTakenOver() {
store.claim(claim(store.newClaimAttempt(OPERATION)));
// The first holder went away. Advancing the Redis fixture clock, not the caller JVM clock,
// expires the distributed processing lease.
gateway.advance(Duration.ofSeconds(60));
RedisIdempotencyStoreAdapter later = store(T0, StubRedisRuntimeClient.serving(gateway));
IdempotencyClaimOutcome outcome =
later.claim(
new IdempotencyClaimRequest(
SCOPE,
FINGERPRINT,
later.newClaimAttempt(OTHER_OPERATION),
Duration.ofSeconds(30),
Duration.ofHours(24),
"json-v2",
1));
assertThat(outcome).isInstanceOf(IdempotencyClaimOutcome.TakenOverClaimed.class);
}
@Test
@DisplayName("inspecting after a lost reply tells the owner what actually happened")
void inspectionRecoversALostReply() {
@@ -13,18 +13,29 @@ import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
/** The Redis idempotency store keeps the port's contract, over the runtime's command fake. */
/**
* The Redis idempotency store keeps the port's contract, over the runtime's command fake.
*
* <p>The fake's clock is the server clock the programs read, and its keys expire on it, so the
* timed cases run here too: they check the fixture's copies of the programs, which the adapter's
* other tests drive (round6 RR6-02-02 — they used to be skipped, and the adapter test copied some
* of them by hand). The programs themselves are proven on a real server by {@code
* LiveRedisIdempotencyStoreContractTest}.
*/
class RedisIdempotencyStoreContractTest extends IdempotencyStoreContract {
private InMemorySemanticRedisCommands commands;
@Override
protected IdempotencyStorePort store() {
commands = new InMemorySemanticRedisCommands();
Map<RedisLane, Integer> limits = new LinkedHashMap<>();
for (RedisConnectionKind kind : RedisConnectionKind.values()) {
limits.put(kind, 4);
}
return new RedisIdempotencyStoreAdapter(
new RedisRuntimeOwner(
StubRedisRuntimeClient.serving(new InMemorySemanticRedisCommands()),
StubRedisRuntimeClient.serving(commands),
limits,
Duration.ofSeconds(1),
Duration.ofSeconds(1)),
@@ -34,4 +45,9 @@ class RedisIdempotencyStoreContractTest extends IdempotencyStoreContract {
Clock.systemUTC(),
Duration.ofSeconds(2));
}
@Override
protected void elapse(Duration duration) {
commands.advance(duration);
}
}
@@ -97,6 +97,11 @@ not grow by wiring accident.
(`docs/jpa/migration-guide.md` "Bound the lock wait"). `MigrationLockWaitTest` refuses one
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`.
- Flyway holds its PostgreSQL migration lock for the session, never in an open transaction, or a
`CREATE INDEX CONCURRENTLY` migration waits for Flyway forever: `spring.flyway.postgresql.transactional-lock:
false` in the module defaults, and every Flyway built in code starts from
`FlywaySchemaPolicy.configure()` (`JpaProductionArchitectureTest` refuses `Flyway.configure()`;
`docs/jpa/migration-guide.md` "Who may change the schema").
- 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.
+16 -5
View File
@@ -401,6 +401,14 @@ machine-readable SSOT다(개수는 registry가 소유한다). `selected` base ca
`postgresqlMigrationLockWaitIntegrationTest` lane이 실제 PostgreSQL에서 상한 안에 실패하는지 본다
(`docs/jpa/migration-guide.md` "Bound the lock wait").
Flyway의 PostgreSQL 마이그레이션 잠금은 트랜잭션이 아니라 세션에 둔다. Flyway 기본값은 실행 내내 트랜잭션을
열어 두고, `CREATE INDEX CONCURRENTLY`·`REINDEX … CONCURRENTLY`는 그 트랜잭션이 끝나기를 기다려 배포가
끝나지 않는다(재리뷰 round6 RR6-03-01). Spring Boot의 Flyway는 `config/module-defaults/persistence-jpa.yml`의
`spring.flyway.postgresql.transactional-lock: false`로, 템플릿이 직접 만드는 Flyway는
`FlywaySchemaPolicy.configure()`로 받는다. 운영 코드가 `Flyway.configure()`를 직접 부르면
`JpaProductionArchitectureTest`가 거부한다. 배포 마이그레이션 도구에도 같은 값을 넣는다
(`docs/jpa/migration-guide.md` "Who may change the schema", lane `postgresqlConcurrentIndexMigrationIntegrationTest`).
적용된 versioned migration은 수정하지 않는다. Flyway가 기동할 때마다 checksum을 검사하므로
바꾼 파일은 이미 그것을 적용한 모든 DB의 기동을 막는다. 변경은 새 버전으로 추가하고,
`src/test/resources/db/applied-migrations.sha256`에 한 줄을 더한다
@@ -421,15 +429,18 @@ machine-readable SSOT다(개수는 registry가 소유한다). `selected` base ca
`PostgreSqlIdempotencyStore`는 row lock을 얻은 뒤 `clock_timestamp()`를 평가한다.
claim takeover와 start/renew/complete/fail/release는 scope/state/owner/attempt/claim operation/
state revision을 SQL predicate로 다시 검증한다. expired `CLAIMED`만 takeover하며 expired
`EXECUTING`은 행을 바꾸지 않고 reconciliation(`RecoveryRequired`)을 요구한다(2026-11-04 소유자 결정 —
이 문단은 그 전의 `ABANDONED`로 닫던 동작을 적고 있었다). raw client key는 저장하지 않고
versioned HMAC scope digest만 쓴다.
state revision을 SQL predicate로 다시 검증한다. expired `CLAIMED`(와 `FAILED_RETRYABLE`)만 takeover하며
expired `EXECUTING`은 행을 바꾸지 않고 reconciliation(`RecoveryRequired`)을 요구한다(2026-11-04 소유자 결정 —
이 문단은 그 전의 `ABANDONED`로 닫던 동작을 적고 있었다). takeover는 같은 attempt의 재생보다 먼저 본다.
시작을 거절당했거나 재시도 가능 실패로 끝난 attempt가 같은 attempt로 다시 claim해도 넘겨받는다(라운드6
RR6-02-01). raw client key는 저장하지 않고 versioned HMAC scope digest만 쓴다.
Redis store·in-memory fake와 같은 계약(`IdempotencyStoreContract`)을 실 PostgreSQL에서 통과한다
(`PostgreSqlIdempotencyStoreContractTest`, `jpaPlatformContractTest`). 그 계약에 맞춰 두 가지를
정했다(review 2026-11-01 01-05). 이전 revision의 핸들은 owner 튜플이 다르므로 `NOT_OWNER`다
(`OPERATION_CONFLICT`는 같은 operation id가 다른 인자로 이미 적용된 경우만). renew는 `EXECUTING`의
(`OPERATION_CONFLICT`는 같은 operation id가 다른 인자로 이미 적용된 경우만). 시작은 핸들 말고 인자가 없어서,
이미 기록된 시작과 digest가 다르면 다른 핸들이다 — 넘겨받기 전 핸들은 `NOT_OWNER`, 재생받은 현재 핸들은
`NOT_CLAIMED`(라운드6 RR6-02-01, 전에는 `OPERATION_CONFLICT`). renew는 `EXECUTING`의
lease만 늘리고, 시작 전 `CLAIMED`는 `NOT_IN_PROGRESS`다.
### outbox V2 (삭제됨)
@@ -99,6 +99,9 @@ dependencies {
testImplementation 'com.querydsl:querydsl-jpa:5.1.0:jakarta'
testImplementation 'org.hibernate.orm:hibernate-envers'
testImplementation libs.archunit.junit5
// FlywaySchemaPolicyTest reads the PostgreSQL lock setting FlywaySchemaPolicy hands Flyway. Test
// scope only: production code outside .postgresql stays free of flyway-database-postgresql types.
testImplementation 'org.flywaydb:flyway-database-postgresql'
// Application-owned provider-neutral contract kit. The adapter supplies real PostgreSQL
// implementations; the fixture supplies only the port semantics every implementation must obey.
@@ -177,6 +180,7 @@ def readinessLanes = [
'runtimeRoleCannotCreateInApplicationSchemaOrTempAndUsesTrustedSearchPath'],
postgresqlMigrationIntegrationTest : ['PostgreSqlMigrationIntegrationTest'],
postgresqlMigrationLockWaitIntegrationTest : ['PostgreSqlMigrationLockWaitIntegrationTest'],
postgresqlConcurrentIndexMigrationIntegrationTest : ['PostgreSqlConcurrentIndexMigrationIntegrationTest'],
postgresqlIntLockMigrationCompatibilityIntegrationTest : ['PostgreSqlIntLockMigrationCompatibilityIntegrationTest'],
postgresqlTransactionIntegrationTest : ['PostgreSqlTransactionIntegrationTest'],
postgresqlDistributedLockIntegrationTest : ['PostgreSqlDistributedLockIntegrationTest'],
@@ -113,7 +113,7 @@ org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.eclipse.angus:angus-activation:2.0.3=jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath
org.flywaydb:flyway-core:11.14.1=compileClasspath,jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath
org.flywaydb:flyway-database-postgresql:11.14.1=jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath
org.flywaydb:flyway-database-postgresql:11.14.1=jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath
org.glassfish.jaxb:jaxb-core:4.0.9=jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath
org.glassfish.jaxb:jaxb-runtime:4.0.9=jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath
org.glassfish.jaxb:txw2:4.0.9=jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.experimental.schema;
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
import dev.caskeleton.application.tenant.TenantId;
import java.util.LinkedHashMap;
import java.util.List;
@@ -48,7 +49,7 @@ public final class SchemaTenantMigrationOrchestrator {
public MigrateResult migrate(TenantId tenant) {
String schema = registry.requireSchema(tenant);
Flyway flyway =
Flyway.configure()
FlywaySchemaPolicy.configure()
.dataSource(dataSource)
.schemas(schema)
.defaultSchema(schema)
@@ -1,9 +1,9 @@
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
import dev.caskeleton.adapter.outbound.support.CapabilitySelectors;
import java.util.Objects;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -82,7 +82,7 @@ public final class IdempotencySchemaStream implements SmartInitializingSingleton
}
private void migrate(String location, String historyTable) {
Flyway.configure()
FlywaySchemaPolicy.configure()
.dataSource(dataSource)
.locations(location)
.table(historyTable)
@@ -138,18 +138,26 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort {
return new IdempotencyClaimOutcome.CompletedReplay(
new StoredResponse(row.responsePayload()), row.replayUntil());
}
if (sameClaimAttempt(row, request.claimAttempt())) {
return new IdempotencyClaimOutcome.ReplayedAcquire(owner(row), row.processingLeaseUntil());
}
if (row.ownerToken().equals(request.claimAttempt().ownerToken())) {
return new IdempotencyClaimOutcome.OwnerOperationConflict();
if (row.state() == IdempotencyState.ABANDONED) {
return new IdempotencyClaimOutcome.RecoveryRequired(row.attempt());
}
// What nothing ran under is taken over by whoever claims next — checked before the same-attempt
// replay below, because the previous holder may be this very attempt, retrying after its start
// was refused or its failure was marked retryable. Replaying it the row it holds handed back a
// claim that cannot start, until the row expired (round6 RR6-02-01). The Redis store answers in
// the same order (IdempotencyStoreContract).
if (row.state() == IdempotencyState.CLAIMED && !dbNow.isBefore(row.processingLeaseUntil())) {
return resetClaim(request, row);
}
if (row.state() == IdempotencyState.FAILED_RETRYABLE) {
return resetClaim(request, row);
}
if (sameClaimAttempt(row, request.claimAttempt())) {
return new IdempotencyClaimOutcome.ReplayedAcquire(owner(row), row.processingLeaseUntil());
}
if (row.ownerToken().equals(request.claimAttempt().ownerToken())) {
return new IdempotencyClaimOutcome.OwnerOperationConflict();
}
// An execution whose lease ran out has an unknown effect, so it is never run again — and the
// row is not touched: its holder may still finish, and its completion or failure is recorded as
// it would have been inside the lease (owner decision 2026-11-04; the row used to be abandoned
@@ -157,9 +165,6 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort {
if (isExpiredExecution(row, dbNow)) {
return new IdempotencyClaimOutcome.RecoveryRequired(row.attempt());
}
if (row.state() == IdempotencyState.ABANDONED) {
return new IdempotencyClaimOutcome.RecoveryRequired(row.attempt());
}
Duration retryAfter =
row.processingLeaseUntil().isAfter(dbNow)
@@ -179,16 +184,14 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort {
return startResult(IdempotencyStartOutcome.ABSENT, null);
}
String startDigest = transitionDigest("START", operationId, owner);
switch (replayVerdict(row, "START", operationId, startDigest)) {
case SAME_ARGUMENTS -> {
return startResult(IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION, owner(row));
}
case DIFFERENT_ARGUMENTS -> {
return startResult(IdempotencyStartOutcome.OPERATION_CONFLICT, null);
}
default -> {
// fall through to the first application
}
// A start carries no argument but the handle, so a recorded start with another digest was
// applied from another handle of the same operation — one from before a takeover by the same
// attempt, or the current one a replayed claim returned. That is a stale or a wrong-state
// handle, which the classification below names as the Redis store does (NOT_OWNER,
// NOT_CLAIMED); it used to be OPERATION_CONFLICT (round6 RR6-02-01). It never reaches the
// update: a recorded start leaves the row EXECUTING until a later transition replaces it.
if (replayVerdict(row, "START", operationId, startDigest) == ReplayVerdict.SAME_ARGUMENTS) {
return startResult(IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION, owner(row));
}
IdempotencyStartOutcome mismatch = classifyStartMismatch(row, owner);
if (mismatch != null) {
@@ -4,6 +4,8 @@ import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.configuration.FluentConfiguration;
/**
* Which schema-management mode each environment runs under, and what is forbidden everywhere
@@ -16,9 +18,20 @@ import java.util.Set;
*
* <p>Repair is not a mode. It is represented only as an operation descriptor an operator invokes
* deliberately, never as startup behaviour (design §8.4).
*
* <p>Every Flyway the template builds itself starts from {@link #configure()}, so they all take
* Flyway's PostgreSQL lock the same way.
*/
public final class FlywaySchemaPolicy {
/**
* Flyway's own key for how it holds its PostgreSQL migration lock: {@code true}, Flyway's
* default, in a transaction left open for the whole run; {@code false} for the session. A {@code
* flyway.conf} and the command line take it under this name, the environment as {@code
* FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK}.
*/
public static final String TRANSACTIONAL_LOCK = "flyway.postgresql.transactional.lock";
/** The {@code ddl-auto} values that mutate a deployed schema and are never permitted. */
private static final Set<String> SCHEMA_MUTATING_DDL_AUTO =
Set.of("update", "create", "create-drop");
@@ -82,4 +95,33 @@ public final class FlywaySchemaPolicy {
public Set<String> permittedDdlAuto() {
return PERMITTED_DDL_AUTO;
}
/**
* A Flyway configuration with the settings every Flyway this template builds shares: Flyway's
* PostgreSQL migration lock held for the session, not in a transaction ({@link
* #TRANSACTIONAL_LOCK} {@code =false}).
*
* <p>Flyway's default holds that lock in a transaction it keeps open until the whole run ends. A
* concurrent index build ({@code CREATE INDEX CONCURRENTLY}, {@code REINDEX ... CONCURRENTLY})
* waits for every transaction older than itself, Flyway's own included, while Flyway waits for
* the build: the migration never ends, and nothing times it out (re-review 2026-11-03 round 6,
* RR6-03-01). Spring Boot's Flyway gets the same value from the module defaults ({@code
* spring.flyway.postgresql.transactional-lock}); a deployment's migration tool has to be given it
* ({@code docs/jpa/migration-guide.md}, "Who may change the schema").
*
* <p>Callers chain their own settings onto the result. Calling {@link Flyway#configure()}
* directly in production code is refused by {@code JpaProductionArchitectureTest}.
*/
public static FluentConfiguration configure() {
return sessionLevelLock(Flyway.configure());
}
/** The same, loading migrations and callbacks through {@code classLoader}. */
public static FluentConfiguration configure(ClassLoader classLoader) {
return sessionLevelLock(Flyway.configure(classLoader));
}
private static FluentConfiguration sessionLevelLock(FluentConfiguration configuration) {
return configuration.configuration(Map.of(TRANSACTIONAL_LOCK, "false"));
}
}
@@ -137,6 +137,16 @@ spring:
# true: keep Flyway `clean` (drops the whole schema) disarmed. Disabling this
# under prod is forbidden — clean is destructive.
clean-disabled: true
postgresql:
# false: hold Flyway's PostgreSQL migration lock for the session. Flyway's default (true)
# holds it in a transaction left open for the whole run, and a CREATE INDEX CONCURRENTLY or
# REINDEX ... CONCURRENTLY migration waits for that transaction while Flyway waits for it:
# startup never ends (re-review 2026-11-03 round 6, RR6-03-01). The streams the template
# builds itself take the same value from FlywaySchemaPolicy.configure(); a deployment's
# migration tool needs it too (FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK=false). Assumes Flyway's
# connection is its own for the run — a direct connection, as Hikari gives, not a pooler in
# transaction mode (docs/jpa/migration-guide.md, "Who may change the schema").
transactional-lock: false
jpa:
hibernate:
# none | validate | update | create | create-drop
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.adapter.outbound.persistence.api.error.SchemaMismatchException;
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.FlywayValidationGate;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -109,7 +110,8 @@ class FlywayUpgradeContractTest {
}
/**
* Builds a Flyway configured the way the platform requires.
* Builds a Flyway configured the way the platform requires, starting from the settings every
* Flyway of the template shares ({@code FlywaySchemaPolicy.configure()}).
*
* <p>{@code ignoreMigrationPatterns} is set to nothing explicitly. Flyway's own default tolerates
* some validation findings, and a deployment that silently tolerates a missing applied migration
@@ -118,7 +120,7 @@ class FlywayUpgradeContractTest {
* inheriting the library's.
*/
private static Flyway flyway(Path migrations, String schema) {
return Flyway.configure()
return FlywaySchemaPolicy.configure()
.dataSource(support.dataSource())
.locations("filesystem:" + migrations.toAbsolutePath())
.schemas(schema)
@@ -0,0 +1,231 @@
package dev.caskeleton.adapter.outbound.persistence.readiness;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import com.zaxxer.hikari.HikariDataSource;
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.sql.DataSource;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.boot.flyway.autoconfigure.FlywayAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DelegatingDataSource;
/**
* A migration that builds or rebuilds an index concurrently finishes under the Flyway settings the
* template ships, against real PostgreSQL (re-review 2026-11-03 round 6, RR6-03-01).
*
* <p>{@code CREATE INDEX CONCURRENTLY} and {@code REINDEX ... CONCURRENTLY} wait until every
* transaction that started before them has ended. Flyway's PostgreSQL default holds its migration
* lock inside a transaction it keeps open for the whole run, so such a migration waits for Flyway
* and Flyway waits for the migration: the deploy never ends, with nothing to time it out. Holding
* the lock for the session instead ({@code flyway.postgresql.transactional.lock=false}) leaves no
* transaction open, and the build finishes.
*
* <p>Each case is a second deploy, shaped the way {@code docs/jpa/migration-guide.md} ("Concurrent
* index builds") says to write it: V1 already applied, then V2 holding the one concurrent statement
* with {@code executeInTransaction=false} beside it. One test builds Flyway the way Spring Boot
* does from the module defaults ({@code config/module-defaults/persistence-jpa.yml}), the other the
* way every Flyway this template constructs itself does ({@link FlywaySchemaPolicy#configure()}). A
* deploy still waiting after {@link #FINISHES_WITHIN} is cancelled, which leaves the invalid index
* an interrupted build leaves in production too.
*/
class PostgreSqlConcurrentIndexMigrationIntegrationTest {
private static final Duration FINISHES_WITHIN = Duration.ofSeconds(30);
private static final String FIRST_RELEASE =
"""
CREATE TABLE probe (id INT PRIMARY KEY, note TEXT);
CREATE INDEX ix_probe_id ON probe (id);
INSERT INTO probe SELECT g, 'note ' || g FROM generate_series(1, 1000) AS g;
""";
private static PostgreSqlReadinessSupport postgres;
@BeforeAll
static void setup() {
postgres = PostgreSqlReadinessSupport.start();
}
@AfterAll
static void cleanup() {
if (postgres != null) {
postgres.close();
}
}
@ParameterizedTest
@ValueSource(
strings = {
"CREATE INDEX CONCURRENTLY ix_probe_note ON probe (note)",
"REINDEX INDEX CONCURRENTLY ix_probe_id"
})
void theFlywaySpringBootBuildsFromTheModuleDefaultsAppliesAConcurrentIndexMigration(
String statement, @TempDir Path stream) throws Exception {
String name = databaseName();
try (HikariDataSource database = postgres.createDatabase(name)) {
// given
Files.writeString(stream.resolve("V1__probe.sql"), FIRST_RELEASE);
migrateTheWaySpringBootDoes(database, stream);
writeConcurrentMigration(stream, statement);
// when
Deploy deploy = within(name, () -> migrateTheWaySpringBootDoes(database, stream));
// then
assertThat(List.of(deploy.finished(), String.valueOf(deploy.failure()), state(database)))
.containsExactly(true, "null", "version 2, indexes valid true");
}
}
@ParameterizedTest
@ValueSource(
strings = {
"CREATE INDEX CONCURRENTLY ix_probe_note ON probe (note)",
"REINDEX INDEX CONCURRENTLY ix_probe_id"
})
void theFlywayTheTemplateBuildsItselfAppliesAConcurrentIndexMigration(
String statement, @TempDir Path stream) throws Exception {
String name = databaseName();
try (HikariDataSource database = postgres.createDatabase(name)) {
// given
Files.writeString(stream.resolve("V1__probe.sql"), FIRST_RELEASE);
migrateTheWayTheTemplateDoes(database, stream);
writeConcurrentMigration(stream, statement);
// when
Deploy deploy = within(name, () -> migrateTheWayTheTemplateDoes(database, stream));
// then
assertThat(List.of(deploy.finished(), String.valueOf(deploy.failure()), state(database)))
.containsExactly(true, "null", "version 2, indexes valid true");
}
}
/** V2: the one concurrent statement, with the companion configuration the guide asks for. */
private static void writeConcurrentMigration(Path stream, String statement) throws IOException {
Files.writeString(stream.resolve("V2__concurrent_index.sql"), statement + ";\n");
Files.writeString(
stream.resolve("V2__concurrent_index.sql.conf"), "executeInTransaction=false\n");
}
/** Migrates with the Flyway Spring Boot builds from the module defaults, as a service starts. */
private static void migrateTheWaySpringBootDoes(DataSource database, Path stream) {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class))
.withInitializer(
context -> {
try {
new YamlPropertySourceLoader()
.load(
"persistence-jpa",
new ClassPathResource("config/module-defaults/persistence-jpa.yml"))
.forEach(
source -> context.getEnvironment().getPropertySources().addLast(source));
} catch (IOException unreadable) {
throw new IllegalStateException(unreadable);
}
})
// A delegate, so closing the context does not close the test's pool with it.
.withBean(DataSource.class, () -> new DelegatingDataSource(database))
.withPropertyValues("spring.flyway.locations=filesystem:" + stream.toAbsolutePath())
.run(
context -> {
if (context.getStartupFailure() != null) {
throw context.getStartupFailure();
}
});
}
/** Migrates with the Flyway the template's own streams build. */
private static void migrateTheWayTheTemplateDoes(DataSource database, Path stream) {
FlywaySchemaPolicy.configure()
.dataSource(database)
.locations("filesystem:" + stream.toAbsolutePath())
.load()
.migrate();
}
/**
* Runs the deploy and gives it {@link #FINISHES_WITHIN}. One still running then is stuck: the
* statements waiting for a lock in its database are cancelled so the deploy ends and the test can
* report it.
*/
private static Deploy within(String databaseName, Runnable migration) throws Exception {
ExecutorService deployer = Executors.newSingleThreadExecutor();
try {
Future<?> deploy = deployer.submit(migration);
try {
deploy.get(FINISHES_WITHIN.toMillis(), TimeUnit.MILLISECONDS);
return new Deploy(true, null);
} catch (ExecutionException failed) {
return new Deploy(true, failed.getCause());
} catch (TimeoutException stuck) {
cancelLockWaits(databaseName);
Throwable after =
catchThrowable(() -> deploy.get(FINISHES_WITHIN.toMillis(), TimeUnit.MILLISECONDS));
return new Deploy(false, after);
}
} finally {
deployer.shutdownNow();
}
}
private static void cancelLockWaits(String databaseName) throws SQLException {
try (Connection admin = postgres.connection();
PreparedStatement cancel =
admin.prepareStatement(
"SELECT pg_cancel_backend(pid) FROM pg_stat_activity"
+ " WHERE datname = ? AND wait_event_type = 'Lock'"
+ " AND pid <> pg_backend_pid()")) {
cancel.setString(1, databaseName);
cancel.execute();
}
}
/** The version the history ends on and whether every index on the table is usable. */
private static String state(DataSource database) {
JdbcTemplate jdbc = new JdbcTemplate(database);
String version =
jdbc.queryForObject(
"SELECT version FROM flyway_schema_history WHERE success"
+ " ORDER BY installed_rank DESC LIMIT 1",
String.class);
Boolean valid =
jdbc.queryForObject(
"SELECT bool_and(indisvalid) FROM pg_index WHERE indrelid = 'probe'::regclass",
Boolean.class);
return "version " + version + ", indexes valid " + valid;
}
private static String databaseName() {
return "concurrent_" + UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ROOT);
}
/** Whether the deploy ended within the bound, and how it failed when it did not succeed. */
private record Deploy(boolean finished, Throwable failure) {}
}
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import com.zaxxer.hikari.HikariDataSource;
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.LockWaitMigrationInspector;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -43,11 +44,18 @@ import org.springframework.jdbc.core.JdbcTemplate;
* against a writer in {@code PostgreSqlOutboxOrderKeyRunbookIntegrationTest}.
*
* <p>The text check ({@link LockWaitMigrationInspector}) repeats which statements Flyway runs
* outside a transaction, where {@code SET LOCAL} bounds nothing. Two cases here hold that copy to
* Flyway itself on this server: the statements it names are exactly those Flyway refuses next to a
* {@code SET LOCAL} (default {@code mixed=false}), and a {@code VACUUM FULL} that Flyway runs
* anyway ({@code mixed=true}) waits out the reader despite its {@code SET LOCAL} (re-review
* 2026-11-03 round 4, RR4-02-01).
* outside a transaction, where {@code SET LOCAL} bounds nothing. Two cases here compare that copy
* with Flyway itself on this server: for each statement the first one lists, the inspector names it
* exactly when Flyway refuses it next to a {@code SET LOCAL} (default {@code mixed=false}), and a
* {@code VACUUM FULL} that Flyway runs anyway ({@code mixed=true}) waits out the reader despite its
* {@code SET LOCAL} (re-review 2026-11-03 round 4, RR4-02-01). The comparison covers the listed
* statements only; a statement Flyway adds to its list in an upgrade is caught by {@code
* LockWaitMigrationInspectorTest}, which pins Flyway's own patterns in the pull request's {@code
* ci} (round 6, RR6-03-03).
*
* <p>The migrations run under the template's Flyway settings ({@code FlywaySchemaPolicy}), whose
* PostgreSQL lock is held for the session rather than in an open transaction (RR6-03-01): the bound
* is shown under the lock the deploy actually takes.
*/
class PostgreSqlMigrationLockWaitIntegrationTest {
@@ -149,7 +157,15 @@ class PostgreSqlMigrationLockWaitIntegrationTest {
"ALTER TABLE probe ADD COLUMN c INT",
"CREATE INDEX ix_probe_plain ON probe (id)",
"COMMENT ON TABLE probe IS 'vacuum full'",
"DO $$ BEGIN PERFORM 1; END $$"
"DO $$ BEGIN PERFORM 1; END $$",
"CREATE TABLESPACE probe_ts LOCATION '/tmp'",
"DROP TABLESPACE IF EXISTS probe_ts",
"CREATE SUBSCRIPTION probe_sub CONNECTION 'dbname=probe' PUBLICATION probe_pub",
"DROP SUBSCRIPTION IF EXISTS probe_sub",
"REINDEX SYSTEM probe",
"REINDEX VERBOSE SCHEMA public",
"UPDATE probe SET note = E'it\\'s'; VACUUM FULL probe",
"/* outer /* inner */ VACUUM probe; */ SELECT 1"
})
@DisplayName("검사기가 트랜잭션 밖이라고 보는 문장은 Flyway가 SET LOCAL 옆에서 거부하는 문장과 같다")
void theInspectorNamesExactlyTheStatementsFlywayRunsOutsideATransaction(
@@ -158,14 +174,14 @@ class PostgreSqlMigrationLockWaitIntegrationTest {
// given
new JdbcTemplate(database)
.execute(
"CREATE TABLE probe (id INT PRIMARY KEY);"
"CREATE TABLE probe (id INT PRIMARY KEY, note TEXT);"
+ " CREATE MATERIALIZED VIEW probe_view AS SELECT id FROM probe;"
+ " CREATE UNIQUE INDEX ux_probe_view ON probe_view (id);"
+ " CREATE TYPE probe_status AS ENUM ('a')");
String sql = "SET LOCAL lock_timeout = '5s';\n" + statement + ";\n";
Files.writeString(stream.resolve("V1__probe.sql"), sql);
Flyway flyway =
Flyway.configure()
FlywaySchemaPolicy.configure()
.dataSource(database)
.locations("filesystem:" + stream.toAbsolutePath())
.baselineOnMigrate(true)
@@ -198,7 +214,7 @@ class PostgreSqlMigrationLockWaitIntegrationTest {
Files.writeString(
stream.resolve("V1__vacuum.sql"), "SET LOCAL lock_timeout = '1s';\nVACUUM FULL probe;\n");
Flyway mixed =
Flyway.configure()
FlywaySchemaPolicy.configure()
.dataSource(database)
.locations("filesystem:" + stream.toAbsolutePath())
.baselineOnMigrate(true)
@@ -225,7 +241,7 @@ class PostgreSqlMigrationLockWaitIntegrationTest {
new JdbcTemplate(database).execute("CREATE TABLE probe (id INT PRIMARY KEY)");
Files.writeString(stream.resolve("V1__reindex.sql"), "REINDEX TABLE CONCURRENTLY probe;\n");
Flyway flyway =
Flyway.configure()
FlywaySchemaPolicy.configure()
.dataSource(database)
.locations("filesystem:" + stream.toAbsolutePath())
.baselineOnMigrate(true)
@@ -282,7 +298,7 @@ class PostgreSqlMigrationLockWaitIntegrationTest {
}
private static Flyway outboxStream(HikariDataSource database, int target) {
return Flyway.configure()
return FlywaySchemaPolicy.configure()
.dataSource(database)
.locations("classpath:db/migration/postgresql")
.target(String.valueOf(target))
@@ -292,7 +308,7 @@ class PostgreSqlMigrationLockWaitIntegrationTest {
private static Flyway notificationStream(HikariDataSource database, int target) {
PostgreSqlOptionalStreamLifecycle.Stream stream =
PostgreSqlOptionalStreamLifecycle.notificationPlatform();
return Flyway.configure()
return FlywaySchemaPolicy.configure()
.dataSource(database)
.locations(stream.location())
.table(stream.historyTable())
@@ -305,7 +321,7 @@ class PostgreSqlMigrationLockWaitIntegrationTest {
/** The core stream, applied and promoted: what a deployment has before any capability stream. */
private static void applyCore(HikariDataSource database) {
Flyway core =
Flyway.configure()
FlywaySchemaPolicy.configure()
.dataSource(database)
.locations("classpath:db/migration/jpa/core")
.table("flyway_jpa_core_history")
@@ -99,14 +99,17 @@ class JpaModuleBoundaryTest {
Map.entry("cache", Set.of("api")),
Map.entry("config", Set.of("api")),
Map.entry("envers", Set.of("api")),
Map.entry("experimental", Set.of("api", "hibernate", "springdata", "transaction")),
// `migration` for FlywaySchemaPolicy.configure(): every Flyway this leaf builds starts
// there (re-review 2026-11-03 round 6, RR6-03-01). Same for `idempotency` below.
Map.entry(
"experimental", Set.of("api", "hibernate", "migration", "springdata", "transaction")),
Map.entry("failure", Set.of("api")),
Map.entry(
"h2", Set.of("api", "config", "failure", "idempotency", "outbox", "transaction")),
Map.entry("hibernate", Set.of("api")),
// `transaction` for the one caller-transaction guard (CallerTransaction) the stores
// share.
Map.entry("idempotency", Set.of("api", "audit", "failure", "transaction")),
Map.entry("idempotency", Set.of("api", "audit", "failure", "migration", "transaction")),
Map.entry("lock", Set.of("api")),
Map.entry("migration", Set.of("api")),
Map.entry("observation", Set.of("api")),
@@ -3,8 +3,15 @@ package dev.caskeleton.adapter.outbound.persistence.migration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.util.List;
import org.flywaydb.core.api.configuration.FluentConfiguration;
import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
/** Flyway owns schema change; production validates rather than migrating (design §31). */
class FlywaySchemaPolicyTest {
@@ -30,4 +37,56 @@ class FlywaySchemaPolicyTest {
assertThat(policy.modeFor("local")).isEqualTo(SchemaManagementMode.MIGRATE_ON_STARTUP);
assertThat(policy.modeFor("unknown-profile")).isEqualTo(SchemaManagementMode.VALIDATE_ONLY);
}
@Test
void theFlywayTheTemplateBuildsHoldsItsPostgreSqlLockForTheSession() {
// when
FluentConfiguration configuration = FlywaySchemaPolicy.configure();
// then
assertThat(transactionalLock(configuration)).isFalse();
}
@Test
void theClassLoaderVariantKeepsTheClassLoaderAndTheSessionLock() {
// given
ClassLoader classLoader = new ClassLoader(getClass().getClassLoader()) {};
// when
FluentConfiguration configuration = FlywaySchemaPolicy.configure(classLoader);
// then
assertThat(List.of(configuration.getClassLoader(), transactionalLock(configuration)))
.containsExactly(classLoader, false);
}
@Test
void theModuleDefaultsGiveSpringBootsFlywayTheSameSessionLock() throws IOException {
// given
// the file alone: no operator environment variable may answer for it
StandardEnvironment environment = new StandardEnvironment();
environment
.getPropertySources()
.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
environment
.getPropertySources()
.remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
new YamlPropertySourceLoader()
.load(
"persistence-jpa", new ClassPathResource("config/module-defaults/persistence-jpa.yml"))
.forEach(source -> environment.getPropertySources().addLast(source));
// when
Boolean transactionalLock =
environment.getProperty("spring.flyway.postgresql.transactional-lock", Boolean.class);
// then
assertThat(transactionalLock).isFalse();
}
private static boolean transactionalLock(FluentConfiguration configuration) {
return configuration
.getConfigurationExtension(PostgreSQLConfigurationExtension.class)
.isTransactionalLock();
}
}
@@ -5,6 +5,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/** Plan Task 43 — concurrent index builds must be non-transactional (design §32). */
class ConcurrentIndexMigrationInspectorTest {
@@ -47,6 +49,39 @@ class ConcurrentIndexMigrationInspectorTest {
.isFalse();
}
@ParameterizedTest
@ValueSource(
strings = {
"CREATE UNIQUE INDEX CONCURRENTLY ux_order ON orders (id);",
"create index\nconcurrently ix_order on orders (created_at);",
"REINDEX (CONCURRENTLY) TABLE orders;",
"REINDEX (VERBOSE, CONCURRENTLY true) INDEX ix_order;",
"REINDEX SCHEMA CONCURRENTLY public;"
})
@DisplayName("PostgreSQL이 트랜잭션 안에서 거부하는 동시 인덱스 문장은 UNIQUE·괄호 옵션·줄바꿈이 있어도 찾는다")
void everySpellingOfAConcurrentIndexStatementIsFound(String sql) {
// when
boolean found = inspector.containsConcurrentIndexStatement(sql);
// then
assertThat(found).isTrue();
}
@ParameterizedTest
@ValueSource(
strings = {
"REINDEX (CONCURRENTLY false) TABLE orders;",
"CREATE INDEX ix_order ON orders (id);"
})
@DisplayName("CONCURRENTLY를 끄거나 쓰지 않은 인덱스 문장은 동시 인덱스 문장으로 보지 않는다")
void anIndexStatementWithoutConcurrentlyIsNotOne(String sql) {
// when
boolean found = inspector.containsConcurrentIndexStatement(sql);
// then
assertThat(found).isFalse();
}
@Test
@DisplayName("a concurrent index migration must contain nothing else")
void requiresIsolatedStatement() {
@@ -5,9 +5,14 @@ import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.InstanceOfAssertFactories.STRING;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
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.regex.Pattern;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -258,6 +263,85 @@ class LockWaitMigrationInspectorTest {
assertThat(outside).isEqualTo(expected.isEmpty() ? List.of() : List.of(expected));
}
/**
* The inspector's {@code FLYWAY_OUTSIDE_A_TRANSACTION} is a copy of these patterns, and {@code
* postgresqlMigrationLockWaitIntegrationTest} compares the two only for the statements it lists.
* A Flyway upgrade that adds a statement to the list, or changes one, fails here, in the pull
* request's {@code ci}, instead of passing a migration Flyway refuses at deploy (re-review
* 2026-11-03 round 6, RR6-03-03).
*/
@Test
void flywaysPostgreSqlParserStillHasTheStatementListTheInspectorCopied() throws Exception {
// given
Class<?> parser = Class.forName("org.flywaydb.database.postgresql.PostgreSQLParser");
// when
Map<String, String> patterns = staticPatterns(parser);
// then
assertThat(patterns)
.as(
"Flyway's list of the statements it runs outside a transaction changed: update"
+ " LockWaitMigrationInspector.FLYWAY_OUTSIDE_A_TRANSACTION, the statements"
+ " PostgreSqlMigrationLockWaitIntegrationTest compares with Flyway, and this list"
+ " (docs/jpa/migration-guide.md, \"Bound the lock wait\")")
.isEqualTo(
Map.of(
"COPY_FROM_STDIN_REGEX", "^COPY( .*)? FROM STDIN",
"CREATE_DATABASE_TABLESPACE_SUBSCRIPTION_REGEX",
"^(CREATE|DROP) (DATABASE|TABLESPACE|SUBSCRIPTION)",
"ALTER_SYSTEM_REGEX", "^ALTER SYSTEM",
"CREATE_INDEX_CONCURRENTLY_REGEX", "^(CREATE|DROP)( UNIQUE)? INDEX CONCURRENTLY",
"REINDEX_REGEX", "^REINDEX( VERBOSE)? (SCHEMA|DATABASE|SYSTEM)",
"VACUUM_REGEX", "^VACUUM",
"DISCARD_ALL_REGEX", "^DISCARD ALL",
"ALTER_TYPE_ADD_VALUE_REGEX", "^ALTER TYPE( .*)? ADD VALUE"));
}
@ParameterizedTest
@ValueSource(strings = {"E'it\\'s'", "e'it\\'s'", "E'C:\\\\'", "E'it''s'"})
@DisplayName("백슬래시 escape가 든 E-문자열 뒤의 잠금 문장도 상한 없는 문장으로 찾는다")
void aLockAfterAnEscapeStringIsStillFound(String literal) {
// given
String sql =
"INSERT INTO probe (id, note) VALUES (1, "
+ literal
+ ");\nALTER TABLE probe ADD COLUMN c INT;";
// when
List<String> unbounded = inspector.unboundedLockingStatements(sql);
// then
assertThat(unbounded).containsExactly("alter table probe");
}
@Test
@DisplayName("백슬래시 escape가 든 E-문자열 뒤에 Flyway가 트랜잭션 밖에서 돌리는 문장이 있으면 그 문장을 말한다")
void aStatementFlywayRunsOutsideATransactionAfterAnEscapeStringIsNamed() {
// given
String sql =
"SET LOCAL lock_timeout = '5s';\nUPDATE probe SET note = E'it\\'s';\nVACUUM FULL probe;";
// when
List<String> outside = inspector.statementsFlywayRunsOutsideATransaction(sql);
// then
assertThat(outside).containsExactly("vacuum");
}
@Test
@DisplayName("중첩된 블록 주석은 PostgreSQL·Flyway처럼 바깥 */까지 주석으로 읽는다")
void aStatementInsideANestedBlockCommentIsNotRead() {
// given
String sql = "SET LOCAL lock_timeout = '5s';\n/* outer /* inner */ VACUUM probe; */ SELECT 1;";
// when
List<String> outside = inspector.statementsFlywayRunsOutsideATransaction(sql);
// then
assertThat(outside).isEmpty();
}
@ParameterizedTest
@ValueSource(
strings = {
@@ -296,4 +380,16 @@ class LockWaitMigrationInspectorTest {
// then
assertThat(unbounded).isEmpty();
}
/** Every static {@link Pattern} the class declares, by field name. */
private static Map<String, String> staticPatterns(Class<?> type) throws IllegalAccessException {
Map<String, String> patterns = new TreeMap<>();
for (Field field : type.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers()) && field.getType() == Pattern.class) {
field.setAccessible(true);
patterns.put(field.getName(), ((Pattern) field.get(null)).pattern());
}
}
return patterns;
}
}
@@ -2,29 +2,42 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.migration;
import java.util.Locale;
import java.util.Objects;
import java.util.regex.Pattern;
/**
* Refuses a {@code CREATE INDEX CONCURRENTLY} that Flyway would run inside a transaction (design
* §32).
* Requires a concurrent index statement to say that it runs outside a transaction, and to be alone
* in its migration (design §32; {@code docs/jpa/migration-guide.md}, "Concurrent index builds").
*
* <p>PostgreSQL rejects {@code CREATE INDEX CONCURRENTLY} inside a transaction block outright, and
* Flyway wraps migrations in a transaction by default — so the migration fails on the first
* deployment that runs it, which is the good case. The bad case is a migration that mixes it with
* other statements: those commit, the concurrent index does not, and the schema is left partly
* migrated with a history row that says otherwise.
* <p>PostgreSQL refuses {@code CREATE INDEX CONCURRENTLY}, {@code DROP INDEX CONCURRENTLY} and
* {@code REINDEX ... CONCURRENTLY} inside a transaction block. Flyway 11 runs a script outside its
* transaction on its own when it holds {@code CREATE} or {@code DROP INDEX CONCURRENTLY}, but not
* {@code REINDEX ... CONCURRENTLY}: that one Flyway runs in the transaction, and PostgreSQL refuses
* it at deploy. So {@link #validate} wants {@code executeInTransaction=false} beside every
* concurrent statement, whether Flyway would detect it or not. Next to any other statement, one
* Flyway runs outside a transaction makes Flyway refuse the whole script before it runs any of it
* (its default {@code mixed=false}); {@link #requireIsolatedStatement} wants the statement alone so
* that a failed build is recovered by dropping one invalid index.
*
* <p>{@code DROP INDEX CONCURRENTLY} and {@code REINDEX CONCURRENTLY} carry the same restriction
* and the same failure mode, so all three are checked.
* <p>Outside a transaction, {@code CREATE INDEX CONCURRENTLY} and {@code REINDEX ... CONCURRENTLY}
* still wait for every transaction older than themselves. They finish because the template's Flyway
* holds its PostgreSQL lock for the session ({@code FlywaySchemaPolicy.configure()}): under
* Flyway's default the lock's own open transaction is one of those, and the deploy never ends
* (re-review 2026-11-03 round 6, RR6-03-01 and RR6-03-05).
*/
public final class ConcurrentIndexMigrationInspector {
private static final String[] CONCURRENT_STATEMENTS = {
"create index concurrently",
"drop index concurrently",
"reindex index concurrently",
"reindex table concurrently",
"reindex concurrently"
};
/**
* A concurrent index statement in any spelling PostgreSQL accepts: {@code UNIQUE}, any
* whitespace, and {@code CONCURRENTLY} after the object kind or, for {@code REINDEX}, in its
* option list ({@code (CONCURRENTLY)}, {@code (VERBOSE, CONCURRENTLY true)}; not {@code
* (CONCURRENTLY false)}).
*/
private static final Pattern CONCURRENT_STATEMENT =
Pattern.compile(
"\\b(?:create\\s+(?:unique\\s+)?index|drop\\s+index"
+ "|reindex\\s*(?:\\([^)]*\\)\\s*)?(?:index|table|schema|database|system))"
+ "\\s+concurrently\\b"
+ "|\\breindex\\s*\\((?=[^)]*\\bconcurrently\\b(?!\\s*(?:false|off|0)\\b))");
/**
* Fails when a migration containing a concurrent index statement is transactional.
@@ -39,9 +52,9 @@ public final class ConcurrentIndexMigrationInspector {
}
throw new IllegalStateException(
migration.name()
+ " must set executeInTransaction=false: PostgreSQL rejects concurrent index"
+ " statements inside a transaction block, and a mixed migration would commit its"
+ " other statements while leaving the index unbuilt");
+ " must set executeInTransaction=false: PostgreSQL refuses a concurrent index"
+ " statement inside a transaction block, and Flyway runs REINDEX ... CONCURRENTLY in"
+ " one unless the migration says otherwise");
}
/** Whether the script contains a statement PostgreSQL forbids inside a transaction. */
@@ -49,13 +62,7 @@ public final class ConcurrentIndexMigrationInspector {
if (sql == null) {
return false;
}
String normalized = sql.toLowerCase(Locale.ROOT);
for (String statement : CONCURRENT_STATEMENTS) {
if (normalized.contains(statement)) {
return true;
}
}
return false;
return CONCURRENT_STATEMENT.matcher(sql.toLowerCase(Locale.ROOT)).find();
}
/**
@@ -46,10 +46,11 @@ import java.util.regex.Pattern;
* {@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. 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).
* and {@code RESET} wait without end, a plain {@code SET} outlives the migration. Comments (nested
* ones included) and quoted literals ({@code E'...'} escape strings included) 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).
*
* <p>A migration Flyway runs outside a transaction has no bound at all: {@code SET LOCAL} there
* only warns. Flyway decides that the way {@link #statementsFlywayRunsOutsideATransaction(String)}
@@ -148,8 +149,11 @@ public final class LockWaitMigrationInspector {
* words outside parentheses, lower case and one space apart, match one of these in full. {@code
* ALTER TYPE ... ADD VALUE} is on Flyway's list only below PostgreSQL 12. {@code REINDEX TABLE
* CONCURRENTLY} is not on it: Flyway runs it in the transaction and PostgreSQL refuses it there.
* {@code postgresqlMigrationLockWaitIntegrationTest} holds this list to Flyway itself on real
* PostgreSQL, so a Flyway upgrade that changes it fails there rather than here.
* {@code LockWaitMigrationInspectorTest} pins Flyway's own patterns, read from {@code
* PostgreSQLParser}, so a Flyway upgrade that adds a statement or changes one fails the pull
* request's {@code ci} until this copy follows. {@code
* postgresqlMigrationLockWaitIntegrationTest} compares this copy with Flyway on real PostgreSQL
* for the statements it lists, and only those (re-review 2026-11-03 round 6, RR6-03-03).
*/
private static final List<Pattern> FLYWAY_OUTSIDE_A_TRANSACTION =
List.of(
@@ -428,7 +432,9 @@ public final class LockWaitMigrationInspector {
* Blanks out comments and single-quoted literals, keeping every other character in place, so a
* word in a {@code COMMENT ON ... IS '...'} or a {@code -- } line is not read as a statement. A
* literal that is a number with an optional unit ({@code '5s'}) is kept: it holds no statement,
* and the {@code lock_timeout} value is read from it.
* and the {@code lock_timeout} value is read from it. Literals and comments end where PostgreSQL
* ends them: in an escape string ({@code E'it\'s'}) a backslash escapes the next character, and
* block comments nest (re-review 2026-11-03 round 6, RR6-03-02).
*/
private static String withoutCommentsAndLiterals(String sql) {
StringBuilder kept = new StringBuilder(sql.length());
@@ -440,22 +446,16 @@ public final class LockWaitMigrationInspector {
i = end < 0 ? sql.length() : end;
kept.append(' ');
} else if (c == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') {
int end = sql.indexOf("*/", i + 2);
i = end < 0 ? sql.length() : end + 2;
i = endOfBlockComment(sql, i);
kept.append(' ');
} else if (c == '\'') {
int start = i;
i++;
while (i < sql.length()) {
if (sql.charAt(i) == '\'' && i + 1 < sql.length() && sql.charAt(i + 1) == '\'') {
i += 2;
} else if (sql.charAt(i) == '\'') {
i++;
break;
} else {
i++;
}
boolean escapeString = opensEscapeString(sql, i);
if (escapeString) {
// The E prefix is part of the literal, not a word of the statement.
kept.setCharAt(kept.length() - 1, ' ');
}
int start = i;
i = endOfLiteral(sql, i + 1, escapeString);
String literal = sql.substring(start, i);
boolean duration =
literal.length() >= 2
@@ -470,6 +470,63 @@ public final class LockWaitMigrationInspector {
return kept.toString();
}
/**
* Whether the quote at {@code quote} opens an escape string: an {@code E} or {@code e} right
* before it that is not the end of a longer word.
*/
private static boolean opensEscapeString(String sql, int quote) {
if (quote < 1 || Character.toLowerCase(sql.charAt(quote - 1)) != 'e') {
return false;
}
if (quote < 2) {
return true;
}
char before = sql.charAt(quote - 2);
return !(Character.isLetterOrDigit(before) || before == '_' || before == '$');
}
/**
* Where a literal whose body starts at {@code from} ends, just past its closing quote: a doubled
* quote stays inside, and in an escape string so does any character after a backslash.
*/
private static int endOfLiteral(String sql, int from, boolean escapeString) {
int i = from;
while (i < sql.length()) {
char c = sql.charAt(i);
if (escapeString && c == '\\') {
i += 2;
} else if (c == '\'' && i + 1 < sql.length() && sql.charAt(i + 1) == '\'') {
i += 2;
} else if (c == '\'') {
return i + 1;
} else {
i++;
}
}
return sql.length();
}
/** Where the block comment opening at {@code start} ends, nested comments counted. */
private static int endOfBlockComment(String sql, int start) {
int depth = 0;
int i = start;
while (i + 1 < sql.length()) {
if (sql.charAt(i) == '/' && sql.charAt(i + 1) == '*') {
depth++;
i += 2;
} else if (sql.charAt(i) == '*' && sql.charAt(i + 1) == '/') {
depth--;
i += 2;
if (depth == 0) {
return i;
}
} else {
i++;
}
}
return sql.length();
}
private record Located(int at, String statement) {}
/** What a script's {@code .sql.conf} says about the transaction; nothing leaves it to Flyway. */
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.testkit.migration;
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
@@ -21,6 +22,11 @@ import org.flywaydb.core.api.output.MigrateResult;
* <p>Validation runs after migration rather than instead of it, because a migration can apply
* successfully and still leave a schema the provider disagrees with: a column type that Hibernate
* maps differently is applied without complaint and fails at the first query.
*
* <p>Every Flyway here starts from {@code FlywaySchemaPolicy.configure()}, the settings the
* template migrates with: a concurrent index migration that finishes in a deploy finishes here, and
* one that would stop a deploy under Flyway's default lock is not hidden by a different one
* (re-review 2026-11-03 round 6, RR6-03-01).
*/
public final class MigrationContractRunner {
@@ -46,7 +52,7 @@ public final class MigrationContractRunner {
restore(scenario.snapshot());
Flyway flyway =
Flyway.configure()
FlywaySchemaPolicy.configure()
.dataSource(dataSource)
.locations(migrationLocation)
.cleanDisabled(false)
@@ -58,7 +64,7 @@ public final class MigrationContractRunner {
}
private void cleanDatabase() {
Flyway.configure()
FlywaySchemaPolicy.configure()
.dataSource(dataSource)
.locations(migrationLocation)
.cleanDisabled(false)
@@ -83,7 +89,7 @@ public final class MigrationContractRunner {
.restoreLocation()
.ifPresent(
location ->
Flyway.configure()
FlywaySchemaPolicy.configure()
.dataSource(dataSource)
.locations(location)
.target(snapshot.startingVersion())
@@ -13,9 +13,11 @@ plugins {
// The package was self-contained — it imported `application.notification`, JPA, Hibernate, Spring
// Data, JDBC and Flyway, and not one type from any other `persistence.*` package — so the move
// needed no seam. It contributes entities, repositories and stores to whatever persistence unit the
// application already has. Its one `persistence-jpa` import is `CallerTransaction`: every store
// application already has. It imports two `persistence-jpa` types. `CallerTransaction`: every store
// write joins the use case's transaction, and the guard that refuses a write without one lives
// there, once (owner decision 33, review X1-#4).
// there, once (owner decision 33, review X1-#4). `FlywaySchemaPolicy`: the schema stream builds its
// Flyway from it, so it takes Flyway's PostgreSQL lock the way every stream does (re-review
// 2026-11-03 round 6, RR6-03-01).
//
// The migrations moved with their bytes and their classpath location unchanged
// (`db/migration/jpa/notification-platform`), so Flyway computes the same version and checksum
@@ -1,5 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.notification;
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
import java.util.Objects;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
@@ -55,7 +56,7 @@ public final class NotificationSchemaStream {
*/
public int migrate() {
Flyway flyway =
Flyway.configure()
FlywaySchemaPolicy.configure()
.dataSource(dataSource)
.locations(LOCATION)
.table(HISTORY_TABLE)
@@ -22,7 +22,10 @@ import java.util.concurrent.atomic.AtomicLong;
* {@code LiveRedisSemanticPortsTest}.
*
* <p>Time is explicit: {@link #advance(Duration)} is the only way the clock moves, so a TTL
* assertion is never a race.
* assertion is never a race. A hash expires as a key does once a program gave it a TTL — the
* idempotency programs do ({@code PEXPIRE}) — so a record lives exactly as long under this clock as
* the program makes it live on a server (round6 RR6-02-02: the records here never expired, so a
* contract case about a record's lifetime passed whatever TTL the program set).
*/
public final class InMemorySemanticRedisCommands implements SemanticRedisCommands {
@@ -30,6 +33,9 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
private final Map<String, Map<String, HashEntry>> hashes = new TreeMap<>();
/** When a hash expires, for the hashes a program gave a TTL; a hash without one never does. */
private final Map<String, Long> hashExpiresAtMillis = new HashMap<>();
private final Map<String, String> scriptSources = new HashMap<>();
private final AtomicLong clockMillis = new AtomicLong(System.currentTimeMillis());
@@ -187,6 +193,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
String fingerprint = text(arguments.get(2));
long nowMillis = now();
long leaseTtl = Long.parseLong(text(arguments.get(5)));
String afterLease = text(arguments.get(6));
String state = field(rendered, "state");
if (state == null) {
setField(rendered, "state", "CLAIMED");
@@ -196,6 +203,8 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
setField(rendered, "op", operationId);
setField(rendered, "fp", fingerprint);
setField(rendered, "leaseUntil", Long.toString(nowMillis + leaseTtl));
setField(rendered, "afterLease", afterLease);
expireHashAfter(rendered, leaseTtl + Long.parseLong(afterLease));
return reply("ACQUIRED", 1, 1, ownerToken, "", Long.toString(nowMillis + leaseTtl));
}
if (!fingerprint.equals(field(rendered, "fp"))) {
@@ -212,24 +221,15 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
rev,
owner,
field(rendered, "resp") == null ? "" : field(rendered, "resp"),
"60000");
Long.toString(hashTtlMillis(rendered)));
}
if ("ABANDONED".equals(state)) {
return reply("RECOVERY_REQUIRED", attempt, rev, owner, "", "");
}
if (ownerToken.equals(owner)) {
return operationId.equals(op)
? reply("REPLAYED_ACQUIRE", attempt, rev, owner, "", field(rendered, "leaseUntil"))
: reply("OWNER_OPERATION_CONFLICT", attempt, rev, owner, "", "");
}
long leaseUntil = Long.parseLong(field(rendered, "leaseUntil"));
boolean leaseOver = leaseUntil <= nowMillis;
// As the program: an expired EXECUTING record has an unknown effect, so it is answered
// RECOVERY_REQUIRED, never taken over (re-review 2026-11-04 RR-01-11), and left to its holder,
// whose late completion is still recorded (owner decision 2026-11-04).
if ("EXECUTING".equals(state) && leaseOver) {
return reply("RECOVERY_REQUIRED", attempt, rev, owner, "", "");
}
// As the program, and in its order: what nothing ran under is taken over before a same-owner
// claim is replayed, so the holder's own attempt takes it over too (round6 RR6-02-01).
if ("FAILED_RETRYABLE".equals(state) || ("CLAIMED".equals(state) && leaseOver)) {
setField(rendered, "state", "CLAIMED");
setField(rendered, "owner", ownerToken);
@@ -237,9 +237,22 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
setField(rendered, "rev", Long.toString(rev + 1));
setField(rendered, "op", operationId);
setField(rendered, "leaseUntil", Long.toString(nowMillis + leaseTtl));
setField(rendered, "afterLease", afterLease);
expireHashAfter(rendered, leaseTtl + Long.parseLong(afterLease));
return reply(
"TAKEN_OVER", attempt + 1, rev + 1, ownerToken, "", Long.toString(nowMillis + leaseTtl));
}
if (ownerToken.equals(owner)) {
return operationId.equals(op)
? reply("REPLAYED_ACQUIRE", attempt, rev, owner, "", field(rendered, "leaseUntil"))
: reply("OWNER_OPERATION_CONFLICT", attempt, rev, owner, "", "");
}
// As the program: an expired EXECUTING record has an unknown effect, so it is answered
// RECOVERY_REQUIRED, never taken over (re-review 2026-11-04 RR-01-11), and left to its holder,
// whose late completion is still recorded (owner decision 2026-11-04).
if ("EXECUTING".equals(state) && leaseOver) {
return reply("RECOVERY_REQUIRED", attempt, rev, owner, "", "");
}
return reply("IN_PROGRESS", attempt, rev, owner, "", Long.toString(leaseUntil - nowMillis));
}
@@ -251,6 +264,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
String toState = text(arguments.get(4));
String payload = text(arguments.get(5));
String leaseUntil = text(arguments.get(6));
String recordTtl = text(arguments.get(7));
String state = field(rendered, "state");
if (state == null) {
return reply("ABSENT", 0, 0, "", "", "");
@@ -266,8 +280,10 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
return reply("OPERATION_CONFLICT", attempt, rev, owner, "", "");
}
// ALREADY before the revision check, matching the program: a lost reply leaves the caller
// holding the pre-transition revision.
if (state.equals(toState)) {
// holding the pre-transition revision. A start is confirmed only to the handle it was applied
// from — the record one revision past it — because its ALREADY runs the action (round6
// RR6-02-01); any other handle falls through to NOT_OWNER or WRONG_STATE.
if (state.equals(toState) && (!"CLAIMED".equals(fromState) || rev == expectedRev + 1)) {
String stored = field(rendered, "resp");
return reply("ALREADY", attempt, rev, owner, stored == null ? "" : stored, "");
}
@@ -289,6 +305,9 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
if (!leaseUntil.isEmpty()) {
setField(rendered, "leaseUntil", Long.toString(now() + Long.parseLong(leaseUntil)));
}
if (!recordTtl.isEmpty()) {
expireHashAfter(rendered, Long.parseLong(recordTtl));
}
return reply("APPLIED", attempt, rev + 1, owner, "", "");
}
@@ -334,6 +353,14 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
setField(rendered, "rev", Long.toString(rev + 1));
setField(rendered, "renewedFromRev", handleRevision);
setField(rendered, "renewedLease", leaseMillis);
// As the program: the key's TTL is stretched, never shortened, to the new lease plus the margin
// the claim recorded behind it.
String afterLease = field(rendered, "afterLease");
long keep = Long.parseLong(leaseMillis) + (afterLease == null ? 0 : Long.parseLong(afterLease));
long ttl = hashTtlMillis(rendered);
if (ttl >= 0 && ttl < keep) {
expireHashAfter(rendered, keep);
}
return reply("APPLIED", attempt, rev + 1, owner, "", "");
}
@@ -357,6 +384,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
return reply("WRONG_STATE", attempt, rev, owner, state, "");
}
hashes.remove(rendered);
hashExpiresAtMillis.remove(rendered);
return reply("APPLIED", attempt, rev, owner, "", "");
}
@@ -393,7 +421,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
rev,
owner,
stored == null ? "" : stored,
mine + "|60000|" + (leaseUntil == null ? "" : leaseUntil));
mine + "|" + hashTtlMillis(rendered) + "|" + (leaseUntil == null ? "" : leaseUntil));
}
private static List<Object> reply(
@@ -656,11 +684,30 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand
}
}
/** Returns the live fields of a hash. */
/** Returns the live fields of a hash; one past its TTL is gone, as the server drops the key. */
private Map<String, HashEntry> hash(String rendered) {
Long expiresAt = hashExpiresAtMillis.get(rendered);
if (expiresAt != null && expiresAt <= now()) {
hashes.remove(rendered);
hashExpiresAtMillis.remove(rendered);
}
return hashes.computeIfAbsent(rendered, unusedKey -> new LinkedHashMap<>());
}
/** {@code PEXPIRE}: the hash expires {@code millis} from now. */
private void expireHashAfter(String rendered, long millis) {
hashExpiresAtMillis.put(rendered, now() + millis);
}
/** {@code PTTL}: milliseconds left, {@code -1} without a TTL, {@code -2} when the key is gone. */
private long hashTtlMillis(String rendered) {
if (hash(rendered).isEmpty()) {
return -2;
}
Long expiresAt = hashExpiresAtMillis.get(rendered);
return expiresAt == null ? -1 : expiresAt - now();
}
private Entry live(String rendered) {
Entry entry = entries.get(rendered);
if (entry == null) {
@@ -494,34 +494,101 @@ class ApplicationBoundaryArchitectureTest {
private static final String CONFIGURATION =
"org.springframework.context.annotation.Configuration";
/** The single request-handler types {@code ARE_REQUEST_HANDLER_TYPES} names beside packages. */
private static final Set<String> REQUEST_HANDLER_TYPE_NAMES =
Set.of(
"org.springframework.stereotype.Controller",
"org.springframework.messaging.handler.annotation.MessageMapping",
"org.springframework.web.HttpRequestHandler",
"org.springframework.web.servlet.HandlerInterceptor",
"org.springframework.web.servlet.mvc.Controller",
"org.springframework.web.socket.WebSocketHandler",
"org.springframework.web.socket.WebSocketSession",
"org.springframework.graphql.execution.RuntimeWiringConfigurer",
"jakarta.servlet.Servlet",
"jakarta.servlet.Filter",
"jakarta.servlet.FilterChain",
"jakarta.servlet.ServletRequest",
"jakarta.servlet.ServletResponse",
"jakarta.websocket.Endpoint",
"io.grpc.BindableService",
"io.grpc.ServerServiceDefinition",
"io.grpc.ServerCallHandler",
"io.grpc.ServerInterceptor",
"io.grpc.ServerCall",
"io.grpc.stub.StreamObserver");
/**
* A class a user request comes in through: it lives in a user-transport package, or it is built
* from a user-transport type and is not a configuration.
* The framework types request-handling code is written against: an annotated controller, a
* functional route or handler function, a servlet, filter or handler interceptor, a WebSocket
* handler, a GraphQL data fetcher, runtime wiring or request interceptor, a gRPC service, call
* handler or server interceptor. A configuration names one only when request-handling code is in
* it — a route or data fetcher written as a lambda compiles into a method of the configuration
* itself — and then the configuration is an endpoint (review 2026-11-05 RR6-01-01). The types a
* configuration names to set a transport up — {@code WebMvcConfigurer}, {@code CorsRegistry}, the
* controller beans it builds — are not here (RR4-01-02).
*
* <p>A configuration is the composition root, not a way in. A feature's configuration that
* registers its message handler beside a {@code WebMvcConfigurer} or its controller names web
* types without any request passing through it (review 2026-11-04 RR4-01-02). Leaving it out
* opens nothing: a controller the configuration builds is checked itself, by its package or its
* own transport types, and anything it is handed is a dependency of the controller.
* <p>Like the type list above, this is a list: a request-handler type missing from it is not
* recognised in a configuration (manual 07 「규칙이 못 보는 길」).
*/
private static final DescribedPredicate<JavaClass> ARE_REQUEST_HANDLER_TYPES =
JavaClass.Predicates.resideInAnyPackage(
"org.springframework.web.bind.annotation..",
"org.springframework.web.servlet.function..",
"org.springframework.web.reactive.function.server..",
"org.springframework.web.socket.handler..",
"org.springframework.graphql.data.method.annotation..",
"org.springframework.graphql.server..",
"jakarta.servlet.http..",
"graphql.schema..")
.or(
DescribedPredicate.describe(
"request-handler interfaces",
type -> REQUEST_HANDLER_TYPE_NAMES.contains(type.getName())))
.as("request-handler types (controllers, routes, servlets, filters, interceptors, ...)");
/**
* A class a user request comes in through: it lives in a user-transport package; or it is a
* configuration, or nested in one, that is built from a request-handler type; or it is any other
* class built from a user-transport type.
*
* <p>A configuration is the composition root, and naming a web type does not make it a way in: a
* feature's configuration registers its message handler beside a {@code WebMvcConfigurer} or its
* controller without any request passing through it (review 2026-11-04 RR4-01-02). A controller
* it builds is checked itself, by its package or its own transport types. What does make it a way
* in is request-handling code written in it: a functional route or a data fetcher is a lambda,
* compiled into the configuration's own method, so the configuration that holds one is the
* endpoint (review 2026-11-05 RR6-01-01). A class nested in a configuration — an anonymous {@code
* WebMvcConfigurer} reading the configuration's field — is read the same way, request handlers
* nested there included (RR6-01-02).
*/
private static final DescribedPredicate<JavaClass> ARE_USER_TRANSPORTS =
new DescribedPredicate<>(
"are user transports (in a user-transport package, or a non-configuration built from"
+ " one)") {
"are user transports (in a user-transport package, a configuration with request-handling"
+ " code, or another class built from a user-transport type)") {
@Override
public boolean test(JavaClass candidate) {
if (ARE_USER_TRANSPORT_TYPES.test(candidate)) {
return true;
}
if (candidate.isAnnotatedWith(CONFIGURATION)
|| candidate.isMetaAnnotatedWith(CONFIGURATION)) {
return false;
}
DescribedPredicate<JavaClass> wayIn =
isOrIsNestedInAConfiguration(candidate)
? ARE_REQUEST_HANDLER_TYPES
: ARE_USER_TRANSPORT_TYPES;
return candidate.getDirectDependenciesFromSelf().stream()
.anyMatch(dependency -> ARE_USER_TRANSPORT_TYPES.test(dependency.getTargetClass()));
.anyMatch(dependency -> wayIn.test(dependency.getTargetClass()));
}
};
private static boolean isOrIsNestedInAConfiguration(JavaClass candidate) {
for (JavaClass type = candidate; type != null; type = type.getEnclosingClass().orElse(null)) {
if (type.isAnnotatedWith(CONFIGURATION) || type.isMetaAnnotatedWith(CONFIGURATION)) {
return true;
}
}
return false;
}
/**
* A class marked {@link SystemCaller}, or nested in one: a handler's anonymous or inner helper
* calls the use case on the handler's behalf.
@@ -624,14 +691,17 @@ class ApplicationBoundaryArchitectureTest {
* SystemInvoked} use case, so the rules above do not see it, yet a user request then runs a write
* no permission guards (review 2026-11-04 RR3-01-01). Reaching the job's own interface, or any
* project type the job extends or implements, counts as reaching the job: that is the type the
* endpoint is handed when it injects by interface (RR4-01-01). A configuration is no transport
* and may register the handler beside web beans (RR4-01-02).
* endpoint is handed when it injects by interface (RR4-01-01). A configuration may register the
* handler beside web beans (RR4-01-02), but not beside request-handling code of its own, such as
* a functional route (RR6-01-01).
*
* <p>It reads class dependencies, so it sees every typed path, including {@code
* ObjectProvider<TheJob>} and {@code getBean(TheJob.class)}: both name the type. It cannot see a
* path that names no type the job is handed as — a lookup by bean name or by {@code Object}, or a
* configuration that passes a user transport a function wrapping the job ({@code job::run} as a
* {@code Runnable}). Manual 07 「시스템이 부르는 쓰기」 lists those paths and what holds them.
* {@code Runnable}) — nor request-handling code in a configuration written against a type {@code
* ARE_REQUEST_HANDLER_TYPES} does not list. Manual 07 「시스템이 부르는 쓰기」 lists those paths and what
* holds them.
*/
@ArchTest
static final ArchRule USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS =
@@ -641,8 +711,10 @@ class ApplicationBoundaryArchitectureTest {
.transitivelyDependOnClassesThat(ARE_TYPES_A_SYSTEM_CALLER_IS_HANDED_AS)
.as(
"USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS: a class a user request comes in "
+ "through (a user-transport package, or a non-configuration built from a web, "
+ "JAX-RS, GraphQL, gRPC or WebSocket type) does not reach a @SystemCaller or a "
+ "through (a user-transport package; a configuration, or a class nested in one, "
+ "with request-handling code such as a functional route or a data fetcher; any "
+ "other class built from a web, JAX-RS, GraphQL, gRPC or WebSocket type) does "
+ "not reach a @SystemCaller or a "
+ "project type one extends or implements, directly or through other classes — "
+ "the system caller runs a @SystemInvoked write with no permission check. A "
+ "user-triggered run of the same work is its own use case with "
@@ -659,6 +731,11 @@ class ApplicationBoundaryArchitectureTest {
* {@code job::run}, and a message handler implements the platform's {@code MessageHandler}, which
* is a project type. Anonymous and local classes are exempt: no bean has their type, and a
* function a system caller hands out from inside itself is reached only through the caller.
* Exceptions are exempt too: nothing is handed one as a bean. A record or an enum keeps the
* supertypes the language gives it — {@code Record}; {@code Enum} and what {@code Enum}
* implements — which are no more a type it is injected as than {@code Object} is, so a handler's
* parsed-message record, its outcome enum, or a handler written as a record pass, while a record
* that also implements {@code Runnable} does not (review 2026-11-05 RR6-01-03).
*/
@ArchTest
static final ArchRule SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES =
@@ -668,28 +745,34 @@ class ApplicationBoundaryArchitectureTest {
.areNotAnonymousClasses()
.and()
.areNotLocalClasses()
.and()
.areNotAssignableTo(Throwable.class)
.should(haveNoSupertypeOutsideTheProject())
.as(
"SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES: a @SystemCaller extends and implements "
+ "only project types (dev.caskeleton..), so every type it can be injected as is "
+ "one USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS follows. Instead of Runnable or "
+ "ApplicationRunner, use a @Scheduled method, an @EventListener, or pass job::run "
+ "where the job is registered (manual 07 「시스템이 부르는 쓰기」)")
+ "where the job is registered (manual 07 「시스템이 부르는 쓰기」). A record or "
+ "enum may keep the supertypes the language gives it; exceptions are exempt")
.allowEmptyShould(true);
private static ArchCondition<JavaClass> haveNoSupertypeOutsideTheProject() {
return new ArchCondition<>("have no supertype outside the project") {
@Override
public void check(JavaClass item, ConditionEvents events) {
Set<String> languageGiven = supertypesTheLanguageGives(item);
Set<String> foreign = new TreeSet<>();
for (JavaClass superclass : item.getAllRawSuperclasses()) {
if (!superclass.isEquivalentTo(Object.class)
&& !superclass.getName().startsWith(PROJECT_PACKAGE_PREFIX)) {
&& !superclass.getName().startsWith(PROJECT_PACKAGE_PREFIX)
&& !languageGiven.contains(superclass.getName())) {
foreign.add(superclass.getName());
}
}
for (JavaClass type : item.getAllRawInterfaces()) {
if (!type.getName().startsWith(PROJECT_PACKAGE_PREFIX)) {
if (!type.getName().startsWith(PROJECT_PACKAGE_PREFIX)
&& !languageGiven.contains(type.getName())) {
foreign.add(type.getName());
}
}
@@ -707,6 +790,24 @@ class ApplicationBoundaryArchitectureTest {
};
}
/**
* What a record or an enum is given by the language: its direct superclass {@code
* java.lang.Record} or {@code java.lang.Enum}, which only the compiler writes, and everything
* that superclass extends or implements. Empty for any other class.
*/
private static Set<String> supertypesTheLanguageGives(JavaClass item) {
Set<String> given = new HashSet<>();
item.getRawSuperclass()
.filter(base -> base.isEquivalentTo(Record.class) || base.isEquivalentTo(Enum.class))
.ifPresent(
base -> {
given.add(base.getName());
base.getAllRawSuperclasses().forEach(type -> given.add(type.getName()));
base.getAllRawInterfaces().forEach(type -> given.add(type.getName()));
});
return given;
}
/**
* {@link IntegrationEventDrafts} is where contract id, version, destination and correlation are
* decided for every feature. A feature that calls the ten-field draft constructor itself restates
@@ -56,8 +56,8 @@ class ArchRuleDiscoveryContractTest {
* <p>Comment lines between the annotation and the declaration are skipped, and that is not a
* cosmetic allowance: the first version of this pattern required the declaration on the next line
* and therefore did not see {@code SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES},
* whose nine-line "known defect" note sits in between. A rule could have hidden from this guard
* by being commented — which is precisely the kind of rule most worth keeping an eye on.
* which then had a nine-line "known defect" note in between. A rule could have hidden from this
* guard by being commented — which is precisely the kind of rule most worth keeping an eye on.
*/
private static final Pattern ARCH_TEST_FIELD =
Pattern.compile(
@@ -2,15 +2,19 @@ package dev.caskeleton.bootstrap.architecture;
import static org.assertj.core.api.Assertions.assertThat;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.lang.EvaluationResult;
import dev.caskeleton.application.architecture.violations.ApplicationDiagnosticFrameworkViolation;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.RecordSystemCallerFixture;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerRegistrationFixture;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerWithNestedValueTypesFixture;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.web.PingControllerFixture;
import dev.caskeleton.bootstrap.architecture.allowed.application.CleanProjectionQueryPort;
import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideControllerRegistrationFixture;
import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideFieldReadingWebMvcConfigurerFixture;
import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideWebMvcRegistrationFixture;
import dev.caskeleton.bootstrap.architecture.fixtures.application.RootWriteTransactionBoundaryUseCase;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.SystemCallerRestControllerFixture;
@@ -18,6 +22,7 @@ import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messagin
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.IndirectlyRunnableSystemJobFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.InterfaceExposedSystemJobFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.RunNowJobFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.RunnableRecordSystemJobFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.RunnableSystemJobFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.ScheduledWorkFixture;
import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler.SystemCallerWithNestedEndpointFixture;
@@ -39,6 +44,8 @@ import dev.caskeleton.bootstrap.architecture.violations.application.OutboundWith
import dev.caskeleton.bootstrap.architecture.violations.application.RawLeakQueryPort;
import dev.caskeleton.bootstrap.architecture.violations.application.ReadOnlyRepositoryWriteUseCase;
import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase;
import dev.caskeleton.bootstrap.architecture.violations.configuration.RunNowHandlerFunctionConfigurationFixture;
import dev.caskeleton.bootstrap.architecture.violations.configuration.RunNowRouteConfigurationFixture;
import dev.caskeleton.bootstrap.architecture.violations.domain.AnnotatedPublicNoArgValueObjectFixture;
import dev.caskeleton.bootstrap.architecture.violations.domain.JakartaValidationDomainFixture;
import dev.caskeleton.bootstrap.architecture.violations.domain.entity.FakeDomainEntity;
@@ -298,6 +305,65 @@ class ArchitectureViolationFixtureTest {
.importPackages(
"dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.graphqljava");
// Review 2026-11-05 RR6-01-01: "run now" endpoints written in a configuration — a functional
// route
// and a graphql-java data fetcher, each a lambda compiled into the configuration itself. The data
// fetcher's package is imported (graphql-java is compile-only) with the handler's.
private static final JavaClasses ROUTE_IN_A_CONFIGURATION_FIXTURE_ONLY =
new ClassFileImporter()
.importClasses(
RunNowRouteConfigurationFixture.class,
SystemCallerHandlerFixture.class,
SystemInvokedFixtureUseCase.class);
private static final JavaClasses DATA_FETCHER_IN_A_CONFIGURATION_FIXTURE_ONLY =
new ClassFileImporter()
.importPackages(
"dev.caskeleton.bootstrap.architecture.violations.configuration.graphqljava",
"dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging");
// RR6-01-02: a class nested in a configuration is read as the configuration is — a request
// handler
// nested there is still a transport, a configurer reading the configuration's field is not.
private static final JavaClasses HANDLER_FUNCTION_NESTED_IN_A_CONFIGURATION_FIXTURE_ONLY =
new ClassFileImporter()
.importClasses(
RunNowHandlerFunctionConfigurationFixture.class,
RunNowHandlerFunctionConfigurationFixture.RunNowHandler.class,
SystemCallerHandlerFixture.class,
SystemInvokedFixtureUseCase.class);
// The anonymous configurer has no class literal, so the two packages are imported and narrowed to
// the configuration (with what is nested in it) and the handler.
private static final JavaClasses FIELD_READING_CONFIGURER_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY =
new ClassFileImporter()
.importPackages(
"dev.caskeleton.bootstrap.architecture.allowed.configuration",
"dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging")
.that(
JavaClass.Predicates.belongToAnyOf(
SystemCallerBesideFieldReadingWebMvcConfigurerFixture.class,
SystemCallerHandlerFixture.class));
// RR6-01-03: a system caller's nested record, enum and exception, and a system caller that is a
// record — none of them a type an endpoint injects it as.
private static final JavaClasses SYSTEM_CALLER_WITH_NESTED_VALUE_TYPES_FIXTURE_ONLY =
new ClassFileImporter()
.importClasses(
SystemCallerWithNestedValueTypesFixture.class,
SystemCallerWithNestedValueTypesFixture.Parsed.class,
SystemCallerWithNestedValueTypesFixture.Outcome.class,
SystemCallerWithNestedValueTypesFixture.PoisonMessageException.class,
SystemInvokedFixtureUseCase.class);
private static final JavaClasses RECORD_SYSTEM_CALLER_FIXTURE_ONLY =
new ClassFileImporter()
.importClasses(RecordSystemCallerFixture.class, SystemInvokedFixtureUseCase.class);
private static final JavaClasses RUNNABLE_RECORD_SYSTEM_JOB_FIXTURE_ONLY =
new ClassFileImporter()
.importClasses(RunnableRecordSystemJobFixture.class, SystemInvokedFixtureUseCase.class);
// Review 2026-11-03 RR-01-03: one class that builds the draft by hand.
private static final JavaClasses HAND_BUILT_DRAFT_FIXTURE_ONLY =
new ClassFileImporter().importClasses(HandBuiltIntegrationEventDraftFixture.class);
@@ -495,6 +561,109 @@ class ArchitectureViolationFixtureTest {
detail -> assertThat(detail).contains("graphql.schema.DataFetchingEnvironment"));
}
@Test
void aConfigurationWhoseFunctionalRouteCallsASystemCallerIsCaught() {
// when
EvaluationResult result =
ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate(
ROUTE_IN_A_CONFIGURATION_FIXTURE_ONLY);
// then
assertThat(result.getFailureReport().getDetails())
.anySatisfy(
detail ->
assertThat(detail)
.contains("<" + RunNowRouteConfigurationFixture.class.getName() + ">")
.contains(SystemCallerHandlerFixture.class.getName()));
}
@Test
void aConfigurationWhoseDataFetcherCallsASystemCallerIsCaught() {
// when
EvaluationResult result =
ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate(
DATA_FETCHER_IN_A_CONFIGURATION_FIXTURE_ONLY);
// then
assertThat(result.getFailureReport().getDetails())
.anySatisfy(
detail ->
assertThat(detail)
.contains(
"<dev.caskeleton.bootstrap.architecture.violations.configuration.graphqljava"
+ ".RunNowDataFetcherConfigurationFixture>")
.contains(SystemCallerHandlerFixture.class.getName()));
}
@Test
void aRequestHandlerNestedInAConfigurationThatCallsASystemCallerIsCaught() {
// when
EvaluationResult result =
ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate(
HANDLER_FUNCTION_NESTED_IN_A_CONFIGURATION_FIXTURE_ONLY);
// then
assertThat(result.getFailureReport().getDetails())
.anySatisfy(
detail ->
assertThat(detail)
.contains(
"<"
+ RunNowHandlerFunctionConfigurationFixture.RunNowHandler.class
.getName()
+ ">")
.contains(SystemCallerHandlerFixture.class.getName()));
}
@Test
void aWebMvcConfigurerNestedInAConfigurationMayReadTheConfigurationsField() {
// when
EvaluationResult result =
ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate(
FIELD_READING_CONFIGURER_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY);
// then
assertThat(result.getFailureReport().getDetails()).isEmpty();
}
@Test
void aSystemCallersNestedRecordEnumAndExceptionPassTheSupertypeRule() {
// when
EvaluationResult result =
ApplicationBoundaryArchitectureTest.SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES.evaluate(
SYSTEM_CALLER_WITH_NESTED_VALUE_TYPES_FIXTURE_ONLY);
// then
assertThat(result.getFailureReport().getDetails()).isEmpty();
}
@Test
void aSystemCallerWrittenAsARecordPassesTheSupertypeRule() {
// when
EvaluationResult result =
ApplicationBoundaryArchitectureTest.SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES.evaluate(
RECORD_SYSTEM_CALLER_FIXTURE_ONLY);
// then
assertThat(result.getFailureReport().getDetails()).isEmpty();
}
@Test
void aSystemCallerRecordThatIsARunnableIsCaughtForTheRunnableAlone() {
// when
EvaluationResult result =
ApplicationBoundaryArchitectureTest.SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES.evaluate(
RUNNABLE_RECORD_SYSTEM_JOB_FIXTURE_ONLY);
// then
assertThat(result.getFailureReport().getDetails())
.anySatisfy(
detail ->
assertThat(detail)
.contains(RunnableRecordSystemJobFixture.class.getName())
.contains("[" + Runnable.class.getName() + "]"));
}
@Test
void aFeatureThatBuildsAnIntegrationEventDraftByHandIsCaught() {
EvaluationResult result =
@@ -645,19 +814,6 @@ class ArchitectureViolationFixtureTest {
.isFalse();
}
@Test
void sharedContractScopeRuleCatchesDomainSpecificSharedPackage() {
EvaluationResult result =
ForbiddenApiArchitectureTest.SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES
.evaluate(VIOLATION_CLASSES);
assertThat(result.hasViolation())
.as(
"SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES must catch "
+ "a domain-specific package under ..shared.worklog..")
.isTrue();
}
@Test
void externalOutboundCallsRequireExternalOutboundAllowedCapabilityCatchesUnpermittedCall() {
EvaluationResult result =
@@ -24,6 +24,7 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.regex.Pattern;
import org.hibernate.type.SqlTypes;
@@ -47,40 +48,39 @@ import org.hibernate.type.SqlTypes;
@AnalyzeClasses(packages = "dev.caskeleton", importOptions = ProductionClassImportOption.class)
class ForbiddenApiArchitectureTest {
private static ArchCondition<JavaClass> resideInAllowedSharedContractPackage() {
return new ArchCondition<>("reside in an allowed shared operational contract package") {
private final Set<String> allowedPackages =
Set.of(
"dev.caskeleton.shared",
"dev.caskeleton.shared.response",
"dev.caskeleton.shared.request",
"dev.caskeleton.shared.error",
"dev.caskeleton.shared.logging",
"dev.caskeleton.shared.tracing",
"dev.caskeleton.shared.metrics",
// Not this module at all — see the defect note on the rule above. The Mongo leaf has
// a
// tenancy.shared package of its own and only began tripping this rule when that leaf
// joined the composition root's analysis scope.
"dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.shared",
// feature-authentication-authorization-contract: the Permission
// (resource:action) value object is a Java-only operational
// authorization contract consumed by AuthorizationPort.
"dev.caskeleton.shared.security",
// feature-runtime-context-propagation-contract: the domain-context
// propagation port + its ThreadLocal implementation.
"dev.caskeleton.shared.concurrency");
/**
* The packages shared-contract consists of, below its root {@code dev.caskeleton.shared}. Each is
* a skeleton-wide operational contract with its reason in the module's CLAUDE.md
* 「Responsibility」; the root itself holds only its {@code package-info}. A package that is not
* here is refused, so a business concept cannot settle in the module unnoticed. Adding a contract
* package means adding it here and to that list; {@code SharedContractPackageRuleTest} fails when
* this list and the module's packages differ.
*/
static final Set<String> SHARED_CONTRACT_PACKAGES =
Set.of(
"concurrency",
"digest",
"error",
"metrics",
"observability",
"ratelimit",
"request",
"response",
"retry",
"runtime",
"security",
"tracing");
private static ArchCondition<JavaClass> resideInASharedContractPackageBelow(String root) {
Set<String> listed = new TreeSet<>(SHARED_CONTRACT_PACKAGES);
return new ArchCondition<>("reside in one of the shared contract packages " + listed) {
@Override
public void check(JavaClass item, ConditionEvents events) {
String packageName = item.getPackageName();
boolean allowed = false;
for (String allowedPackage : allowedPackages) {
if (packageName.equals(allowedPackage) || packageName.startsWith(allowedPackage + ".")) {
allowed = true;
break;
}
}
boolean allowed =
packageName.equals(root)
? "package-info".equals(item.getSimpleName())
: listed.contains(packageName.substring(root.length() + 1).split("\\.", 2)[0]);
if (!allowed) {
events.add(
SimpleConditionEvent.violated(
@@ -89,29 +89,41 @@ class ForbiddenApiArchitectureTest {
+ item.getName()
+ " resides in "
+ packageName
+ ", which is not an allowed shared operational contract package"));
+ ", which is not one of the shared contract packages below "
+ root
+ " "
+ listed));
}
}
};
}
/**
* shared-contract holds skeleton-wide operational contracts and nothing else (its CLAUDE.md
* 「Forbidden」: no business or domain concept). This is the module's only package check.
*/
@ArchTest
// KNOWN DEFECT, deliberately left as found. Two things are wrong and they mask each other: the
// subject pattern "..shared.." CleanArchitectureRuleSupport.matches any package named shared
// anywhere rather than this module,
// and the allowlist below holds the bare module root while the check
// CleanArchitectureRuleSupport.matches by prefix — so every
// package inside dev.caskeleton.shared is blessed automatically. The rule therefore catches
// nothing in the module it is named after, and does catch unrelated leaves that happen to have a
// "shared" package. Fixing it needs the violation fixture to move inside dev.caskeleton.shared,
// which puts it in this rule's own analysis scope, which needs the fixture-scanning structure
// reworked. That is a separate change; see the Wave 1 progress note.
static final ArchRule SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES =
classes()
.that()
.resideInAPackage("..shared..")
.should(resideInAllowedSharedContractPackage())
.allowEmptyShould(true);
sharedContractContainsOnlyOperationalContractPackages("dev.caskeleton.shared");
/**
* The rule for a module rooted at {@code root}. Production passes {@code dev.caskeleton.shared};
* the fixtures pass a stand-in root, so they prove the rule without living inside the module
* (review 2026-11-05 RR6-01-09).
*/
static ArchRule sharedContractContainsOnlyOperationalContractPackages(String root) {
return classes()
.that()
.resideInAPackage(root + "..")
.should(resideInASharedContractPackageBelow(root))
.as(
"SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES: every class below "
+ root
+ " lives in one of the listed operational contract packages, and the root holds"
+ " only its package-info; a business or domain concept belongs to the module that"
+ " owns it (shared-contract CLAUDE.md)")
.allowEmptyShould(true);
}
@ArchTest
static final ArchRule NO_JACKSON_LAISSEZ_FAIRE_SUBTYPE_VALIDATOR =
@@ -1,9 +1,11 @@
package dev.caskeleton.bootstrap.architecture;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static org.assertj.core.api.Assertions.assertThat;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
import dev.caskeleton.adapter.outbound.persistence.testkit.arch.JpaArchitectureRules;
import jakarta.persistence.Entity;
import java.util.List;
@@ -162,6 +164,31 @@ class JpaProductionArchitectureTest {
.check(productionClasses);
}
@Test
@DisplayName("Flyway.configure()를 부르는 운영 코드는 FlywaySchemaPolicy뿐이다")
void everyProductionFlywayIsConfiguredThroughTheSchemaPolicy() {
// Flyway's PostgreSQL default holds its lock in a transaction left open for the whole run, and
// a concurrent index build waits for it without end (re-review 2026-11-03 round 6, RR6-03-01).
// FlywaySchemaPolicy.configure() holds it for the session; a stream that builds its own Flyway
// gets the default back. The inbox stream of adapter:inbound:messaging may not depend on
// persistence-jpa and keeps its own copy, held to the same value by its own test.
noClasses()
.that()
.doNotHaveFullyQualifiedName(FlywaySchemaPolicy.class.getName())
.and()
.doNotHaveFullyQualifiedName(
"dev.caskeleton.adapter.inbound.messaging.MessagingInboxSchemaStream")
.should()
.callMethod("org.flywaydb.core.Flyway", "configure")
.orShould()
.callMethod("org.flywaydb.core.Flyway", "configure", "java.lang.ClassLoader")
.because(
"every Flyway the template builds starts from FlywaySchemaPolicy.configure(), which"
+ " holds Flyway's PostgreSQL lock for the session (docs/jpa/migration-guide.md,"
+ " \"Concurrent index builds\")")
.check(productionClasses);
}
@Test
@DisplayName("no tenant-scoped repository inherits the tenant-blind CRUD surface")
void noTenantScopedRepositoryInheritsBroadCrud() {
@@ -0,0 +1,121 @@
package dev.caskeleton.bootstrap.architecture;
import static org.assertj.core.api.Assertions.assertThat;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.lang.EvaluationResult;
import dev.caskeleton.bootstrap.architecture.violations.shared.BusinessRuleAtTheSharedRootFixture;
import dev.caskeleton.bootstrap.architecture.violations.shared.worklog.WorkLogStatus;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
/**
* {@code SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES} catches what it claims inside
* the shared-contract module, and its package list names exactly the packages the module has.
*
* <p>The rule takes the module root as a parameter, so its fixtures prove it under a stand-in root
* ({@code violations.shared}, {@code allowed.shared}) instead of living in {@code
* dev.caskeleton.shared} itself (review 2026-11-05 RR6-01-09).
*/
class SharedContractPackageRuleTest {
private static final String VIOLATION_ROOT =
"dev.caskeleton.bootstrap.architecture.violations.shared";
private static final String ALLOWED_ROOT = "dev.caskeleton.bootstrap.architecture.allowed.shared";
private static final String MODULE_ROOT = "dev.caskeleton.shared";
@Test
void aBusinessPackageInsideTheSharedContractIsCaught() {
// given
JavaClasses workLogPackage = new ClassFileImporter().importClasses(WorkLogStatus.class);
// when
EvaluationResult result =
ForbiddenApiArchitectureTest.sharedContractContainsOnlyOperationalContractPackages(
VIOLATION_ROOT)
.evaluate(workLogPackage);
// then
assertThat(result.getFailureReport().getDetails())
.anySatisfy(detail -> assertThat(detail).contains(WorkLogStatus.class.getName()));
}
@Test
void aClassDirectlyInTheSharedContractRootIsCaught() {
// given
JavaClasses rootClass =
new ClassFileImporter().importClasses(BusinessRuleAtTheSharedRootFixture.class);
// when
EvaluationResult result =
ForbiddenApiArchitectureTest.sharedContractContainsOnlyOperationalContractPackages(
VIOLATION_ROOT)
.evaluate(rootClass);
// then
assertThat(result.getFailureReport().getDetails())
.anySatisfy(
detail ->
assertThat(detail).contains(BusinessRuleAtTheSharedRootFixture.class.getName()));
}
@Test
void aListedContractPackageAndTheRootPackageInfoPassTheRule() {
// given
JavaClasses contractShape = new ClassFileImporter().importPackages(ALLOWED_ROOT);
// when
EvaluationResult result =
ForbiddenApiArchitectureTest.sharedContractContainsOnlyOperationalContractPackages(
ALLOWED_ROOT)
.evaluate(contractShape);
// then
assertThat(result.getFailureReport().getDetails()).isEmpty();
}
@Test
void aPackageNamedSharedOutsideTheSharedContractModuleIsNotChecked() {
// given
JavaClasses otherSharedPackage = new ClassFileImporter().importClasses(WorkLogStatus.class);
// when
EvaluationResult result =
ForbiddenApiArchitectureTest.SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES
.evaluate(otherSharedPackage);
// then
assertThat(result.getFailureReport().getDetails()).isEmpty();
}
@Test
void thePackageListNamesExactlyThePackagesTheSharedContractHas() {
// when
JavaClasses module =
new ClassFileImporter()
.withImportOption(new ProductionClassImportOption())
.importPackages(MODULE_ROOT);
// then
assertThat(topLevelPackages(module))
.as(
"ForbiddenApiArchitectureTest.SHARED_CONTRACT_PACKAGES names a package"
+ " dev.caskeleton.shared no longer has, or misses one it has")
.isEqualTo(new TreeSet<>(ForbiddenApiArchitectureTest.SHARED_CONTRACT_PACKAGES));
}
private static Set<String> topLevelPackages(JavaClasses classes) {
String prefix = MODULE_ROOT + ".";
return classes.stream()
.map(JavaClass::getPackageName)
.filter(name -> name.startsWith(prefix))
.map(name -> name.substring(prefix.length()).split("\\.", 2)[0])
.collect(Collectors.toCollection(TreeSet::new));
}
}
@@ -0,0 +1,17 @@
package dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging;
import dev.caskeleton.application.security.SystemCaller;
import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase;
/**
* A handler written as a record. {@code java.lang.Record} is a supertype the language gives every
* record, as {@code Object} is for a class, so it is no type an endpoint injects the handler as
* (review 2026-11-05 RR6-01-03).
*/
@SystemCaller(reason = "fixture: the broker consumer calls it for each delivery")
public record RecordSystemCallerFixture(String destination) {
public void handle() {
new SystemInvokedFixtureUseCase().handle();
}
}
@@ -0,0 +1,36 @@
package dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging;
import dev.caskeleton.application.security.SystemCaller;
import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase;
/**
* A handler with the nested types a consumer usually keeps to itself: the parsed message as a
* record, the outcome as an enum, and the poison-message failure. None of them is a bean, so none
* is a type an endpoint could be handed the handler as (review 2026-11-05 RR6-01-03).
*/
@SystemCaller(reason = "fixture: the broker consumer calls it for each delivery")
public final class SystemCallerWithNestedValueTypesFixture {
private final SystemInvokedFixtureUseCase useCase = new SystemInvokedFixtureUseCase();
public Outcome handle(Parsed parsed) {
if (parsed.id().isEmpty()) {
throw new PoisonMessageException();
}
useCase.handle();
return Outcome.DONE;
}
/** The delivery after parsing. */
public record Parsed(String id) {}
/** What handling came to. */
public enum Outcome {
DONE
}
/** A delivery that can never be handled. */
public static final class PoisonMessageException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
}
@@ -0,0 +1,42 @@
package dev.caskeleton.bootstrap.architecture.allowed.configuration;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* One feature configuration: a web MVC customisation that reads the configuration's own setting,
* and the feature's message handler. The anonymous configurer depends on the configuration through
* the field it reads, and the configuration on the handler; the configurer is part of the
* configuration, not a way in (review 2026-11-05 RR6-01-02).
*
* <p>The review's probe read a CORS origin; this reads an async timeout instead, because
* FindSecBugs' CORS detector fails to analyse an origin read from a field, and the test-source
* SpotBugs gate treats an incomplete analysis as a failure.
*/
@Configuration(proxyBeanMethods = false)
public class SystemCallerBesideFieldReadingWebMvcConfigurerFixture {
private final long asyncTimeoutMillis;
public SystemCallerBesideFieldReadingWebMvcConfigurerFixture(long asyncTimeoutMillis) {
this.asyncTimeoutMillis = asyncTimeoutMillis;
}
@Bean
WebMvcConfigurer featureAsyncTimeout() {
return new WebMvcConfigurer() {
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(asyncTimeoutMillis);
}
};
}
@Bean
SystemCallerHandlerFixture systemCallerHandler() {
return new SystemCallerHandlerFixture();
}
}
@@ -0,0 +1,7 @@
package dev.caskeleton.bootstrap.architecture.allowed.shared.error;
/** A transport-neutral error contract, in the {@code error} package the shared contract lists. */
public interface SharedErrorContractFixture {
String code();
}
@@ -0,0 +1,6 @@
/**
* "Allowed-as-data" stand-in for the shared-contract module root {@code dev.caskeleton.shared}:
* {@code SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES} checked with this package as
* its root must accept the root's {@code package-info} and a class in a listed contract package.
*/
package dev.caskeleton.bootstrap.architecture.allowed.shared;
@@ -0,0 +1,18 @@
package dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.scheduler;
import dev.caskeleton.application.security.SystemCaller;
import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase;
/**
* A marked job written as a record that also implements {@link Runnable}. The record supertype is
* the language's and is ignored; {@code Runnable} is not, so an endpoint injecting a {@code
* Runnable} could still be handed this job.
*/
@SystemCaller(reason = "fixture: the scheduler ticks it")
public record RunnableRecordSystemJobFixture(String name) implements Runnable {
@Override
public void run() {
new SystemInvokedFixtureUseCase().handle();
}
}
@@ -0,0 +1,39 @@
package dev.caskeleton.bootstrap.architecture.violations.configuration;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.function.HandlerFunction;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;
/**
* Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: the configuration
* itself names no request-handler type, but the handler function it registers is a class nested in
* it. A class nested in a configuration is read as the configuration is, request handlers included,
* so the nested endpoint is still a user transport (review 2026-11-05 RR6-01-02).
*/
@Configuration(proxyBeanMethods = false)
public class RunNowHandlerFunctionConfigurationFixture {
@Bean
RunNowHandler runNowHandler(SystemCallerHandlerFixture handler) {
return new RunNowHandler(handler);
}
/** The "run now" endpoint, kept beside the configuration that registers it. */
public static final class RunNowHandler implements HandlerFunction<ServerResponse> {
private final SystemCallerHandlerFixture handler;
RunNowHandler(SystemCallerHandlerFixture handler) {
this.handler = handler;
}
@Override
public ServerResponse handle(ServerRequest request) {
handler.handle();
return ServerResponse.accepted().build();
}
}
}
@@ -0,0 +1,30 @@
package dev.caskeleton.bootstrap.architecture.violations.configuration;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;
/**
* Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a "run now" endpoint
* written as a Spring MVC functional route in a feature configuration. The handler is a lambda,
* which compiles into a method of this class, so the configuration is the endpoint and a user
* request runs the system caller (review 2026-11-05 RR6-01-01).
*/
@Configuration(proxyBeanMethods = false)
public class RunNowRouteConfigurationFixture {
@Bean
RouterFunction<ServerResponse> runNowRoute(SystemCallerHandlerFixture handler) {
return RouterFunctions.route()
.POST(
"/admin/nightly/run-now",
request -> {
handler.handle();
return ServerResponse.accepted().build();
})
.build();
}
}
@@ -0,0 +1,24 @@
package dev.caskeleton.bootstrap.architecture.violations.configuration.graphqljava;
import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture;
import graphql.schema.DataFetcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a GraphQL "runNow"
* mutation whose graphql-java data fetcher is a lambda in a feature configuration, so the
* configuration is the endpoint (review 2026-11-05 RR6-01-01). Loaded with {@code importPackages}:
* graphql-java is compile-only for this source set.
*/
@Configuration(proxyBeanMethods = false)
public class RunNowDataFetcherConfigurationFixture {
@Bean
DataFetcher<Boolean> runNowFetcher(SystemCallerHandlerFixture handler) {
return environment -> {
handler.handle();
return Boolean.TRUE;
};
}
}
@@ -0,0 +1,14 @@
package dev.caskeleton.bootstrap.architecture.violations.shared;
/**
* Intentional violation of {@code SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES},
* checked with this package standing in for the module root {@code dev.caskeleton.shared}: a class
* placed directly in the root rather than in one of the contract packages. The root holds only its
* {@code package-info}.
*/
public final class BusinessRuleAtTheSharedRootFixture {
public boolean eligible(int age) {
return age >= 19;
}
}
+5 -1
View File
@@ -267,7 +267,11 @@ application 계층이 claim·replay·복구 **정책** 을 소유하고, 저장
- action 결과는 `IdempotentAction.Outcome` 으로 분류한다. `RetryableNoEffect` 만 재시도 가능한
실패로 기록하고, `EffectUnknown` 이나 그냥 던진 예외는 "효과 불명"(`ABANDONED`)으로 남긴다.
한 번 실행됐을지 모르는 작업을 재시도로 두 번 돌리지 않기 위해서다.
- processing lease 와 replay TTL 은 따로 간다. 만료된 `CLAIMED` 만 다른 caller 가 가져갈 수 있고,
- processing lease 와 replay TTL 은 따로 간다. 넘겨받을 수 있는 것은 만료된 `CLAIMED` 와 재시도 가능한
실패뿐이고, 다음 claim 이 누구든 넘겨받는다 — 같은 attempt 를 다시 보낸 caller 도 새 attempt 번호로
넘겨받는다(라운드6 RR6-02-01: 전에는 같은 attempt 가 이 기록을 재생받아 시작을 다시 거절당했다). 넘겨받기 전
핸들은 같은 attempt 가 들고 있어도 낡은 핸들이라 시작이 확인되지 않는다. 한 attempt 를 두 호출이 동시에 쓰는
것은 가려내지 못하므로 재시도는 앞 호출이 돌아온 뒤에 한다.
만료된 `EXECUTING` 은 다른 caller 에게 `RECOVERY_REQUIRED` 로 답하되 기록은 그대로 둔다. 주인이 늦게
보고한 결과·실패는 기록된다 — 먼저 온 보고 하나만 남고 뒤의 보고는 거절된다(2026-11-04 소유자 결정,
재리뷰 RR5-01-03). lease 가 이미 끝났으면 주인도 시작(`markExecutionStarted`)과 `renew` 를 할 수 없고
@@ -4,7 +4,16 @@ import dev.caskeleton.application.transaction.OperationId;
import java.util.Objects;
import java.util.regex.Pattern;
/** Caller-retained identity for one claim send/retry sequence. */
/**
* Caller-retained identity for one claim send/retry sequence.
*
* <p>Resend with it after any answer. A claim whose reply was lost is replayed. A claim refused
* before anything ran — its start came after its lease, or its action failed retryably without
* effect — is taken over again as the attempt's next try; it used to be replayed and refused again
* until the record expired (round6 RR6-02-01, {@code IdempotencyStoreContract}). One attempt is one
* sender at a time: a handle from before a takeover is stale, but two calls sending the same
* attempt at once are not told apart — retry after the call has returned, not beside it.
*/
public record IdempotencyClaimAttempt(String ownerToken, OperationId operationId) {
private static final Pattern OWNER_TOKEN = Pattern.compile("[0-9a-f]{64}");
@@ -25,11 +25,13 @@ public sealed interface IdempotencyClaimOutcome {
}
/**
* This caller now holds a record somebody else held before: a claim whose lease ran out before it
* started executing, or an attempt marked retryable without effect. Nothing ran under the
* previous holder, so running the action is safe. A record whose execution had started is never
* taken over — its effect is unknown, and the claim answers {@link RecoveryRequired} instead
* (re-review 2026-11-04 RR-01-11, {@code IdempotencyStoreContract}).
* This caller now holds a record held before — by somebody else, or by this same attempt's
* earlier claim: a claim whose lease ran out before it started executing, or an attempt marked
* retryable without effect. Nothing ran under the previous holder, so running the action is safe.
* The attempt counter and the revision move on, so a handle from before the takeover is stale,
* even in the same attempt's hands (round6 RR6-02-01). A record whose execution had started is
* never taken over — its effect is unknown, and the claim answers {@link RecoveryRequired}
* instead (re-review 2026-11-04 RR-01-11, {@code IdempotencyStoreContract}).
*/
record TakenOverClaimed(IdempotencyOwner owner, Instant processingLeaseUntil)
implements IdempotencyClaimOutcome {
@@ -83,7 +83,9 @@ public final class IdempotencyExecutor {
}
/**
* Mints the attempt a caller retains across a lost response.
* Mints the attempt a caller retains across a lost response, and across an {@link
* IdempotencyUnavailableException} that ran nothing: executing again with it takes over a claim
* whose start came after its lease (round6 RR6-02-01, {@link IdempotencyClaimAttempt}).
*
* @param operationId the caller's operation identifier
* @return the claim attempt
@@ -193,8 +195,9 @@ public final class IdempotencyExecutor {
runStarted(request, advanced(started, owner), action, codec);
case UNAVAILABLE -> throw new IdempotencyUnavailableException();
// The claim's lease ran out before it started, so the store did not start it: nothing ran,
// and the next same-key request takes the claim over. "Not applied" is the truth here;
// "recovery required" would send the client after an effect that cannot exist (RR5-01-02).
// and the next same-key request takes the claim over — a retry with this same attempt too
// (round6 RR6-02-01). "Not applied" is the truth here; "recovery required" would send the
// client after an effect that cannot exist (RR5-01-02).
case LEASE_EXPIRED ->
throw new IdempotencyUnavailableException(
"the claim's processing lease ran out before the action started; nothing ran: "
@@ -4,7 +4,14 @@ package dev.caskeleton.application.idempotency;
public enum IdempotencyStartOutcome {
/** The claim is now executing; the returned handle carries the advanced revision. */
STARTED(true),
/** This exact start was already applied (a lost reply); the handle is the current one. */
/**
* This exact start — from the handle presented — was already applied (a lost reply); the handle
* returned is the current one. Another handle of the same attempt meeting a record that is
* already executing is not this: one from before a takeover is {@link #NOT_OWNER}, the current
* one a replayed claim returned is {@link #NOT_CLAIMED} (round6 RR6-02-01 — the Redis store
* confirmed both and the action ran twice; the PostgreSQL store answered {@link
* #OPERATION_CONFLICT}).
*/
ALREADY_STARTED_SAME_OPERATION(true),
/** No record exists: it expired, was released, or was never there. */
ABSENT(false),
@@ -19,9 +26,11 @@ public enum IdempotencyStartOutcome {
* The caller still holds the claim, but its processing lease ran out before it started, so it is
* not started and nothing ran. The lease is the window a claim has to start in: once it has run
* out the next claim takes the record over and runs it, as it does when the holder never comes
* back. Starting anyway would leave an execution that every other request is told is past its
* lease — "recovery required" instead of "in progress" — from its first moment. Both stores
* refuse the same start (re-review 2026-11-04 README 15 — the Redis store started it).
* back — the holder's own retry with the same attempt included (round6 RR6-02-01: it used to be
* replayed this claim and refused again). Starting anyway would leave an execution that every
* other request is told is past its lease — "recovery required" instead of "in progress" — from
* its first moment. Both stores refuse the same start (re-review 2026-11-04 README 15 — the Redis
* store started it).
*/
LEASE_EXPIRED(false),
/** The same operation id already started this record with different arguments. */
@@ -55,7 +55,10 @@ import org.junit.jupiter.api.Test;
* <li>a claim whose lease ran out before it started is not started by its holder either ({@code
* LEASE_EXPIRED}): nothing ran, so the next claim takes it over and runs it (re-review
* 2026-11-04 README 15 — the Redis store started it, the PostgreSQL store refused it as
* {@code NOT_OWNER});
* {@code NOT_OWNER}) — the refused caller's own retry with the same attempt included. That
* retry used to be replayed the claim it already held, whose start was refused again, until
* the record expired (round6 RR6-02-01). The handle it held before the takeover is stale: a
* late start through it is not confirmed as the start that followed the takeover;
* <li>a record outlives its processing lease by the replay TTL, whatever the two are set to. A
* record that expired first — Redis at its key TTL, PostgreSQL at the reaper — let the next
* claim of a running operation acquire it fresh (re-review 2026-11-04 RR-03-11), and one that
@@ -63,10 +66,10 @@ import org.junit.jupiter.api.Test;
* </ul>
*
* <p>A store reaches time through {@link #elapse(Duration)}, which also runs whatever expires the
* store's records (Redis does it itself; the PostgreSQL contract runs the reaper). A store that
* cannot move its clock — the in-memory fake, which models no expiry, and the Redis store over the
* command fake — keeps the default, which aborts the timed case so the report shows it skipped
* instead of passing a case that never ran its clock (review 2026-11-03 RR-01-06).
* store's records (Redis does it itself — the command fake through its own clock and key TTL; the
* PostgreSQL contract runs the reaper). A store that cannot move its clock — the in-memory fake,
* which models no expiry — keeps the default, which aborts the timed case so the report shows it
* skipped instead of passing a case that never ran its clock (review 2026-11-03 RR-01-06).
*
* <p>Every call goes through {@link #inTransaction(Supplier)}, the way the store's callers make it:
* the PostgreSQL store refuses to run outside an application-owned write transaction.
@@ -174,7 +177,12 @@ public abstract class IdempotencyStoreContract {
}
private static IdempotencyOwner executing(IdempotencyStorePort store) {
return store.markExecutionStarted(acquire(store), OPERATION).owner().orElseThrow();
return started(store, acquire(store));
}
/** Starts a claim, failing the case when the store does not start it. */
private static IdempotencyOwner started(IdempotencyStorePort store, IdempotencyOwner claimed) {
return store.markExecutionStarted(claimed, OPERATION).owner().orElseThrow();
}
@Test
@@ -330,6 +338,92 @@ public abstract class IdempotencyStoreContract {
assertThat(next).isInstanceOf(IdempotencyClaimOutcome.RecoveryRequired.class);
}
@Test
@DisplayName("재시도 가능한 실패로 끝난 attempt가 같은 attempt로 다시 claim하면 attempt 2로 넘겨받는다")
void theSameAttemptTakesOverItsOwnRetryableFailure() {
// given
// Nothing ran with an effect, as for a new attempt. The stores replayed the claim instead,
// which cannot be started, so a caller retaining its attempt was told "recovery required" for
// work that had no effect until the record expired (round6 RR6-02-01).
IdempotencyStorePort store = subject();
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
IdempotencyOwner claimed = ownerOf(store.claim(claim(attempt, FINGERPRINT)));
store.markFailed(
store.markExecutionStarted(claimed, OPERATION).owner().orElseThrow(),
IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE,
Duration.ofHours(1),
OPERATION);
// when
IdempotencyClaimOutcome again = store.claim(claim(attempt, FINGERPRINT));
// then
assertThat(again)
.isInstanceOfSatisfying(
IdempotencyClaimOutcome.TakenOverClaimed.class,
takenOver -> assertThat(takenOver.owner().attempt()).isEqualTo(2));
}
@Test
void theSameAttemptIsToldItsAbandonedOperationRequiresRecovery() {
// given
IdempotencyStorePort store = subject();
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
IdempotencyOwner claimed = ownerOf(store.claim(claim(attempt, FINGERPRINT)));
store.markFailed(
store.markExecutionStarted(claimed, OPERATION).owner().orElseThrow(),
IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED,
Duration.ofHours(1),
OPERATION);
// when
IdempotencyClaimOutcome again = store.claim(claim(attempt, FINGERPRINT));
// then
assertThat(again).isInstanceOf(IdempotencyClaimOutcome.RecoveryRequired.class);
}
@Test
void theSameAttemptStartingAnExecutionItAlreadyStartedIsToldItIsNotClaimed() {
// given
// A second call with the attempt while the first still executes — a retry wrapper that stopped
// waiting. The Redis store confirmed its start as already applied and the executor ran the
// action beside the first; the PostgreSQL store refused it as OPERATION_CONFLICT, which says
// the same operation id applied the start with other arguments (re-review round5 Declined,
// round6 RR6-02-01).
IdempotencyStorePort store = subject();
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
store.markExecutionStarted(ownerOf(store.claim(claim(attempt, FINGERPRINT))), OPERATION);
IdempotencyOwner replayed =
((IdempotencyClaimOutcome.ReplayedAcquire) store.claim(claim(attempt, FINGERPRINT)))
.owner();
// when
IdempotencyMutationResult<IdempotencyStartOutcome> started =
store.markExecutionStarted(replayed, OPERATION);
// then
assertThat(started.outcome()).isEqualTo(IdempotencyStartOutcome.NOT_CLAIMED);
}
@Test
void aRetryableFailureStillAnswersADifferentRequestWithAFingerprintMismatch() {
// given
IdempotencyStorePort store = subject();
store.markFailed(
executing(store),
IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE,
Duration.ofHours(1),
OPERATION);
// when
IdempotencyClaimOutcome other =
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), OTHER_FINGERPRINT));
// then
assertThat(other).isInstanceOf(IdempotencyClaimOutcome.FingerprintMismatch.class);
}
@Test
@DisplayName("실행 전 release는 scope를 비우고 실행 뒤 release는 거부된다")
void releaseFreesTheScopeOnlyBeforeExecution() {
@@ -522,7 +616,10 @@ public abstract class IdempotencyStoreContract {
store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT, lease));
// then
assertThat(next).isInstanceOf(IdempotencyClaimOutcome.RecoveryRequired.class);
assertThat(next)
.isInstanceOfSatisfying(
IdempotencyClaimOutcome.RecoveryRequired.class,
recovery -> assertThat(recovery.currentAttempt()).isEqualTo(1));
}
@Test
@@ -770,6 +867,53 @@ public abstract class IdempotencyStoreContract {
takenOver -> assertThat(takenOver.owner().attempt()).isEqualTo(2));
}
@Test
@DisplayName("lease가 지나 시작을 거절당한 attempt가 같은 attempt로 다시 claim하면 attempt 2로 넘겨받는다")
void anAttemptWhoseStartWasRefusedTakesItsClaimOverWhenItClaimsAgain() {
// given
// The caller was told 503 "nothing ran, resend" and resends with the attempt it retains. Both
// stores replayed the claim it already held and refused its start again, so it got the same 503
// until the record expired (round6 RR6-02-01).
IdempotencyStorePort store = subject();
Duration lease = processingLease();
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
IdempotencyOwner claimed = ownerOf(store.claim(claim(attempt, FINGERPRINT, lease)));
elapse(lease.multipliedBy(2));
store.markExecutionStarted(claimed, OPERATION);
// when
IdempotencyClaimOutcome again = store.claim(claim(attempt, FINGERPRINT, lease));
// then
assertThat(again)
.isInstanceOfSatisfying(
IdempotencyClaimOutcome.TakenOverClaimed.class,
takenOver -> assertThat(takenOver.owner().attempt()).isEqualTo(2));
}
@Test
void aLateStartThroughTheHandleBeforeTheTakeoverIsRefusedAsAStaleOwner() {
// given
// The first call of the attempt stalled past its lease, its retry took the claim over and
// started it, and then the stalled call sends its start. Its handle names the same owner and
// operation as the record, only an older attempt and revision; a store that confirmed it as
// the start already applied would run the action twice (round6 RR6-02-01).
IdempotencyStorePort store = subject();
Duration lease = processingLease();
IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION);
IdempotencyOwner stalled = ownerOf(store.claim(claim(attempt, FINGERPRINT, lease)));
elapse(lease.multipliedBy(2));
IdempotencyOwner retried = ownerOf(store.claim(claim(attempt, FINGERPRINT, lease)));
started(store, retried);
// when
IdempotencyMutationResult<IdempotencyStartOutcome> late =
store.markExecutionStarted(stalled, OPERATION);
// then
assertThat(late.outcome()).isEqualTo(IdempotencyStartOutcome.NOT_OWNER);
}
@Test
@DisplayName("replay TTL보다 긴 처리 lease로 claim해도 lease가 끝날 때까지 기록이 남아 다른 요청은 진행 중으로 막힌다")
void aLeaseLongerThanTheReplayTtlKeepsTheRecordForTheWholeLease() {
@@ -51,28 +51,37 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort {
@Override
public synchronized IdempotencyClaimOutcome claim(IdempotencyClaimRequest request) {
Row row = rows.get(request.scope().digest());
if (row == null || row.state == IdempotencyState.FAILED_RETRYABLE) {
long attempt = row == null ? 1 : row.owner.attempt() + 1;
long revision = row == null ? 0 : row.owner.stateRevision() + 1;
Row claimed = new Row(request.requestFingerprint(), request, attempt, revision);
if (row == null) {
Row claimed = new Row(request.requestFingerprint(), request, 1, 0);
rows.put(request.scope().digest(), claimed);
return row == null
? new IdempotencyClaimOutcome.Acquired(claimed.owner, Instant.MAX)
: new IdempotencyClaimOutcome.TakenOverClaimed(claimed.owner, Instant.MAX);
return new IdempotencyClaimOutcome.Acquired(claimed.owner, Instant.MAX);
}
// The stores' order (IdempotencyStoreContract): a different request is refused whatever the
// record's state — a retryable failure included — and what nothing ran under is taken over
// before a same-attempt claim is replayed, and an abandoned record answers that attempt too.
if (!row.fingerprint.equals(request.requestFingerprint())) {
return new IdempotencyClaimOutcome.FingerprintMismatch();
}
if (row.state == IdempotencyState.COMPLETED) {
return new IdempotencyClaimOutcome.CompletedReplay(row.response, Instant.MAX);
}
if (row.state == IdempotencyState.ABANDONED) {
return new IdempotencyClaimOutcome.RecoveryRequired(row.owner.attempt());
}
if (row.state == IdempotencyState.FAILED_RETRYABLE) {
Row claimed =
new Row(
request.requestFingerprint(),
request,
row.owner.attempt() + 1,
row.owner.stateRevision() + 1);
rows.put(request.scope().digest(), claimed);
return new IdempotencyClaimOutcome.TakenOverClaimed(claimed.owner, Instant.MAX);
}
if (row.owner.ownerToken().equals(request.claimAttempt().ownerToken())
&& row.owner.claimOperationId().equals(request.claimAttempt().operationId())) {
return new IdempotencyClaimOutcome.ReplayedAcquire(row.owner, Instant.MAX);
}
if (row.state == IdempotencyState.ABANDONED) {
return new IdempotencyClaimOutcome.RecoveryRequired(row.owner.attempt());
}
return new IdempotencyClaimOutcome.InProgress(Duration.ZERO, row.owner.attempt());
}
File diff suppressed because one or more lines are too long
+4
View File
@@ -104,4 +104,8 @@ gradlePlugin {
tasks.named('test') {
useJUnitPlatform()
// GradleCommandLineTest runs the launcher of the Gradle that runs this build — the distribution
// the workflows' ./gradlew starts — and holds the workflow reader's copy of its command-line
// options to it (review 2026-11-05 RR6-04-02).
systemProperty 'ca.gradle.home', gradle.gradleHomeDir.absolutePath
}
@@ -3,7 +3,11 @@ package dev.caskeleton.buildlogic.strictlane;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -18,16 +22,40 @@ import java.util.regex.Pattern;
* definitions) are read as the shell reads them, so a {@code cd} inside a heredoc or a multi-line
* string is data, not a directory change.
*
* <p>A command counts only when the step certainly fails if it fails (README 15, RR5-02-02). Under
* GitHub's default {@code bash -e} that is a command whose failure ends the shell, or that is the
* script's last command. Every other shape is returned with the reason it does not count: one
* joined with {@code ||} (its failure is handled) or after it (it runs only on a failure); one
* before {@code &&}, or after an {@code &&} whose left side can fail and let the script go on — both
* unless the list is the script's last command, whose status is the step's; a pipe's left side
* without {@code pipefail}; {@code !}; a background {@code &}; the condition of {@code if}/{@code
* while}/{@code until}; anything inside a compound command, a function body, a command
* substitution or {@code bash -c}; anything after {@code set +e} or a top-level {@code exit}.
* {@code pipefail} is on when the step's shell is {@code bash} (GitHub runs it as {@code -eo
* <p>A command counts only when it certainly runs and the step certainly fails if it fails (README
* 15, RR5-02-02). Under {@code bash -e} — the default shell of a Linux or macOS runner — that is a
* command whose failure ends the shell, or that is the script's last command. Every other shape is
* returned with the reason it does not count, which is one of three (review 2026-11-05 RR6-04-05):
*
* <ol>
* <li>its failure may not fail the step: joined with an {@code ||} other than {@code || exit
* <non-zero>} ({@code || true}, {@code || :}); a pipe's left side without {@code pipefail};
* {@code !}; a background {@code &}; the condition of {@code if}/{@code while}/{@code until};
* the part before {@code &&} of a list that is not the script's last command; anything after
* {@code set +e}, or after a {@code trap} whose {@code EXIT} or {@code ERR} action may {@code
* exit} with status 0;
* <li>it may not run: after {@code ||}; after an {@code &&} of a list that is not the script's
* last command; inside {@code if}/{@code while}/{@code until}/{@code for}/{@code case} or a
* function body; after a top-level {@code exit}, {@code exec <command>} or {@code set -n}
* (it never runs), or after one elsewhere — in a compound command, an and-or list or a
* function the script calls — that may end the script with status 0 ({@code exit 0}, a bare
* {@code exit}, an {@code exit} whose value is not a literal), replace it ({@code exec}) or
* stop it running commands ({@code set -n}, {@code set -o noexec}) first (RR6-04-03);
* <li>this reader does not read it, although its failure would fail the step: {@code || exit
* <non-zero>} or {@code || { …; exit <non-zero>; }}, inside {@code { }} or {@code ( )}, a
* command substitution or {@code bash -c}. That is a false failure on purpose (README 16);
* the message says to put the command on a line of its own.
* </ol>
*
* <p>An {@code exit} that fails the step — a literal non-zero value, or a bare {@code exit} right
* after {@code ||}, which keeps the failed status — does not stop the commands after it from
* counting: if the script goes on, they run, and if it ends there, the step fails. Neither does one
* in a function no command calls, in a {@code ( )} subshell or a command substitution, which ends
* only that subshell. A bare {@code exit} in an {@code EXIT} trap keeps the status the script was
* ending with, so it does not swallow a failure; in an {@code ERR} trap it returns the status of
* the trap's last command, so it may.
*
* <p>{@code pipefail} is on when the step's shell is {@code bash} (GitHub runs it as {@code -eo
* pipefail}) or after a top-level {@code set -o pipefail}. A script that does not parse is not
* guessed: its Gradle commands are returned with that reason.
*
@@ -43,6 +71,13 @@ import java.util.regex.Pattern;
* compound command, and only a false failure if that is too strict.
*/
final class ShellScript {
/** What a message tells a workflow author to do with a stage command this reader does not read. */
static final String PUT_IT_ON_ITS_OWN_LINE = "put the stage command on a line of its own";
private static final String GROUP = "{ … }";
private static final String SUBSHELL = "a subshell ( … )";
private static final Pattern INTEGER = Pattern.compile("[+-]?[0-9]+");
/** A {@code cd} argument this reader follows: relative, with no variable, glob or {@code ~}. */
private static final Pattern LITERAL_RELATIVE_PATH =
Pattern.compile("[A-Za-z0-9._][A-Za-z0-9._/-]*");
@@ -140,7 +175,8 @@ final class ShellScript {
words.subList(index, words.size()),
startDirectory,
null,
"its run: script does not parse as a shell script (" + problem + ")"));
"its run: script does not parse as a shell script (" + problem
+ "), so this check does not read it"));
break;
}
}
@@ -610,7 +646,7 @@ final class ShellScript {
throw new IllegalStateException("a ( subshell is not closed");
}
return new Compound(
"a subshell ( … )", List.of(new Part(false, body)), redirections(new ArrayList<>()));
SUBSHELL, List.of(new Part(false, body)), redirections(new ArrayList<>()));
}
if (token.kind() != Kind.WORD) {
throw new IllegalStateException("unexpected '" + token.text() + "'");
@@ -643,7 +679,7 @@ final class ShellScript {
Sequence body = sequence(Set.of("}"));
expectWord("}");
return new Compound(
"{ … }", List.of(new Part(false, body)), redirections(new ArrayList<>()));
GROUP, List.of(new Part(false, body)), redirections(new ArrayList<>()));
}
case "[[" -> {
next();
@@ -847,8 +883,16 @@ final class ShellScript {
}
}
/** What a {@code set} command does to the two options this reader follows. */
private record SetEffect(Boolean errexit, Boolean pipefail, boolean unknown) {}
/** What a {@code set} command does to the options this reader follows. */
private record SetEffect(Boolean errexit, Boolean pipefail, Boolean noexec, boolean unknown) {}
/** A function an {@code EXIT} or {@code ERR} trap calls that was not defined when it was set. */
private record TrapCall(String trap, boolean bareExitKeepsStatus) {}
/** A simple command the shell runs, with whether it runs in this shell and right after {@code ||}. */
private interface CommandVisitor {
void visit(Simple simple, boolean mainShell, boolean afterOr);
}
private static final class Evaluator {
private final List<Command> commands = new ArrayList<>();
@@ -858,6 +902,16 @@ final class ShellScript {
private boolean pipefail;
/** Why nothing after this point runs, or {@code null}. */
private String terminated;
/** Why the script may have ended before this point, or {@code null}. */
private String mayHaveEnded;
/** Why a failure after this point may still end the script with status 0, or {@code null}. */
private String exitTrap;
/** The functions defined so far, by name. */
private final Map<String, FunctionDefinition> functions = new HashMap<>();
/** Commands an {@code EXIT}/{@code ERR} trap runs, by name, in case a function defines them. */
private final Map<String, TrapCall> trapCalls = new HashMap<>();
/** How deep the reader is in function bodies it reads where they are defined, not called. */
private int definingFunction;
Evaluator(ShellDirectory start, Options options) {
directory = start;
@@ -878,6 +932,9 @@ final class ShellScript {
ShellDirectory current = directory;
String followedCd = null;
boolean directoryChanged = false;
boolean alone =
pipelines.size() == 1 && !list.async() && !pipelines.get(0).negated()
&& pipelines.get(0).commands().size() == 1;
for (int index = 0; index < pipelines.size(); index++) {
Pipeline pipeline = pipelines.get(index);
String text = "`" + pipeline.text() + "`";
@@ -911,7 +968,13 @@ final class ShellScript {
followedCd = text;
}
}
pipeline(pipeline, current, listReason(list, index, last));
pipeline(
pipeline,
current,
listReason(list, index, last),
alone,
pipeline.commands().size() == 1 && !list.async(),
"||".equals(previous));
}
if (directoryChanged) {
if (pipelines.size() > 1 && followedCd != null) {
@@ -927,56 +990,50 @@ final class ShellScript {
}
directory = current;
}
boolean alone =
pipelines.size() == 1 && !list.async() && !pipelines.get(0).negated()
&& pipelines.get(0).commands().size() == 1;
for (Pipeline pipeline : pipelines) {
for (Node node : pipeline.commands()) {
if (!(node instanceof Simple simple) || terminated != null) {
continue;
}
List<String> words = values(simple.words());
if (commandWord(words) != 0 || words.isEmpty()) {
continue;
}
String text = "`" + String.join(" ", words) + "`";
if (words.get(0).equals("set")) {
// A set that may not have run keeps only its turning an option off.
applySet(setEffect(words), text, alone);
} else if (words.get(0).equals("exit") && alone) {
terminated = "it comes after " + text + " at the top level, so it never runs";
}
}
}
}
/** Why a command in pipeline {@code index} of {@code list} cannot fail the step, or null. */
/**
* Why a command in pipeline {@code index} of {@code list} may not run or may not fail the step,
* or null.
*/
private String listReason(AndOr list, int index, boolean last) {
List<String> operators = list.operators();
if (terminated != null) {
return terminated;
}
if (mayHaveEnded != null) {
return mayHaveEnded;
}
if (exitTrap != null) {
return exitTrap;
}
if (list.async()) {
return "it runs in the background (&), so the step does not wait for it";
return "it runs in the background (&), so the step does not wait for it and its failure"
+ " cannot fail the step";
}
int orBefore = operators.subList(0, index).lastIndexOf("||");
if (orBefore >= 0) {
return "it follows `" + list.pipelines().get(orBefore).text()
+ "` through ||, so it runs only when that fails";
+ "` through ||, so it may not run: it runs only when that fails";
}
int orAfter = operators.subList(index, operators.size()).indexOf("||");
if (orAfter >= 0) {
return "its failure is handled by the `|| " + list.pipelines().get(index + orAfter + 1).text()
+ "` after it";
Pipeline handler = list.pipelines().get(index + orAfter + 1);
if (orAfter == 0 && failsTheStep(handler)) {
return "its failure runs the `|| " + handler.text() + "` after it, which fails the step"
+ " too, but this check does not read that shape; " + PUT_IT_ON_ITS_OWN_LINE;
}
return "its failure goes to the `|| " + handler.text() + "` after it, so it cannot fail"
+ " the step unless that fails too";
}
if (index > 0 && !last) {
return "it runs only if `" + list.pipelines().get(index - 1).text()
+ "` succeeds (&&), and when that fails the script goes on, because this && list is"
+ " not the script's last command";
+ "` succeeds (&&), and when that fails the script goes on without it, because this"
+ " && list is not the script's last command, so it may not run";
}
if (index < operators.size() && !last) {
return "a failure only skips the rest of its && list, and the script goes on, because"
+ " this && list is not the script's last command";
return "a failure only skips the rest of its && list and the script goes on, because"
+ " this && list is not the script's last command, so its failure cannot fail the step";
}
if (errexitOff != null && !last) {
return errexitOff;
@@ -984,27 +1041,37 @@ final class ShellScript {
return null;
}
/** The commands of one top-level pipeline, each with {@code reason} or the pipe's own. */
private void pipeline(Pipeline pipeline, ShellDirectory current, String reason) {
/**
* The commands of one top-level pipeline, each with {@code reason} or the pipe's own, and what
* its simple commands do to the shell.
*/
private void pipeline(
Pipeline pipeline,
ShellDirectory current,
String reason,
boolean alone,
boolean mainShell,
boolean afterOr) {
int count = pipeline.commands().size();
for (int index = 0; index < count; index++) {
String own = reason;
if (own == null && pipeline.negated()) {
own = "! inverts its status, so its failure does not stop the script";
own = "! inverts its status, so its failure cannot fail the step";
}
if (own == null && index < count - 1 && !pipefail) {
own = "it is piped into the next command and the shell has no pipefail, so the pipe's"
+ " status is the last command's";
+ " status is the last command's and its failure cannot fail the step";
}
Node node = pipeline.commands().get(index);
if (node instanceof Simple simple) {
report(simple, current, own);
effects(simple, alone, mainShell, afterOr);
continue;
}
// A compound command or a function definition: nothing inside counts, and a directory
// change or a set inside may or may not have run when the script goes on.
ShellDirectory[] inside = {current};
enclosed(node, inside, own, true);
enclosed(node, inside, own, true, mainShell, false);
if (inside[0].unread() != null && current.unread() == null) {
directory = directory.unreadBecause(inside[0].unread());
}
@@ -1014,10 +1081,17 @@ final class ShellScript {
/**
* The commands inside {@code node}, a compound command or a function definition, none of them
* counted: each gets {@code reason}, or the construct's own. A directory change anywhere inside
* makes {@code inside} unread from there on; a {@code set} inside keeps only its turning an
* option off, when the commands run in this shell ({@code sameShell}).
* makes {@code inside} unread from there on; what a command does to the shell — a {@code set},
* an {@code exit}, an {@code exec}, a {@code trap}, a call — is kept when the commands run in
* this shell ({@code sameShell}), as something that may have happened.
*/
private void enclosed(Node node, ShellDirectory[] inside, String reason, boolean sameShell) {
private void enclosed(
Node node,
ShellDirectory[] inside,
String reason,
boolean sameShell,
boolean mainShell,
boolean afterOr) {
switch (node) {
case Simple simple -> {
List<String> words = values(simple.words());
@@ -1028,48 +1102,69 @@ final class ShellScript {
+ " body or a substitution, so whether it ran before the command is not"
+ " read");
}
if (sameShell && !words.isEmpty() && commandWord(words) == 0
&& words.get(0).equals("set")) {
applySet(setEffect(words), "`" + String.join(" ", words) + "`", false);
}
report(simple, inside[0], reason);
if (sameShell) {
effects(simple, false, mainShell, afterOr);
}
}
case Compound compound -> {
substitutions(compound.others(), inside[0]);
boolean bodyShell = sameShell && mainShell && !compound.kind().equals(SUBSHELL);
for (Part part : compound.parts()) {
String own =
reason != null
? reason
: part.condition()
? "it is the condition of " + compound.kind()
+ ", where a failure only picks the branch"
: "it runs inside " + compound.kind()
+ ", only when and as often as that runs it";
enclosed(part.body(), inside, own, sameShell);
enclosed(part.body(), inside, reason != null ? reason : partReason(compound, part),
bodyShell);
}
}
case FunctionDefinition function ->
case FunctionDefinition function -> {
if (sameShell) {
defined(function);
}
definingFunction++;
try {
enclosed(
function.body(),
inside,
reason != null
? reason
: "it is in the body of function " + function.name()
+ ", which runs only where the function is called",
sameShell);
+ ", so it may not run: it runs only where the function is called",
sameShell,
true,
false);
} finally {
definingFunction--;
}
}
}
}
private void enclosed(Sequence body, ShellDirectory[] inside, String reason, boolean sameShell) {
for (AndOr list : body.items()) {
for (Pipeline pipeline : list.pipelines()) {
for (int index = 0; index < list.pipelines().size(); index++) {
Pipeline pipeline = list.pipelines().get(index);
boolean mainShell = pipeline.commands().size() == 1 && !list.async();
boolean afterOr = index > 0 && list.operators().get(index - 1).equals("||");
for (Node node : pipeline.commands()) {
enclosed(node, inside, reason, sameShell);
enclosed(node, inside, reason, sameShell, mainShell, afterOr);
}
}
}
}
/** Why a command in {@code part} of {@code compound} does not count. */
private static String partReason(Compound compound, Part part) {
if (part.condition()) {
return "it is the condition of " + compound.kind()
+ ", where a failure only picks the branch, so it cannot fail the step";
}
if (compound.kind().equals(GROUP) || compound.kind().equals(SUBSHELL)) {
return "it runs inside " + compound.kind() + ", which this check does not read (its"
+ " failure would fail the step); " + PUT_IT_ON_ITS_OWN_LINE;
}
return "it runs inside " + compound.kind()
+ ", so it may not run: it runs only when and as often as that runs it";
}
/** Records a simple command and reads the commands its substitutions and bash -c run. */
private void report(Simple simple, ShellDirectory current, String reason) {
List<String> words = values(simple.words());
@@ -1086,8 +1181,8 @@ final class ShellScript {
child(
words.get(index + 1),
current,
"it runs in a child shell started by " + words.get(at) + " -c, whose failure"
+ " handling this reader does not follow");
"it runs in a child shell started by " + words.get(at) + " -c, which this check"
+ " does not read; " + PUT_IT_ON_ITS_OWN_LINE);
return;
}
}
@@ -1099,8 +1194,9 @@ final class ShellScript {
child(
substitution,
current,
"it runs inside a command substitution, whose status the command around it can"
+ " drop");
"it runs inside a command substitution, where whether its failure fails the step"
+ " depends on the command around it, which this check does not read; "
+ PUT_IT_ON_ITS_OWN_LINE);
}
}
}
@@ -1119,18 +1215,354 @@ final class ShellScript {
enclosed(parsed, new ShellDirectory[] {current}, reason, false);
}
/**
* What {@code simple} does to this shell: a {@code set}; an {@code exit}, an {@code exec
* <command>} or a {@code set -n} that ends the script — certainly, when the command stands
* alone at the top level ({@code certain}), or perhaps; a {@code trap} on {@code EXIT} or
* {@code ERR}; a call of a function that does one of these. Only {@code set} is read in a body
* read where its function is defined; the rest happen where the function is called.
*/
private void effects(Simple simple, boolean certain, boolean mainShell, boolean afterOr) {
if (terminated != null) {
return;
}
List<String> words = values(simple.words());
int at = commandWord(words);
String text = "`" + String.join(" ", words) + "`";
if (!words.isEmpty() && at == 0 && words.get(0).equals("set")) {
// A set that may not have run keeps only its turning an option off.
applySet(setEffect(words), text, certain);
return;
}
if (!mainShell || definingFunction > 0) {
return;
}
if (replacesShell(words)) {
if (certain) {
terminated =
"it comes after " + text + " at the top level, which replaces the shell, so it never"
+ " runs";
} else {
mayEnd(text + " before it may replace the shell");
}
return;
}
if (at < 0 || at >= words.size()) {
return;
}
String command = words.get(at);
if (command.equals("exit")) {
if (certain) {
terminated = "it comes after " + text + " at the top level, so it never runs";
} else if (exitsWithSuccess(words, at, afterOr)) {
mayEnd(text + " before it may end the script first, with status 0");
}
} else if (command.equals("trap")) {
trap(simple.words().subList(at + 1, simple.words().size()), text);
} else if (functions.containsKey(command)) {
called(functions.get(command), text);
}
}
private void mayEnd(String what) {
if (mayHaveEnded == null) {
mayHaveEnded = what + ", so it may not run";
}
}
private void endsWithStatusZero(String trap, String ending) {
if (exitTrap == null) {
exitTrap =
trap + " before it runs " + ending + " when the script ends or a command fails, which"
+ " can end the script with status 0, so its failure may not fail the step";
}
}
/** A function definition: kept for the calls after it, and checked for a trap that calls it. */
private void defined(FunctionDefinition function) {
functions.put(function.name(), function);
TrapCall trap = trapCalls.remove(function.name());
if (trap == null || definingFunction > 0 || terminated != null) {
return;
}
String ending =
endingIn(
function.body(),
trap.bareExitKeepsStatus(),
true,
new HashSet<>(Set.of(function.name())),
new ArrayList<>());
if (ending != null) {
endsWithStatusZero(trap.trap(), "`" + function.name() + "`, which runs " + ending);
}
}
/** A call of {@code function}: what its body does to the shell happens here. */
private void called(FunctionDefinition function, String call) {
List<List<Word>> traps = new ArrayList<>();
String ending =
endingIn(function.body(), false, false, new HashSet<>(Set.of(function.name())), traps);
for (List<Word> trap : traps) {
trap(trap, call + "'s `trap " + String.join(" ", values(trap)) + "`");
}
if (ending != null) {
mayEnd(call + " before it may end the script first (it runs " + ending + ")");
}
}
/**
* A {@code trap} with {@code arguments}. An action on {@code EXIT} or {@code ERR} that may
* {@code exit} with status 0 — directly, through a function it calls, or through a command this
* reader cannot see ({@code "$handler"}) — ends a failing script with status 0, so no command
* after it can fail the step. A function the action calls that is not defined yet is checked
* where it is.
*/
private void trap(List<Word> arguments, String text) {
int index = 0;
while (index < arguments.size()) {
String option = arguments.get(index).value();
if (option.equals("--")) {
index++;
break;
}
if (!option.startsWith("-") || option.equals("-")) {
break;
}
if (option.contains("p") || option.contains("l")) {
return; // it prints traps and sets none
}
index++;
}
List<Word> rest = arguments.subList(index, arguments.size());
if (rest.size() < 2
|| rest.get(0).value().equals("-")
|| INTEGER.matcher(rest.get(0).value()).matches()) {
return; // it resets the conditions it names
}
Set<String> conditions = new HashSet<>();
for (Word condition : rest.subList(1, rest.size())) {
String name = condition.value().toUpperCase(Locale.ROOT);
conditions.add(name.startsWith("SIG") ? name.substring(3) : name);
}
boolean onError = conditions.contains("ERR");
if (!onError && !conditions.contains("EXIT") && !conditions.contains("0")) {
return;
}
// A bare exit in an EXIT trap keeps the status the script was ending with; in an ERR trap it
// returns the status of the trap's last command.
boolean bareExitKeepsStatus = !onError;
Sequence action;
try {
action = new Parser(rest.get(0).value()).script();
} catch (IllegalStateException unreadable) {
endsWithStatusZero(text, "an action this check cannot read");
return;
}
Compound body = new Compound(GROUP, List.of(new Part(false, action)), List.of());
walk(
body,
(simple, mainShell, afterOr) -> {
List<String> words = values(simple.words());
int at = commandWord(words);
if (at >= 0 && at < words.size() && !functions.containsKey(words.get(at))) {
trapCalls.put(words.get(at), new TrapCall(text, bareExitKeepsStatus));
}
});
String ending = endingIn(body, bareExitKeepsStatus, true, new HashSet<>(), new ArrayList<>());
if (ending != null) {
endsWithStatusZero(text, ending);
}
}
/**
* The first command {@code node} runs in this shell that may end the script with status 0 — an
* {@code exit} that is not a literal non-zero value, {@code exec <command>}, a {@code set -n}
* — following the functions it calls, or, with {@code unknownEnds}, a command whose name is an
* expansion; {@code null} when there is none. Each {@code trap} it runs is added to {@code
* traps}.
*/
private String endingIn(
Node node,
boolean bareExitKeepsStatus,
boolean unknownEnds,
Set<String> visiting,
List<List<Word>> traps) {
String[] found = {null};
walk(
node,
(simple, mainShell, afterOr) -> {
if (found[0] != null || !mainShell) {
return;
}
List<String> words = values(simple.words());
int at = commandWord(words);
String text = "`" + String.join(" ", words) + "`";
if (replacesShell(words)) {
found[0] = text;
return;
}
if (at < 0 || at >= words.size()) {
return;
}
String command = words.get(at);
if (command.equals("exit")) {
if (exitsWithSuccess(words, at, afterOr || bareExitKeepsStatus)) {
found[0] = text;
}
} else if (command.equals("set")) {
SetEffect effect = setEffect(words);
if (effect.unknown() || Boolean.TRUE.equals(effect.noexec())) {
found[0] = text;
}
} else if (command.equals("trap")) {
traps.add(simple.words().subList(at + 1, simple.words().size()));
} else if (functions.containsKey(command)) {
if (visiting.add(command)) {
String inner =
endingIn(
functions.get(command).body(),
bareExitKeepsStatus,
unknownEnds,
visiting,
traps);
if (inner != null) {
found[0] = text + ", which runs " + inner;
}
}
} else if (unknownEnds && (command.contains("$") || command.contains("`"))) {
found[0] = text;
}
});
return found[0];
}
/**
* Each simple command {@code node} runs, without running it: the bodies of compound commands,
* but not a subshell's, a piped compound's or a function definition's.
*/
private static void walk(Node node, CommandVisitor visitor) {
walk(node, visitor, true, false);
}
private static void walk(Node node, CommandVisitor visitor, boolean mainShell, boolean afterOr) {
switch (node) {
case Simple simple -> visitor.visit(simple, mainShell, afterOr);
case Compound compound -> {
if (mainShell && !compound.kind().equals(SUBSHELL)) {
for (Part part : compound.parts()) {
for (AndOr list : part.body().items()) {
for (int index = 0; index < list.pipelines().size(); index++) {
Pipeline pipeline = list.pipelines().get(index);
boolean single = pipeline.commands().size() == 1 && !list.async();
boolean or = index > 0 && list.operators().get(index - 1).equals("||");
for (Node inner : pipeline.commands()) {
walk(inner, visitor, single, or);
}
}
}
}
}
}
case FunctionDefinition ignored -> {
// defining a function runs nothing
}
}
}
/** Whether {@code words} is {@code exec <command>}, which replaces the shell with the command. */
private static boolean replacesShell(List<String> words) {
int index = 0;
while (index < words.size()
&& (words.get(index).equals("command") || words.get(index).equals("builtin"))) {
index++;
}
if (index >= words.size() || !words.get(index).equals("exec")) {
return false;
}
index++;
while (index < words.size() && words.get(index).startsWith("-")) {
String option = words.get(index);
index += option.equals("-a") ? 2 : 1;
if (option.equals("--")) {
break;
}
}
return index < words.size();
}
/**
* Whether {@code exit} at {@code at} may end the shell with status 0: a value that is not a
* literal number, or one that is 0 modulo 256, or no value unless {@code bareKeepsFailure}.
*/
private static boolean exitsWithSuccess(List<String> words, int at, boolean bareKeepsFailure) {
if (at + 1 >= words.size()) {
return !bareKeepsFailure;
}
String value = words.get(at + 1);
if (!INTEGER.matcher(value).matches()) {
return true;
}
try {
return Long.parseLong(value) % 256 == 0;
} catch (NumberFormatException tooLong) {
return true;
}
}
/**
* Whether {@code handler}, which runs on a failure through {@code ||}, certainly fails the step:
* {@code exit} with a literal non-zero value or none (it keeps the failed status), or a group
* whose last command is {@code exit} with a literal non-zero value.
*/
private static boolean failsTheStep(Pipeline handler) {
if (handler.negated() || handler.commands().size() != 1) {
return false;
}
Node node = handler.commands().get(0);
if (node instanceof Simple simple) {
return failingExit(simple, true);
}
if (node instanceof Compound compound
&& (compound.kind().equals(GROUP) || compound.kind().equals(SUBSHELL))) {
List<AndOr> items = compound.parts().get(0).body().items();
if (items.isEmpty()) {
return false;
}
AndOr last = items.get(items.size() - 1);
return last.pipelines().size() == 1
&& !last.async()
&& !last.pipelines().get(0).negated()
&& last.pipelines().get(0).commands().size() == 1
&& last.pipelines().get(0).commands().get(0) instanceof Simple simple
&& failingExit(simple, false);
}
return false;
}
private static boolean failingExit(Simple simple, boolean bareKeepsFailure) {
List<String> words = values(simple.words());
int at = commandWord(words);
return at >= 0
&& at < words.size()
&& words.get(at).equals("exit")
&& !exitsWithSuccess(words, at, bareKeepsFailure);
}
private void applySet(SetEffect effect, String text, boolean certain) {
if (effect.unknown()) {
if (errexitOff == null) {
errexitOff =
text + " may have turned off exit-on-error, so its failure may not stop the script";
text + " may have turned off exit-on-error, so its failure may not fail the step";
}
pipefail = false;
if (definingFunction == 0) {
mayEnd(text + " before it may have stopped the shell from running commands (set -n)");
}
return;
}
if (Boolean.FALSE.equals(effect.errexit()) && errexitOff == null) {
errexitOff =
text + " turned off exit-on-error before it, so its failure does not stop the script";
text + " turned off exit-on-error before it, so its failure cannot fail the step";
} else if (Boolean.TRUE.equals(effect.errexit()) && certain) {
errexitOff = null;
}
@@ -1139,16 +1571,26 @@ final class ShellScript {
} else if (Boolean.TRUE.equals(effect.pipefail()) && certain) {
pipefail = true;
}
if (Boolean.TRUE.equals(effect.noexec()) && definingFunction == 0) {
if (certain) {
terminated =
"it comes after " + text + ", after which the shell reads commands without running"
+ " them, so it never runs";
} else {
mayEnd(text + " before it may stop the shell from running commands");
}
}
}
/** What {@code set <words>} does to {@code -e} and {@code pipefail}. */
/** What {@code set <words>} does to {@code -e}, {@code pipefail} and {@code -n}. */
private static SetEffect setEffect(List<String> words) {
Boolean errexit = null;
Boolean pipefailValue = null;
Boolean noexec = null;
for (int index = 1; index < words.size(); index++) {
String word = words.get(index);
if (word.contains("$") || word.contains("`")) {
return new SetEffect(null, null, true);
return new SetEffect(null, null, null, true);
}
if (word.equals("--") || word.equals("-")
|| !(word.startsWith("-") || word.startsWith("+"))) {
@@ -1158,19 +1600,23 @@ final class ShellScript {
for (char letter : word.substring(1).toCharArray()) {
if (letter == 'e') {
errexit = on;
} else if (letter == 'n') {
noexec = on;
} else if (letter == 'o' && index + 1 < words.size()) {
String option = words.get(++index);
if (option.contains("$") || option.contains("`")) {
return new SetEffect(null, null, true);
return new SetEffect(null, null, null, true);
} else if (option.equals("errexit")) {
errexit = on;
} else if (option.equals("pipefail")) {
pipefailValue = on;
} else if (option.equals("noexec")) {
noexec = on;
}
}
}
}
return new SetEffect(errexit, pipefailValue, false);
return new SetEffect(errexit, pipefailValue, noexec, false);
}
/** The command of {@code pipeline} that changes directory, or null. */
@@ -32,13 +32,13 @@ import org.gradle.api.execution.TaskExecutionGraph;
* <li>every strict lane that is not {@code explicitOnly} is in the task plan of a declared stage
* as a workflow runs it — a lane the command removes with {@code -x} is not covered, matched
* the way Gradle matches it, abbreviations included ({@link TaskSelectors});
* <li>every declared stage is executed by a workflow — a {@code --dry-run}, a command for another
* build, a command whose failure cannot fail its step ({@code || true}, a pipe without
* {@code pipefail}, an {@code if} condition and the other shapes {@code ShellScript} names),
* a command line Gradle rejects, a command under {@code continue-on-error} or an {@code if:}
* other than a status function, and a command of a workflow that starts only on {@code
* workflow_dispatch} do not count (review 2026-11-03 RR-06-04, 2026-11-04 RR2-04-04 and
* RR5-02-02).
* <li>every declared stage is executed by a workflow. Not counted ({@code NOT_COUNTED}; review
* 2026-11-03 RR-06-04, 2026-11-04 RR2-04-04, RR5-02-02, 2026-11-05 RR6-04-01..06): a command
* after which Gradle runs no task ({@code --dry-run}, {@code -v}, {@code --help}, …) or that
* Gradle rejects (a short-option bundle such as {@code -mx}), one for another build, and one
* that does not gate for one of three reasons — its failure may not fail its step, it may not
* run, or this check does not read it although its failure would fail the step ({@code
* WorkflowGradleInvocations} and {@code ShellScript} name the shapes).
* </ol>
*
* <p>Each build that holds strict lanes applies it at its own root: the main build, and the
@@ -57,6 +57,23 @@ import org.gradle.api.execution.TaskExecutionGraph;
public final class StrictLaneStagesPlugin implements Plugin<Project> {
public static final String TASK_NAME = "verifyStrictLaneStages";
/** What a failure names as not counted, in the three reasons the readers give, and what to do. */
static final String NOT_COUNTED =
"Not counted: a command after which Gradle runs no task (--dry-run, -m, -v, --help,"
+ " --status, ...) or that Gradle rejects (a short-option bundle such as -mx), and one"
+ " for another build; one whose failure may not fail its step (|| true, a pipe without"
+ " pipefail, !, &, an if/while condition, the part before && of a list that is not the"
+ " script's last command, after set +e or a trap that exits 0, continue-on-error); one"
+ " that may not run (after ||, inside if/while/for/case or a function, after an exit 0,"
+ " exec or set -n, under an if: other than always()/success()/!cancelled(), in a"
+ " workflow that starts only on a request or a reusable one no counted job calls, in a"
+ " job that needs a job that may be skipped); and one this check does not read although"
+ " its failure"
+ " would fail the step (|| exit 1, inside { } or ( ), $( ), bash -c, gradlew as"
+ " another command's argument, after a cd it does not follow, a shell other than bash"
+ " or sh, a runner that may be Windows). Run the stage as ./gradlew on a line of its"
+ " own, in a step and job that run on every push, pull request or schedule";
@Override
public void apply(Project project) {
if (project != project.getRootProject()) {
@@ -150,10 +167,8 @@ public final class StrictLaneStagesPlugin implements Plugin<Project> {
+ workflowDirectory.getName()
+ " for the build in "
+ buildDirectory
+ " (a --dry-run, a command started in another directory, a command after a cd this"
+ " check does not follow, a command whose failure cannot fail its step, a command"
+ " under continue-on-error or an if: other than always()/success()/!cancelled(),"
+ " and a workflow that starts only on workflow_dispatch do not count)"
+ ". "
+ NOT_COUNTED
+ notCounted(invocationsByWorkflow, stage, buildDirectory));
continue;
}
@@ -259,20 +274,21 @@ public final class StrictLaneStagesPlugin implements Plugin<Project> {
return files;
}
/** Each workflow file's Gradle commands, by file name, in file order. */
/**
* Each workflow file's Gradle commands, by file name, in file order — read together, because a
* reusable workflow runs only through the workflows that call it (RR6-04-06).
*/
private static Map<String, List<WorkflowGradleInvocations.Invocation>> invocations(
File workflowDirectory) {
Map<String, List<WorkflowGradleInvocations.Invocation>> invocations = new LinkedHashMap<>();
Map<String, String> workflows = new LinkedHashMap<>();
for (File file : workflowFiles(workflowDirectory)) {
try {
invocations.put(
file.getName(),
WorkflowGradleInvocations.read(Files.readString(file.toPath(), StandardCharsets.UTF_8)));
workflows.put(file.getName(), Files.readString(file.toPath(), StandardCharsets.UTF_8));
} catch (IOException exception) {
throw new UncheckedIOException("failed to read " + file, exception);
}
}
return invocations;
return WorkflowGradleInvocations.readAll(workflows);
}
/**
@@ -3,16 +3,18 @@ package dev.caskeleton.buildlogic.strictlane;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The {@code ./gradlew} commands a GitHub Actions workflow file runs, read from its {@code run:}
* The {@code ./gradlew} commands GitHub Actions workflow files run, read from their {@code run:}
* steps.
*
* <p>Not a YAML parser: it reads the two shapes the workflows use — a one-line {@code run:} and a
@@ -21,22 +23,52 @@ import java.util.regex.Pattern;
* dropped before anything is matched, so a task named only in a comment is not "run".
*
* <p>A command is read with what decides whether it gates anything (review 2026-11-03 RR-06-04):
* its {@code -x} exclusions and {@code -m}, read the way Gradle 9.0's command-line parser reads
* them (see {@code gradleInvocation}), and the {@code continue-on-error} and {@code if:} of its step
* and its job. A command whose failure cannot fail the run, or that runs only under a condition
* other than a status function, is still returned, with the reason it does not count. So is a
* command of a workflow that starts only on {@code workflow_dispatch}: nothing runs it unless
* someone asks, the same reason an {@code if:} on the event name does not count (review 2026-11-04
* RR2-04-04).
* its {@code -x} exclusions, its {@code -m}, the options after which Gradle runs no task ({@code
* -v}, {@code --help}, {@code --status}, …), all read the way Gradle 9.0's command-line parser
* reads them (see {@code gradleInvocation}); and whether the workflow, the job and the shell
* certainly run it and certainly fail when it fails. A command that does not count is still
* returned, with its reason, which is one of three kinds (review 2026-11-05 RR6-04-05):
*
* <p>The script itself is read by {@code ShellScript}, in the shell the step runs: GitHub's default
* {@code bash -e}, {@code shell: bash} ({@code bash -eo pipefail}) or {@code shell: sh} ({@code sh
* -e}), from the step, the job's or the workflow's {@code defaults.run.shell}. A step in any other
* shell is returned with that reason (round 9). Inside the script a command counts only when its
* failure certainly fails the step — not after {@code ||}, before {@code ||}, in a pipe's left side
* without {@code pipefail}, under {@code if}/{@code while}, in the background, and so on
* (README 15, RR5-02-02) — and {@code gradlew} has to be the command, not an argument of
* {@code echo}.
* <ol>
* <li>its failure may not fail the step: {@code continue-on-error}, and the shapes {@code
* ShellScript} names ({@code || true}, a pipe without {@code pipefail}, …);
* <li>it may not run: an {@code if:} other than a status function on its step or job, a workflow
* only a request starts, a reusable workflow no counted caller calls, a job that needs a job
* that may be skipped, and the shapes {@code ShellScript} names;
* <li>this reader does not read it, although its failure would fail the step: a {@code shell:}
* other than {@code bash} or {@code sh}, the default shell of a runner that may be Windows, a
* directory change it does not follow, {@code gradlew} as another command's argument, and the
* shapes {@code ShellScript} names. That is a false failure on purpose (README 16).
* </ol>
*
* <p><b>When a workflow runs.</b> A workflow counts when one of its triggers is part of the change
* or release flow: {@code push}, {@code pull_request} or {@code pull_request_target} (with a {@code
* types} list, only when it holds {@code opened}, {@code synchronize} or {@code reopened}), {@code
* merge_group}, {@code schedule}, {@code release}. One that starts only on other events — {@code
* workflow_dispatch}, {@code repository_dispatch}, {@code issue_comment}, a {@code labeled} pull
* request, {@code workflow_run} and the rest — runs only when someone or something asks (review
* 2026-11-04 RR2-04-04, RR6-04-06). A workflow that starts only on {@code workflow_call} counts
* through the jobs that call it ({@code uses: ./.github/workflows/<file>}): through one whose own
* workflow counts and whose {@code if:}, {@code continue-on-error} and {@code needs:} pass. A
* workflow with no {@code on:} is not judged here; GitHub refuses it as invalid on every event.
*
* <p><b>{@code needs:}.</b> A job runs only when every job it needs succeeded, unless its {@code
* if:} is {@code always()} or {@code !cancelled()}. So a job that needs — directly or through the
* jobs it needs — a job with an {@code if:} other than a status function (skipped while the run
* passes) or with {@code continue-on-error} may not run.
*
* <p><b>The shell.</b> The script is read by {@code ShellScript}, in the shell the step runs:
* {@code shell: bash} ({@code bash -eo pipefail}) or {@code shell: sh} ({@code sh -e}), from the
* step, the job's or the workflow's {@code defaults.run.shell}. With none, it is the runner's
* default: {@code bash -e} on Linux and macOS, {@code sh -e} in a job's {@code container:} — both
* read the same way — and {@code pwsh} on Windows, which this reader does not read. So a step with no
* shell counts only in a job with a {@code container:}, or whose {@code runs-on} names an {@code
* ubuntu-*} or {@code macos-*} runner or a {@code linux} or {@code macos} label; a Windows label, an
* expression such as {@code ${{ matrix.os }}} or a self-hosted label set without one may be
* Windows (RR6-04-04). A job with no {@code runs-on} is not judged here; GitHub refuses it as
* invalid. A step in any other shell is returned with that reason (round 9). Inside the script,
* {@code gradlew} has to be the command the shell runs, not an argument of {@code echo} or {@code
* timeout}.
*
* <p>Which build a command starts is where it starts: the step's {@code working-directory} (or the
* job's or the workflow's {@code defaults.run.working-directory}), then each {@code cd} the same
@@ -52,11 +84,21 @@ public final class WorkflowGradleInvocations {
private static final Pattern MAPPING_KEY =
Pattern.compile("^(\\s*)(?:-\\s+)?([A-Za-z0-9_-]+):(?:\\s+(.*?))?\\s*$");
private static final Pattern JOB_KEY = Pattern.compile("^(\\s*)([A-Za-z0-9_-]+):\\s*(#.*)?$");
private static final Pattern JOBS_KEY = Pattern.compile("^jobs:\\s*(#.*)?$");
/** The top-level {@code on:} key, which YAML 1.1 readers want quoted. */
private static final Pattern TRIGGER_KEY = Pattern.compile("^(?:on|\"on\"|'on'):(?:\\s+(.*?))?\\s*$");
/** Conditions under which a step still runs on every run whose earlier steps passed. */
private static final Set<String> STATUS_CONDITIONS =
Set.of("always()", "success()", "!cancelled()", "true");
/** Conditions under which a job runs even when a job it needs was skipped or failed. */
private static final Set<String> RUNS_AFTER_ANY_NEEDED_JOB = Set.of("always()", "!cancelled()");
/** The triggers of the change and release flow: a workflow with one runs without being asked. */
private static final Set<String> CHANGE_TRIGGERS =
Set.of("push", "pull_request", "pull_request_target", "merge_group", "schedule", "release");
/** The pull-request activity types that come with every new change. */
private static final Set<String> PULL_REQUEST_CHANGE_TYPES =
Set.of("opened", "synchronize", "reopened");
private static final String REUSABLE_WORKFLOWS = "./.github/workflows/";
/**
* Gradle 9.0's command-line options that take a value, by every name it accepts. Probed against
* the 9.0.0 distribution (round 9): {@code gradle -q<letter> --unknown} answers "No argument was
@@ -69,18 +111,36 @@ public final class WorkflowGradleInvocations {
"project-prop", "gradle-user-home", "project-dir", "exclude-task",
"configuration-cache-problems", "console", "include-build", "max-workers", "priority",
"project-cache-dir", "update-locks", "warning-mode");
/** Gradle 9.0's command-line options that take no value, probed the same way. */
/** Gradle 9.0's command-line options that take no value and leave the build to run its tasks. */
private static final Set<String> GRADLE_FLAGS =
Set.of(
"?", "a", "d", "h", "i", "m", "q", "s", "t", "v", "w", "S", "U", "V",
"help", "no-rebuild", "build-cache", "no-build-cache", "configuration-cache",
"a", "d", "i", "m", "q", "s", "t", "w", "S", "U", "V",
"no-rebuild", "build-cache", "no-build-cache", "configuration-cache",
"no-configuration-cache", "configure-on-demand", "no-configure-on-demand", "continue",
"no-continue", "debug", "daemon", "no-daemon", "export-keys", "foreground", "info",
"no-continue", "debug", "daemon", "no-daemon", "export-keys", "info",
"dry-run", "offline", "parallel", "no-parallel", "problems-report", "no-problems-report",
"profile", "property-upgrade-report", "quiet", "refresh-keys", "rerun-tasks",
"full-stacktrace", "stacktrace", "scan", "no-scan", "status", "stop", "continuous",
"refresh-dependencies", "show-version", "version", "warn", "watch-fs", "no-watch-fs",
"full-stacktrace", "stacktrace", "scan", "no-scan", "continuous",
"refresh-dependencies", "show-version", "warn", "watch-fs", "no-watch-fs",
"write-locks");
/**
* Gradle 9.0's command-line options that take no value and after which it runs no task, with what
* it does instead (review 2026-11-05 RR6-04-01). The launcher answers {@code --help} and {@code
* --version} itself; its {@code BuildActionsFactory} returns a daemon action, not a build, for
* {@code --stop}, {@code --status} and {@code --foreground}. {@code GradleCommandLineTest} holds
* all of these tables to the running Gradle's {@code --help}, and runs the launcher with each of
* these options but {@code --stop} and {@code --foreground}.
*/
private static final Map<String, String> GRADLE_OPTIONS_THAT_RUN_NO_TASK =
Map.of(
"?", "prints its help and ends",
"h", "prints its help and ends",
"help", "prints its help and ends",
"v", "prints its version and ends",
"version", "prints its version and ends",
"status", "shows its daemons' status and ends",
"stop", "stops its daemons and ends",
"foreground", "runs a daemon in the foreground instead of a build");
/**
* Options of Gradle's built-in tasks that take a value. Gradle hands an option it does not know to
* the task before it; these are read with their value so that {@code help --task ci} does not
@@ -108,9 +168,9 @@ public final class WorkflowGradleInvocations {
* @param tasks the task selectors it requests, in order
* @param dryRun whether it only plans ({@code --dry-run} or {@code -m}) instead of executing
* @param excludedTasks the {@code -x} / {@code --exclude-task} selectors, in order
* @param uncountedReason why the command gates nothing although it runs — {@code
* continue-on-error}, a condition other than a status function, or a directory change before
* it that this reader does not follow — or {@code null}
* @param uncountedReason why the command gates nothing although it names tasks — it may not run,
* its failure may not fail its step, this reader does not read it, or Gradle runs no task —
* or {@code null}
*/
public record Invocation(
String workingDirectory,
@@ -156,7 +216,7 @@ public final class WorkflowGradleInvocations {
if (!buildDirectory().equals(normalized(buildDirectory))) {
return "it starts the build in " + buildDirectory() + ", not " + normalized(buildDirectory);
}
return dryRun ? "it only plans the tasks (--dry-run)" : null;
return dryRun ? "it only plans the tasks (--dry-run), so Gradle runs no task" : null;
}
/** Whether the command names the task at {@code taskPath}, whatever build it starts. */
@@ -196,14 +256,60 @@ public final class WorkflowGradleInvocations {
ShellScript.Options shell,
String uncountedReason) {}
/** One workflow file: its name, its lines, its triggers with their {@code types}, its jobs. */
private record Workflow(
String file, List<String> lines, Map<String, List<String>> triggers, Map<String, Job> jobs) {}
/** A job: its id, the line of its key, and the column of its own keys (-1 when it has none). */
private record Job(String id, int header, int keyIndent) {}
private WorkflowGradleInvocations() {}
/**
* The Gradle commands of one workflow, read on its own: a reusable workflow ({@code
* workflow_call}) has no caller here, so its commands do not count.
*
* @param workflow the workflow file's text
* @return its Gradle commands, in file order
*/
public static List<Invocation> read(String workflow) {
List<Invocation> invocations = new ArrayList<>();
for (RunStep step : runSteps(workflow)) {
invocations.addAll(stepInvocations(step));
return readAll(Map.of("workflow.yml", workflow)).get("workflow.yml");
}
/**
* The Gradle commands of each workflow of one directory: read together, because a reusable
* workflow runs when, and only when, a workflow that calls it does.
*
* @param workflowsByFile each workflow file's text by its file name, as a {@code uses:
* ./.github/workflows/<file>} names it
* @return each file's Gradle commands, in file order, by file name in the order given
*/
public static Map<String, List<Invocation>> readAll(Map<String, String> workflowsByFile) {
Map<String, Workflow> workflows = new LinkedHashMap<>();
workflowsByFile.forEach((file, text) -> workflows.put(file, parse(file, text)));
Map<String, List<Invocation>> invocations = new LinkedHashMap<>();
for (Workflow workflow : workflows.values()) {
String notStarted = startReason(workflow, workflows, new HashSet<>());
List<Invocation> commands = new ArrayList<>();
for (RunStep step : runSteps(workflow, notStarted)) {
commands.addAll(stepInvocations(step));
}
invocations.put(workflow.file(), List.copyOf(commands));
}
return List.copyOf(invocations);
return invocations;
}
/** Every option name Gradle 9.0's {@code --help} lists, without dashes. */
static Set<String> gradleOptionNames() {
Set<String> names = new TreeSet<>(GRADLE_VALUE_OPTIONS);
names.addAll(GRADLE_FLAGS);
names.addAll(GRADLE_OPTIONS_THAT_RUN_NO_TASK.keySet());
return names;
}
/** The option names after which Gradle 9.0 runs no task. */
static Set<String> optionsThatRunNoTask() {
return new TreeSet<>(GRADLE_OPTIONS_THAT_RUN_NO_TASK.keySet());
}
/**
@@ -216,7 +322,10 @@ public final class WorkflowGradleInvocations {
ShellScript.commands(step.script(), step.workingDirectory(), step.shell())) {
String reason = step.uncountedReason();
if (reason == null && command.unreadDirectory() != null) {
reason = "the directory it starts in is not read: " + command.unreadDirectory();
reason =
"the directory it starts in is not read: " + command.unreadDirectory()
+ "; start the stage command from the step's working-directory, or after a cd to"
+ " a literal relative path on a line of its own";
}
if (reason == null) {
reason = command.uncountedReason();
@@ -276,14 +385,14 @@ public final class WorkflowGradleInvocations {
return List.copyOf(problems);
}
static List<String> runScripts(String workflow) {
return runSteps(workflow).stream().map(RunStep::script).toList();
private static Workflow parse(String file, String text) {
List<String> lines = text.lines().toList();
return new Workflow(file, lines, triggers(lines), jobs(lines));
}
private static List<RunStep> runSteps(String workflow) {
List<String> lines = workflow.lines().toList();
private static List<RunStep> runSteps(Workflow workflow, String notStarted) {
List<String> lines = workflow.lines();
List<RunStep> scripts = new ArrayList<>();
String dispatchOnly = dispatchOnlyReason(lines);
for (int index = 0; index < lines.size(); index++) {
Matcher run = RUN_KEY.matcher(lines.get(index));
if (!run.matches() || !isStepRun(lines, index)) {
@@ -291,9 +400,13 @@ public final class WorkflowGradleInvocations {
}
int keyIndent = run.group(1).length();
String value = run.group(2).trim();
Job job = jobAt(workflow, index);
String uncounted = uncountedReason(lines, index);
if (uncounted == null && job != null) {
uncounted = needsReason(workflow, job);
}
if (uncounted == null) {
uncounted = dispatchOnly;
uncounted = notStarted;
}
String directory = runSetting(lines, index, "working-directory");
String shellName = runSetting(lines, index, "shell");
@@ -302,8 +415,11 @@ public final class WorkflowGradleInvocations {
uncounted =
"its step runs in shell: "
+ shellName
+ ", whose failure handling this reader does not follow (only the default, bash"
+ " and sh are read)";
+ ", whose failure handling this check does not read (only bash and sh are"
+ " read); run the stage command with shell: bash";
}
if (uncounted == null && shellName == null) {
uncounted = defaultShellReason(workflow, job);
}
if (shell == null) {
shell = SHELLS.get("");
@@ -357,12 +473,15 @@ public final class WorkflowGradleInvocations {
return false;
}
// ---------------------------------------------------------------------------------------------
// When the workflow runs
/**
* Why every command of the workflow gates nothing, when it starts only on {@code
* workflow_dispatch}; {@code null} when it has another trigger or none is written.
* The workflow's triggers, each with its {@code types} list, or {@code null} when it has none;
* empty when no {@code on:} is written.
*/
private static String dispatchOnlyReason(List<String> lines) {
Set<String> triggers = new LinkedHashSet<>();
private static Map<String, List<String>> triggers(List<String> lines) {
Map<String, List<String>> triggers = new LinkedHashMap<>();
for (int index = 0; index < lines.size(); index++) {
Matcher on = TRIGGER_KEY.matcher(lines.get(index));
if (!on.matches()) {
@@ -370,45 +489,308 @@ public final class WorkflowGradleInvocations {
}
String inline =
on.group(1) == null || on.group(1).startsWith("#") ? "" : stripScalarComment(on.group(1));
if (!inline.isEmpty()) {
if (inline.startsWith("{") && inline.endsWith("}")) {
for (String entry : flowItems(inline.substring(1, inline.length() - 1))) {
int colon = entry.indexOf(':');
triggers.put(
stripScalarComment(colon < 0 ? entry : entry.substring(0, colon)),
colon < 0 ? null : flowTypes(entry.substring(colon + 1).trim()));
}
} else if (!inline.isEmpty()) {
String list =
inline.startsWith("[") && inline.endsWith("]")
? inline.substring(1, inline.length() - 1)
: inline;
for (String trigger : list.split(",")) {
if (!trigger.isBlank()) {
triggers.add(stripScalarComment(trigger.trim()));
}
}
break;
}
int childIndent = -1;
for (int next = index + 1; next < lines.size(); next++) {
String line = lines.get(next);
if (line.isBlank() || line.trim().startsWith("#")) {
continue;
}
int indent = indentOf(line);
if (indent == 0) {
break;
}
if (childIndent < 0) {
childIndent = indent;
}
if (indent == childIndent) {
String key = line.trim();
key = key.startsWith("-") ? key.substring(1).trim() : key;
int colon = key.indexOf(':');
triggers.add(stripScalarComment(colon < 0 ? key : key.substring(0, colon)));
for (String trigger : flowItems(list)) {
triggers.put(trigger, null);
}
} else {
blockTriggers(lines, index, triggers);
}
break;
}
return !triggers.isEmpty() && triggers.stream().allMatch("workflow_dispatch"::equals)
? "its workflow starts only on workflow_dispatch, so nothing runs it unless asked"
: null;
return triggers;
}
/** The triggers of a block {@code on:} at {@code onLine}: a mapping or a list. */
private static void blockTriggers(
List<String> lines, int onLine, Map<String, List<String>> triggers) {
int childIndent = childIndent(lines, onLine);
for (int next = onLine + 1; next < lines.size(); next++) {
String line = lines.get(next);
if (line.isBlank() || line.trim().startsWith("#")) {
continue;
}
int indent = indentOf(line);
if (indent == 0) {
break;
}
if (indent != childIndent) {
continue;
}
String key = line.trim();
boolean item = key.startsWith("-");
key = item ? key.substring(1).trim() : key;
int colon = key.indexOf(':');
List<String> types = null;
String inlineDetail = colon < 0 ? "" : key.substring(colon + 1).trim();
if (!item && inlineDetail.startsWith("{")) {
types = flowTypes(stripScalarComment(inlineDetail));
} else if (!item && colon >= 0) {
int detailIndent = childIndent(lines, next);
int typesLine =
detailIndent > childIndent ? mappingKey(lines, next + 1, detailIndent, "types") : -1;
types = typesLine < 0 ? null : listValue(lines, typesLine);
}
triggers.put(stripScalarComment(colon < 0 ? key : key.substring(0, colon)), types);
}
}
/** The {@code types} of a flow-mapping trigger value such as {@code {types: [created]}}. */
private static List<String> flowTypes(String value) {
if (!value.startsWith("{") || !value.endsWith("}")) {
return null;
}
for (String entry : flowItems(value.substring(1, value.length() - 1))) {
int colon = entry.indexOf(':');
if (colon >= 0 && stripScalarComment(entry.substring(0, colon)).equals("types")) {
String types = entry.substring(colon + 1).trim();
return types.startsWith("[") && types.endsWith("]")
? flowItems(types.substring(1, types.length() - 1))
: List.of(stripScalarComment(types));
}
}
return null;
}
/**
* Why the workflow does not run on every change, or {@code null} when it does or writes no {@code
* on:}. A reusable workflow runs through its callers ({@code visiting} guards a cycle).
*/
private static String startReason(
Workflow workflow, Map<String, Workflow> workflows, Set<String> visiting) {
Map<String, List<String>> triggers = workflow.triggers();
if (triggers.isEmpty()) {
return null;
}
for (Map.Entry<String, List<String>> trigger : triggers.entrySet()) {
if (runsOnChanges(trigger.getKey(), trigger.getValue())) {
return null;
}
}
String described = describe(triggers);
if (!triggers.containsKey("workflow_call")) {
return "its workflow starts only on "
+ described
+ ", which happen only when someone or something asks, not on every push, pull request"
+ " or schedule, so it may not run";
}
if (!visiting.add(workflow.file())) {
return "its workflow is called only through a cycle of workflow_call";
}
List<String> callers = new ArrayList<>();
for (Workflow caller : workflows.values()) {
for (Job job : caller.jobs().values()) {
String uses = jobValue(caller, job, "uses");
if (uses == null || !calls(uses, workflow.file())) {
continue;
}
String reason = gatingProblem(caller.lines(), job.header() + 1, job.keyIndent(), "job");
if (reason == null) {
reason = needsReason(caller, job);
}
if (reason == null) {
reason = startReason(caller, workflows, new HashSet<>(visiting));
}
if (reason == null) {
return null;
}
callers.add(caller.file() + " job " + job.id() + ": " + reason);
}
}
return "its workflow starts only on "
+ described
+ ", and no workflow that runs on every change calls it ("
+ (callers.isEmpty()
? "no workflow in this directory calls it"
: String.join("; ", callers))
+ "), so it may not run";
}
private static boolean runsOnChanges(String trigger, List<String> types) {
if (!CHANGE_TRIGGERS.contains(trigger)) {
return false;
}
return types == null
|| !trigger.startsWith("pull_request")
|| types.stream().anyMatch(PULL_REQUEST_CHANGE_TYPES::contains);
}
private static String describe(Map<String, List<String>> triggers) {
List<String> described = new ArrayList<>();
triggers.forEach(
(trigger, types) ->
described.add(
types == null ? trigger : trigger + " (types: " + String.join(", ", types) + ")"));
return String.join(", ", described);
}
/** Whether a job's {@code uses:} calls the workflow {@code file} of this directory. */
private static boolean calls(String uses, String file) {
String target = stripScalarComment(uses);
int ref = target.indexOf('@');
return (ref < 0 ? target : target.substring(0, ref)).equals(REUSABLE_WORKFLOWS + file);
}
// ---------------------------------------------------------------------------------------------
// Jobs
/** The jobs under the top-level {@code jobs:}, by id, in file order. */
private static Map<String, Job> jobs(List<String> lines) {
Map<String, Job> jobs = new LinkedHashMap<>();
int jobsLine = -1;
for (int index = 0; index < lines.size() && jobsLine < 0; index++) {
if (JOBS_KEY.matcher(lines.get(index)).matches()) {
jobsLine = index;
}
}
int jobIndent = jobsLine < 0 ? -1 : childIndent(lines, jobsLine);
if (jobIndent <= 0) {
return jobs;
}
for (int index = jobsLine + 1; index < lines.size(); index++) {
String line = lines.get(index);
if (line.isBlank() || line.trim().startsWith("#")) {
continue;
}
if (indentOf(line) == 0) {
break;
}
Matcher job = JOB_KEY.matcher(line);
if (indentOf(line) == jobIndent && job.matches()) {
int keyIndent = childIndent(lines, index);
jobs.put(
job.group(2), new Job(job.group(2), index, keyIndent > jobIndent ? keyIndent : -1));
}
}
return jobs;
}
/** The job holding the line at {@code index}, or {@code null}. */
private static Job jobAt(Workflow workflow, int index) {
int header = jobHeader(workflow.lines(), index);
for (Job job : workflow.jobs().values()) {
if (job.header() == header) {
return job;
}
}
return null;
}
private static String jobValue(Workflow workflow, Job job, String key) {
return job.keyIndent() < 0
? null
: mappingValue(workflow.lines(), job.header() + 1, job.keyIndent(), key);
}
private static int jobKey(Workflow workflow, Job job, String key) {
return job.keyIndent() < 0
? -1
: mappingKey(workflow.lines(), job.header() + 1, job.keyIndent(), key);
}
/**
* Why {@code job} may not run although its own conditions pass: a job it needs, directly or
* through the jobs that one needs, may be skipped or fail while the run passes; {@code null} when
* none may, or when its {@code if:} runs it after any needed job.
*/
private static String needsReason(Workflow workflow, Job job) {
String chain = needsChain(workflow, job, new HashSet<>(Set.of(job.id())));
return chain == null
? null
: "its job needs "
+ chain
+ "; a job whose needed job is skipped or fails is skipped too while the run can pass,"
+ " so it may not run";
}
private static String needsChain(Workflow workflow, Job job, Set<String> visiting) {
String condition = jobValue(workflow, job, "if");
if (condition != null && RUNS_AFTER_ANY_NEEDED_JOB.contains(expression(condition))) {
return null;
}
int needs = jobKey(workflow, job, "needs");
if (needs < 0) {
return null;
}
for (String need : listValue(workflow.lines(), needs)) {
Job needed = workflow.jobs().get(need);
if (needed == null || !visiting.add(need)) {
continue;
}
String neededCondition = jobValue(workflow, needed, "if");
if (neededCondition != null && !STATUS_CONDITIONS.contains(expression(neededCondition))) {
return need + ", which runs only if: " + neededCondition;
}
String continueOnError = jobValue(workflow, needed, "continue-on-error");
if (continueOnError != null && !continueOnError.equals("false")) {
return need + ", which has continue-on-error: " + continueOnError;
}
String deeper = needsChain(workflow, needed, visiting);
if (deeper != null) {
return need + ", which needs " + deeper;
}
}
return null;
}
/**
* Why a step with no {@code shell:} may run in a shell this reader does not read: its job's
* {@code runs-on} may be a Windows runner, whose default is {@code pwsh}. {@code null} for a job
* with a {@code container:} (default {@code sh -e}), a Linux or macOS runner, or no {@code
* runs-on}.
*/
private static String defaultShellReason(Workflow workflow, Job job) {
if (job == null || jobKey(workflow, job, "container") >= 0) {
return null;
}
int runsOn = jobKey(workflow, job, "runs-on");
if (runsOn < 0) {
return null;
}
List<String> labels = runnerLabels(workflow.lines(), runsOn);
for (String label : labels) {
String plain = label.toLowerCase(Locale.ROOT);
if (plain.startsWith("ubuntu-")
|| plain.startsWith("macos-")
|| plain.equals("linux")
|| plain.equals("macos")) {
return null;
}
}
return "its job runs on "
+ (labels.isEmpty() ? "a runner group with no labels" : String.join(", ", labels))
+ ", which may be a Windows runner, whose default shell is pwsh, and this check does not"
+ " read pwsh; give the step shell: bash, or the job defaults.run.shell: bash";
}
/** The labels of {@code runs-on}: a scalar, a list, or the {@code labels} of a mapping. */
private static List<String> runnerLabels(List<String> lines, int runsOn) {
List<String> labels = listValue(lines, runsOn);
if (!labels.isEmpty()) {
return labels;
}
int detailIndent = childIndent(lines, runsOn);
int labelsLine =
detailIndent > keyColumn(lines.get(runsOn))
? mappingKey(lines, runsOn + 1, detailIndent, "labels")
: -1;
return labelsLine < 0 ? List.of() : listValue(lines, labelsLine);
}
// ---------------------------------------------------------------------------------------------
// Steps
/**
* The {@code run:} setting {@code key} ({@code working-directory} or {@code shell}) of the step
* at {@code runIndex}: its step's, else its job's {@code defaults.run}, else the workflow's;
@@ -484,6 +866,61 @@ public final class WorkflowGradleInvocations {
return -1;
}
/**
* The items of the list at the key on {@code keyLine}: a flow list {@code [a, b]}, a single
* scalar, or the {@code - item} lines under it; empty when it holds a mapping or nothing.
*/
private static List<String> listValue(List<String> lines, int keyLine) {
Matcher key = MAPPING_KEY.matcher(lines.get(keyLine));
String inline = key.matches() && key.group(3) != null ? stripScalarComment(key.group(3)) : "";
if (inline.startsWith("[") && inline.endsWith("]")) {
return flowItems(inline.substring(1, inline.length() - 1));
}
if (!inline.isEmpty()) {
return List.of(inline);
}
List<String> items = new ArrayList<>();
int keyIndent = keyColumn(lines.get(keyLine));
for (int index = keyLine + 1; index < lines.size(); index++) {
String line = lines.get(index);
if (line.isBlank() || line.trim().startsWith("#")) {
continue;
}
if (indentOf(line) < keyIndent || !line.trim().startsWith("-")) {
break;
}
items.add(stripScalarComment(line.trim().substring(1).trim()));
}
return items;
}
/** The items of a flow collection's inside, split at its top-level commas, quotes removed. */
private static List<String> flowItems(String inside) {
List<String> items = new ArrayList<>();
int depth = 0;
char quote = 0;
int start = 0;
for (int index = 0; index <= inside.length(); index++) {
char current = index < inside.length() ? inside.charAt(index) : ',';
if (quote != 0) {
quote = current == quote ? 0 : quote;
} else if (current == '\'' || current == '"') {
quote = current;
} else if (current == '[' || current == '{') {
depth++;
} else if (current == ']' || current == '}') {
depth--;
} else if (current == ',' && depth == 0) {
String item = inside.substring(start, Math.min(index, inside.length())).trim();
if (!item.isEmpty()) {
items.add(item.contains(":") ? item : stripScalarComment(item));
}
start = index + 1;
}
}
return items;
}
/** The indentation of the first content line after {@code index}. */
private static int childIndent(List<String> lines, int index) {
for (int next = index + 1; next < lines.size(); next++) {
@@ -543,6 +980,9 @@ public final class WorkflowGradleInvocations {
/** The first {@code continue-on-error} or {@code if:} at {@code keyIndent} in the mapping. */
private static String gatingProblem(List<String> lines, int start, int keyIndent, String scope) {
if (keyIndent < 0) {
return null;
}
for (int index = start; index < lines.size(); index++) {
String line = lines.get(index);
if (line.isBlank() || line.trim().startsWith("#")) {
@@ -557,14 +997,16 @@ public final class WorkflowGradleInvocations {
}
String value = stripScalarComment(key.group(3) == null ? "" : key.group(3));
if (key.group(2).equals("continue-on-error") && !value.equals("false")) {
return "its " + scope + " has continue-on-error: " + value + ", so its failure fails nothing";
return "its " + scope + " has continue-on-error: " + value
+ ", so its failure fails nothing";
}
if (key.group(2).equals("if") && !STATUS_CONDITIONS.contains(expression(value))) {
return "its "
+ scope
+ " runs only if: "
+ value
+ ", not on every run (only always(), success() and !cancelled() count)";
+ ", not on every run (only always(), success() and !cancelled() count), so it may not"
+ " run";
}
}
return null;
@@ -594,7 +1036,7 @@ public final class WorkflowGradleInvocations {
private static int jobHeader(List<String> lines, int index) {
int jobs = -1;
for (int line = 0; line < index; line++) {
if (lines.get(line).matches("^jobs:\\s*(#.*)?$")) {
if (JOBS_KEY.matcher(lines.get(line)).matches()) {
jobs = line;
}
}
@@ -650,20 +1092,29 @@ public final class WorkflowGradleInvocations {
return plain;
}
// ---------------------------------------------------------------------------------------------
// The Gradle command line
/**
* The Gradle command a simple command runs, or {@code null} when it names no {@code gradlew}. A
* {@code gradlew} that is not the command the shell runs ({@code echo ./gradlew ci}) is returned
* with that reason.
* {@code gradlew} that is not the command the shell runs ({@code echo ./gradlew ci}, {@code
* timeout 60 ./gradlew ci}) is returned with that reason.
*
* <p>The arguments are read the way Gradle 9.0's {@code CommandLineParser} reads them (checked
* against the 9.0.0 distribution in round 9, and pinned by {@code StrictLaneStagesFunctionalTest}):
* after {@code --} every word is a task; {@code --name} and {@code --name=value} are long options,
* and Gradle also takes a short name there ({@code --m}); {@code -c=value} gives a one-letter
* option a value; a word that is a whole option name after one dash is that option ({@code
* -dry-run}); otherwise the letters are a bundle in which only the first may take a value, as
* the rest of the word ({@code -xtask}, {@code -pdir}) — {@code -qm} is a dry run, and {@code
* -mx} is a command line Gradle rejects, because {@code -x} needs a value it is not given there.
* A rejected command runs nothing, so it does not count.
* against the 9.0.0 distribution in round 9): after {@code --} every word is a task; {@code
* --name} and {@code --name=value} are long options, and Gradle also takes a short name there
* ({@code --m}); {@code -c=value} gives a one-letter option a value; a word that is a whole option
* name after one dash is that option ({@code -dry-run}); otherwise the letters are a bundle in
* which only the first may take a value, as the rest of the word ({@code -xtask}, {@code -pdir})
* — {@code -qm} is a dry run, {@code -qv} prints the version and ends, and {@code -mx} is a
* command line Gradle rejects, because {@code -x} needs a value it is not given there. Gradle
* also rejects a value given to an option that takes none ({@code -m=yes}, {@code
* --offline=true}). A rejected command runs nothing, and neither does one with an option after
* which Gradle runs no task, so neither counts. {@code StrictLaneStagesFunctionalTest} runs
* {@code -qm} and {@code -mx} through TestKit; {@code GradleCommandLineTest} compares the option
* tables with the running Gradle's {@code --help} and runs the options that run no task.
* Whether each option takes a value was probed against 9.0.0 and is not re-run by a test: an
* upgrade that adds an option fails that test until the option is placed in a table.
*/
private static Invocation gradleInvocation(
List<String> words, String workingDirectory, String uncountedReason) {
@@ -684,12 +1135,15 @@ public final class WorkflowGradleInvocations {
reason =
"it is an argument of `"
+ String.join(" ", words.subList(0, start))
+ "`, not the command the shell runs";
+ "`, and this check does not read what another command does with its arguments; "
+ ShellScript.PUT_IT_ON_ITS_OWN_LINE
+ ", with gradlew as the command";
}
}
String projectDir = null;
boolean dryRun = false;
String rejected = null;
String runsNoTask = null;
List<String> tasks = new ArrayList<>();
List<String> excluded = new ArrayList<>();
boolean onlyTasks = false;
@@ -707,17 +1161,16 @@ public final class WorkflowGradleInvocations {
int equals = word.indexOf('=');
name = equals < 0 ? word.substring(2) : word.substring(2, equals);
value = equals < 0 ? null : word.substring(equals + 1);
if (value != null && GRADLE_FLAGS.contains(name) && rejected == null) {
if (value != null && isFlag(name) && rejected == null) {
rejected = "Gradle rejects " + word + ": --" + name + " takes no value";
}
} else if (word.length() > 2 && word.charAt(2) == '=') {
name = word.substring(1, 2);
value = word.substring(3);
if (GRADLE_FLAGS.contains(name) && rejected == null) {
if (isFlag(name) && rejected == null) {
rejected = "Gradle rejects " + word + ": -" + name + " takes no value";
}
} else if (GRADLE_VALUE_OPTIONS.contains(word.substring(1))
|| GRADLE_FLAGS.contains(word.substring(1))) {
} else if (GRADLE_VALUE_OPTIONS.contains(word.substring(1)) || isFlag(word.substring(1))) {
name = word.substring(1);
} else {
String first = word.substring(1, 2);
@@ -727,7 +1180,7 @@ public final class WorkflowGradleInvocations {
} else {
for (int letter = 1; letter < word.length(); letter++) {
String option = word.substring(letter, letter + 1);
if (!GRADLE_FLAGS.contains(option)) {
if (!isFlag(option)) {
if (rejected == null) {
rejected =
"Gradle rejects "
@@ -741,6 +1194,9 @@ public final class WorkflowGradleInvocations {
break;
}
dryRun |= option.equals("m");
if (runsNoTask == null && GRADLE_OPTIONS_THAT_RUN_NO_TASK.containsKey(option)) {
runsNoTask = noTask(word, option);
}
}
continue;
}
@@ -749,6 +1205,9 @@ public final class WorkflowGradleInvocations {
&& (GRADLE_VALUE_OPTIONS.contains(name) || TASK_OPTIONS_WITH_VALUE.contains(name))) {
value = index + 1 < words.size() ? words.get(++index) : "";
}
if (runsNoTask == null && GRADLE_OPTIONS_THAT_RUN_NO_TASK.containsKey(name)) {
runsNoTask = noTask(word, name);
}
switch (name) {
case "m", "dry-run" -> dryRun = true;
case "x", "exclude-task" -> excluded.add(value);
@@ -759,11 +1218,22 @@ public final class WorkflowGradleInvocations {
}
}
if (reason == null) {
reason = rejected;
reason = rejected != null ? rejected : runsNoTask;
}
return new Invocation(workingDirectory, projectDir, tasks, dryRun, excluded, reason);
}
private static boolean isFlag(String name) {
return GRADLE_FLAGS.contains(name) || GRADLE_OPTIONS_THAT_RUN_NO_TASK.containsKey(name);
}
private static String noTask(String word, String option) {
return "Gradle runs no task when given "
+ word
+ ": it "
+ GRADLE_OPTIONS_THAT_RUN_NO_TASK.get(option);
}
private static boolean isGradlew(String word) {
return word.equals("gradlew") || word.endsWith("/gradlew");
}
@@ -0,0 +1,162 @@
package dev.caskeleton.buildlogic.strictlane;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Holds the workflow reader's copy of Gradle's command-line options to the Gradle that runs this
* build — the distribution the workflows' {@code ./gradlew} starts (review 2026-11-05 RR6-04-01/02).
*
* <p>It runs that distribution's own launcher ({@code bin/gradle}) rather than TestKit: {@code
* --help}, {@code --version}, {@code --status} and {@code --stop} are the launcher's options, and a
* workflow step runs the launcher. An upgrade that adds an option (9.2's {@code --task-graph}) fails
* the first test until the reader is told whether the option takes a value and whether Gradle then
* runs any task.
*/
class GradleCommandLineTest {
/**
* Options the reader reads as ending without a task that this test does not run: {@code --stop}
* stops every daemon of this Gradle version in the user home it is given, and {@code --foreground}
* runs a daemon until it is idle. Gradle's {@code BuildActionsFactory} returns a daemon action, not
* a build, for both.
*/
private static final Set<String> NOT_RUN_HERE = Set.of("stop", "foreground");
@TempDir Path temp;
private Path project;
@BeforeEach
void setUp() throws IOException {
project = temp.resolve("project");
Files.createDirectories(project);
Files.writeString(project.resolve("settings.gradle"), "rootProject.name = 'probe'\n");
Files.writeString(
project.resolve("build.gradle"),
"""
tasks.register('ci') {
def marker = file('ci-ran')
doLast { marker.text = 'ran' }
}
""");
}
@Test
@DisplayName("판독기의 Gradle 옵션 표는 이 빌드를 돌리는 Gradle의 --help가 보이는 옵션과 정확히 같다")
void theReadersOptionTableNamesExactlyTheOptionsTheRunningGradleLists() throws Exception {
// when
Run help = gradle("--help");
// then
assertThat(help.exitCode()).as(help.output()).isZero();
assertThat(optionNames(help.output()))
.as("the options of the Gradle in %s", gradleHome())
.containsExactlyInAnyOrderElementsOf(WorkflowGradleInvocations.gradleOptionNames());
}
@Test
@DisplayName("판독기가 작업 없이 끝난다고 읽는 옵션을 붙이면 Gradle은 성공으로 끝나고 작업을 실행하지 않는다")
void gradleEndsWithoutRunningTheTaskWhenGivenAnOptionTheReaderReadsAsRunningNoTask()
throws Exception {
// given
List<String> options = new ArrayList<>();
for (String name : WorkflowGradleInvocations.optionsThatRunNoTask()) {
if (!NOT_RUN_HERE.contains(name)) {
options.add(name.length() == 1 ? "-" + name : "--" + name);
}
}
options.add("-qv");
// when
Map<String, Run> runs = new LinkedHashMap<>();
for (String option : options) {
runs.put(option, gradle(":ci", option));
}
// then
assertThat(options).contains("-v", "--version", "-h", "-?", "--help", "--status");
runs.forEach(
(option, run) -> {
assertThat(run.exitCode()).as(option + "\n" + run.output()).isZero();
assertThat(project.resolve("ci-ran")).as(option).doesNotExist();
});
}
@Test
@DisplayName("버전을 찍고 계속하는 -V를 붙이면 Gradle은 작업을 실행하므로, 위 검사는 실행을 알아볼 수 있다")
void gradleRunsTheTaskWhenGivenShowVersionWhichContinues() throws Exception {
// when
Run run = gradle(":ci", "-V");
// then
assertThat(run.exitCode()).as(run.output()).isZero();
assertThat(project.resolve("ci-ran")).exists();
}
/** The option names a {@code --help} lists, without dashes; {@code --} itself is not an option. */
private static Set<String> optionNames(String help) {
Set<String> names = new LinkedHashSet<>();
for (String line : help.lines().toList()) {
if (!line.startsWith("-")) {
continue;
}
for (String spelling : line.split("\\s{2,}", 2)[0].split(",\\s*")) {
String name = spelling.strip().replaceFirst("^-+", "");
if (!name.isEmpty()) {
names.add(name);
}
}
}
return names;
}
private record Run(int exitCode, String output) {}
/** Runs the launcher of this build's Gradle on the probe project, isolated from every daemon. */
private Run gradle(String... arguments) throws IOException, InterruptedException {
List<String> command = new ArrayList<>();
boolean windows = System.getProperty("os.name").startsWith("Windows");
command.add(gradleHome().resolve(windows ? "bin/gradle.bat" : "bin/gradle").toString());
command.addAll(
List.of(
"--no-daemon",
"--gradle-user-home",
temp.resolve("gradle-user-home").toString(),
"--project-dir",
project.toString()));
command.addAll(List.of(arguments));
Path output = Files.createTempFile(temp, "gradle", ".log");
ProcessBuilder builder =
new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(output.toFile());
builder.environment().put("JAVA_HOME", System.getProperty("java.home"));
builder.environment().remove("GRADLE_OPTS");
Process process = builder.start();
if (!process.waitFor(5, TimeUnit.MINUTES)) {
process.destroyForcibly();
throw new IllegalStateException("gradle " + String.join(" ", arguments) + " did not end");
}
return new Run(process.exitValue(), Files.readString(output, StandardCharsets.UTF_8));
}
private static Path gradleHome() {
String home = System.getProperty("ca.gradle.home");
assertThat(home)
.as("build-logic's test task passes the running Gradle's home as ca.gradle.home")
.isNotBlank();
return Path.of(home);
}
}
@@ -605,6 +605,99 @@ class StrictLaneStagesFunctionalTest {
.contains("Gradle rejects -mx");
}
@Test
@DisplayName("실패하면 단계도 실패하지만 검사가 읽지 않는 모양으로만 부른 단계는 세지 않고, 그 명령을 혼자 한 줄로 두라고 안내한다")
void aStageCalledOnlyInAShapeTheCheckDoesNotReadFailsSayingToPutItOnALineOfItsOwn()
throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
defaults:
run:
working-directory: src
jobs:
main:
steps:
- run: ./gradlew :ci --stacktrace
- run: |
./gradlew :integrationCheck || { echo "::error::integration failed"; exit 1; }
echo done
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("this check does not read")
.contains("put the stage command on a line of its own");
}
@Test
@DisplayName("재사용 workflow의 단계는 매 변경에 도는 workflow가 부를 때만 세고, 요청으로만 부르면 세지 않는다")
void aStageInAReusableWorkflowCountsOnlyThroughACallerThatRunsOnEveryChange()
throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
on:
workflow_call:
jobs:
gate:
runs-on: ubuntu-latest
steps:
- working-directory: src
run: ./gradlew :ci --stacktrace
""");
Files.writeString(
repository.resolve(".github/workflows/integration.yml"),
"""
on:
workflow_call:
jobs:
lanes:
runs-on: ubuntu-latest
steps:
- working-directory: src
run: ./gradlew :integrationCheck --continue
""");
Files.writeString(
repository.resolve(".github/workflows/pull-request.yml"),
"""
on: pull_request
jobs:
gate:
uses: ./.github/workflows/main.yml
""");
Files.writeString(
repository.resolve(".github/workflows/on-request.yml"),
"""
on: [workflow_dispatch, repository_dispatch]
jobs:
lanes:
uses: ./.github/workflows/integration.yml
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("integration.yml: gradlew :integrationCheck")
.contains("workflow_call")
.doesNotContain("stage :ci is executed by no workflow");
}
private void leafLanes(String lanes) throws Exception {
Files.writeString(
gradleRoot.resolve("leaf/build.gradle"),
@@ -873,6 +873,544 @@ class WorkflowGradleInvocationsTest {
});
}
@Test
@DisplayName("Gradle이 버전·도움말·데몬 상태만 보이고 작업 없이 끝나는 옵션을 붙인 명령은 실행으로 세지 않는다")
void aCommandWithAnOptionAfterWhichGradleRunsNoTaskDoesNotCount() {
// given
String workflow =
"""
- run: ./gradlew :ci -v
- run: ./gradlew :ci --version
- run: ./gradlew -v :ci
- run: ./gradlew :ci --help
- run: ./gradlew :ci -h
- run: ./gradlew :ci -?
- run: ./gradlew -qv :ci
- run: ./gradlew :ci --status
- run: ./gradlew :ci --stop
- run: ./gradlew :ci --foreground
""";
// when
List<Invocation> invocations = WorkflowGradleInvocations.read(workflow);
// then
assertThat(invocations)
.hasSize(10)
.allSatisfy(
invocation -> {
assertThat(invocation.uncountedReason()).contains("runs no task");
assertThat(invocation.executes(":ci", ".")).isFalse();
});
}
@Test
@DisplayName("버전을 찍고 계속하는 -V는 작업을 실행하므로 센다")
void showVersionThatContinuesStillRunsTheTasks() {
// given
String workflow =
"""
- run: ./gradlew -V :ci
""";
// when
List<Invocation> invocations = WorkflowGradleInvocations.read(workflow);
// then
assertThat(invocations).singleElement().satisfies(
invocation -> assertThat(invocation.executes(":ci", ".")).isTrue());
}
@Test
@DisplayName("조건부 exit 0·인자 없는 exit·값을 모르는 exit·exec·set -n 뒤의 gradlew는 돌지 않을 수 있으므로 세지 않는다")
void gradlewAfterACommandThatMayEndTheScriptFirstDoesNotCount() {
// given
String workflow =
"""
defaults:
run:
working-directory: src
jobs:
main:
steps:
- run: |
if git diff --quiet origin/main -- .; then echo "no source change"; exit 0; fi
./gradlew :ci
- run: |
[ "$SKIP_CI" = true ] && exit 0
./gradlew :ci
- run: |
if [ -f skip ]; then echo skipping; exit; fi
./gradlew :ci
- run: |
if [ -f skip ]; then exit "$code"; fi
./gradlew :ci
- run: |
skip() { echo skip; exit 0; }
skip
./gradlew :ci
- run: |
exec ./gradlew :help
./gradlew :ci
- run: |
set -n
./gradlew :ci
- run: |
set -o noexec
./gradlew :ci
""";
// when
List<Invocation> invocations = WorkflowGradleInvocations.read(workflow);
// then
assertThat(invocations.stream().filter(invocation -> invocation.requests(":ci")).toList())
.hasSize(8)
.allSatisfy(
invocation -> {
assertThat(invocation.uncountedReason()).isNotBlank();
assertThat(invocation.executes(":ci", "src")).isFalse();
});
}
@Test
@DisplayName("EXIT·ERR trap이 exit하면 gradlew가 실패해도 단계가 성공할 수 있으므로 그 뒤 gradlew는 세지 않는다")
void gradlewAfterATrapThatExitsOnExitOrErrDoesNotCount() {
// given
String workflow =
"""
defaults:
run:
working-directory: src
jobs:
main:
steps:
- run: |
trap 'exit 0' EXIT
./gradlew :ci
- run: |
trap 'echo failed; exit 0' ERR
./gradlew :ci
- run: |
trap 'echo failed; exit' err
./gradlew :ci
- run: |
trap cleanup EXIT
cleanup() { rm -f build.lock; exit 0; }
./gradlew :ci
""";
// when
List<Invocation> invocations = WorkflowGradleInvocations.read(workflow);
// then
assertThat(invocations)
.hasSize(4)
.allSatisfy(
invocation -> {
assertThat(invocation.uncountedReason()).contains("trap");
assertThat(invocation.executes(":ci", "src")).isFalse();
});
}
@Test
@DisplayName("단계를 실패시키는 exit, 부르지 않은 함수·서브셸·명령 치환 안의 exit, 상태를 지키는 trap, 명령 없는 exec 뒤의 gradlew는 센다")
void gradlewAfterAnExitThatFailsTheStepOrThatDoesNotEndTheScriptStillCounts() {
// given
String workflow =
"""
defaults:
run:
working-directory: src
jobs:
main:
steps:
- run: |
if [ ! -s snapshot.txt ]; then echo "::error::missing"; exit 1; fi
./gradlew :ci
- run: |
[ -n "$RUN" ] || exit
./gradlew :ci
- run: |
skip() { exit 0; }
./gradlew :ci
- run: |
( exit 0 )
echo "$(exit 0)"
./gradlew :ci
- run: |
trap 'rm -f build.lock' EXIT
./gradlew :ci
- run: |
trap 'rm -f build.lock; exit' EXIT
./gradlew :ci
- run: |
exec 2>&1
./gradlew :ci
""";
// when
List<Invocation> invocations = WorkflowGradleInvocations.read(workflow);
// then
assertThat(invocations)
.hasSize(7)
.allSatisfy(
invocation -> {
assertThat(invocation.uncountedReason()).isNull();
assertThat(invocation.executes(":ci", "src")).isTrue();
});
}
@Test
@DisplayName("셸을 정하지 않은 단계는 Windows일 수 있는 runner면 기본 셸이 pwsh일 수 있으므로 세지 않는다")
void aDefaultShellStepOnARunnerThatMayBeWindowsDoesNotCount() {
// given
String workflow =
"""
defaults:
run:
working-directory: src
jobs:
windows:
runs-on: windows-latest
steps:
- run: ./gradlew :ci
matrix:
runs-on: ${{ matrix.os }}
steps:
- run: ./gradlew :ci
unknown-self-hosted:
runs-on: [self-hosted, gpu]
steps:
- run: ./gradlew :ci
linux:
runs-on: ubuntu-latest
steps:
- run: ./gradlew :ci
mac:
runs-on: macos-14
steps:
- run: ./gradlew :ci
linux-self-hosted:
runs-on:
- self-hosted
- Linux
steps:
- run: ./gradlew :ci
windows-bash:
runs-on: windows-latest
defaults:
run:
shell: bash
steps:
- run: ./gradlew :ci
linux-container:
runs-on: ${{ matrix.runner }}
container: eclipse-temurin:21
steps:
- run: ./gradlew :ci
""";
// when
List<Invocation> invocations = WorkflowGradleInvocations.read(workflow);
// then
assertThat(invocations)
.extracting(invocation -> invocation.executes(":ci", "src"))
.containsExactly(false, false, false, true, true, true, true, true);
assertThat(invocations.subList(0, 3))
.allSatisfy(invocation -> assertThat(invocation.uncountedReason()).contains("pwsh"));
}
@Test
@DisplayName("실패하면 단계도 실패하지만 판독기가 읽지 않는 모양은 실패를 막지 못한다고 하지 않고, 읽지 않는다며 혼자 한 줄로 두라고 말한다")
void aShapeThatWouldFailTheStepButIsNotReadSaysSoInsteadOfClaimingItCannotFail() {
// given
String workflow =
"""
defaults:
run:
working-directory: src
jobs:
main:
steps:
- run: |
./gradlew :ci || exit 1
echo done
- run: |
./gradlew :ci || { echo "::error::ci failed"; exit 1; }
echo done
- run: |
{ ./gradlew :ci; }
echo done
- run: |
( ./gradlew :ci )
echo done
- run: |
./gradlew :ci || true
echo done
- run: |
if [ -n "$RUN" ]; then ./gradlew :ci; fi
echo done
""";
// when
List<Invocation> invocations = WorkflowGradleInvocations.read(workflow);
// then
assertThat(invocations).extracting(Invocation::uncountedReason)
.satisfiesExactly(
reason -> assertThat(reason).contains("does not read").contains("line of its own"),
reason -> assertThat(reason).contains("does not read").contains("line of its own"),
reason -> assertThat(reason).contains("does not read").contains("line of its own"),
reason -> assertThat(reason).contains("does not read").contains("line of its own"),
reason -> assertThat(reason).contains("|| true").doesNotContain("does not read"),
reason -> assertThat(reason).contains("may not run").doesNotContain("does not read"));
}
@Test
@DisplayName("요청이 있어야 시작하는 trigger만 있는 workflow의 명령은 세지 않는다")
void aWorkflowThatStartsOnlyOnRequestsGatesNothing() {
// given
List<String> workflows =
List.of(
"""
on: [workflow_dispatch, repository_dispatch]
jobs:
main:
steps:
- working-directory: src
run: ./gradlew :ci
""",
"""
on:
issue_comment:
types: [created]
jobs:
main:
steps:
- working-directory: src
run: ./gradlew :ci
""",
"""
on:
pull_request:
types: [labeled]
jobs:
main:
steps:
- working-directory: src
run: ./gradlew :ci
""");
// when
List<Invocation> invocations =
workflows.stream().flatMap(workflow -> WorkflowGradleInvocations.read(workflow).stream())
.toList();
// then
assertThat(invocations).extracting(Invocation::uncountedReason)
.satisfiesExactly(
reason -> assertThat(reason).contains("repository_dispatch"),
reason -> assertThat(reason).contains("issue_comment"),
reason -> assertThat(reason).contains("labeled"));
}
@Test
@DisplayName("push·pull_request·merge_group·schedule·release 중 하나로도 시작하는 workflow의 명령은 센다")
void aWorkflowThatAlsoStartsOnTheChangeOrReleaseFlowCounts() {
// given
List<String> workflows =
List.of(
"""
on: {pull_request: {branches: [main]}, issue_comment: {types: [created]}}
jobs:
main:
steps:
- working-directory: src
run: ./gradlew :ci
""",
"""
on:
merge_group:
workflow_dispatch:
jobs:
main:
steps:
- working-directory: src
run: ./gradlew :ci
""",
"""
on:
schedule:
- cron: '0 3 * * *'
jobs:
main:
steps:
- working-directory: src
run: ./gradlew :ci
""",
"""
on:
release:
types: [published]
jobs:
main:
steps:
- working-directory: src
run: ./gradlew :ci
""",
"""
on:
pull_request:
types: [opened, synchronize, labeled]
jobs:
main:
steps:
- working-directory: src
run: ./gradlew :ci
""");
// when
List<Invocation> invocations =
workflows.stream().flatMap(workflow -> WorkflowGradleInvocations.read(workflow).stream())
.toList();
// then
assertThat(invocations)
.hasSize(5)
.allSatisfy(invocation -> assertThat(invocation.executes(":ci", "src")).isTrue());
}
@Test
@DisplayName("workflow_call로만 시작하는 재사용 workflow의 명령은 매 변경에 도는 호출 job이 있을 때만 센다")
void aReusableWorkflowCountsOnlyThroughACallerThatRunsOnEveryChange() {
// given
String reusable =
"""
on:
workflow_call:
inputs:
lane:
type: string
jobs:
stage:
runs-on: ubuntu-latest
steps:
- working-directory: src
run: ./gradlew :ci
""";
String pushCaller =
"""
on: push
jobs:
call:
uses: ./.github/workflows/reusable.yml
""";
String conditionalCaller =
"""
on: push
jobs:
call:
if: github.ref == 'refs/heads/release'
uses: ./.github/workflows/reusable.yml
""";
String manualCaller =
"""
on: workflow_dispatch
jobs:
call:
uses: ./.github/workflows/reusable.yml
""";
// when
List<Map<String, List<Invocation>>> readings =
List.of(
WorkflowGradleInvocations.readAll(Map.of("reusable.yml", reusable)),
WorkflowGradleInvocations.readAll(
Map.of("reusable.yml", reusable, "push.yml", pushCaller)),
WorkflowGradleInvocations.readAll(
Map.of("reusable.yml", reusable, "conditional.yml", conditionalCaller)),
WorkflowGradleInvocations.readAll(
Map.of("reusable.yml", reusable, "manual.yml", manualCaller)));
// then
assertThat(readings)
.extracting(reading -> reading.get("reusable.yml").get(0).executes(":ci", "src"))
.containsExactly(false, true, false, false);
assertThat(readings.get(0).get("reusable.yml").get(0).uncountedReason())
.contains("workflow_call");
assertThat(readings.get(2).get("reusable.yml").get(0).uncountedReason())
.contains("conditional.yml");
}
@Test
@DisplayName("조건부 job이나 continue-on-error job을 needs로 기다리는 job의 명령은 세지 않고, always()로 끊으면 센다")
void aJobThatNeedsAJobThatMayBeSkippedDoesNotCount() {
// given
String workflow =
"""
defaults:
run:
working-directory: src
jobs:
changes:
runs-on: ubuntu-latest
if: github.event_name == 'push'
steps:
- run: echo changed
advisory:
runs-on: ubuntu-latest
continue-on-error: true
steps:
- run: echo maybe
plain:
runs-on: ubuntu-latest
steps:
- run: echo plain
after-changes:
runs-on: ubuntu-latest
needs: changes
steps:
- run: ./gradlew :ci
chained:
runs-on: ubuntu-latest
needs: [plain, after-changes]
steps:
- run: ./gradlew :ci
after-advisory:
runs-on: ubuntu-latest
needs:
- advisory
steps:
- run: ./gradlew :ci
always-after-changes:
runs-on: ubuntu-latest
needs: changes
if: ${{ !cancelled() }}
steps:
- run: ./gradlew :ci
after-plain:
runs-on: ubuntu-latest
needs: plain
steps:
- run: ./gradlew :ci
""";
// when
List<Invocation> invocations = WorkflowGradleInvocations.read(workflow);
// then
List<Invocation> gradle =
invocations.stream().filter(invocation -> invocation.requests(":ci")).toList();
assertThat(gradle)
.extracting(invocation -> invocation.executes(":ci", "src"))
.containsExactly(false, false, false, true, true);
assertThat(gradle.subList(0, 3))
.allSatisfy(invocation -> assertThat(invocation.uncountedReason()).contains("needs"));
}
@Test
@DisplayName("uses 단계의 with 입력에 적힌 run은 셸 명령이 아니므로 읽지 않는다")
void aRunInputOfAnActionIsNotAShellCommand() {
@@ -31,6 +31,14 @@ def sharedMigrationFileSources = tasks.register('sharedMigrationFileSources', Sy
into(layout.buildDirectory.dir('generated/sources/sharedMigrationFiles/java'))
}
sourceSets.integrationTest.java.srcDir(sharedMigrationFileSources)
// The copy is not this build's to format: Spotless here would name the generated file, and its
// spotlessApply would rewrite only that copy, which the next Sync puts back (re-review 2026-11-03
// round 6, RR6-03-04). The main build's persistence-jpa spotlessCheck formats the original.
spotless {
java {
targetExclude('build/generated/sources/sharedMigrationFiles/**')
}
}
// Durable mutation idempotency: the operation ledger entity, its state machine, the vendor-neutral
// repository port and the Spring Data JPA binding, plus the migration that owns the unique
@@ -29,10 +29,18 @@ import org.testcontainers.postgresql.PostgreSQLContainer;
*
* <p>A transaction that has written the ledger stays open for fifteen seconds — a claim in flight,
* an operator's {@code BEGIN}. A write is the holder both migrations wait for: V003's ALTER TABLE
* would wait for a read too, V002's plain CREATE INDEX only for a write. The migration runs the way
* Flyway runs it, in one transaction. Unbounded it waits until the writer leaves, with every claim
* queued behind it, and then applies; bounded it fails with {@code lock_not_available} first and
* its rollback leaves the ledger as it was.
* would wait for a read too, V002's plain CREATE INDEX only for a write. The migration runs in one
* transaction, which is how Flyway runs the files this tree has: a {@code SET LOCAL lock_timeout}
* and statements that run in a transaction. Unbounded it waits until the writer leaves, with every
* claim queued behind it, and then applies; bounded it fails with {@code lock_not_available} first
* and its rollback leaves the ledger as it was.
*
* <p>A file Flyway runs outside a transaction — one holding {@code CREATE INDEX CONCURRENTLY} or
* another statement on Flyway's list, or with {@code executeInTransaction=false} beside it — is not
* one this test can judge: run here in a transaction, PostgreSQL refuses it ({@code 25001}), and no
* {@code SET LOCAL} would bound it in a deploy anyway. Name such a file as an exception in this
* test, and keep it alone in its migration ({@code docs/jpa/migration-guide.md}, "Concurrent index
* builds"; re-review 2026-11-03 round 6, RR6-03-05).
*
* <p>Every migration after V001 is held to this, read from the tree itself ({@link
* GrpcOperationLedgerMigrations#inOrder()}), so a V004 is checked without anyone naming it here.
@@ -46,6 +54,7 @@ import org.testcontainers.postgresql.PostgreSQLContainer;
class GrpcOperationLedgerMigrationLockWaitIT {
private static final String LOCK_NOT_AVAILABLE = "55P03";
private static final String ACTIVE_SQL_TRANSACTION = "25001";
private static final Duration WRITER_STAYS = Duration.ofSeconds(15);
private static final Duration GIVES_UP_WITHIN = Duration.ofSeconds(10);
@@ -86,8 +95,14 @@ class GrpcOperationLedgerMigrationLockWaitIT {
schema(statement)))
.as(
"%s must put SET LOCAL lock_timeout = '5s'; before it locks the ledger"
+ " (docs/jpa/migration-guide.md, \"Bound the lock wait\")",
migration)
+ " (docs/jpa/migration-guide.md, \"Bound the lock wait\")%s",
migration,
ACTIVE_SQL_TRANSACTION.equals(attempt.sqlState())
? ". PostgreSQL refused it inside a transaction (25001): Flyway runs such a file"
+ " outside one, where SET LOCAL bounds nothing, so it is no case for this"
+ " test. Keep it alone in its migration and name it as an exception here"
+ " (\"Concurrent index builds\")"
: "")
.containsExactly(LOCK_NOT_AVAILABLE, true, schemaBefore);
}
}
@@ -1,5 +1,6 @@
package dev.caskeleton.sample.portfolio.bootstrap.persistence;
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationVersion;
import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy;
@@ -38,7 +39,10 @@ public class SamplePostgreSqlPersistenceConfig {
static org.flywaydb.core.api.configuration.FluentConfiguration sampleFlywayConfiguration(
javax.sql.DataSource dataSource) {
return Flyway.configure(SamplePostgreSqlPersistenceConfig.class.getClassLoader())
// Through the persistence leaf's policy, so this stream takes Flyway's PostgreSQL lock the way
// every other one does (re-review 2026-11-03 round 6, RR6-03-01). A service's own stream starts
// from the same call.
return FlywaySchemaPolicy.configure(SamplePostgreSqlPersistenceConfig.class.getClassLoader())
.dataSource(dataSource)
.locations("classpath:db/sample-migration")
.table("flyway_sample_schema_history")
+15
View File
@@ -35,6 +35,21 @@ envelope shape, metric cardinality bounds, tracing seam, domain-context propagat
that pins its output to a vector computed outside the JVM.
- `observability/MdcKeys`: the snake_case MDC key names (registry `docs/registries/mdc-keys.yaml`)
every transport puts a request's correlation under — web, GraphQL, STOMP and gRPC alike.
- `ratelimit/`: the provider-neutral edge rate-limit port (`EdgeRateLimitPort`) and its value types,
between the web edge and the Redis adapter (README 「ratelimit」).
- `security/Permission`: the `resource:action` permission value `AuthorizationPort` is asked about
(README 「security」).
- `concurrency/`: the domain-context propagation port and its `ThreadLocal` default (README
「concurrency」).
- `runtime/RuntimeEnvironment`: the one runtime-profile vocabulary every leaf answers "is this
production?" with.
- `metrics/ForbiddenMetricTags`: the high-cardinality tag keys no metric may carry.
- These are the module's packages and the only ones it may have:
`ForbiddenApiArchitectureTest.SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES` refuses a
class in any other package below `dev.caskeleton.shared` or directly in the root, which holds only
its `package-info`. A new contract package goes into that test's `SHARED_CONTRACT_PACKAGES` and
into this list together; `SharedContractPackageRuleTest` fails when `SHARED_CONTRACT_PACKAGES` and
the module's packages differ.
- Registry-rule mirrors read only by contract tests live in `testFixtures`, not `main`:
`metrics/MetricNaming`, `metrics/CardinalityBounds`, `metrics/AlertSeverity`,
`tracing/BaggageAllowlist`. Move one to `main` only when production code consumes it.
+5
View File
@@ -91,6 +91,11 @@ Spring/Lettuce 타입을 노출하지 않는다.
사고가 아니다). `IDEMPOTENCY_RECOVERY_REQUIRED`는 예외 메시지 끝의 scope digest로 runbook이 기록을 찾는다.
- 전송은 자기 상관 정보를 뒤에 붙인다: gRPC ` (method=<서비스/메서드>)`, GraphQL ` (executionId=<id>)`.
예외는 늘 마지막 인자라 SLF4J가 예외로 받는다.
- `IllegalArgumentException`을 `BAD_PARAMETER`로 답하면 네 전송 모두 `refusedArgument`의 WARN 한 줄
`request refused as BAD_PARAMETER by <예외 타입>`을 남긴다. 사고가 아니라 잘못된 요청이라 ERROR가 아니고,
사실은 서버 조립 실수(`IllegalStateException`이어야 할 것)인 400도 흔적이 남도록 타입은 적는다. 메시지는
입력값이 들 수 있어 남기지 않고 예외도 붙이지 않는다(재리뷰 RR6-01-06 전에는 web만 이 줄을 남기고 STOMP는
ERROR에 메시지까지 남겼다).
### OperationalError (enum)
스켈레톤 공통 운영/전송/보안 에러 코드의 집합이다. `USER_NOT_FOUND` 같은 **도메인 전용 코드는
@@ -27,6 +27,10 @@ import java.util.Optional;
* transport hands {@link #format(String)} and {@link #arguments(Object...)} straight to {@code
* Logger.error}. A transport adds its own correlation (a gRPC method, a GraphQL execution id) as a
* suffix; the failure stays last.
*
* <p>One line is not an error: {@link #refusedArgument(IllegalArgumentException)}, which every
* transport writes at WARN when it answers an {@link IllegalArgumentException} as {@link
* OperationalError#BAD_PARAMETER}.
*/
public final class ServerFailureLog {
@@ -74,6 +78,23 @@ public final class ServerFailureLog {
return Optional.empty();
}
/**
* The WARN line for an {@link IllegalArgumentException} a transport answers as {@link
* OperationalError#BAD_PARAMETER}: the request was wrong, so it is not an error, but the line
* names the exception type so that a refusal which is really a misassembled server — code that
* should have thrown {@link IllegalStateException} — still leaves a trace. The message is not
* logged and nothing is attached: it may echo request input. Web, GraphQL, gRPC and STOMP write
* the same line (review 2026-11-05 RR6-01-06).
*
* @param failure the refused argument; a carrier is logged by {@link #of} instead
*/
public static ServerFailureLog refusedArgument(IllegalArgumentException failure) {
return new ServerFailureLog(
"request refused as " + OperationalError.BAD_PARAMETER.code() + " by {}",
new Object[] {failure.getClass().getName()},
null);
}
/**
* The message pattern, followed by the transport's own placeholders.
*
@@ -87,6 +87,23 @@ class ServerFailureLogTest {
assertThat(line).isEmpty();
}
@Test
void aRefusedArgumentNamesTheExceptionTypeWithoutItsMessage() {
// given
IllegalArgumentException failure =
new IllegalArgumentException("unknown recipient alice@example.com");
// when
ServerFailureLog line = ServerFailureLog.refusedArgument(failure);
// then
assertThat(
new Object[] {line.format(" (method={})"), line.arguments("orders.v1.Orders/Charge")})
.containsExactly(
"request refused as BAD_PARAMETER by {} (method={})",
new Object[] {"java.lang.IllegalArgumentException", "orders.v1.Orders/Charge"});
}
@Test
void aTransportsOwnFieldsGoBetweenTheClassificationAndTheAttachedFailure() {
// given