From 7535a4ca7a75db6d5398ff55c47d25a324dda1ec Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 07:50:40 +0900 Subject: [PATCH] =?UTF-8?q?fix(idempotency)!:=20=EC=A0=81=EC=9A=A9?= =?UTF-8?q?=ED=95=9C=20=ED=95=B8=EB=93=A4=EC=9D=98=20=EC=9E=AC=EC=A0=84?= =?UTF-8?q?=EC=86=A1=EC=9D=84=20=EC=A0=84=EC=9D=B4=20=EC=A2=85=EB=A5=98?= =?UTF-8?q?=EC=99=80=20=EC=9D=B8=EC=9E=90=EB=A1=9C=20=EA=B0=80=EB=A6=B0?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 전이를 적용한 핸들이 그 전이를 다시 보낼 때 세 저장소가 서로, 그리고 포트 Javadoc과 다르게 답한다(재리뷰 round8 RR8-04-01·02, 같은 원인). - markFailed를 다른 disposition으로 다시 보내면 fake·Redis·PostgreSQL 모두 NOT_OWNER다. 기록을 남이 가져갔다는 틀린 신호이고 Javadoc은 OPERATION_CONFLICT라고 적는다. - retention만 다르면 fake·Redis는 ALREADY_MARKED_SAME_OPERATION, PostgreSQL은 fail digest에 retention이 들어 있어 OPERATION_CONFLICT다. - Redis는 start가 돌려준 핸들로 renew한 뒤 그 핸들로 start를 보내면 ALREADY_STARTED_SAME_OPERATION으로 답한다. renew도 기록을 EXECUTING· revision+1로 두어 TRANSITION이 상태와 revision만으로는 start와 구별하지 못한다. executor는 그 답에 action을 실행해 이미 도는 작업을 한 번 더 돌린다. fake·PostgreSQL은 NOT_OWNER다. 원인은 하나다. "적용한 핸들"을 revision 하나로만 가리고 전이 종류와 인자를 같이 보지 않는다. 방법: 소유자 결정(2026-11-07, 1103 README 19.4절 ② (a))대로 다른 disposition은 OPERATION_CONFLICT, 다른 retention은 "이미 처리됨"으로 맞춘다. retention은 complete의 replay TTL처럼 결과를 얼마나 보관하나일 뿐이라 비교하지 않는다. - Redis: 기록 hash에 lastKind(CLAIM·START·RENEW·COMPLETE·FAIL)를 남긴다. TRANSITION의 재전송 판정은 "rev == 핸들 rev + 1 그리고 lastKind == 이 전이"다. 그 안에서 상태가 목표면 ALREADY, 아니면(다른 disposition의 실패) OPERATION_CONFLICT. claim·takeover는 CLAIM을 써 넘겨받기 전 종류가 남지 않게 한다. 어댑터가 전이 종류를 9번째 인자로 보낸다. 명령 fake를 같이 고친다. - PostgreSQL: fail 재생 판정이 두 실패 종류(FAIL_RETRYABLE·FAIL_ABANDONED)를 모두 실패의 재생으로 읽는다. fail digest에서 retention을 뺀다. - fake: 적용한 핸들의 markFailed 재전송에 disposition이 다르면 OPERATION_CONFLICT. - 공유 계약 IdempotencyStoreContract에 케이스 셋(다른 retention, 다른 disposition과 기록 유지, renew 뒤 같은 핸들의 start)을 더했다. - PostgreSqlIdempotencyIntegrationTest의 "다른 retention은 conflict" 케이스가 옛 동작을 고정하고 있어 결정대로 "이미 처리됨, 처음 retention 유지"로 바꿨다(...IsConfirmedAndKeepsItsRetention). IdempotencyFailOutcome·IdempotencyStartOutcome·IdempotencyStorePort Javadoc, 결정 색인 2.4절(새 행과 「넘겨받기 전 핸들의 재전송」 적용 조건), application-core CLAUDE.md·README, cache-redis·persistence-jpa README, TESTING_STRATEGY, 업그레이드 안내 5절 행을 같이 고쳤다. 버린 대안: 다른 disposition을 NOT_OWNER로 두고 Javadoc만 고치기(19.4절 ② (b), 소유자가 고르지 않음, 적용한 핸들에 "넘겨받혔다"는 틀린 신호), 다른 retention도 OPERATION_CONFLICT(② (c), Redis 기록에 retention을 더하고 Lua를 바꿔야 하며 보관 기간을 인자로 본다), Redis start 분기만 "renewedFromRev가 있으면 ALREADY 아님"으로 막기(같은 상태에 머무는 전이가 늘면 다시 갈라진다). 위험·한계: 템플릿 호출자(IdempotencyExecutor)는 같은 인자로만 다시 보내고 renew를 부르지 않아 HTTP 동작은 같다. 포트를 직접 부르는 코드만 답이 바뀐다. 이 배포 전에 쓰인 Redis 기록에는 lastKind가 없어, 새 프로그램이 그 기록의 전이를 재전송으로 보지 않는다. 핸들은 프로세스 메모리에만 있고 같은 프로세스는 같은 프로그램을 돌리므로, 새 프로그램이 옛 프로그램이 적용한 전이의 핸들을 받는 경로는 템플릿에 없다고 본다(실행으로 확인하지 않음). PostgreSQL도 같은 이유로 옛 fail digest(retention 포함)와 새 digest를 같은 핸들로 비교하는 경로가 없다고 보고 digest VERSION을 올리지 않았다. 검증: desktop, 공유 잠금, --no-build-cache, 기준 3eb3b067. - RED(기준 커밋 + 계약 케이스만, 로그 ~/r9-g4-red-logs/red-summary.txt): fake 62 중 1 실패(다른 disposition "expected: OPERATION_CONFLICT but was: NOT_OWNER"), Redis 명령 fake 62 중 2·실 Redis(redisContainerContractTest) 103 중 2 실패(다른 disposition, renew 뒤 start "expected: NOT_OWNER but was: ALREADY_STARTED_SAME_OPERATION"), 실 PostgreSQL 62 중 2 실패(다른 disposition, 다른 retention "expected: ALREADY_MARKED_SAME_OPERATION but was: OPERATION_CONFLICT"). - GREEN(이 커밋과 같은 트리 5a74698d, 로그 ~/r9-g4-green-logs/와 pass2/, 수는 결과 XML에서 셈 test-counts.txt): 네 leaf check(application-core 426· skip 19 fake 시간 케이스, cache-redis 228, redis-runtime 65, persistence-jpa 666)와 testQualityCheck, redisContainerContractTest 103, jpaPlatformContractTest 432, fake를 쓰는 leaf(composition:idempotency 32, redis-sdk 310, web 341, sample-portfolio 339), documentContractTest 67 — 모두 rc=0, 실패 0. postgresqlIdempotencyIntegrationTest는 1차에서 위 옛 케이스 1건이 실패했고, 고친 뒤 pass2에서 persistence-jpa spotlessCheck· check·testQualityCheck와 함께 10 중 실패 0, rc=0. - scripts/check-work-docs.py rc=0, git diff --check 통과. BREAKING CHANGE: IdempotencyStorePort 구현은 적용한 핸들이 markFailed를 다른 disposition으로 다시 보내면 OPERATION_CONFLICT, retention만 다르면 ALREADY_MARKED_SAME_OPERATION으로 답해야 하고, renew를 적용한 핸들의 start를 "이미 시작됨"으로 확인하면 안 된다(NOT_OWNER). 직접 구현한 store는 IdempotencyStoreContract의 새 케이스로 확인한다. --- docs/testing/TESTING_STRATEGY.md | 5 ++ docs/upgrade/2026-11-maturity-review.md | 4 +- docs/work/reference/decisions.md | 3 +- src/adapter/outbound/cache-redis/README.md | 10 ++- .../redis/idempotency/IdempotencyScripts.java | 47 +++++++---- .../RedisIdempotencyStoreAdapter.java | 20 ++++- .../outbound/persistence-jpa/README.md | 7 +- .../postgresql/IdempotencyDigestPolicy.java | 10 ++- .../PostgreSqlIdempotencyStore.java | 38 +++++---- .../PostgreSqlIdempotencyIntegrationTest.java | 11 +-- .../InMemorySemanticRedisCommands.java | 18 ++++- src/application-core/CLAUDE.md | 12 ++- src/application-core/README.md | 6 +- .../idempotency/IdempotencyFailOutcome.java | 9 ++- .../idempotency/IdempotencyStartOutcome.java | 4 +- .../idempotency/IdempotencyStorePort.java | 5 +- .../testkit/IdempotencyStoreContract.java | 77 +++++++++++++++++++ .../testkit/InMemoryIdempotencyStore.java | 11 ++- 18 files changed, 234 insertions(+), 63 deletions(-) diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index c224d85f..d2f5e7c7 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -267,6 +267,11 @@ source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌 markFailed·renew·release는 `OPERATION_CONFLICT`로 답했다 — 주인이 renew가 돌려준 핸들로 다시 renew해도 그랬다. fake는 complete 말고는 적용한 핸들의 재전송도 `NOT_OWNER`였다. 셋 다 적용한 핸들(기록보다 revision이 하나 낮은 핸들)에게만 확인하고 다른 핸들은 `NOT_OWNER`로 맞췄다(2026-11-06 소유자 결정). + (5) 그 "적용한 핸들"을 Redis는 revision 하나로만 가렸다. 그래서 renew를 적용한 핸들이 start를 보내면 Redis만 + "이미 시작됨"(호출자가 작업을 다시 돌린다), fake·PostgreSQL은 `NOT_OWNER`였다. Redis 기록에 마지막 전이 + 종류(`lastKind`)를 남겨 그 전이일 때만 확인한다. 적용한 핸들이 markFailed를 다른 disposition으로 다시 보내면 + 셋 다 `NOT_OWNER`였고, 다른 retention이면 PostgreSQL만 `OPERATION_CONFLICT`, Redis·fake는 "이미 처리됨"이었다. + 다른 disposition은 `OPERATION_CONFLICT`, 다른 retention은 "이미 처리됨"으로 맞췄다(2026-11-07 소유자 결정). - `OutboxAppendContract`는 static helper 두 개였고 JPA readiness 테스트만 불렀다. 추상 계약으로 바꿔 readiness 테스트가 상속한다(같은 두 케이스 + 트랜잭션 밖·읽기 전용·중복 eventId). 실 PostgreSQL에서 `inRead` 안의 append가 예외 없이 사라지는 것을 찾았다(실측: 예외 없음, 행 없음) — JPA 트랜잭션 diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index 5990e3ab..ddde2ca4 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -4,7 +4,7 @@ - 커밋: `34565130` High·P1 19건 · `1400dc15` 남은 발견·매뉴얼·생성 명령 · `5786126c` 남은 항목과 합친 뒤 결함 · `7ef8d0b4` 재리뷰 기록 · `bbe944bd` 재리뷰 결함 · `ecc74b7d` 2차 재리뷰 기록·이 안내 · `1885bf8d` 2차 재리뷰 결함 · `339cf8fd` 3차 확인 리뷰 기록 · `f40c03c6` 3차 확인 리뷰 Minor · `c2e55510` 마지막 확인 리뷰 기록 · - `2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) · `paths` 필터 trigger를 단계 실행으로 세지 않음(2026-11-06 소유자 결정, B-36) · r8-f1 전송 오류 처리(2026-11-07, B-45~B-48) · 태그 push·`release` workflow는 `releaseCheck`에만 셈(2026-11-07 소유자 결정, B-36) — `docs(...)` 커밋은 문서만 바꾼다 + `2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) · `paths` 필터 trigger를 단계 실행으로 세지 않음(2026-11-06 소유자 결정, B-36) · r8-f1 전송 오류 처리(2026-11-07, B-45~B-48) · 태그 push·`release` workflow는 `releaseCheck`에만 셈(2026-11-07 소유자 결정, B-36) · 멱등 저장소의 markFailed 재전송 인자와 renew 뒤 start(2026-11-07 소유자 결정, 5절) — `docs(...)` 커밋은 문서만 바꾼다 - 근거 문서: `docs/reviews/2026-11-01-maturity-review/README.md` 13~16절, `docs/reviews/2026-11-03-rereview/README.md` 4·6·8~13절, 각 커밋의 `BREAKING CHANGE:` 꼬리말 - 아래 표의 각 줄은 위 범위의 diff와 코드로 확인했다. 확인하지 못한 것은 그 자리에 "확인 못 함"으로 적었고 9절에 @@ -248,7 +248,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | 멱등성(lease가 끝난 시작, r9) | lease가 지난 `CLAIMED`는 주인도 시작할 수 없다(`LEASE_EXPIRED`). executor는 작업을 돌리지 않고 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거부, 메시지 `the claim's processing lease ran out before the action started`)로 답하고, 다음 같은 키 요청이 그 claim을 넘겨받아 실행한다. 전에는 Redis가 시작해 작업을 돌렸고 그동안 다른 요청은 lease가 지난 실행으로 500을 받았다. PostgreSQL은 `NOT_OWNER`로 거절해 500 `IDEMPOTENCY_RECOVERY_REQUIRED`였다. | claim과 시작 사이가 lease(기본 30s)보다 길었던 드문 요청이 500 대신 503(같은 키 재전송)을 받는다. 클라이언트는 `error.code`로 이미 가르므로 바꿀 것이 없다. 운영자는 이 503에서 저장소 장애를 찾지 않는다(runbook) | r9(재리뷰 README 15 남음, RR5-01-02·03) · `IdempotencyExecutor.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java` | | 멱등성(같은 attempt의 재시도, r10) | lease가 지나 시작을 거절당한 claim과 재시도 가능 실패 기록은 같은 attempt로 다시 claim해도 넘겨받는다(`TakenOverClaimed`, attempt+1). 전에는 두 저장소가 그 claim을 재생해(`ReplayedAcquire`) 시작이 다시 거절되거나(503, 기록이 사라질 때까지) 시작할 수 없는 기록이라 500 `IDEMPOTENCY_RECOVERY_REQUIRED`였다. 효과 불명으로 포기한 기록은 같은 attempt에도 `RecoveryRequired`(PostgreSQL은 전에 `ReplayedAcquire`). Redis는 이미 실행 중인 기록에 같은 attempt의 다른 핸들(넘겨받기 전 핸들, 재생받은 현재 핸들)로 온 시작을 `ALREADY_STARTED_SAME_OPERATION`으로 확인하지 않는다 — 전에는 executor가 작업을 한 번 더 돌렸다(PostgreSQL은 전부터 거절). in-memory fake는 재시도 가능 실패 기록에 다른 요청 본문이 오면 넘겨주지 않고 `FingerprintMismatch` | attempt를 재시도 사이에 들고 있다가 503 뒤 같은 attempt로 다시 부르는 호출자(재시도 래퍼, 메시지 소비자)가 이제 실행된다. 요청마다 새 attempt를 만드는 호출자(템플릿의 HTTP 경로)는 바뀌는 것이 없다. 같은 attempt를 두 호출이 동시에 쓰는 것은 여전히 가려내지 못한다 — 재시도는 앞 호출이 돌아온 뒤에. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다 | r10(라운드6 RR6-02-01) · `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java` | | 멱등성(전이의 operation id·release·inspect, 2026-11-06) | owner token이 같아도 호출이 claim과 다른 operation id를 대면 PostgreSQL·in-memory fake도 다섯 전이(start·renew·complete·fail·release)를 `OPERATION_CONFLICT`로 거절하고 기록을 바꾸지 않는다(전에는 적용했다. Redis는 전부터 거절). in-memory fake의 claim은 같은 token·다른 operation에 `OwnerOperationConflict`(전에는 `InProgress`), inspect는 `OPERATION_CONFLICT`(전에는 `IN_PROGRESS_OTHER`). PostgreSQL·fake의 inspect는 완료된 기록에도 `OPERATION_CONFLICT`(전에는 응답을 재생). PostgreSQL complete는 같은 operation id를 쓴 다른 attempt에 `NOT_OWNER`(전에는 `ALREADY_COMPLETED_SAME_RESULT`). Redis release는 기록이 없으면 `ABSENT`(전에는 `ALREADY_RELEASED_SAME_OPERATION`)이고 핸들 revision을 본다: 같은 attempt가 넘겨받기 전 핸들로 release하면 `NOT_OWNER`(전에는 지금의 claim을 지웠다) | 템플릿의 호출자(`IdempotencyExecutor`)는 늘 claim의 operation id를 넘기고 release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접 부르며 전이마다 다른 operation id를 넘기던 코드는 이제 `OPERATION_CONFLICT`를 받는다 — `IdempotencyOwner.claimOperationId()`를 넘긴다. Redis release의 `ALREADY_RELEASED_SAME_OPERATION`을 기다리던 코드는 `ABSENT`도 "해제됨"으로 읽는다. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다 | 2026-11-06(소유자 결정 "(a)로 진행", 라운드6 02 Declined) · `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `RedisIdempotencyStoreAdapter.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java` | -| 멱등성(이미 적용된 전이의 재전송, 2026-11-06) | 이미 적용된 전이를 "이미 처리됨"으로 확인받는 것은 그 전이를 적용한 핸들(기록보다 revision이 하나 낮은 핸들)뿐이다. 같은 attempt가 넘겨받기 전 핸들로, 넘겨받은 뒤 적용된 complete·markFailed를 다시 보내면 `NOT_OWNER`(전에는 Redis가 `ALREADY_COMPLETED_SAME_RESULT`·`ALREADY_MARKED_SAME_OPERATION`, PostgreSQL이 `ALREADY_COMPLETED_SAME_RESULT`·`OPERATION_CONFLICT`). PostgreSQL은 renew가 돌려준 핸들로 다시 renew하면 한 번 더 renew한다(전에는 `OPERATION_CONFLICT`). 넘겨받기 전 핸들의 renew는 `NOT_OWNER`, release는 `NOT_OWNER`(전에는 둘 다 `OPERATION_CONFLICT`). in-memory fake는 적용한 핸들이 start·renew·markFailed를 다시 보내면 `ALREADY_STARTED_SAME_OPERATION`·`ALREADY_RENEWED_SAME_OPERATION`(다른 lease면 `OPERATION_CONFLICT`)·`ALREADY_MARKED_SAME_OPERATION`(전에는 `NOT_OWNER`). release한 핸들로 start하면 PostgreSQL은 `NOT_OWNER`, Redis·fake는 `ABSENT`이고 계약은 둘 다 받는다(동작 변경 없음, Javadoc만) | 템플릿의 호출자(`IdempotencyExecutor`)는 넘겨받기 전 핸들로 다시 보내지 않고 renew·release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접 부르며 heartbeat로 renew를 이어 부르는 코드는 PostgreSQL에서 두 번째 renew부터 거절당하던 것이 이제 된다. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다. fake로 lost reply를 흉내 내던 테스트는 이제 "이미 처리됨"을 받는다 | 2026-11-06(소유자 결정 「넘겨받기 전 핸들의 재전송」「해제된 핸들로 start」) · `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java`, `IdempotencyStartOutcome.java` | +| 멱등성(이미 적용된 전이의 재전송, 2026-11-06·11-07) | 이미 적용된 전이를 "이미 처리됨"으로 확인받는 것은 그 전이를 적용한 핸들(기록보다 revision이 하나 낮고 기록의 마지막 전이가 그 전이인 핸들)뿐이다. 같은 attempt가 넘겨받기 전 핸들로, 넘겨받은 뒤 적용된 complete·markFailed를 다시 보내면 `NOT_OWNER`(전에는 Redis가 `ALREADY_COMPLETED_SAME_RESULT`·`ALREADY_MARKED_SAME_OPERATION`, PostgreSQL이 `ALREADY_COMPLETED_SAME_RESULT`·`OPERATION_CONFLICT`). PostgreSQL은 renew가 돌려준 핸들로 다시 renew하면 한 번 더 renew한다(전에는 `OPERATION_CONFLICT`). 넘겨받기 전 핸들의 renew는 `NOT_OWNER`, release는 `NOT_OWNER`(전에는 둘 다 `OPERATION_CONFLICT`). in-memory fake는 적용한 핸들이 start·renew·markFailed를 다시 보내면 `ALREADY_STARTED_SAME_OPERATION`·`ALREADY_RENEWED_SAME_OPERATION`(다른 lease면 `OPERATION_CONFLICT`)·`ALREADY_MARKED_SAME_OPERATION`(전에는 `NOT_OWNER`). release한 핸들로 start하면 PostgreSQL은 `NOT_OWNER`, Redis·fake는 `ABSENT`이고 계약은 둘 다 받는다(동작 변경 없음, Javadoc만). Redis는 renew를 적용한 핸들로 start하면 `NOT_OWNER`(전에는 `ALREADY_STARTED_SAME_OPERATION`). 적용한 핸들이 markFailed를 다른 disposition으로 다시 보내면 셋 다 `OPERATION_CONFLICT`이고 기록된 실패는 그대로다(전에는 셋 다 `NOT_OWNER`). retention만 다르면 셋 다 `ALREADY_MARKED_SAME_OPERATION`이고 처음 retention이 남는다(전에는 PostgreSQL만 `OPERATION_CONFLICT`) | 템플릿의 호출자(`IdempotencyExecutor`)는 넘겨받기 전 핸들로 다시 보내지 않고 renew·release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접 부르며 heartbeat로 renew를 이어 부르는 코드는 PostgreSQL에서 두 번째 renew부터 거절당하던 것이 이제 된다. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다. fake로 lost reply를 흉내 내던 테스트는 이제 "이미 처리됨"을 받는다. Redis 기록 hash에 `lastKind` 필드가 생긴다(claim·renew·전이 프로그램이 쓴다) | 2026-11-06(소유자 결정 「넘겨받기 전 핸들의 재전송」「해제된 핸들로 start」) · 2026-11-07(소유자 결정 「적용한 핸들의 markFailed 재전송 인자」, 재리뷰 round8 RR8-04-01·02) · `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java`, `IdempotencyStartOutcome.java`, `IdempotencyFailOutcome.java` | | 빌드 단계(HTTP client) | `httpClientFailureInjectionTest`(Toxiproxy 장애 주입)가 `mainCheck`에서 빠졌다. `integrationCheck`에만 있고, main push·nightly의 `integration-main.yml` `integration-check` job이 돌린다 | main push마다 같은 lane이 `main-check`·`integration-check` 두 job에서 두 번 돌던 것이 한 번이 된다. 로컬에서 `mainCheck`만 돌리면 이 lane은 돌지 않는다(`integrationCheck`로 돌린다) | r9 · `src/adapter/outbound/httpclient/build.gradle` | | 서버 로그(GraphQL·gRPC·STOMP) | carrier로 답한 실패를 web과 같은 줄(shared-contract `ServerFailureLog`)로 ERROR에 남긴다: persistence 실패는 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. gRPC는 ` (method=…)`, GraphQL은 ` (executionId=…)`를 붙인다. gRPC는 인식 못 한 실패(`INTERNAL_ERROR`)도 `unhandled failure on …`로 남긴다. 클라이언트가 취소한 호출은 남기지 않고, 서비스가 `CANCELLED` status로 끝낸 살아 있는 호출은 남긴다. raw status는 넘겼든 던졌든 설명을 남기지 않는다(원인 예외가 있으면 그것만 붙인다). `IllegalArgumentException`(`BAD_PARAMETER`)은 web과 같은 WARN 한 줄 `request refused as BAD_PARAMETER by <예외 타입>`(메시지 없음)으로 남긴다. STOMP `@MessageMapping` 실패는 Spring의 `Unhandled exception from message handler method`(예외 전체) 대신 같은 줄로 남는다 | ERROR 로그가 늘어난다(전에는 gRPC가 아무것도 남기지 않았다). GraphQL·gRPC·STOMP는 잘못된 입력마다 WARN 한 줄이 생긴다. STOMP에서 Spring 문구로 경보를 걸었다면 고친다. `IDEMPOTENCY_RECOVERY_REQUIRED`의 scope digest를 모든 전송에서 찾을 수 있다(`docs/runbooks/idempotency-unavailable.md`) | r9 · `src/shared-contract/.../error/ServerFailureLog.java`, `GrpcExceptionHandlingInterceptor.java`, `GraphQlWireErrorMapper.java`, `StompHandlerFailureLog.java` | | 서버 로그(STOMP 거부·감싼 carrier, 2026-11-07) | `@MessageMapping` 앞에서 Spring이 거부한 메시지를 WARN 한 줄 `request refused as by <예외 타입>`으로 남긴다: 읽지 못한 payload(`MessageConversionException`)·비었거나 검증에 걸린 payload(`MethodArgumentNotValidException`)는 `VALIDATION_FAILED`, 변환되지 않는 `@DestinationVariable`·`@Header`(`ConversionFailedException`)는 `BAD_PARAMETER`. 전에는 ERROR에 예외 메시지(받은 JSON 조각·값)까지 남겼다. 응답을 쓰지 못한 변환 실패는 그대로 ERROR. 네 전송 모두 감싼 carrier를 그 carrier 줄로 남긴다(감싼 persistence 실패는 분류만, SQL 원인 없음) | ERROR 경보가 클라이언트의 잘못된 메시지에 울리지 않는다. 그 실패를 찾던 로그 검색은 WARN으로 바꾼다 | r8-f1(재리뷰 RR7-01-06·RR7-01-05) · `src/adapter/inbound/websocket/.../stomp/StompHandlerFailureLog.java`, `src/shared-contract/.../error/ServerFailureLog.java` `refused` | diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index 00e6217f..dbcac900 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -114,7 +114,8 @@ | complete 재생 판정 | 완료 확인은 같은 owner token에만 준다. 같은 operation id를 쓴 다른 attempt의 늦은 complete는 `NOT_OWNER`. → 아래 「넘겨받기 전 핸들의 재전송」이 적용한 핸들 하나로 좁혔다 | 기본값(2026-11-06) | Redis TRANSITION에 맞춤, `IdempotencyStoreContract` | | 기록 없는 release | 저장소 셋 다 `ABSENT`로 답한다(확인할 수 없는 해제를 확인하지 않는다). Redis release도 핸들 revision을 본다. release한 기록을 지울지 남길지는 저장소가 정하므로 release 재시도 답은 `ABSENT`(Redis·fake)와 `ALREADY_RELEASED_SAME_OPERATION`(PostgreSQL)으로 갈린다 | 기본값(2026-11-06) | JPA 설계 22.2 "affected row가 0이면 성공으로 간주하지 않는다", `IdempotencyStoreContract` | | Redis 연결 예산 | 캐시 조건부 쓰기는 멱등성·lease와 다른 연결 예산(SCRIPT lane) | 위임 | `1103` 4절(RR-04-02) | -| 넘겨받기 전 핸들의 재전송 | 같은 attempt를 넘겨받기 전의 핸들이 이미 일어난 complete·markFailed를 다시 보내면, 그 전이를 실제로 적용한 핸들에게만 "이미 처리됨"으로 확인하고 그 밖의 핸들은 거절한다. Redis TRANSITION 주석의 원래 의도를 뒤집는다. 적용: 적용한 핸들은 기록보다 revision이 하나 낮은 핸들이고, 거절은 `NOT_OWNER`다. 같은 규칙을 start·renew·release에도 맞췄다 | 소유자 | t5 보고 「남은 문제」, 2026-11-06, `IdempotencyStoreContract` | +| 넘겨받기 전 핸들의 재전송 | 같은 attempt를 넘겨받기 전의 핸들이 이미 일어난 complete·markFailed를 다시 보내면, 그 전이를 실제로 적용한 핸들에게만 "이미 처리됨"으로 확인하고 그 밖의 핸들은 거절한다. Redis TRANSITION 주석의 원래 의도를 뒤집는다. 적용: 적용한 핸들은 기록보다 revision이 하나 낮고 기록의 마지막 전이가 그 전이인 핸들이고, 거절은 `NOT_OWNER`다. 같은 규칙을 start·renew·release에도 맞췄다. 마지막 전이 종류 조건은 2026-11-07에 더했다: renew를 적용한 핸들의 start를 Redis만 "이미 시작됨"으로 확인해 호출자가 작업을 다시 돌렸다 | 소유자(적용 조건 보완은 기본값 2026-11-07) | t5 보고 「남은 문제」, 2026-11-06, `1103` 19절(RR8-04-02), `IdempotencyStoreContract` | +| 적용한 핸들의 markFailed 재전송 인자 | 적용한 핸들이 markFailed를 다른 disposition으로 다시 보내면 `OPERATION_CONFLICT`이고 기록된 실패는 그대로다(「전이의 operation id」의 "같은 id·다른 인자"). retention만 다르면 "이미 처리됨"(`ALREADY_MARKED_SAME_OPERATION`)이고 처음 retention이 남는다. retention은 complete의 replay TTL처럼 결과를 얼마나 보관하나일 뿐 결과를 바꾸지 않아 비교하지 않는다. PostgreSQL fail digest에서 retention을 뺐다. 전에는 다른 disposition에 세 저장소 모두 `NOT_OWNER`, 다른 retention에 PostgreSQL만 `OPERATION_CONFLICT`였다 | 소유자(2026-11-07) | `1103` 19.4절 ② (a), RR8-04-01, `IdempotencyFailOutcome`, `IdempotencyStoreContract` | | 해제된 핸들로 start | 계약은 `ABSENT`와 `NOT_OWNER`를 둘 다 받는다. 포트 Javadoc에 그렇게 적는다 | 소유자 | t5 보고 「남은 문제」, 2026-11-06, `IdempotencyStartOutcome`, `IdempotencyStoreContract` | ### 2.5 영속성 diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index c7fd0f6c..515dc06e 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -278,11 +278,17 @@ revision) come from app-bootstrap `IdempotencySettings`. This leaf reads only `k `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. That answer is given only to the handle -the transition was applied from — the record one revision past it. Another handle of the same +the transition was applied from — the record one revision past it, with `lastKind` (written by the +claim, renew and transition programs) naming that transition. Another handle of the same attempt (one from before a takeover, or the current one a replayed claim returned) used to be told a start was applied and ran the action a second time (round6 RR6-02-01), and to be told a completion or failure that followed a takeover was its own (owner decision 2026-11-06); it is now `NOT_OWNER` -or `NOT_CLAIMED`/`NOT_IN_PROGRESS`, as in the PostgreSQL store. The renew program checks owner, +or `NOT_CLAIMED`/`NOT_IN_PROGRESS`, as in the PostgreSQL store. Without the kind, a start through the +handle a renewal was applied from was confirmed too — renewal leaves the record `EXECUTING` one +revision past that handle (round8 RR8-04-02); it is `NOT_OWNER`. A failure from the handle that +applied one, asking for the other disposition, is `OPERATION_CONFLICT` (it fell through to +`NOT_OWNER`); the record keeps no retention, so another retention is confirmed (owner decision +2026-11-07). 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, diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java index 6a942373..d92ddc04 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java @@ -62,7 +62,7 @@ public final class IdempotencyScripts { redis.call('HSET', KEYS[1], 'state', 'CLAIMED', 'owner', ARGV[1], 'attempt', 1, 'rev', 1, 'op', ARGV[2], 'fp', ARGV[3], 'codec', ARGV[4], 'policy', ARGV[5], - 'leaseUntil', nowMillis + leaseMillis, 'afterLease', afterLease) + 'leaseUntil', nowMillis + leaseMillis, 'afterLease', afterLease, 'lastKind', 'CLAIM') redis.call('PEXPIRE', KEYS[1], leaseMillis + afterLease) return {'ACQUIRED', 1, 1, ARGV[1], '', tostring(nowMillis + leaseMillis)} end @@ -91,7 +91,8 @@ public final class IdempotencyScripts { -- 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) + 'op', ARGV[2], 'leaseUntil', nowMillis + leaseMillis, 'afterLease', afterLease, + 'lastKind', 'CLAIM') redis.call('PEXPIRE', KEYS[1], leaseMillis + afterLease) return {'TAKEN_OVER', attempt + 1, rev + 1, ARGV[1], '', tostring(nowMillis + leaseMillis)} @@ -128,6 +129,16 @@ public final class IdempotencyScripts { * from. A completion or failure used to be reported back to any handle of its operation, so the * same attempt's handle from before a takeover was told the completion that followed it was its * own (owner decision 2026-11-06). + * + *

"Applied from this handle" is the record one revision past it and {@code lastKind} + * naming this transition. Every program that moves the revision writes {@code lastKind} (claim, + * renew and this one; release deletes the record). The revision alone confirmed a start through + * the handle a renewal was applied from: renewal leaves the record {@code EXECUTING}, the start's + * target, one revision past that handle (round8 RR8-04-02). A failure from the handle that + * applied one, asking for the other disposition, is {@code OPERATION_CONFLICT}: the same + * transition with other arguments, which used to fall through to {@code NOT_OWNER} (owner + * decision 2026-11-07). Its retention is not compared — the record does not keep it, and a resend + * with another retention is confirmed. */ private static final String TRANSITION = """ @@ -145,25 +156,31 @@ public final class IdempotencyScripts { if op ~= ARGV[3] then return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''} 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 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. + if rev == tonumber(ARGV[2]) + 1 and redis.call('HGET', KEYS[1], 'lastKind') == ARGV[9] then + -- This transition, applied from this handle, 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 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. -- -- 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. 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); either one presenting a completion or failure -- applied after the takeover was told it was its own. A transition 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 (owner decision 2026-11-06). The PostgreSQL store answers the same: it reads a - -- recorded transition as a replay only for the handle one revision behind the row. - if rev == tonumber(ARGV[2]) + 1 then + -- the handle it was applied from — the record one revision past it, moved there by this + -- kind of transition — and any other falls through to the revision check: NOT_OWNER for a + -- stale handle, WRONG_STATE for the current one (owner decision 2026-11-06). The kind is + -- what tells a start from the renewal that followed it (round8 RR8-04-02). The PostgreSQL + -- store answers the same: it reads a recorded transition as a replay only for the handle + -- one revision behind the row and only for the kind the row records. + if state == ARGV[5] then return {'ALREADY', attempt, rev, owner, redis.call('HGET', KEYS[1], 'resp') or '', ''} end + -- The same transition with another target: a failure asking for the other disposition + -- than the one recorded. The same id with other arguments (owner decision 2026-11-07). + return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''} end if rev ~= tonumber(ARGV[2]) then -- Stale handle: somebody moved the record on after this owner read it, and the target @@ -181,7 +198,7 @@ public final class IdempotencyScripts { return {'LEASE_EXPIRED', attempt, rev, owner, '', ''} end end - redis.call('HSET', KEYS[1], 'state', ARGV[5], 'rev', rev + 1) + redis.call('HSET', KEYS[1], 'state', ARGV[5], 'rev', rev + 1, 'lastKind', ARGV[9]) if ARGV[6] ~= '' then redis.call('HSET', KEYS[1], 'resp', ARGV[6]) end @@ -261,7 +278,7 @@ public final class IdempotencyScripts { end redis.call('HSET', KEYS[1], 'leaseUntil', nowMillis + tonumber(ARGV[4]), 'rev', rev + 1, - 'renewedFromRev', ARGV[2], 'renewedLease', ARGV[4]) + 'renewedFromRev', ARGV[2], 'renewedLease', ARGV[4], 'lastKind', 'RENEW') local keep = tonumber(ARGV[4]) + tonumber(redis.call('HGET', KEYS[1], 'afterLease') or '0') local ttl = redis.call('PTTL', KEYS[1]) diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java index c1890ffd..edb8f3c7 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java @@ -169,7 +169,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort return transition( ownerHandle, operationId, - new Transition("CLAIMED", "EXECUTING", "", "", ""), + new Transition("START", "CLAIMED", "EXECUTING", "", "", ""), Map.of( ScriptStatus.APPLIED, IdempotencyStartOutcome.STARTED, ScriptStatus.ALREADY, IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION, @@ -230,6 +230,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort session.commands(), keys.recordKey(ownerHandle.scope()), new Transition( + "COMPLETE", "EXECUTING", "COMPLETED", response.payload(), @@ -270,8 +271,13 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort // EFFECT_UNKNOWN_ABANDONED does not, because retrying an unknown effect is how it happens // twice. boolean retryable = disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE; + // One kind for both dispositions: a resend from the handle that applied the failure, asking for + // the other one, is the same transition with other arguments — OPERATION_CONFLICT, not a stale + // owner (owner decision 2026-11-07). The retention is not sent for comparison; the record does + // not keep it. Transition transition = new Transition( + "FAIL", "EXECUTING", retryable ? "FAILED_RETRYABLE" : "ABANDONED", "", @@ -425,6 +431,8 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort /** * One owner+revision compare-and-set, as the transition program takes it. * + * @param kind which transition, recorded so a resend is confirmed only as the transition the + * record last took ({@code START}, {@code COMPLETE}, {@code FAIL}) * @param fromState the state the record must be in * @param toState the state it moves to * @param payload the response to store, empty for none @@ -432,7 +440,12 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort * @param ttlMillis a new record TTL, empty to keep the current one */ private record Transition( - String fromState, String toState, String payload, String leaseMillis, String ttlMillis) { + String kind, + String fromState, + String toState, + String payload, + String leaseMillis, + String ttlMillis) { List arguments(IdempotencyOwner ownerHandle, OperationId operationId) { return List.of( @@ -443,7 +456,8 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort toState, payload, leaseMillis, - ttlMillis); + ttlMillis, + kind); } } diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index 02d748bc..065b17a0 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -451,7 +451,12 @@ revision이 하나 낮은 핸들)에게만 재생으로 읽는다(2026-11-06 소 달라 `OPERATION_CONFLICT`였다). renew가 돌려준 핸들로 다시 renew하면 한 번 더 renew된다(전에는 앞 renew의 digest와 달라 `OPERATION_CONFLICT`였다). 시작은 핸들 말고 인자가 없어서, 넘겨받기 전 핸들은 `NOT_OWNER`, 재생받은 현재 핸들은 `NOT_CLAIMED`다(라운드6 RR6-02-01, 전에는 `OPERATION_CONFLICT`). release한 핸들로 시작하면 행이 남아 있어 -`NOT_OWNER`다. 행을 지우는 Redis·fake는 `ABSENT`이고 계약은 둘 다 받는다. renew는 `EXECUTING`의 +`NOT_OWNER`다. 행을 지우는 Redis·fake는 `ABSENT`이고 계약은 둘 다 받는다. 실패는 disposition마다 전이 종류가 +둘(`FAIL_RETRYABLE`·`FAIL_ABANDONED`)이라, 적용한 핸들이 다른 disposition으로 다시 보내면 종류가 달라 재생으로 +읽히지 않고 `NOT_OWNER`였다. 두 종류를 모두 실패의 재생으로 읽어, 다른 disposition은 digest가 달라 +`OPERATION_CONFLICT`다. fail digest에는 retention을 넣지 않는다 — complete의 replay TTL처럼 결과를 얼마나 +보관하나일 뿐이라, retention만 다른 재전송은 "이미 처리됨"이고 처음 retention이 남는다(전에는 +`OPERATION_CONFLICT`, 2026-11-07 소유자 결정). renew는 `EXECUTING`의 lease만 늘리고, 시작 전 `CLAIMED`는 `NOT_IN_PROGRESS`다. ### outbox V2 (삭제됨) diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java index 3bb75bd4..d0aea51b 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java @@ -14,8 +14,12 @@ import java.util.Objects; *

It omitted several. {@code transition|operationId|ownerToken|attempt|stateRevision} covers who * and when, and nothing about what: a {@code FAIL} recorded with a retryable disposition and one * recorded as abandoned produced identical digests, as did two completions carrying different - * responses or different retention. A replay comparing digests concluded "same transition" for two - * transitions whose whole difference was the part that mattered. + * responses. A replay comparing digests concluded "same transition" for two transitions whose whole + * difference was the part that mattered. + * + *

How long a result is kept is not part of what a failure decided: a failure's retention is left + * out, so a resend with another retention is the failure already recorded (owner decision + * 2026-11-07 — it was a conflict here and confirmed by the Redis store). * *

Length-framed, because every component is variable-width text and at least one — the owner * token — is not this platform's to constrain. Joining with a delimiter means two different @@ -37,7 +41,7 @@ final class IdempotencyDigestPolicy { * @param attempt the owner's attempt number * @param stateRevision the record revision the transition was applied to * @param semanticArguments every further input that changes what the transition means — - * disposition, retention, response digest, codec identity — in a fixed order + * disposition, response digest, replay TTL, codec identity — in a fixed order */ static String of( String transition, diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java index dec82c02..52e748f4 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java @@ -27,6 +27,7 @@ import java.time.Instant; import java.util.HexFormat; import java.util.Objects; import java.util.Optional; +import java.util.Set; import org.springframework.jdbc.core.JdbcOperations; /** @@ -62,6 +63,9 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { private static final Duration MAXIMUM_PROCESSING_LEASE = Duration.ofHours(1); private static final Duration MAXIMUM_RETENTION = Duration.ofDays(30); + /** The two kinds a failure is recorded under, one per disposition. */ + private static final Set FAILURE_KINDS = Set.of("FAIL_RETRYABLE", "FAIL_ABANDONED"); + private static final String ACTIVE_CAPABILITY_SQL = """ select count(*) @@ -193,7 +197,7 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { // 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, owner, "START", operationId, startDigest) + if (replayVerdict(row, owner, Set.of("START"), operationId, startDigest) == ReplayVerdict.SAME_ARGUMENTS) { return startResult(IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION, owner(row)); } @@ -232,7 +236,7 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { // caller went on believing it held the record for longer than the row says it does. String renewDigest = transitionDigest("RENEW", operationId, owner, Long.toString(processingLeaseTtl.toMillis())); - switch (replayVerdict(row, owner, "RENEW", operationId, renewDigest)) { + switch (replayVerdict(row, owner, Set.of("RENEW"), operationId, renewDigest)) { case SAME_ARGUMENTS -> { return renewResult(IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION, owner(row)); } @@ -337,14 +341,13 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE ? "FAIL_RETRYABLE" : "FAIL_ABANDONED"; - String failDigest = - transitionDigest( - transitionKind, - operationId, - owner, - disposition.name(), - Long.toString(retention.toMillis())); - switch (replayVerdict(row, owner, transitionKind, operationId, failDigest)) { + // The disposition is what a failure decided, so it is in the digest, and a failure of either + // kind recorded from this handle is this failure resent: with the other disposition it is a + // conflict, not a stale owner (owner decision 2026-11-07 — it fell through to NOT_OWNER). The + // retention is not: like a completion's replay TTL it is how long the result is kept, so a + // resend with another one is confirmed and the row keeps the first (it was OPERATION_CONFLICT). + String failDigest = transitionDigest(transitionKind, operationId, owner, disposition.name()); + switch (replayVerdict(row, owner, FAILURE_KINDS, operationId, failDigest)) { case SAME_ARGUMENTS -> { return IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION; } @@ -394,7 +397,7 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return IdempotencyReleaseOutcome.OPERATION_CONFLICT; } String releaseDigest = transitionDigest("RELEASE", operationId, owner); - switch (replayVerdict(row, owner, "RELEASE", operationId, releaseDigest)) { + switch (replayVerdict(row, owner, Set.of("RELEASE"), operationId, releaseDigest)) { case SAME_ARGUMENTS -> { return IdempotencyReleaseOutcome.ALREADY_RELEASED_SAME_OPERATION; } @@ -623,14 +626,21 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { * the same attempt's handle from before a takeover resending a failure or a release that followed * it. Neither is a replay — the first is a new transition, the second a stale owner — so both go * on to the ownership checks, as in the Redis store (owner decision 2026-11-06). + * + *

{@code transitionKinds} is every kind the call's transition is recorded under. A failure has + * two, one per disposition, and a resend from the applying handle with the other disposition used + * to find the other kind and go on to the ownership checks as a stale owner; it is the same + * failure with another argument, so a conflict (owner decision 2026-11-07). */ private static ReplayVerdict replayVerdict( IdempotencyRecordRow row, IdempotencyOwner owner, - String transitionKind, + Set transitionKinds, OperationId operationId, String expectedDigest) { - if (!transitionKind.equals(row.lastTransitionKind()) + // A claim leaves no transition recorded, and an immutable set refuses a null lookup. + if (row.lastTransitionKind() == null + || !transitionKinds.contains(row.lastTransitionKind()) || !operationId.value().equals(row.lastTransitionOperationId()) || !appliedFrom(row, owner)) { return ReplayVerdict.NOT_A_REPLAY; @@ -705,7 +715,7 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { * when, and nothing about what. A {@code FAIL} recorded as retryable and one recorded as * abandoned produced the same digest, and so did two completions carrying different responses. * - * @param semanticArguments disposition, retention, response digest, codec identity — whatever + * @param semanticArguments disposition, response digest, replay TTL, codec identity — whatever * this particular transition also decided */ private static String transitionDigest( diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java index 646191ce..7285703c 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java @@ -406,7 +406,7 @@ class PostgreSqlIdempotencyIntegrationTest { } @Test - void aFailureRepeatedUnderOneOperationIdWithDifferentRetentionIsAConflict() { + void aFailureRepeatedUnderOneOperationIdWithDifferentRetentionIsConfirmedAndKeepsItsRetention() { IdempotencyOwner executing = claimAndStart("claim-fail-conflict"); transactions.execute( @@ -425,11 +425,12 @@ class PostgreSqlIdempotencyIntegrationTest { Duration.ofHours(9), executing.claimOperationId())); + // The retention is how long the failure is kept, not what it decided, so it is not compared: + // the resend is the failure already recorded, and the row keeps the first retention (owner + // decision 2026-11-07 — this store answered OPERATION_CONFLICT, the Redis store confirmed it). assertThat(different) - .as( - "the recorded failure kept the record for an hour; reporting this call as the one" - + " already applied would tell the caller it got nine") - .isEqualTo(IdempotencyFailOutcome.OPERATION_CONFLICT); + .as("the resend asked for nine hours; the row still keeps the failure for one") + .isEqualTo(IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION); assertThat( jdbc.queryForObject( "select extract(epoch from (expires_at - updated_at))::bigint " diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java index bd13f4c3..bd44bf14 100644 --- a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java +++ b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java @@ -204,6 +204,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand setField(rendered, "fp", fingerprint); setField(rendered, "leaseUntil", Long.toString(nowMillis + leaseTtl)); setField(rendered, "afterLease", afterLease); + setField(rendered, "lastKind", "CLAIM"); expireHashAfter(rendered, leaseTtl + Long.parseLong(afterLease)); return reply("ACQUIRED", 1, 1, ownerToken, "", Long.toString(nowMillis + leaseTtl)); } @@ -238,6 +239,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand setField(rendered, "op", operationId); setField(rendered, "leaseUntil", Long.toString(nowMillis + leaseTtl)); setField(rendered, "afterLease", afterLease); + setField(rendered, "lastKind", "CLAIM"); expireHashAfter(rendered, leaseTtl + Long.parseLong(afterLease)); return reply( "TAKEN_OVER", attempt + 1, rev + 1, ownerToken, "", Long.toString(nowMillis + leaseTtl)); @@ -265,6 +267,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand String payload = text(arguments.get(5)); String leaseUntil = text(arguments.get(6)); String recordTtl = text(arguments.get(7)); + String kind = text(arguments.get(8)); String state = field(rendered, "state"); if (state == null) { return reply("ABSENT", 0, 0, "", "", ""); @@ -281,10 +284,15 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand } // ALREADY before the revision check, matching the program: a lost reply leaves the caller // holding the pre-transition revision. A transition is confirmed only to the handle it was - // applied from — the record one revision past it (round6 RR6-02-01 for a start, owner decision - // 2026-11-06 for a completion or failure); any other handle falls through to NOT_OWNER or - // WRONG_STATE. - if (state.equals(toState) && rev == expectedRev + 1) { + // applied from — the record one revision past it, moved there by this kind of transition + // (round6 RR6-02-01 for a start, owner decision 2026-11-06 for a completion or failure, round8 + // RR8-04-02 for a start after a renewal); any other handle falls through to NOT_OWNER or + // WRONG_STATE. The same kind with another target is a failure asking for the other disposition: + // OPERATION_CONFLICT (owner decision 2026-11-07). + if (rev == expectedRev + 1 && kind.equals(field(rendered, "lastKind"))) { + if (!state.equals(toState)) { + return reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); + } String stored = field(rendered, "resp"); return reply("ALREADY", attempt, rev, owner, stored == null ? "" : stored, ""); } @@ -300,6 +308,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand } setField(rendered, "state", toState); setField(rendered, "rev", Long.toString(rev + 1)); + setField(rendered, "lastKind", kind); if (!payload.isEmpty()) { setField(rendered, "resp", payload); } @@ -354,6 +363,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand setField(rendered, "rev", Long.toString(rev + 1)); setField(rendered, "renewedFromRev", handleRevision); setField(rendered, "renewedLease", leaseMillis); + setField(rendered, "lastKind", "RENEW"); // 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"); diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index 7b42e637..64110b78 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -291,9 +291,15 @@ generation; the V1 `IdempotencyScope`/`tryBegin` API is gone. Another one is `OPERATION_CONFLICT` in every store and changes nothing; so is an inspection that brings the owner token under another operation (owner decision 2026-11-06). - A transition already applied is confirmed ("already …") only to the handle it was applied from — - the record one revision past it. Any other handle is `NOT_OWNER`, the same attempt's handle from - before a takeover included; a start through a released handle is `ABSENT` or `NOT_OWNER` by - whether the store keeps the released record (owner decision 2026-11-06, `IdempotencyStoreContract`). + the record one revision past it, moved there by that kind of transition. Any other handle is + `NOT_OWNER`, the same attempt's handle from before a takeover included, and so is a start through + the handle a renewal was applied from; a start through a released handle is `ABSENT` or + `NOT_OWNER` by whether the store keeps the released record (owner decision 2026-11-06, + `IdempotencyStoreContract`). +- The applying handle resending `markFailed` with another disposition is `OPERATION_CONFLICT` and + the recorded failure stays; with only another retention it is `ALREADY_MARKED_SAME_OPERATION` and + the first retention stays — retention, like a completion's replay TTL, is not compared (owner + decision 2026-11-07). The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency` and its fixture were removed when this branch merged. diff --git a/src/application-core/README.md b/src/application-core/README.md index 5668a61e..aa882e73 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -272,7 +272,11 @@ application 계층이 claim·replay·복구 **정책** 을 소유하고, 저장 넘겨받는다(라운드6 RR6-02-01: 전에는 같은 attempt 가 이 기록을 재생받아 시작을 다시 거절당했다). 넘겨받기 전 핸들은 같은 attempt 가 들고 있어도 낡은 핸들이라 시작이 확인되지 않는다. 이미 적용된 전이(start·renew· complete·markFailed·release)를 "이미 처리됨"으로 확인받는 것은 그 전이를 적용한 핸들뿐이다. 넘겨받은 뒤에 - 일어난 complete·markFailed 를 넘겨받기 전 핸들로 다시 보내면 `NOT_OWNER` 다(2026-11-06 소유자 결정). 한 attempt 를 + 일어난 complete·markFailed 를 넘겨받기 전 핸들로 다시 보내면 `NOT_OWNER` 다(2026-11-06 소유자 결정). renew 를 + 적용한 핸들로 start 해도 `NOT_OWNER` 다 — 기록은 그 핸들보다 revision 이 하나 높지만 거기로 옮긴 것은 start 가 + 아니라 renew 다. markFailed 를 적용한 핸들이 다른 disposition 으로 다시 보내면 `OPERATION_CONFLICT`(기록된 실패는 + 그대로), retention 만 다르면 "이미 처리됨"이다. retention 은 complete 의 replay TTL 처럼 비교하지 않는다(2026-11-07 + 소유자 결정). 한 attempt 를 두 호출이 동시에 쓰는 것은 가려내지 못하므로 재시도는 앞 호출이 돌아온 뒤에 한다. 만료된 `EXECUTING` 은 다른 caller 에게 `RECOVERY_REQUIRED` 로 답하되 기록은 그대로 둔다. 주인이 늦게 보고한 결과·실패는 기록된다 — 먼저 온 보고 하나만 남고 뒤의 보고는 거절된다(2026-11-04 소유자 결정, diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java index aecee742..ffa97ff1 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java @@ -9,7 +9,9 @@ public enum IdempotencyFailOutcome { * the failure was applied from is told so; another handle of the same attempt — one from before a * takeover — is {@link #NOT_OWNER} (owner decision 2026-11-06: the Redis store confirmed it and * the PostgreSQL store answered {@link #OPERATION_CONFLICT}; the in-memory fake refused even the - * handle that applied it). + * handle that applied it). A resend with another retention is this too: the retention is how long + * the failure is kept, not what it decided, and the record keeps the first one (owner decision + * 2026-11-07 — the PostgreSQL store answered {@link #OPERATION_CONFLICT}). */ ALREADY_MARKED_SAME_OPERATION, ABSENT, @@ -17,8 +19,9 @@ public enum IdempotencyFailOutcome { NOT_IN_PROGRESS, /** * The call names an operation other than the one the record was claimed under (owner decision - * 2026-11-06), or this failure was already recorded with another disposition or retention. - * Nothing changed. + * 2026-11-06), or the failure the handle presented applied was already recorded with another + * disposition (owner decision 2026-11-07 — every store answered {@link #NOT_OWNER}). Nothing + * changed: the recorded disposition stays. */ OPERATION_CONFLICT, INDETERMINATE, diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java index 3806ad6e..d4a1a540 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java @@ -10,7 +10,9 @@ public enum IdempotencyStartOutcome { * 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}). + * #OPERATION_CONFLICT}). Nor is a start through the handle a renewal was applied from: the record + * is executing one revision past it, but the renewal moved it there, so the handle is stale and + * the answer is {@link #NOT_OWNER} (round8 RR8-04-02 — the Redis store confirmed it). */ ALREADY_STARTED_SAME_OPERATION(true), /** diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java index 8e93af90..7635f032 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java @@ -28,7 +28,10 @@ import java.time.Duration; * operation to a record still in progress is {@link * IdempotencyClaimOutcome.OwnerOperationConflict}, and an inspection is {@code OPERATION_CONFLICT} * in every state (owner decision 2026-11-06). For renew and failure {@code OPERATION_CONFLICT} also - * still means the same transition was already applied with other arguments. + * still means the same transition was already applied, from the handle presented, with other + * arguments: another lease for a renewal, another disposition for a failure. A failure's retention + * is not one of them — like a completion's replay TTL, it is how long the result is kept, and a + * resend with another one is confirmed (owner decision 2026-11-07). */ public interface IdempotencyStorePort { diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java index d2cb5e34..619de7bb 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java @@ -830,6 +830,63 @@ public abstract class IdempotencyStoreContract { assertThat(resent).isEqualTo(IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION); } + @Test + @DisplayName("markFailed를 적용한 핸들이 다른 retention으로 다시 보내면 이미 처리됨으로 확인한다") + void aFailureResentThroughTheHandleItWasAppliedFromWithAnotherRetentionIsConfirmed() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + + // when + IdempotencyFailOutcome resent = + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(2), + OPERATION); + + // then + // The retention is how long the recorded failure is kept, not what it decided, so a resend is + // not compared on it — as a completion's replay TTL is not (owner decision 2026-11-07: the + // Redis store and the fake confirmed it, the PostgreSQL store answered OPERATION_CONFLICT). + assertThat(resent).isEqualTo(IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION); + } + + @Test + @DisplayName("markFailed를 적용한 핸들이 다른 disposition으로 다시 보내면 OPERATION_CONFLICT이고 기록된 실패는 그대로다") + void aFailureResentThroughTheHandleItWasAppliedFromWithAnotherDispositionIsAConflict() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + + // when + IdempotencyFailOutcome resent = + store.markFailed( + executing, + IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED, + Duration.ofHours(1), + OPERATION); + + // then + // The failure this handle applied, asked for again with other arguments: the same id with + // other arguments is OPERATION_CONFLICT (owner decision 2026-11-07). Every store answered + // NOT_OWNER, which tells the handle that applied the failure that the record went to somebody + // else. The recorded disposition stays, so the next claim still takes the record over. + assertThat(resent).isEqualTo(IdempotencyFailOutcome.OPERATION_CONFLICT); + assertThat(store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT))) + .isInstanceOf(IdempotencyClaimOutcome.TakenOverClaimed.class); + } + @Test @DisplayName("release한 핸들로 start하면 ABSENT나 NOT_OWNER로 거절되고 아무것도 시작되지 않는다") void startingThroughAReleasedHandleStartsNothing() { @@ -871,6 +928,26 @@ public abstract class IdempotencyStoreContract { assertThat(resent.owner().orElseThrow().stateRevision()).isEqualTo(started.stateRevision()); } + @Test + @DisplayName("start가 돌려준 핸들로 renew한 뒤 그 핸들로 start하면 이미 시작됨이 아니라 NOT_OWNER다") + void aStartThroughTheHandleARenewalWasAppliedFromIsNotConfirmed() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // when + IdempotencyMutationResult started = + store.markExecutionStarted(executing, OPERATION); + + // then + // The record is executing one revision past this handle, but a renewal moved it there, not a + // start, so the handle is stale. The Redis store read only the state and the revision and + // confirmed the start, and the executor runs the action on that answer — a second run of an + // execution that is already running. + assertThat(started.outcome()).isEqualTo(IdempotencyStartOutcome.NOT_OWNER); + } + @Test @DisplayName("renew를 적용한 핸들이 같은 lease로 다시 보내면 이미 renew됨과 현재 핸들을 받는다") void aRenewalResentThroughTheHandleItWasAppliedFromIsConfirmedWithTheCurrentHandle() { diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java index 39c02f4d..77800bac 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java @@ -187,10 +187,13 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (row.namesAnotherOperation(owner, operationId)) { return IdempotencyFailOutcome.OPERATION_CONFLICT; } - // The failing handle retried with the same disposition, as after a lost reply. Another - // disposition is not this failure and falls through to NOT_OWNER, as in the stores. - if (row.repeats(owner, Transition.FAIL) && disposition.equals(row.applied.argument())) { - return IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION; + // The failing handle retried, as after a lost reply: the same disposition is a no-op, another + // disposition is a conflict, exactly as the stores answer. The retention is not compared: it is + // how long the failure is kept, and the first one stays (owner decision 2026-11-07). + if (row.repeats(owner, Transition.FAIL)) { + return disposition.equals(row.applied.argument()) + ? IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION + : IdempotencyFailOutcome.OPERATION_CONFLICT; } if (!row.owner.equals(owner)) { return IdempotencyFailOutcome.NOT_OWNER;