diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index b3ddcad8..fbf3664e 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -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분 | diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 352a80b4..96fe6213 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -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` | — | — | diff --git a/src/adapters/http/backend-envelope.ts b/src/adapters/http/backend-envelope.ts index 8e769232..374ca0c1 100644 --- a/src/adapters/http/backend-envelope.ts +++ b/src/adapters/http/backend-envelope.ts @@ -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. diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index 6fa152a4..0cea32da 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -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 = 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( let validated: ValidatorInvocation; 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( 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( : refusalReason === undefined ? {} : { diagnosticReason: refusalReason }), + ...(keyedResend ? { keyedResend: true as const } : {}), }); } diff --git a/tests/integration/http-execution-v3-envelope.test.ts b/tests/integration/http-execution-v3-envelope.test.ts index a1c5f6d6..39d217c8 100644 --- a/tests/integration/http-execution-v3-envelope.test.ts +++ b/tests/integration/http-execution-v3-envelope.test.ts @@ -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" }] }],