fix(http): KEYED 명령이 백엔드의 실행 전 거절에 같은 키로 다시 보낸다
문제 V2 클라이언트는 보낸 KEYED 요청이 503·408·425·502·504·network·timeout으로 끝나면 같은 키로 자동 재시도했다. 048f490으로 그 동작이 없어졌다. 설계 정본 (2026-07-30 closed deep design 8.3)은 KEYED 자동 재시도를 "known response status가 retry 가능하다고 package가 명시한 경우만" 허용하고, 응답 없는 network·timeout 뒤에는 금지한다. V2는 응답 없는 실패 뒤에도 보내 정본과 어긋났고, V3는 응답이 재시도를 허락해도 보내지 않아 정본보다 좁았다. 짝 백엔드는 503 IDEMPOTENCY_UNAVAILABLE을 "작업 실행 전에 거부됐다. 같은 키로 나중에 다시 보낸다"로 정한다(http-contract.md §2). 고른 방법 - backend-envelope.ts의 invitesKeyedResend: 503 + IDEMPOTENCY_UNAVAILABLE. - Envelope operation의 실패 해석에서 KEYED 명령이 그 답을 받으면 AdmissionOutcome에 keyedResend를 싣는다. 재시도 루프는 그때 retryBudget· MAX_RETRY_ATTEMPTS·상한 2 안에서 같은 frozen 요청(같은 Idempotency-Key)을 다시 보낸다. certainty는 MAYBE_APPLIED로 두어, 다 쓰면 결과 불명으로 끝나고 키를 지킨다. 버린 대안 - V2처럼 KEYED의 모든 재시도 가능 status·network 실패에서 재시도: 정본 8.3이 응답 없는 실패 뒤 재시도를 금지한다. - 409 IDEMPOTENT_IN_FLIGHT도 자동 재시도: 처리 중 요청은 47fec5c의 사용자 재전송(Retry-After 대기)이 이미 같은 키로 다룬다. V2도 409는 자동으로 다시 보내지 않았다. 위험·한계 - retryBudget이 0인 명령(참조 기능 CREATE)은 그대로 다시 보내지 않는다. - Envelope가 아닌 operation은 백엔드 code를 몰라 이 재전송이 없다. 검증 - RED: tests/integration/http-execution-v3-envelope.test.ts "KEYED resend on the backend's pre-execution refusal" 3건 중 2건 실패(한 번만 보내고 PROBLEM). 다른 503(REQUEST_TIMEOUT)을 다시 보내지 않는 행은 처음부터 통과. - GREEN: 같은 파일 35건 통과. 두 번 보낸 키가 같다. - check:types, lint, check:architecture, test:unit 2,568, test:integration 117, test:component 245, tests/features 99 통과. Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.7
This commit is contained in:
@@ -548,7 +548,7 @@ query invalidate hint로만 쓸지 operation별 reducer contract가 필요하다
|
||||
|
||||
| 규칙 | V3 contract executor | Browser RPC |
|
||||
|---|---|---|
|
||||
| KEYED 명령 자동 재시도 | 전송 전 실패만 재시도한다. 전송 뒤 실패는 재시도하지 않고 `MAYBE_APPLIED`다. 응답(5xx·429)으로는 재시도하지 않는다 (`src/adapters/http/http-retry-lifecycle.ts` `canRetryTransport`, `isRetryableSemantics`) | `KEYED_COMMAND`는 유효한 키가 있고 profile `retryOwner`가 `FRONTEND_ADAPTER`면 `retryableFailures`에서 같은 키로 다시 보낸다 (`src/adapters/browser-rpc/browser-rpc-runtime.ts` `shouldRetry`) |
|
||||
| KEYED 명령 자동 재시도 | 전송 전 실패만 재시도한다. 전송 뒤 실패는 재시도하지 않고 `MAYBE_APPLIED`다. 응답으로는 재시도하지 않는다. 예외: Envelope operation이 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절, 백엔드 §2가 같은 키 재전송을 요구)을 받으면 `retryBudget` 안에서 같은 키로 다시 보낸다 (`src/adapters/http/http-retry-lifecycle.ts` `canRetryTransport`, `isRetryableSemantics`, `backend-envelope.ts` `invitesKeyedResend`) | `KEYED_COMMAND`는 유효한 키가 있고 profile `retryOwner`가 `FRONTEND_ADAPTER`면 `retryableFailures`에서 같은 키로 다시 보낸다 (`src/adapters/browser-rpc/browser-rpc-runtime.ts` `shouldRetry`) |
|
||||
| 재시도 횟수 상한 | min(계약 `retryBudget`, `MAX_RETRY_ATTEMPTS`, 2) (`http-execution-v3.ts` `retryCeiling`) | profile `maxAttempts`(시도 횟수), 하드 상한 4 (`src/contracts/browser-rpc.ts` `BROWSER_RPC_HARD_LIMITS`) |
|
||||
| `Retry-After` | 5초를 넘으면 재시도하지 않는다. 이하면 hint에 jitter를 더해 기다린다 (`http-retry-lifecycle.ts` `retryDelayFor`) | profile `maxRetryAfterMs`로 잘라 max(backoff, hint)만큼 기다린다. 하드 상한 60초 (`browser-rpc-runtime.ts` `retryDelay`) |
|
||||
| `REQUEST_TIMEOUT_MS` | 상한이다. 계약 `totalDeadlineMs`를 줄이기만 한다 (`runtime-adapters.ts` `requestDeadlineCeilingMs`) | 쓰지 않는다. operation `totalDeadlineMs`만 쓴다. 하드 상한 30분 |
|
||||
|
||||
@@ -87,7 +87,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
|
||||
| | `KEYED` | `IDEMPOTENT` | `NEVER` |
|
||||
|---|---|---|---|
|
||||
| 서버 보장 | 멱등 키(`Idempotency-Key` 헤더)로 같은 요청의 중복 적용을 막는다 | 같은 요청을 여러 번 적용해도 결과가 같다 (키 없이) | 중복을 막지 못한다 |
|
||||
| 자동 재시도 | 실제로 보내기 전까지만. 보낸 뒤 결과를 모르면 결과 불명(4절)으로 넘긴다 | 된다 | 하지 않는다 |
|
||||
| 자동 재시도 | 실제로 보내기 전까지만. 보낸 뒤 결과를 모르면 결과 불명(4절)으로 넘긴다. 예외: 짝 백엔드가 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절)로 답하면 `retryBudget` 안에서 같은 키로 다시 보낸다 | 된다 | 하지 않는다 |
|
||||
| descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 참조 기능은 `retryBudget: 0` | — | `retryBudget: 0` 필수 |
|
||||
| 뮤테이션 정책 | `requiresIdempotencyKey: true` | — | — |
|
||||
|
||||
|
||||
@@ -173,6 +173,19 @@ export function envelopeFailureEffect(
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* §2. The one answer after which the backend asks for the same request again
|
||||
* with the same key: 503 IDEMPOTENCY_UNAVAILABLE, refused before the command
|
||||
* ran. A KEYED command may be resent on it automatically (runtime design
|
||||
* §8.3: only on a known answer that says resending is safe).
|
||||
*/
|
||||
export function invitesKeyedResend(
|
||||
status: number,
|
||||
error: EnvelopeError,
|
||||
): boolean {
|
||||
return status === 503 && error.code === "IDEMPOTENCY_UNAVAILABLE";
|
||||
}
|
||||
|
||||
/**
|
||||
* Q-6.3-3b. A gateway 5xx/408/425 is a server outage, not a contract breach:
|
||||
* it keeps the SERVER_FAILURE retry rule.
|
||||
|
||||
@@ -48,6 +48,7 @@ import { parseRetryAfterDelay } from "../platform/retry-after.ts";
|
||||
import {
|
||||
envelopeFailureEffect,
|
||||
idempotencyRefusalReason,
|
||||
invitesKeyedResend,
|
||||
readFailureEnvelope,
|
||||
readSuccessEnvelope,
|
||||
type IdempotencyRefusalReason,
|
||||
@@ -1097,13 +1098,14 @@ export function createContractHttpExecutor(
|
||||
return terminalOutcomeFor("ADMISSION");
|
||||
}
|
||||
if (
|
||||
outcome.retryHint &&
|
||||
// Q-6.3-7. An answer that says the command may already be applied
|
||||
// is not replayed; reconciliation owns it from here.
|
||||
outcome.certainty !== "MAYBE_APPLIED" &&
|
||||
outcome.certainty !== "APPLIED_CONFIRMED" &&
|
||||
retryIndex < retryCeiling &&
|
||||
isRetryableSemantics(contract.retrySemantics)
|
||||
(outcome.keyedResend === true ||
|
||||
(outcome.retryHint &&
|
||||
// Q-6.3-7. An answer that says the command may already be
|
||||
// applied is not replayed; reconciliation owns it from here.
|
||||
outcome.certainty !== "MAYBE_APPLIED" &&
|
||||
outcome.certainty !== "APPLIED_CONFIRMED" &&
|
||||
isRetryableSemantics(contract.retrySemantics))) &&
|
||||
retryIndex < retryCeiling
|
||||
) {
|
||||
const delay = retryDelayFor(outcome.retryAfterMs, retryIndex, random);
|
||||
if (delay !== null && delay < remaining() && admitRetry()) {
|
||||
@@ -1214,6 +1216,12 @@ type AdmissionOutcome<Value, Problem> = Readonly<{
|
||||
retryHint: boolean;
|
||||
retryAfterMs: number | null;
|
||||
diagnosticReason?: HttpDiagnosticReason;
|
||||
/**
|
||||
* §8.3. The server refused this KEYED command before it ran and asked for
|
||||
* the same request with the same key. The certainty stays MAYBE_APPLIED so
|
||||
* an exhausted resend still keeps the key.
|
||||
*/
|
||||
keyedResend?: true;
|
||||
}>;
|
||||
|
||||
/**
|
||||
@@ -1678,6 +1686,7 @@ async function admitProblem<Input, WireOutput, Problem>(
|
||||
let validated: ValidatorInvocation<Problem>;
|
||||
let backendEffect: "NOT_APPLIED" | "MAYBE_APPLIED" | undefined;
|
||||
let refusalReason: IdempotencyRefusalReason | undefined;
|
||||
let keyedResend = false;
|
||||
if (enveloped) {
|
||||
const framed = readFailureEnvelope(decoded.value);
|
||||
validated = framed.ok
|
||||
@@ -1686,6 +1695,10 @@ async function admitProblem<Input, WireOutput, Problem>(
|
||||
if (framed.ok) {
|
||||
backendEffect = envelopeFailureEffect(status, framed.value);
|
||||
refusalReason = idempotencyRefusalReason(framed.value.code, status);
|
||||
keyedResend =
|
||||
isCommand &&
|
||||
contract.retrySemantics === "KEYED" &&
|
||||
invitesKeyedResend(status, framed.value);
|
||||
}
|
||||
} else {
|
||||
validated = invokeValidator(contract.problemValidator, decoded.value);
|
||||
@@ -1737,6 +1750,7 @@ async function admitProblem<Input, WireOutput, Problem>(
|
||||
: refusalReason === undefined
|
||||
? {}
|
||||
: { diagnosticReason: refusalReason }),
|
||||
...(keyedResend ? { keyedResend: true as const } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -610,6 +610,75 @@ describe("V3 Envelope diagnostics name idempotency refusals", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// §8.3 of the runtime design: a KEYED command is resent automatically only
|
||||
// on a known answer that says resending is safe, never after a lost response.
|
||||
// The paired backend's 503 IDEMPOTENCY_UNAVAILABLE is one (http-contract.md
|
||||
// §2): refused before the command ran, resend with the same key.
|
||||
describe("KEYED resend on the backend's pre-execution refusal", () => {
|
||||
const RETRYING_CREATE = Object.freeze({
|
||||
contract: CREATE_CONTRACT.contract,
|
||||
frontend: Object.freeze({ ...CREATE_CONTRACT.frontend, retryBudget: 1 as const }),
|
||||
});
|
||||
|
||||
async function run(answers: readonly (() => Response)[]) {
|
||||
const keys: (string | null)[] = [];
|
||||
server.use(
|
||||
http.post(`${BASE_URL}/api/envelope-items`, ({ request }) => {
|
||||
keys.push(request.headers.get("idempotency-key"));
|
||||
const next = answers[Math.min(keys.length - 1, answers.length - 1)]!;
|
||||
return next();
|
||||
}),
|
||||
);
|
||||
const executor = createContractHttpExecutor({
|
||||
baseUrl: BASE_URL,
|
||||
maxRetryAttempts: 2,
|
||||
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
|
||||
sleep: async () => {},
|
||||
random: () => 0,
|
||||
});
|
||||
const outcome = await executor.execute(RETRYING_CREATE, Object.freeze({}), {
|
||||
routeId: "ENVELOPE_ROUTE",
|
||||
scope: scope(),
|
||||
intent: intent("ENVELOPE_CREATE_ITEM"),
|
||||
});
|
||||
return { outcome, keys };
|
||||
}
|
||||
|
||||
const unavailable = () =>
|
||||
HttpResponse.json(failure("IDEMPOTENCY_UNAVAILABLE", "TRANSIENT_DEPENDENCY", true), {
|
||||
status: 503,
|
||||
});
|
||||
const created = () =>
|
||||
HttpResponse.json(success({ id: "item-1", name: "First" }), { status: 201 });
|
||||
|
||||
it("resends once with the same key and takes the second answer", async () => {
|
||||
const { outcome, keys } = await run([unavailable, created]);
|
||||
|
||||
expect(outcome).toMatchObject({ kind: "SUCCESS", effect: "APPLIED_CONFIRMED" });
|
||||
expect(keys).toEqual([KEY, KEY]);
|
||||
});
|
||||
|
||||
it("keeps the key and an unknown result when the budget runs out", async () => {
|
||||
const { outcome, keys } = await run([unavailable]);
|
||||
|
||||
expect(outcome).toMatchObject({ kind: "PROBLEM", effect: "MAYBE_APPLIED" });
|
||||
expect(keys).toEqual([KEY, KEY]);
|
||||
});
|
||||
|
||||
it("does not resend a 503 the backend did not mark as a pre-execution refusal", async () => {
|
||||
const { outcome, keys } = await run([
|
||||
() =>
|
||||
HttpResponse.json(failure("REQUEST_TIMEOUT", "TRANSIENT_DEPENDENCY", true), {
|
||||
status: 503,
|
||||
}),
|
||||
created,
|
||||
]);
|
||||
|
||||
expect(outcome).toMatchObject({ kind: "PROBLEM", effect: "MAYBE_APPLIED" });
|
||||
expect(keys).toEqual([KEY]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shared MSW scenarios for an Envelope operation", () => {
|
||||
it.each([
|
||||
["success", { ok: true, value: [{ id: "item-1", name: "First" }] }],
|
||||
|
||||
Reference in New Issue
Block a user