fix(query): IDEMPOTENT 쓰기는 결과 불명 뒤에도 다시 보낼 수 있게 한다

문제: 0929/03-03의 두 가드(재전송 버튼 canResend, 같은 입력 재제출 거절)가
intent의 키 유무로만 가른다. 뮤테이션 정책은 키 여부만 실어서 훅이 NEVER와
IDEMPOTENT를 가를 수 없다. 그래서 IDEMPOTENT 쓰기(손으로 쓴 PUT·DELETE)도
결과 불명 뒤 재전송 버튼이 없고 같은 입력 저장이 UNKNOWN_EFFECT_PENDING으로
거절된다. 출구는 사실을 모르는 "변경됨으로 확인"이나 새로고침뿐이다. 매뉴얼은
IDEMPOTENT를 "여러 번 적용해도 결과가 같다"로 적고, 실행기도 보낸 뒤에
다시 보낸다.

고른 방법(리뷰 03-03 대안 (a)): commandMutationIdentity가 resendSafe
(KEYED 또는 IDEMPOTENT)를 함께 준다. BoundMutation에 선택 칸 resendSafe를
더했다(추가만). 훅은 admission마다 resendable(키가 있거나 정책이
resendSafe)을 적고, 두 가드가 키 대신 그 값을 본다. 칸이 없는 손으로 쓴
정책은 지금처럼 키 유무로 간다. NEVER의 재전송 금지와 같은 입력 거절은
그대로다. 매뉴얼 01·02와 런북 6.3-4에 IDEMPOTENT 행을 적었다.
버린 대안: 문서만 고치기(회복 경로가 그대로 불편하다), IDEMPOTENT에도 키를
붙이기(백엔드가 키를 읽지 않으면 의미가 없고 실행기가
UNEXPECTED_IDEMPOTENCY_KEY로 거절한다).

위험·한계: commandMutationIdentity의 반환 객체에 칸이 하나 늘었다. 그 값을
toEqual로 비교하던 테스트는 칸을 더해야 한다(이 repo는 1곳을 고쳤다).
IDEMPOTENT로 잘못 선언한 쓰기(백엔드가 실제로는 중복을 막지 못함)는 이제
결과 불명 뒤 사용자가 다시 보낼 수 있다. 선언의 정확성은 기능 작성자
몫이다(02 결정표 3절). 템플릿 안에는 IDEMPOTENT 쓰기 소비자가 없다.
CHANGELOG 행은 문서 담당이 적는다.

검증: desktop batch에서 확인. node scripts/run-vitest.ts run
tests/component/application-mutation-admission.test.tsx
tests/unit/command-mutation-identity.test.ts

Refs: 1106/03-03
This commit is contained in:
DongHyeonka
2026-11-06 05:31:30 +09:00
parent 25685871f1
commit 815ea58e80
8 changed files with 103 additions and 19 deletions
+1 -1
View File
@@ -512,7 +512,7 @@ projectRequest: (input) => Object.freeze({
① **정할 것**
- 페이지 템플릿. [02 결정표 6절](02-decision-tables.md#6-페이지-템플릿)
- 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 키가 있는 요청(`KEYED`)에만 그려진다. `NEVER` 쓰기는 확인만 남는다. 폼 밖에서 `mutation.submit`을 부르는 화면도 `NEVER` 쓰기의 같은 입력을 다시 보낼 수 없다. 훅이 `DUPLICATE_IN_FLIGHT`(code `UNKNOWN_EFFECT_PENDING`)로 거절한다. `AsyncSurface`에 손으로 만든 상태를 넘기면 재전송 버튼은 그려지지 않는다(코디네이터의 `state`를 넘긴다).
- 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 다시 보내도 되는 요청(`KEYED`, `IDEMPOTENT`. 뮤테이션 정책의 `resendSafe`)에만 그려진다. `NEVER` 쓰기는 확인만 남는다. 폼 밖에서 `mutation.submit`을 부르는 화면도 `NEVER` 쓰기의 같은 입력을 다시 보낼 수 없다. 훅이 `DUPLICATE_IN_FLIGHT`(code `UNKNOWN_EFFECT_PENDING`)로 거절한다. `AsyncSurface`에 손으로 만든 상태를 넘기면 재전송 버튼은 그려지지 않는다(코디네이터의 `state`를 넘긴다).
- 폼이면 서버 필드 오류를 받을 필드(`useAppForm`의 `allowedServerFields`). 짝 백엔드는 필드 검증 거절을 400 `VALIDATION_FAILED`와 `details[{field, code}]`로 보낸다(422가 아니다). 공유 MSW 시나리오에는 짝 백엔드가 보내지 않는 `validation-422`만 있고, Envelope operation에서 그 답은 결과 불명이다. 짝 백엔드 모양의 필드 오류 테스트는 생성된 작성 폼 테스트(`<base>-create-page.test.tsx`)처럼 400 본문을 손으로 적는다.
② **기준**
+2 -1
View File
@@ -89,7 +89,8 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
| 서버 보장 | 멱등 키(`Idempotency-Key` 헤더)로 같은 요청의 중복 적용을 막는다 | 같은 요청을 여러 번 적용해도 결과가 같다 (키 없이) | 중복을 막지 못한다 |
| 자동 재시도 | 실제로 보내기 전까지만. 보낸 뒤 결과를 모르면 결과 불명(4절)으로 넘긴다. 예외: 짝 백엔드가 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절)로 답하면 `retryBudget` 안에서 같은 키로 다시 보낸다 | 된다 | 하지 않는다 |
| descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 짝 백엔드는 `retryBudget: 1`(아래 표), 참조 기능은 `0` | — | `retryBudget: 0` 필수 |
| 뮤테이션 정책 | `...commandMutationIdentity(<OPERATION>_CONTRACT)`가 `requiresIdempotencyKey: true`를 준다 | 같은 함수가 `false`를 준다 | 같은 함수가 `false`를 준다 |
| 뮤테이션 정책 | `...commandMutationIdentity(<OPERATION>_CONTRACT)`가 `requiresIdempotencyKey: true`, `resendSafe: true`를 준다 | 같은 함수가 `requiresIdempotencyKey: false`, `resendSafe: true`를 준다 | 같은 함수가 둘 다 `false`로 준다 |
| 결과 불명 뒤 | "같은 요청으로 다시 보내기"와 같은 입력 저장이 같은 키로 간다 | 다시 보내기와 같은 입력 저장이 키 없이 간다(1106/03-03) | 확인만 남는다. 같은 입력 저장은 보내지 않는다 |
- 멱등 키: 서버가 "같은 쓰기 요청"을 알아보게 하는 값이다.
- 결과를 모를 때 새 키로 다시 보내면 안 된다. 서버는 새 키를 다른 요청으로 보고 막지 못한다.
@@ -265,7 +265,8 @@ diagnostics에만 남고 `api.request.failed`에는 세지 않는다(03-07). 그
보내지 않는다. 훅의 `submit`이 `NOT_STARTED` `DUPLICATE_IN_FLIGHT`(code
`UNKNOWN_EFFECT_PENDING`)를 돌려주고, 결과 불명 요청이 확인될 때까지 그대로다. 폼
밖에서 `submit`을 부르는 화면도 같다. 화면은 상태에 `unknownEffectResendable: true`가
있을 때만 재전송 버튼을 그린다.
있을 때만 재전송 버튼을 그린다. `IDEMPOTENT` command는 키가 없어도 두 번 적용한
결과가 같아서 재전송과 같은 입력 재저장을 보낸다(정책 `resendSafe`, 1106/03-03).
5. backend status/receipt로 `COMMITTED`면 cache reconcile/invalidate한다. 화면의
"변경됨으로 확인"이 이 경로다.
6. `NOT_APPLIED`가 증명된 경우만 정책에 따라 retry한다. 화면은 근거 없는
+2 -1
View File
@@ -71,7 +71,8 @@ export type AsyncSignals = Readonly<{
hasMutationEffectUnknown?: boolean;
/**
* 0929/03-03. Whether the unknown-effect request can be sent again as the
* same request: it carries an idempotency key.
* same request: it carries an idempotency key, or (1106/03-03) its
* command is IDEMPOTENT.
*/
isUnknownEffectResendable?: boolean;
hasMutationConflict?: boolean;
+17 -2
View File
@@ -283,7 +283,10 @@ export type MutationOperationId = string & {
* second time: the operation id its intent names (the executor refuses an
* intent whose id is not its descriptor's, before sending, reported as a
* missing idempotency key) and whether the intent carries a key (a KEYED
* command only). Spread it into the policy:
* command only). 1106/03-03. Also whether the same request may be sent
* again after an unknown result (`resendSafe`): KEYED (the key lets the
* server recognise it) or IDEMPOTENT (applying it twice gives the same
* result). Spread it into the policy:
*
* ...commandMutationIdentity(INVOICE_CREATE_CONTRACT),
*
@@ -299,7 +302,11 @@ export function commandMutationIdentity(
retrySemantics: RetrySemantics;
}>;
}>,
): Readonly<{ operationId: MutationOperationId; requiresIdempotencyKey: boolean }> {
): Readonly<{
operationId: MutationOperationId;
requiresIdempotencyKey: boolean;
resendSafe: boolean;
}> {
const { operationId, method, retrySemantics } = command.contract;
if (method === "GET" || method === "HEAD") {
throw new TypeError(
@@ -309,6 +316,7 @@ export function commandMutationIdentity(
return Object.freeze({
operationId: operationId as MutationOperationId,
requiresIdempotencyKey: retrySemantics === "KEYED",
resendSafe: retrySemantics === "KEYED" || retrySemantics === "IDEMPOTENT",
});
}
@@ -318,6 +326,13 @@ export type BoundMutation<Input, Value> = Readonly<{
/** 1103/16-05. From `commandMutationIdentity(<OPERATION>_CONTRACT)`. */
operationId: MutationOperationId;
requiresIdempotencyKey: boolean;
/**
* 1106/03-03. From `commandMutationIdentity`: the request may be sent
* again after an unknown result (resend, or saving the same input), as a
* KEYED or IDEMPOTENT command may. Left out, only a request whose intent
* carries a key may (a NEVER command never).
*/
resendSafe?: boolean;
/**
* @deprecated 1103/16-06. The mutation coordinator never reads it. Leave
* it out; it is removed in a later release.
@@ -249,6 +249,7 @@ type ApplicationMutationController<Input, Value> = Readonly<{
* key. 0929/03-03. Without a key it is not sent: the result is a
* `NOT_STARTED` `DUPLICATE_IN_FLIGHT` failure with code
* `UNKNOWN_EFFECT_PENDING` until the unknown request is reconciled.
* 1106/03-03. A `resendSafe` (IDEMPOTENT) policy sends it without a key.
*/
submit(input: Input): Promise<ApplicationResult<Value>>;
resolveConflict(): Promise<void>;
@@ -264,15 +265,17 @@ type ApplicationMutationController<Input, Value> = Readonly<{
* intent, so a keyed command carries the same `Idempotency-Key`. Resolves
* to `null` when nothing is waiting to be resent, and (0929/03-03) when
* that request has no key: the server could not tell a second one from a
* new request, so it could apply twice. 1106/03-01. A resend that ends
* `NOT_APPLIED` or `NOT_STARTED` resolves to that failure and leaves the
* request unknown with its key; only success or `APPLIED_CONFIRMED`
* settles it.
* new request, so it could apply twice. An IDEMPOTENT command
* (`resendSafe`) is sent without one (1106/03-03). 1106/03-01. A resend
* that ends `NOT_APPLIED` or `NOT_STARTED` resolves to that failure and
* leaves the request unknown with its key; only success or
* `APPLIED_CONFIRMED` settles it.
*/
resendUnknownEffect(): Promise<ApplicationResult<Value> | null>;
/**
* 0929/03-03. `resendUnknownEffect` would send: the oldest request is
* unknown, carries an idempotency key and is not being reconciled.
* unknown, carries an idempotency key or comes from a `resendSafe`
* policy (1106/03-03), and is not being reconciled.
* `state.unknownEffectResendable` carries the same answer to `AsyncSurface`.
*/
canResendUnknownEffect: boolean;
@@ -287,6 +290,11 @@ type MutationAdmission = {
state: "ACTIVE" | "UNKNOWN" | "RECONCILING" | "SETTLED";
readonly input: unknown;
intent: MutationIntent | null;
/**
* 1106/03-03. Sending this request again cannot apply it twice: its intent
* carries a key (KEYED) or the policy is `resendSafe` (IDEMPOTENT).
*/
resendable: boolean;
/** Held while UNKNOWN so the same input keeps the same identity token. */
identityLease: Readonly<{ release(): void }> | null;
/** `performance.now()` before which a resend waits (see RESEND_WAIT_CEILING_MS). */
@@ -371,6 +379,7 @@ export function useApplicationMutation<Input, Value>(
"requiresIdempotencyKey" in options
? options.requiresIdempotencyKey
: false;
const resendSafe = "resendSafe" in options && options.resendSafe === true;
const unknownEffectChannelKey = scope
? `bound:${scope.generation}:${scope.fingerprint}:${definitionId}:${definitionVersion}`
: `legacy:${definitionId}:${
@@ -573,8 +582,9 @@ export function useApplicationMutation<Input, Value>(
// request from this one, so saving the same input again could apply it
// twice. The unknown request is settled first (reconcileUnknownEffect),
// never repeated; a page that calls submit outside the form meets this
// too.
if (replayed && replayed.intent?.idempotencyKey === undefined) {
// too. 1106/03-03. An IDEMPOTENT command has no key but applying it
// twice gives the same result, so it is sent (`resendable`).
if (replayed && !replayed.resendable) {
identityLease?.release();
return Promise.resolve({
ok: false,
@@ -589,6 +599,7 @@ export function useApplicationMutation<Input, Value>(
state: "ACTIVE",
input,
intent: null,
resendable: false,
identityLease: null,
resendNotBefore: 0,
scope: scope ?? null,
@@ -639,6 +650,8 @@ export function useApplicationMutation<Input, Value>(
requiresIdempotencyKey,
});
admission.intent = intent;
admission.resendable =
intent.idempotencyKey !== undefined || resendSafe;
execution = Object.freeze({ kind: "BOUND", input, intent });
} else {
execution = Object.freeze({ kind: "LEGACY", input });
@@ -777,6 +790,7 @@ export function useApplicationMutation<Input, Value>(
mutationIntentFactory,
mutationOperationId,
requiresIdempotencyKey,
resendSafe,
scope,
unknownEffectChannel,
],
@@ -876,7 +890,9 @@ export function useApplicationMutation<Input, Value>(
/**
* D-1 / 0929/03-03. A resend repeats the unknown request with its original
* intent. Without an idempotency key (a `NEVER` command) nothing lets the
* server recognise the repeat, so it is not offered.
* server recognise the repeat, so it is not offered. 1106/03-03. An
* IDEMPOTENT command (`resendSafe`) is: applying it twice gives the same
* result.
*/
function canResend(
channel: UnknownEffectChannel,
@@ -884,7 +900,7 @@ function canResend(
): boolean {
return (
head.state === "UNKNOWN" &&
head.intent?.idempotencyKey !== undefined &&
head.resendable &&
!channel.reconciliationInFlight
);
}
@@ -410,6 +410,7 @@ describe("application mutation intent admission", () => {
options: Readonly<{
maxIdentities?: number;
keyed?: boolean;
resendSafe?: boolean;
optimistic?: Readonly<{
queryKey: readonly unknown[];
update(previous: unknown, input: string): unknown;
@@ -442,6 +443,9 @@ describe("application mutation intent admission", () => {
scope,
execute,
invalidate: [],
...(options.resendSafe === undefined
? {}
: { resendSafe: options.resendSafe }),
...(options.optimistic === undefined
? {}
: { optimistic: options.optimistic }),
@@ -612,6 +616,41 @@ describe("application mutation intent admission", () => {
expect(hook.result.current.state.unknownEffectResendable).toBe(true);
});
// 1106/03-03. An IDEMPOTENT command has no key, but applying it twice
// gives the same result: after an unknown result it is offered for
// resend and the same input is sent again, unlike NEVER (above).
it("resends an unknown IDEMPOTENT request and sends the same input again", async () => {
const { hook, intents, execute } = renderKeyedCreate([unknown, unknown], {
keyed: false,
resendSafe: true,
});
await act(() => hook.result.current.submit("idempotent-input"));
expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown");
expect(hook.result.current.canResendUnknownEffect).toBe(true);
expect(hook.result.current.state.unknownEffectResendable).toBe(true);
let resent: ApplicationResult<string> | null | undefined;
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
expect(resent).toMatchObject({ ok: false, error: { effect: "MAYBE_APPLIED" } });
let again: ApplicationResult<string> | undefined;
await act(async () => {
again = await hook.result.current.submit("idempotent-input");
});
expect(again).toEqual({ ok: true, value: "idempotent-input" });
expect(execute).toHaveBeenCalledTimes(3);
expect(intents[1]).toBe(intents[0]);
expect(intents[2]).toBe(intents[0]);
expect(intents.map((intent) => intent.idempotencyKey)).toEqual([
undefined,
undefined,
undefined,
]);
});
// 백엔드 1101/02-01. The paired backend answers a same-key request while
// the first still runs with 409 IDEMPOTENT_IN_FLIGHT and Retry-After.
it("holds a resend until the Retry-After of the unknown answer", async () => {
+15 -4
View File
@@ -21,17 +21,28 @@ describe("commandMutationIdentity", () => {
expect(commandMutationIdentity(TEST_CREATE_HTTP_CONTRACT)).toEqual({
operationId: "TEST_CREATE_ENTITY",
requiresIdempotencyKey: true,
resendSafe: true,
});
});
it.each(["NEVER", "IDEMPOTENT"] as const)(
"sends no key for a %s command",
(retrySemantics) => {
// 1106/03-03. An IDEMPOTENT command carries no key, but sending it again
// gives the same result, so the coordinator may resend it after an
// unknown result. A NEVER command may not.
it.each([
["NEVER", false],
["IDEMPOTENT", true],
] as const)(
"sends no key for a %s command, resend safe: %s",
(retrySemantics, resendSafe) => {
expect(
commandMutationIdentity({
contract: { ...TEST_CREATE_HTTP_CONTRACT.contract, retrySemantics },
}),
).toEqual({ operationId: "TEST_CREATE_ENTITY", requiresIdempotencyKey: false });
).toEqual({
operationId: "TEST_CREATE_ENTITY",
requiresIdempotencyKey: false,
resendSafe,
});
},
);