fix(query): resend an unknown-effect write with its original idempotency key (03-01, 08-03)

A save whose response was lost minted a new key on the next submit, and the
screen let the user declare "not applied" without evidence. The same canonical
input now reuses the unknown admission's intent; the screen offers "send the
same request again" and a list refresh link instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-25 22:09:28 +09:00
co-authored by Claude Opus 5.5
parent 926f448fce
commit dfb1b9e0ee
9 changed files with 386 additions and 97 deletions
@@ -1,5 +1,5 @@
import { useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { Link, useNavigate } from "react-router-dom";
import {
Button,
@@ -13,6 +13,8 @@ import {
useAppForm,
useDirtyNavigationGuard,
} from "../../../presentation/design-system/index.ts";
import { useQueryInvalidationCoordinator } from "../../../presentation/adapters/query/query-invalidation-provider.tsx";
import { REFERENCE_RESOURCE_INVALIDATION_TOPIC } from "../contracts/reference-feature-contract.ts";
import {
REFERENCE_FORM_DEFAULTS,
referenceResourceFormSchema,
@@ -29,6 +31,7 @@ const FIELD_LABELS = Object.freeze({
export default function ReferenceResourceFormPage() {
const navigate = useNavigate();
const mutation = useReferenceCreate();
const invalidation = useQueryInvalidationCoordinator();
const submit = useCallback(
(command: ReturnType<typeof toCreateReferenceCommand>) =>
mutation.submit(command),
@@ -127,18 +130,31 @@ export default function ReferenceResourceFormPage() {
}
feedback={
mutationEffectUnknown ? (
<AsyncSurface
state={mutation.state}
onReconcileUnknownEffect={(resolution) => {
void mutation.reconcileUnknownEffect(resolution).then(() => {
if (resolution === "APPLIED") {
form.settleApplied();
} else {
form.settleNotApplied();
}
});
}}
/>
<>
<AsyncSurface
state={mutation.state}
onReconcileUnknownEffect={(resolution) => {
void mutation
.reconcileUnknownEffect(resolution)
.then(form.settleApplied);
}}
onResendUnknownEffect={() => {
void form.resendUnknown(mutation.resendUnknownEffect);
}}
/>
<p>
<Link
to="/examples/reference-resources"
onClick={() => {
void invalidation
?.invalidate([REFERENCE_RESOURCE_INVALIDATION_TOPIC])
.catch(() => {});
}}
>
목록을 새로 불러와 확인
</Link>
</p>
</>
) : form.result === "success" ? (
<p role="status">저장했습니다.</p>
) : form.result === "conflict" ? (
@@ -219,9 +219,19 @@ type ApplicationMutationController<Input, Value> = Readonly<{
state: AsyncState;
submit(input: Input): Promise<ApplicationResult<Value>>;
resolveConflict(): Promise<void>;
/**
* Settles the oldest unknown effect. `NOT_APPLIED` needs evidence (an
* inspect operation or a server read); without it, resend instead.
*/
reconcileUnknownEffect(
resolution: "APPLIED" | "NOT_APPLIED",
): Promise<void>;
/**
* D-1. Sends the oldest unknown-effect request again with its original
* intent, so a keyed command carries the same `Idempotency-Key`. Resolves
* to `null` when nothing is waiting to be resent.
*/
resendUnknownEffect(): Promise<ApplicationResult<Value> | null>;
}>;
type MutationExecution<Input> =
@@ -231,7 +241,10 @@ type MutationExecution<Input> =
type MutationAdmission = {
sequence: number;
state: "ACTIVE" | "UNKNOWN" | "RECONCILING" | "SETTLED";
readonly input: unknown;
intent: MutationIntent | null;
/** Held while UNKNOWN so the same input keeps the same identity token. */
identityLease: Readonly<{ release(): void }> | null;
scope: CacheScopeSnapshot | null;
optimisticLayer: OptimisticLayerLease | null;
optimisticQueryKey: readonly unknown[] | null;
@@ -486,10 +499,19 @@ export function useApplicationMutation<Input, Value>(
),
});
}
// D-1. Saving the same canonical input again is the same logical
// request: it reuses the unknown admission's intent (and key).
const replayed = unknownEffectChannel.admissions.find(
(candidate) =>
candidate.state === "UNKNOWN" &&
candidate.intent?.canonicalInputIdentity === identity,
);
const admission: MutationAdmission = {
sequence: unknownEffectChannel.nextSequence++,
state: "ACTIVE",
input,
intent: null,
identityLease: null,
scope: scope ?? null,
optimisticLayer: null,
optimisticQueryKey: optimistic?.queryKey ?? null,
@@ -498,6 +520,12 @@ export function useApplicationMutation<Input, Value>(
};
unknownEffectChannel.admissions.push(admission);
unknownEffectChannel.registry.activeAdmissions += 1;
if (replayed) {
// The new attempt re-applies its own optimistic layer and owns the
// outcome from here.
replayed.optimisticLayer?.reconcile("NOT_APPLIED");
settleMutationAdmission(unknownEffectChannel, replayed);
}
notifyUnknownEffectChannel(unknownEffectChannel);
setConflict(null);
mutation.reset();
@@ -506,11 +534,13 @@ export function useApplicationMutation<Input, Value>(
const pending = (async (): Promise<ApplicationResult<Value>> => {
let execution: MutationExecution<Input>;
if (scope) {
const intent = mutationIntentFactory.create({
operationId: mutationOperationId,
canonicalInputIdentity: identity,
requiresIdempotencyKey,
});
const intent =
replayed?.intent ??
mutationIntentFactory.create({
operationId: mutationOperationId,
canonicalInputIdentity: identity,
requiresIdempotencyKey,
});
admission.intent = intent;
execution = Object.freeze({ kind: "BOUND", input, intent });
} else {
@@ -572,6 +602,10 @@ export function useApplicationMutation<Input, Value>(
optimisticLayer?.markUncertain();
if (!scope || scope.isCurrent()) {
admission.state = "UNKNOWN";
if (identityLease) {
identityLease.acquire();
admission.identityLease = identityLease;
}
notifyUnknownEffectChannel(unknownEffectChannel);
} else {
settleMutationAdmission(unknownEffectChannel, admission);
@@ -699,6 +733,19 @@ export function useApplicationMutation<Input, Value>(
[mutation, queryClient, unknownEffectChannel],
);
const resendUnknownEffect = useCallback(async () => {
const head = unknownEffectChannel?.admissions[0];
if (
!head ||
head.state !== "UNKNOWN" ||
!head.intent ||
unknownEffectChannel?.reconciliationInFlight
) {
return null;
}
return submit(head.input as Input);
}, [submit, unknownEffectChannel]);
const unknownEffectHead = unknownEffectChannel?.admissions[0];
return Object.freeze({
@@ -714,6 +761,7 @@ export function useApplicationMutation<Input, Value>(
submit,
resolveConflict,
reconcileUnknownEffect,
resendUnknownEffect,
});
}
@@ -822,6 +870,8 @@ function markMutationAdmissionSettled(
): void {
if (admission.state === "SETTLED") return;
admission.state = "SETTLED";
admission.identityLease?.release();
admission.identityLease = null;
channel.registry.activeAdmissions = Math.max(
0,
channel.registry.activeAdmissions - 1,
+14 -15
View File
@@ -96,9 +96,10 @@ export type AsyncSurfaceProps = Readonly<{
onAction?: () => void;
onRetry?: () => void;
onResolveConflict?: () => void;
onReconcileUnknownEffect?: (
resolution: "APPLIED" | "NOT_APPLIED",
) => void;
/** Only `APPLIED` is offered: "not applied" needs evidence the UI lacks. */
onReconcileUnknownEffect?: (resolution: "APPLIED") => void;
/** D-1. Resends the unknown request with its original intent and key. */
onResendUnknownEffect?: () => void;
}>;
export function AsyncSurface({
@@ -109,6 +110,7 @@ export function AsyncSurface({
onRetry,
onResolveConflict,
onReconcileUnknownEffect,
onResendUnknownEffect,
}: AsyncSurfaceProps) {
const { message } = useLocale();
if (state.base === "idle") return idle ?? null;
@@ -155,18 +157,15 @@ export function AsyncSurface({
) : null}
{state.indicator === "mutation-effect-unknown" &&
onReconcileUnknownEffect ? (
<>
<Button
onClick={() => onReconcileUnknownEffect("APPLIED")}
>
{message("action.confirmMutationApplied")}
</Button>
<Button
onClick={() => onReconcileUnknownEffect("NOT_APPLIED")}
>
{message("action.confirmMutationNotApplied")}
</Button>
</>
<Button onClick={() => onReconcileUnknownEffect("APPLIED")}>
{message("action.confirmMutationApplied")}
</Button>
) : null}
{state.indicator === "mutation-effect-unknown" &&
onResendUnknownEffect ? (
<Button onClick={onResendUnknownEffect}>
{message("action.resendMutation")}
</Button>
) : null}
</div>
) : null}
+72 -33
View File
@@ -175,6 +175,44 @@ export function useAppForm<
setResult("idle");
}, []);
const applyOutcome = useCallback(
(outcome: FormResult<Output>, submittedValues: Values) => {
if (outcome.ok) {
settleSuccessfulValues(submittedValues);
return;
}
if (outcome.error.kind === "VALIDATION_REJECTED") {
unknownSubmissionRef.current = null;
const mapped = mapValidationFailureToFields<Values>(
outcome.error,
allowedServerFields,
message,
);
setFieldErrors(mapped.fieldErrors);
setFormErrors(mapped.formErrors);
setResult("validation-error");
focusFirstError(mapped.fieldErrors);
} else if (outcome.error.effect === "MAYBE_APPLIED") {
unknownSubmissionRef.current = submittedValues;
setFormErrors([]);
setResult("effect-unknown");
} else if (outcome.error.effect === "APPLIED_CONFIRMED") {
settleSuccessfulValues(submittedValues);
} else if (outcome.error.kind === "CONFLICT") {
unknownSubmissionRef.current = null;
setFormErrors([
message("form.conflict"),
]);
setResult("conflict");
} else {
unknownSubmissionRef.current = null;
setFormErrors([message("form.unavailable")]);
setResult("unavailable");
}
},
[allowedServerFields, focusFirstError, message, settleSuccessfulValues],
);
const validateAndSubmit = useCallback(
async (): Promise<FormResult<Output> | null> => {
setFieldErrors({} as FieldErrors<Values>);
@@ -205,38 +243,7 @@ export function useAppForm<
setPending(true);
try {
const outcome = await submit(command);
if (outcome.ok) {
settleSuccessfulValues(parsed.data);
return outcome;
}
if (outcome.error.kind === "VALIDATION_REJECTED") {
unknownSubmissionRef.current = null;
const mapped = mapValidationFailureToFields<Values>(
outcome.error,
allowedServerFields,
message,
);
setFieldErrors(mapped.fieldErrors);
setFormErrors(mapped.formErrors);
setResult("validation-error");
focusFirstError(mapped.fieldErrors);
} else if (outcome.error.effect === "MAYBE_APPLIED") {
unknownSubmissionRef.current = parsed.data;
setFormErrors([]);
setResult("effect-unknown");
} else if (outcome.error.effect === "APPLIED_CONFIRMED") {
settleSuccessfulValues(parsed.data);
} else if (outcome.error.kind === "CONFLICT") {
unknownSubmissionRef.current = null;
setFormErrors([
message("form.conflict"),
]);
setResult("conflict");
} else {
unknownSubmissionRef.current = null;
setFormErrors([message("form.unavailable")]);
setResult("unavailable");
}
applyOutcome(outcome, parsed.data);
return outcome;
} finally {
setPending(false);
@@ -244,11 +251,11 @@ export function useAppForm<
},
[
allowedServerFields,
applyOutcome,
focusFirstError,
mapToCommand,
message,
schema,
settleSuccessfulValues,
submit,
values,
],
@@ -270,6 +277,37 @@ export function useAppForm<
[validateAndSubmit],
);
/**
* 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.
*/
const resendUnknown = useCallback(
(
send: () => Promise<FormResult<Output> | null>,
): Promise<FormResult<Output> | null> => {
if (pendingRef.current) return pendingRef.current;
// After a remount the form no longer holds the submitted values.
const submittedValues = unknownSubmissionRef.current ?? values;
const resend = (async () => {
setPending(true);
try {
const outcome = await send();
if (outcome) applyOutcome(outcome, submittedValues);
return outcome;
} finally {
setPending(false);
}
})().finally(() => {
pendingRef.current = null;
});
pendingRef.current = resend;
return resend;
},
[applyOutcome, values],
);
return Object.freeze({
formId,
values,
@@ -284,6 +322,7 @@ export function useAppForm<
focusField,
setValue,
submitForm,
resendUnknown,
reset,
settleApplied,
settleNotApplied,
+2 -2
View File
@@ -12,7 +12,7 @@ const PLATFORM_KO_MESSAGES = {
"action.contactSupport": "지원 정보 확인",
"action.resolveConflict": "충돌 해결",
"action.confirmMutationApplied": "변경됨으로 확인",
"action.confirmMutationNotApplied": "변경되지 않음으로 확인",
"action.resendMutation": "같은 요청으로 다시 보내기",
"action.continueEditing": "계속 작성",
"action.discardAndLeave": "변경 버리고 이동",
"action.signIn": "로그인 시작",
@@ -171,7 +171,7 @@ const PLATFORM_EN_MESSAGES = {
"action.contactSupport": "View support information",
"action.resolveConflict": "Resolve conflict",
"action.confirmMutationApplied": "Confirm the change was applied",
"action.confirmMutationNotApplied": "Confirm the change was not applied",
"action.resendMutation": "Send the same request again",
"action.continueEditing": "Continue editing",
"action.discardAndLeave": "Discard and leave",
"action.signIn": "Start sign-in",
@@ -8,6 +8,9 @@ import {
useApplicationMutation,
} from "../../src/presentation/adapters/query/application-query.ts";
import type { MutationIntentFactory } from "../../src/application/ports/mutation-intent-factory.ts";
import { createFailure } from "../../src/contracts/errors.ts";
import type { MutationIntent } from "../../src/contracts/mutation-intent.ts";
import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts";
import { MUTATION_COORDINATOR_BOUNDS } from "../../src/contracts/server-state.ts";
import {
RESOURCE_INVALIDATION_TOPIC,
@@ -371,4 +374,124 @@ describe("application mutation intent admission", () => {
});
});
describe("unknown-effect replay (D-1)", () => {
function replayScope() {
let token = 0;
return {
...scopeSnapshot(),
identities: createRuntimeIdentityRegistry({
tokenFactory: () => `replay-identity-token-${String(++token).padStart(4, "0")}`,
}),
};
}
function renderKeyedCreate(
outcomes: ApplicationResult<string>[],
) {
const client = queryClient();
const intents: MutationIntent[] = [];
const execute = vi.fn(
async (
input: string,
context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>,
): Promise<ApplicationResult<string>> => {
intents.push(context.intent);
return outcomes.shift() ?? { ok: true, value: input };
},
);
const scope = replayScope();
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "replay-intent-v1",
definitionVersion: 1,
operationId: "CREATE_REPLAYED",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
return { hook, intents, execute };
}
const unknown: ApplicationResult<string> = {
ok: false,
error: createFailure("SERVER_FAILURE", "CREATE_REPLAYED", 0, {
effect: "MAYBE_APPLIED",
}),
};
it("sends the same intent when the same input is saved again after an unknown effect", async () => {
const { hook, intents } = renderKeyedCreate([unknown]);
await act(() => hook.result.current.submit("same-input"));
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() => hook.result.current.submit("same-input"));
expect(intents).toHaveLength(2);
expect(intents[1]).toBe(intents[0]);
expect(intents[1]?.idempotencyKey).toBe("key-1");
await waitFor(() =>
expect(hook.result.current.state.indicator).toBeNull(),
);
});
it("mints a new key when the input changes after an unknown effect", async () => {
const { hook, intents } = renderKeyedCreate([unknown]);
await act(() => hook.result.current.submit("first-input"));
await act(() => hook.result.current.submit("changed-input"));
expect(intents.map((intent) => intent.idempotencyKey)).toEqual([
"key-1",
"key-2",
]);
// The first request is still unresolved; a different request cannot
// settle it.
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
});
it("resends the unknown head request with its original key", async () => {
const { hook, intents, execute } = renderKeyedCreate([unknown, unknown]);
await act(() => hook.result.current.submit("resent-input"));
let resent: ApplicationResult<string> | null | undefined;
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
expect(resent).toMatchObject({
ok: false,
error: { effect: "MAYBE_APPLIED" },
});
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
expect(resent).toEqual({ ok: true, value: "resent-input" });
expect(execute.mock.calls.map(([input]) => input)).toEqual([
"resent-input",
"resent-input",
"resent-input",
]);
expect(new Set(intents.map((intent) => intent.idempotencyKey))).toEqual(
new Set(["key-1"]),
);
await waitFor(() =>
expect(hook.result.current.state.indicator).toBeNull(),
);
// Nothing is left to resend once the effect is settled.
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
expect(resent).toBeNull();
expect(execute).toHaveBeenCalledTimes(3);
});
});
});
+9 -4
View File
@@ -53,10 +53,11 @@ describe("async UI state matrix", () => {
});
});
it("renders unknown mutation effects with reconciliation-only actions", async () => {
it("renders unknown mutation effects with confirm-applied and resend only", async () => {
const user = userEvent.setup();
const retry = vi.fn();
const reconcile = vi.fn();
const resend = vi.fn();
const state = deriveAsyncState({
data: ["value"],
hasMutationEffectUnknown: true,
@@ -67,6 +68,7 @@ describe("async UI state matrix", () => {
state={state}
onRetry={retry}
onReconcileUnknownEffect={reconcile}
onResendUnknownEffect={resend}
>
existing content
</AsyncSurface>,
@@ -81,12 +83,15 @@ describe("async UI state matrix", () => {
expect(
screen.queryByRole("button", { name: "다시 시도" }),
).not.toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "변경되지 않음으로 확인" }),
).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "변경됨으로 확인" }));
await user.click(
screen.getByRole("button", { name: "변경되지 않음으로 확인" }),
screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
expect(reconcile).toHaveBeenNthCalledWith(1, "APPLIED");
expect(reconcile).toHaveBeenNthCalledWith(2, "NOT_APPLIED");
expect(reconcile).toHaveBeenCalledExactlyOnceWith("APPLIED");
expect(resend).toHaveBeenCalledOnce();
expect(retry).not.toHaveBeenCalled();
});
@@ -337,25 +337,29 @@ describe("reference feature page states", () => {
expect(screen.getByLabelText("설명")).toHaveValue("Keep this input");
});
it("blocks resubmit and exposes only reconciliation for an unknown create effect", async () => {
it("blocks a new save and resends an unknown create with the same key", async () => {
const user = userEvent.setup();
const createResource = vi.fn(async () => ({
ok: false as const,
error: createFailure(
"SERVER_FAILURE",
"CREATE_REFERENCE_RESOURCE",
0,
{ effect: "MAYBE_APPLIED" },
),
}));
const createResource = vi
.fn<ReferenceFeatureInput["createResource"]>()
.mockResolvedValueOnce({
ok: false,
error: createFailure(
"SERVER_FAILURE",
"CREATE_REFERENCE_RESOURCE",
0,
{ effect: "MAYBE_APPLIED" },
),
})
.mockResolvedValue({
ok: true,
value: { resourceId: "created", title: "Unknown result", createdAt: null },
});
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Unknown result",
);
const name = await screen.findByRole("textbox", { name: /새 항목 이름/ });
await user.type(name, "Unknown result");
await user.click(screen.getByRole("button", { name: "저장" }));
expect(
@@ -365,22 +369,28 @@ describe("reference feature page states", () => {
expect(
screen.queryByText("저장하지 못했습니다. 잠시 후 다시 시도해 주세요."),
).not.toBeInTheDocument();
// No path lets the user declare "not applied" without evidence.
expect(
screen.queryByRole("button", { name: "변경되지 않음으로 확인" }),
).not.toBeInTheDocument();
expect(
screen.getByRole("link", { name: "목록을 새로 불러와 확인" }),
).toHaveAttribute("href", "/examples/reference-resources");
await user.click(screen.getByRole("button", { name: "저장" }));
expect(createResource).toHaveBeenCalledOnce();
expect(
screen.getByRole("textbox", { name: /새 항목 이름/ }),
).toHaveValue("Unknown result");
expect(name).toHaveValue("Unknown result");
await user.click(
screen.getByRole("button", { name: "변경되지 않음으로 확인" }),
screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
await waitFor(() =>
expect(screen.getByRole("button", { name: "저장" })).toBeEnabled(),
);
expect(createResource).toHaveBeenCalledOnce();
expect(
screen.getByRole("textbox", { name: /새 항목 이름/ }),
).toHaveValue("Unknown result");
expect(await screen.findByRole("status")).toHaveTextContent("저장했습니다.");
expect(createResource).toHaveBeenCalledTimes(2);
const [first, second] = createResource.mock.calls;
expect(second?.[0]).toEqual(first?.[0]);
expect(first?.[1]?.intent?.idempotencyKey).toBe("reference-page-key-1");
expect(second?.[1]?.intent?.idempotencyKey).toBe("reference-page-key-1");
expect(name).toHaveValue("");
});
it("settles the form after confirming an unknown create was applied", async () => {
@@ -2,6 +2,7 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
import {
afterAll,
afterEach,
@@ -118,4 +119,50 @@ describe("reference feature production vertical path", () => {
expect(createRequests).toHaveBeenCalledWith({ name: "Created" });
expect(listRequests.mock.calls.length).toBeGreaterThanOrEqual(2);
});
it("resends a create whose 504 lost the response with the same Idempotency-Key", async () => {
const user = userEvent.setup();
const idempotencyKeys: (string | null)[] = [];
mockApi.server.use(
http.post("https://api.test/api/reference-resources", async ({ request }) => {
idempotencyKeys.push(request.headers.get("idempotency-key"));
// The first request reaches the server; only its response is lost.
if (idempotencyKeys.length === 1) {
return new HttpResponse(null, { status: 504 });
}
const body = (await request.json()) as { name: string };
return HttpResponse.json(
{
id: "reference-created",
name: body.name,
createdAt: "2026-07-26T00:00:00.000Z",
},
{ status: 201 },
);
}),
);
const composition = await createRuntimeComposition({
fetcher: absoluteFetch,
host: {},
});
window.history.pushState({}, "", "/examples/reference-resources/new");
render(<RuntimeApplication composition={composition} />);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Lost response",
);
await user.click(screen.getByRole("button", { name: "저장" }));
await user.click(
await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
expect(await screen.findByText("저장했습니다.")).toBeVisible();
expect(idempotencyKeys).toHaveLength(2);
expect(idempotencyKeys[0]).toMatch(/^[\x21-\x7e]+$/u);
expect(idempotencyKeys[1]).toBe(idempotencyKeys[0]);
});
});