fix(query): 쓰기 전에 거절된 같은 키 재전송 뒤에도 결과 불명과 키를 지킨다

문제: KEYED 결과 불명 요청을 같은 키로 다시 보냈는데 그 시도가 쓰기 전
거절(429, 엣지 rate limiter의 503 RATE_LIMIT_*, 401)이나 보내기 전 실패
(NOT_STARTED)로 끝나면, 훅이 그 판정을 논리 요청 전체의 판정으로 써서
결과 불명과 intent를 버린다. 폼은 retry-later가 되고 다음 저장이 새 키로
나간다. 첫 요청이 적용됐으면 같은 항목이 둘 생긴다. 재전송의 NOT_APPLIED는
그 시도만 증명한다. 백엔드 http-contract.md §2와 런북 6.3-4는 결과 불명에
새 키를 금지한다(리뷰 실험 03-R1 X1~X3·X5: keys key-1, key-1, key-2).

고른 방법(결정 D10, 메인 세션, 2026-11-06: 리뷰 03-01 대안 (a)):
- 훅(application-query.ts submit): 결과 불명 intent를 다시 쓴 시도가
  NOT_APPLIED·NOT_STARTED로 끝나면 새 admission을 UNKNOWN으로 되돌리고 그
  intent와 키를 남긴다. 실패는 그대로 돌려준다. Retry-After는 MAYBE_APPLIED와
  같이 다음 재전송의 대기 시각이 된다. 낙관적 층은 rollback 대신
  markUncertain이다(첫 요청이 적용됐을 수 있다). 훅 안의 보내기 전 예외
  (.catch, NOT_STARTED)도 같다. 이 경우 충돌 상태는 세우지 않는다. 화면은
  결과 불명을 먼저 보여야 한다. 처음 보내는 요청의 NOT_APPLIED, 재전송의
  성공·APPLIED_CONFIRMED, scope가 바뀐 경우는 지금처럼 정리한다.
- 폼은 (i)을 골랐다: use-app-form.ts resendUnknown이 그런 결과에서
  unknownSubmissionRef를 지우지 않고 result를 effect-unknown으로 둔다. 문구
  하나("form.resendLater": "잠시 뒤 같은 요청으로 다시 보내 주세요")를
  formErrors에 싣고 feedback으로 포커스를 옮긴다. 이유: 폼은 이미 그 ref로
  저장을 막는다(submitForm). 결과 불명 화면(확인·같은 키로 다시 보내기)이
  그대로 남아 다음 행동이 재전송이다. (ii)는 useAppForm이 코디네이터 상태를
  받는 새 옵션이 필요하다. 폼과 훅을 새로 묶는 일이라 지난 라운드 3.5 (B)로
  미룬 설계 변경이다. 401은 D-2대로 다시 로그인이 먼저다.
버린 대안: 표에서 rate-limit 503을 다시 MAYBE_APPLIED로(429·401·NOT_STARTED가
남고 1105/03-02의 이득을 잃는다), 생성 페이지의 "다시 시도"만 고치기(생성
기능만 덮는다).

위험·한계: 재전송이 rate limit에 막힌 동안 결과 불명 화면이 남는다. 다시
보내기는 Retry-After(상한 5초)를 기다린다. 폼 밖에서 submit을 부른 같은
입력 재저장이 NOT_APPLIED로 끝나면 훅은 키를 지키지만 폼은 retry-later를
보인다. 그때 "다시 시도"도 같은 키로 간다. 새 문구가 초기 JS를 조금
늘린다(check:bundle). CHANGELOG 행은 문서 담당이 적는다.

검증: desktop batch에서 확인. node scripts/run-vitest.ts run
tests/component/application-mutation-admission.test.tsx
tests/component/form-foundation.test.tsx, 리뷰 실험 03-R1 패치를 이 커밋에
적용해 X1~X3 keys [key-1,key-1,key-1], X5 세 번째 요청 없음 또는 key-1.

Refs: 1106/03-01
This commit is contained in:
DongHyeonka
2026-11-06 05:28:30 +09:00
parent 302d3a5359
commit 25685871f1
6 changed files with 248 additions and 14 deletions
@@ -256,6 +256,10 @@ diagnostics에만 남고 `api.request.failed`에는 세지 않는다(03-07). 그
다시 보내기"는 그 intent와 같은 `Idempotency-Key`로 보낸다. 입력이 바뀌면 새
key다. 자동 재전송은 없다(`src/presentation/adapters/query/application-query.ts`
`submit`·`resendUnknownEffect`, 화면 `src/presentation/components/async-surface.tsx`).
다시 보낸 요청이 쓰기 전에 거절되거나(429, 503 `RATE_LIMIT_*`, 401) 보내지 못하면
(`NOT_STARTED`) 그 시도만 적용되지 않은 것이다. 결과 불명과 key는 그대로다. 폼은
"잠시 뒤 같은 요청으로 다시 보내 주세요"를 보이고 저장을 받지 않는다. 401은 다시
로그인 안내가 먼저다(1106/03-01, `use-app-form.ts` `resendUnknown`).
키가 없는 command(`NEVER`)는 서버가 두 번째 요청을 가려내지 못하므로 재전송 버튼을
그리지 않는다(`canResendUnknownEffect`, 0929/03-03). 같은 canonical input의 재저장도
보내지 않는다. 훅의 `submit`이 `NOT_STARTED` `DUPLICATE_IN_FLIGHT`(code
@@ -264,7 +264,10 @@ 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.
* 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.
*/
resendUnknownEffect(): Promise<ApplicationResult<Value> | null>;
/**
@@ -605,6 +608,24 @@ export function useApplicationMutation<Input, Value>(
notifyUnknownEffectChannel(unknownEffectChannel);
setConflict(null);
mutation.reset();
const holdUnknown = (retryAfterMs: number | undefined): void => {
admission.state = "UNKNOWN";
admission.resendNotBefore =
performance.now() +
Math.min(retryAfterMs ?? 0, RESEND_WAIT_CEILING_MS);
if (identityLease) {
identityLease.acquire();
admission.identityLease = identityLease;
}
notifyUnknownEffectChannel(unknownEffectChannel);
};
// 1106/03-01. A resend of an unknown request that is refused before
// the write (429, the edge's 503 RATE_LIMIT_*) or never sent shows only
// that this attempt did not apply; the first may have. The request
// stays unknown with its intent, so the next save or resend carries
// the same key, never a new one (backend http-contract.md §2).
const resendLeavesUnknown = (): boolean =>
replayed !== undefined && (!scope || scope.isCurrent());
let runtimeExecution: RuntimeMutationExecution<Value> | undefined;
const pending = (async (): Promise<ApplicationResult<Value>> => {
@@ -666,6 +687,11 @@ export function useApplicationMutation<Input, Value>(
switch (failure.effect) {
case "NOT_STARTED":
case "NOT_APPLIED":
if (resendLeavesUnknown()) {
optimisticLayer?.markUncertain();
holdUnknown(failure.retryAfterMs);
break;
}
optimisticLayer?.rollback();
if (failure.kind === "CONFLICT") setConflict(failure);
settleMutationAdmission(unknownEffectChannel, admission);
@@ -684,15 +710,7 @@ export function useApplicationMutation<Input, Value>(
case "MAYBE_APPLIED":
optimisticLayer?.markUncertain();
if (!scope || scope.isCurrent()) {
admission.state = "UNKNOWN";
admission.resendNotBefore =
performance.now() +
Math.min(failure.retryAfterMs ?? 0, RESEND_WAIT_CEILING_MS);
if (identityLease) {
identityLease.acquire();
admission.identityLease = identityLease;
}
notifyUnknownEffectChannel(unknownEffectChannel);
holdUnknown(failure.retryAfterMs);
} else {
settleMutationAdmission(unknownEffectChannel, admission);
}
@@ -724,6 +742,11 @@ export function useApplicationMutation<Input, Value>(
}),
"NOT_STARTED",
);
if (resendLeavesUnknown()) {
admission.optimisticLayer?.markUncertain();
holdUnknown(undefined);
return { ok: false as const, error: failure };
}
settleMutationAdmission(unknownEffectChannel, admission);
if (failure.kind === "CONFLICT") setConflict(failure);
return { ok: false as const, error: failure };
+27 -2
View File
@@ -397,7 +397,10 @@ export function useAppForm<
* D-1. Runs a resend of the unknown submission (for example
* `mutation.resendUnknownEffect`) through the same outcome handling as a
* submit. The form never builds a new command here: the caller resends the
* original request with its original key.
* original request with its original key. 1106/03-01. A resend refused
* before the write (429, 503 `RATE_LIMIT_*`) or never sent leaves the
* result unknown: the form keeps the submission, so a save does not go
* out as a new request, and asks for the same request again later.
*/
const resendUnknown = useCallback(
(
@@ -410,7 +413,15 @@ export function useAppForm<
setPending(true);
try {
const outcome = await send();
if (outcome) applyOutcome(outcome, submittedValues);
if (outcome && resendLeftUnknown(outcome)) {
focusFeedbackRef.current = true;
unknownSubmissionRef.current = submittedValues;
setFieldErrors({} as FieldErrors<Values>);
setFormErrors(["form.resendLater"]);
setResult("effect-unknown");
} else if (outcome) {
applyOutcome(outcome, submittedValues);
}
return outcome;
} finally {
setPending(false);
@@ -486,6 +497,20 @@ function refusalFor<Values extends FormValues>(
: undefined;
}
/**
* 1106/03-01. The resend did not reach the write: the request it repeats is
* still unknown, and the mutation coordinator keeps its key. Signing in again
* still comes first (D-2).
*/
function resendLeftUnknown(outcome: FormResult<unknown>): boolean {
return (
!outcome.ok &&
(outcome.error.effect === "NOT_APPLIED" ||
outcome.error.effect === "NOT_STARTED") &&
outcome.error.action !== "reauth"
);
}
/** 1105/08-01. Nothing has focus: the focused element left the document. */
function focusIsLost(): boolean {
const active = document.activeElement;
+4
View File
@@ -152,6 +152,8 @@ const PLATFORM_KO_MESSAGES = {
"form.validation.configuration": "입력 구성을 다시 확인해 주세요.",
"form.conflict":
"다른 변경과 충돌했습니다. 입력은 유지되었으니 최신 상태를 확인해 주세요.",
"form.resendLater":
"다시 보낸 요청이 처리되지 않았습니다. 잠시 뒤 같은 요청으로 다시 보내 주세요.",
"form.reauthLosesInput":
"다시 로그인하면 이 화면에 입력한 내용은 사라집니다. 필요하면 먼저 복사해 두세요.",
"form.remaining": "{count}자 남음",
@@ -356,6 +358,8 @@ const PLATFORM_EN_MESSAGES = {
"form.validation.configuration": "Review the input configuration.",
"form.conflict":
"Another update conflicts with this change. Your input has been preserved.",
"form.resendLater":
"The request sent again was not processed. Send the same request again shortly.",
"form.reauthLosesInput":
"Signing in again clears what you entered on this page. Copy it first if you need it.",
"form.remaining": "{count} characters remaining",
@@ -407,7 +407,14 @@ describe("application mutation intent admission", () => {
function renderKeyedCreate(
outcomes: ApplicationResult<string>[],
options: Readonly<{ maxIdentities?: number; keyed?: boolean }> = {},
options: Readonly<{
maxIdentities?: number;
keyed?: boolean;
optimistic?: Readonly<{
queryKey: readonly unknown[];
update(previous: unknown, input: string): unknown;
}>;
}> = {},
) {
const client = queryClient();
const intents: MutationIntent[] = [];
@@ -435,6 +442,9 @@ describe("application mutation intent admission", () => {
scope,
execute,
invalidate: [],
...(options.optimistic === undefined
? {}
: { optimistic: options.optimistic }),
}),
{ wrapper: wrapper(client) },
);
@@ -647,5 +657,101 @@ describe("application mutation intent admission", () => {
vi.useRealTimers();
}
});
// 1106/03-01. A same-key resend refused before the write (429, the
// edge's 503 RATE_LIMIT_*) or never sent says nothing about the first
// request, which may have applied. It stays unknown, and the next save
// carries its key, not a new one (review experiment 03-R1 X1-X3: keys
// key-1, key-1, key-2).
it.each([
[
"refused by the edge's 503 RATE_LIMIT_UNAVAILABLE",
createFailure("SERVER_FAILURE", "CREATE_REPLAYED", 0, {
code: "RATE_LIMIT_UNAVAILABLE",
httpStatus: 503,
effect: "NOT_APPLIED",
}),
],
[
"refused with 429",
createFailure("RATE_LIMITED", "CREATE_REPLAYED", 0, {
code: "RATE_LIMIT_EXCEEDED",
httpStatus: 429,
effect: "NOT_APPLIED",
}),
],
[
"not sent",
createFailure("NETWORK_UNREACHABLE", "CREATE_REPLAYED", 0, {
effect: "NOT_STARTED",
}),
],
])("keeps the request unknown with its key when the resend is %s", async (_label, refusal) => {
const { hook, intents } = renderKeyedCreate([
unknown,
{ ok: false, error: refusal },
]);
await act(() => hook.result.current.submit("same-input"));
let resent: ApplicationResult<string> | null | undefined;
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
expect(resent).toMatchObject({
ok: false,
error: { kind: refusal.kind, effect: refusal.effect },
});
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
expect(hook.result.current.canResendUnknownEffect).toBe(true);
await act(() => hook.result.current.submit("same-input"));
expect(intents.map((intent) => intent.idempotencyKey)).toEqual([
"key-1",
"key-1",
"key-1",
]);
});
// 1106/03-01. The same when the resend fails in the coordinator itself
// before anything is sent (here the page's optimistic update throws).
it("keeps the request unknown with its key when the resend fails before sending", async () => {
let projectionBroken = false;
const { hook, intents } = renderKeyedCreate([unknown], {
optimistic: {
queryKey: ["resource", "replayed-projection"],
update: (_previous, input) => {
if (projectionBroken) throw new Error("projection defect");
return [input];
},
},
});
await act(() => hook.result.current.submit("same-input"));
projectionBroken = true;
let resent: ApplicationResult<string> | null | undefined;
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
expect(resent).toMatchObject({
ok: false,
error: { effect: "NOT_STARTED" },
});
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
projectionBroken = false;
await act(() => hook.result.current.submit("same-input"));
expect(intents.map((intent) => intent.idempotencyKey)).toEqual([
"key-1",
"key-1",
]);
});
});
});
+73 -1
View File
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { render, screen, waitFor } from "@testing-library/react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { createMemoryRouter, RouterProvider, useNavigate } from "react-router-dom";
@@ -889,7 +889,12 @@ describe("correcting a field after a server validation refusal", () => {
<Button type="submit" disabled={form.pending || blocked}>
Submit
</Button>
<Button onClick={() => void form.resendUnknown(mutation.resendUnknownEffect)}>
Resend
</Button>
<output data-testid="result">{form.result}</output>
<output data-testid="indicator">{mutation.state.indicator ?? "none"}</output>
<output data-testid="form-errors">{form.formErrors.join(" ")}</output>
</Form>
);
}
@@ -1141,4 +1146,71 @@ describe("correcting a field after a server validation refusal", () => {
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
expect(fetcher).toHaveBeenCalledTimes(1);
});
// 1106/03-01. The answer is lost, and the same-key resend meets the edge
// rate limiter's 503 RATE_LIMIT_UNAVAILABLE, refused before the write. The
// first request may still have applied: the result stays unknown, a save
// sends nothing new, and the next resend carries the same key (review
// experiment 03-R1 X5: keys key-1, key-1, key-2).
it("keeps a lost create unknown when its resend is refused before the write", async () => {
const user = userEvent.setup();
const fetcher = vi
.fn<typeof fetch>()
.mockRejectedValueOnce(new TypeError("Failed to fetch"))
.mockResolvedValueOnce(
Response.json(
{
success: false,
error: {
code: "RATE_LIMIT_UNAVAILABLE",
category: "TRANSIENT_DEPENDENCY",
retryable: true,
},
meta,
},
{ status: 503 },
),
)
.mockImplementation(async () =>
Response.json({
success: true,
data: { id: "entity-1", name: "Saved" },
meta,
}),
);
const { container } = render(<CoordinatedForm fetcher={fetcher} />, {
wrapper: wrapper(queryClient()),
});
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"),
);
await user.click(screen.getByRole("button", { name: "Resend" }));
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
await waitFor(() =>
expect(screen.getByTestId("form-errors")).toHaveTextContent(
formatMessage("ko-KR", "form.resendLater"),
),
);
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown");
expect(screen.getByTestId("indicator")).toHaveTextContent(
"mutation-effect-unknown",
);
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
// A save that reaches the form anyway (Enter in the field) sends nothing.
const form = container.querySelector("form");
if (!form) throw new Error("expected the form");
fireEvent.submit(form);
expect(fetcher).toHaveBeenCalledTimes(2);
await user.click(screen.getByRole("button", { name: "Resend" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(sentKeys(fetcher)).toEqual(["key-1", "key-1", "key-1"]);
});
});