fix(query): 키 없는 결과 불명 요청의 같은 입력 재제출을 훅이 막는다

문제
0929/03-03은 화면 버튼 쪽만 고쳐졌다. 남은 길이 둘이다.
- useApplicationMutation의 submit은 같은 canonical input의 결과 불명
  admission을 찾아 그 intent를 그대로 다시 보낸다. 키 없는 intent(NEVER)면
  서버가 가려낼 수 없는 두 번째 요청이다. 막는 곳은 폼(unknownSubmissionRef)과
  두 페이지의 버튼·onSubmit 검사뿐이라, 폼 밖에서 submit을 부르는 화면은 같은
  항목을 둘 만들 수 있다(리뷰 실험 X1: 재전송은 null인데 같은 입력 submit이
  두 번째 POST를 보냈고 keys=[null,null]).
- AsyncSurface는 state.unknownEffectResendable !== false일 때 재전송 버튼을
  그린다. 코디네이터 없이 손으로 만든 AsyncState(플래그 없음)는 지금도 버튼을
  그린다(실험 X3).

고른 방법
- submit이 같은 입력의 결과 불명 admission을 찾았는데 그 intent에 키가 없으면
  보내지 않고 NOT_STARTED DUPLICATE_IN_FLIGHT(code UNKNOWN_EFFECT_PENDING)를
  돌려준다. admission을 만들기 전이라 결과 불명 상태와 identity lease는 그대로다.
  KEYED의 같은 키 재전송, 입력이 바뀐 새 요청은 바뀌지 않는다. LEGACY(테스트
  하네스) 경로는 intent가 없어 replay 자체가 없으므로 영향이 없다.
- AsyncSurface는 unknownEffectResendable === true일 때만 재전송 버튼을 그린다.
  코디네이터의 state는 늘 이 값을 싣는다(canResendUnknownEffect).
- 기존 async-surface 테스트 "renders unknown mutation effects with
  confirm-applied and resend only"는 플래그 없는 상태로 버튼을 기대했다. 이
  수정의 의도대로 isUnknownEffectResendable: true를 입력에 적었다. 단언은 그대로다.
- 런북 6.3-4와 매뉴얼 01에 키 없는 재제출과 손으로 만든 상태를 적었다.

버린 대안
FailureKind에 새 kind를 더한다: 닫힌 레지스트리를 넓히는 계약 변경이다.
"같은 논리 요청이 아직 끝나지 않았다"는 DUPLICATE_IN_FLIGHT(action none)로
충분하다.

위험·한계
- 다운스트림이 AsyncSurface에 손으로 만든 결과 불명 상태와 onResendUnknownEffect를
  넘기던 화면은 재전송 버튼이 사라진다. 코디네이터의 state를 넘기면 그대로다.
- 결과 불명 admission은 메모리에만 있다. 새로고침 뒤 같은 입력은 막지 못한다
  (런북 6.3-7의 한계 그대로).

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

Refs: 0929/03-03
This commit is contained in:
DongHyeonka
2026-11-06 02:33:16 +09:00
parent c6c37f395b
commit 683ccfb56b
7 changed files with 92 additions and 6 deletions
+1 -1
View File
@@ -504,7 +504,7 @@ projectRequest: (input) => Object.freeze({
① **정할 것**
- 페이지 템플릿. [02 결정표 6절](02-decision-tables.md#6-페이지-템플릿)
- 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 키가 있는 요청(`KEYED`)에만 그려진다. `NEVER` 쓰기는 확인만 남는다.
- 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 키가 있는 요청(`KEYED`)에만 그려진다. `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 본문을 손으로 적는다.
② **기준**
@@ -257,7 +257,11 @@ diagnostics에만 남고 `api.request.failed`에는 세지 않는다(03-07). 그
key다. 자동 재전송은 없다(`src/presentation/adapters/query/application-query.ts`
`submit`·`resendUnknownEffect`, 화면 `src/presentation/components/async-surface.tsx`).
키가 없는 command(`NEVER`)는 서버가 두 번째 요청을 가려내지 못하므로 재전송 버튼을
그리지 않는다(`canResendUnknownEffect`, 0929/03-03).
그리지 않는다(`canResendUnknownEffect`, 0929/03-03). 같은 canonical input의 재저장도
보내지 않는다. 훅의 `submit`이 `NOT_STARTED` `DUPLICATE_IN_FLIGHT`(code
`UNKNOWN_EFFECT_PENDING`)를 돌려주고, 결과 불명 요청이 확인될 때까지 그대로다. 폼
밖에서 `submit`을 부르는 화면도 같다. 화면은 상태에 `unknownEffectResendable: true`가
있을 때만 재전송 버튼을 그린다.
5. backend status/receipt로 `COMMITTED`면 cache reconcile/invalidate한다. 화면의
"변경됨으로 확인"이 이 경로다.
6. `NOT_APPLIED`가 증명된 경우만 정책에 따라 retry한다. 화면은 근거 없는
+3 -1
View File
@@ -86,7 +86,9 @@ export type AsyncState = Readonly<{
/**
* 0929/03-03. Only with `indicator: "mutation-effect-unknown"`, when the
* coordinator said: `false` means the request has no idempotency key, so
* sending it again is a second, unprotected request and no resend is drawn.
* sending it again is a second, unprotected request. A resend is drawn
* only for `true`; absent (a state built without the coordinator) draws
* none.
*/
unknownEffectResendable?: boolean;
}>;
@@ -243,6 +243,13 @@ export type LegacyMutationOptions<Input, Value> = LegacyMutationBase<Input, Valu
type ApplicationMutationController<Input, Value> = Readonly<{
state: AsyncState;
/**
* D-1. The same canonical input as an unknown-effect request is the same
* logical request: a keyed command sends it again with that request's
* 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.
*/
submit(input: Input): Promise<ApplicationResult<Value>>;
resolveConflict(): Promise<void>;
/**
@@ -559,6 +566,21 @@ export function useApplicationMutation<Input, Value>(
candidate.state === "UNKNOWN" &&
candidate.intent?.canonicalInputIdentity === identity,
);
// 0929/03-03. Without an idempotency key the server cannot tell that
// 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) {
identityLease?.release();
return Promise.resolve({
ok: false,
error: createFailure("DUPLICATE_IN_FLIGHT", definitionId, 0, {
code: "UNKNOWN_EFFECT_PENDING",
effect: "NOT_STARTED",
}),
});
}
const admission: MutationAdmission = {
sequence: unknownEffectChannel.nextSequence++,
state: "ACTIVE",
@@ -128,8 +128,10 @@ export type AsyncSurfaceProps = Readonly<{
onReconcileUnknownEffect?: (resolution: "APPLIED") => void;
/**
* D-1. Resends the unknown request with its original intent and key.
* 0929/03-03. Not drawn when `state.unknownEffectResendable` is `false`:
* a request without a key would go out as a second, unprotected one.
* 0929/03-03. Drawn only when `state.unknownEffectResendable` is `true`
* (the coordinator's `canResendUnknownEffect`): a request without a key
* would go out as a second, unprotected one, and a state built by hand
* without that answer draws no resend either.
*/
onResendUnknownEffect?: () => void;
/** 08-05. Title level of the empty and failure surfaces it renders. */
@@ -224,7 +226,7 @@ export function AsyncSurface({
) : null}
{state.indicator === "mutation-effect-unknown" &&
onResendUnknownEffect &&
state.unknownEffectResendable !== false ? (
state.unknownEffectResendable === true ? (
<Button onClick={onResendUnknownEffect}>
{message("action.resendMutation")}
</Button>
@@ -555,6 +555,43 @@ describe("application mutation intent admission", () => {
expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown");
});
// 0929/03-03. Saving the same input again reuses the unknown request's
// intent. Without a key that is a second request the server cannot tell
// from the first, so the hook refuses it before sending, whatever page
// calls it (review experiment X1: keys [null, null]).
it("refuses to send a keyless unknown request again for the same input", async () => {
const { hook, execute } = renderKeyedCreate([unknown], { keyed: false });
await act(() => hook.result.current.submit("keyless-input"));
expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown");
let again: ApplicationResult<string> | undefined;
await act(async () => {
again = await hook.result.current.submit("keyless-input");
});
expect(again).toMatchObject({
ok: false,
error: {
kind: "DUPLICATE_IN_FLIGHT",
code: "UNKNOWN_EFFECT_PENDING",
effect: "NOT_STARTED",
},
});
expect(execute).toHaveBeenCalledOnce();
expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown");
});
it("still sends another input while a keyless request is unknown", async () => {
const { hook, execute } = renderKeyedCreate([unknown], { keyed: false });
await act(() => hook.result.current.submit("first-input"));
await act(() => hook.result.current.submit("changed-input"));
expect(execute.mock.calls.map(([input]) => input)).toEqual([
"first-input",
"changed-input",
]);
});
it("offers the same-key resend for an unknown keyed request", async () => {
const { hook } = renderKeyedCreate([unknown]);
expect(hook.result.current.canResendUnknownEffect).toBe(false);
+19
View File
@@ -65,9 +65,11 @@ describe("async UI state matrix", () => {
const retry = vi.fn();
const reconcile = vi.fn();
const resend = vi.fn();
// 0929/03-03. The coordinator says the request carries a key.
const state = deriveAsyncState({
data: ["value"],
hasMutationEffectUnknown: true,
isUnknownEffectResendable: true,
});
render(
@@ -123,6 +125,23 @@ describe("async UI state matrix", () => {
expect(screen.getByRole("button", { name: "변경됨으로 확인" })).toBeInTheDocument();
});
// 0929/03-03. A state built by hand without the coordinator's answer does
// not know the request has a key, so it draws no resend (review X3).
it("draws no resend for an unknown state that does not say it can be resent", () => {
render(
<AsyncSurface
state={deriveAsyncState({ data: ["value"], hasMutationEffectUnknown: true })}
onReconcileUnknownEffect={vi.fn()}
onResendUnknownEffect={vi.fn()}
/>,
);
expect(
screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }),
).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "변경됨으로 확인" })).toBeInTheDocument();
});
it("keeps the resend state to an unknown mutation only", () => {
expect(
deriveAsyncState({ data: ["value"], isUnknownEffectResendable: false }),