fix(http): V3 Envelope 진단이 V2와 같은 멱등성 거절 reason을 싣는다

문제
V2 클라이언트는 짝 백엔드의 422 IDEMPOTENT_REQUEST_MISMATCH와 400
IDEMPOTENCY_KEY_INVALID를 진단(http.request.completed)의 reason으로
남긴다(93782b0). V3 실행기의 진단에는 백엔드 code가 없다(리뷰 README
14.4). Problem 타입이 계약 패키지 소유라 실행기가 code를 몰랐기 때문이다.
7db32e1 뒤로 responseEnvelope: "ENVELOPE_V1" operation의 실행기는
Envelope error.code를 읽는다.

고른 방법
- Envelope operation의 실패에서 backend-envelope.ts의
  idempotencyRefusalReason(code, status)를 불러 V2와 같은 두 값을
  HttpDiagnosticReason으로 싣는다. projector(runtime-adapters.ts)는 이미
  diagnosticReason을 reason으로 옮기므로 bootstrap은 바꾸지 않았다.
- 표의 reason 타입을 IdempotencyRefusalReason으로 좁혀 두 값이 닫힌
  목록임을 타입으로 둔다.

버린 대안
- 백엔드 code를 reason에 그대로 넣기: reason은 이 repo가 소유한 닫힌
  목록(taxonomy)이고, 서버 code를 그대로 넣지 않는다는 93782b0 결정과
  어긋난다. V2도 넣지 않는다.
- 새 진단 키(problem_code) 추가: src/contracts/diagnostics.ts 허용 목록과
  bootstrap projector를 함께 바꿔야 하고 cardinality 등급을 새로 정해야
  한다. 이 변경 범위를 넘는다.

위험·한계
- 그 밖의 백엔드 code는 진단에 없다. 실패의 AppFailure.code에만 있다.
- DTO 모드 operation(참조 기능)의 진단에는 여전히 code가 없다.
- classifyProblem이 던져 CLASSIFIER_FAILED가 되는 경우는 Envelope 판정이
  있으면 분류기를 부르지 않으므로 둘이 겹치지 않는다.

검증
- RED: tests/integration/http-execution-v3-envelope.test.ts의 "V3 Envelope
  diagnostics name what V2 names" 4행 중 2행 실패(422·400에서 V3 reason
  undefined). 409 두 행은 처음부터 통과(reason 없음 고정).
- GREEN: 같은 파일 29건 통과. 같은 응답의 V2 진단 기록과 V3 진단 기록의
  reason을 비교한다.
- check:types, lint, check:architecture, check:diagnostics 통과.
  test:unit 2,604, test:integration 204, test:component 244,
  tests/features·tests/contract 124건 통과.
- check:bundle 통과(203,352 / 204,800 B, 7db32e1 대비 +31 B).

Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.4, 14.6
This commit is contained in:
DongHyeonka
2026-11-03 20:13:02 +09:00
parent 7db32e1343
commit bd83b496cc
3 changed files with 67 additions and 9 deletions
+6 -2
View File
@@ -55,8 +55,12 @@ export function readFailureEnvelope(
* gets the same answer. Only the documented status and code together count.
* The value is the diagnostics `reason`, named for what is wrong on this side.
*/
export type IdempotencyRefusalReason =
| "IDEMPOTENT_REQUEST_MISMATCH"
| "IDEMPOTENCY_KEY_RULE_MISMATCH";
const IDEMPOTENCY_REFUSALS: Readonly<
Record<string, Readonly<{ status: number; reason: string }>>
Record<string, Readonly<{ status: number; reason: IdempotencyRefusalReason }>>
> = Object.freeze({
// The same key went out with another body.
IDEMPOTENT_REQUEST_MISMATCH: Object.freeze({
@@ -74,7 +78,7 @@ const IDEMPOTENCY_REFUSALS: Readonly<
export function idempotencyRefusalReason(
code: string,
status: number | undefined,
): string | undefined {
): IdempotencyRefusalReason | undefined {
const refusal = Object.hasOwn(IDEMPOTENCY_REFUSALS, code)
? IDEMPOTENCY_REFUSALS[code]
: undefined;
+15 -5
View File
@@ -47,8 +47,10 @@ import {
import { parseRetryAfter } from "./retry-policy.ts";
import {
envelopeFailureEffect,
idempotencyRefusalReason,
readFailureEnvelope,
readSuccessEnvelope,
type IdempotencyRefusalReason,
} from "./backend-envelope.ts";
import {
createExecutionContext,
@@ -336,10 +338,14 @@ export type HttpExecutionObservation = Readonly<{
* `MAYBE_APPLIED` (03-05).
* - an `HttpRequestRejectionReason`: copied from the refused request's
* violation (03-02).
* - an `IdempotencyRefusalReason`: an Envelope operation's backend refused
* the idempotency key, the reason the V2 client records (1101 README 14.4).
* No other backend code reaches diagnostics; the failure's code carries it.
*/
export type HttpDiagnosticReason =
| "CLASSIFIER_FAILED"
| HttpRequestRejectionReason;
| HttpRequestRejectionReason
| IdempotencyRefusalReason;
/**
* The outcome is the single authority for the observed error kind. The terminal
@@ -1669,14 +1675,16 @@ async function admitProblem<Input, WireOutput, Problem>(
// A body that is not a failure Envelope is an unreadable problem.
let validated: ValidatorInvocation<Problem>;
let backendEffect: "NOT_APPLIED" | "MAYBE_APPLIED" | undefined;
let refusalReason: IdempotencyRefusalReason | undefined;
if (enveloped) {
const framed = readFailureEnvelope(decoded.value);
validated = framed.ok
? invokeValidator(contract.problemValidator, framed.value)
: UNFRAMED_PROBLEM;
backendEffect = framed.ok
? envelopeFailureEffect(status, framed.value)
: undefined;
if (framed.ok) {
backendEffect = envelopeFailureEffect(status, framed.value);
refusalReason = idempotencyRefusalReason(framed.value.code, status);
}
} else {
validated = invokeValidator(contract.problemValidator, decoded.value);
}
@@ -1724,7 +1732,9 @@ async function admitProblem<Input, WireOutput, Problem>(
retryAfterMs: metadata.retryAfterMs ?? null,
...(isCommand && classification.contractRuntimeFailure
? { diagnosticReason: "CLASSIFIER_FAILED" as const }
: {}),
: refusalReason === undefined
? {}
: { diagnosticReason: refusalReason }),
});
}
@@ -8,8 +8,11 @@ import {
createContractHttpExecutor,
createFeatureHttpBinding,
defineFeatureHttpOperation,
type HttpExecutionObservation,
type InstalledHttpOperationExecutor,
} from "../../src/adapters/http/index.ts";
import { createHttpObservationProjector } from "../../src/bootstrap/runtime-adapters.ts";
import type { DiagnosticRecordInput } from "../../src/contracts/diagnostics.ts";
import { mappingSuccess } from "../../src/contracts/boundary-mapper.ts";
import type { AppFailure } from "../../src/contracts/errors.ts";
import {
@@ -253,10 +256,14 @@ function scope() {
});
}
function v3Executor(fetcher?: typeof fetch): InstalledHttpOperationExecutor {
function v3Executor(
fetcher?: typeof fetch,
observe?: (observation: HttpExecutionObservation) => void,
): InstalledHttpOperationExecutor {
const executor = createContractHttpExecutor({
baseUrl: BASE_URL,
...(fetcher === undefined ? {} : { fetcher }),
...(observe === undefined ? {} : { observe }),
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
random: () => 0,
@@ -325,10 +332,14 @@ const V2_PAYLOADS: Readonly<Record<string, z.ZodType>> = Object.freeze({
EnvelopeTestItem: itemSchema,
});
function v2(fetcher?: typeof fetch) {
function v2(
fetcher?: typeof fetch,
diagnostics?: Readonly<{ record(input: DiagnosticRecordInput): void }>,
) {
return createHttpClient({
baseUrl: BASE_URL,
...(fetcher === undefined ? {} : { fetcher }),
...(diagnostics === undefined ? {} : { diagnostics }),
maxRetryAttempts: 0,
clock: { now: () => 0, sleep: async () => {} },
authSession: createDemoSessionAdapter("authenticated"),
@@ -614,6 +625,39 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () =>
});
});
// 1101 README 14.4. V2 names an idempotency refusal in diagnostics (`reason`,
// a closed taxonomy). An Envelope operation's executor now knows the backend
// code and names the same ones; any other code stays out of diagnostics.
describe("V3 Envelope diagnostics name what V2 names", () => {
it.each([
["422 IDEMPOTENT_REQUEST_MISMATCH", 422, "IDEMPOTENT_REQUEST_MISMATCH", "IDEMPOTENT_REQUEST_MISMATCH"],
["400 IDEMPOTENCY_KEY_INVALID", 400, "IDEMPOTENCY_KEY_INVALID", "IDEMPOTENCY_KEY_RULE_MISMATCH"],
["409 IDEMPOTENT_IN_FLIGHT", 409, "IDEMPOTENT_IN_FLIGHT", undefined],
["409 domain conflict", 409, "RESOURCE_CONFLICT", undefined],
] as const)("%s", async (_label, status, code, reason) => {
answer("post", "/api/envelope-items", failure(code, "VALIDATION", false), { status });
const v2Records: DiagnosticRecordInput[] = [];
const v3Records: DiagnosticRecordInput[] = [];
const project = createHttpObservationProjector({
diagnostics: { record: (input) => v3Records.push(input) },
telemetry: { emit: () => {} },
});
await v2(undefined, { record: (input) => v2Records.push(input) }).execute(
"ENVELOPE_CREATE_ITEM",
{ body: {}, idempotencyKey: KEY },
);
await v3CreateFailure(
createFeatureHttpBinding(v3Executor(undefined, project), OPERATIONS),
);
expect(v2Records).toHaveLength(1);
expect(v3Records).toHaveLength(1);
expect(v3Records[0]?.context?.reason).toBe(reason);
expect(v3Records[0]?.context?.reason).toBe(v2Records[0]?.context?.reason);
});
});
describe("shared MSW scenarios for an Envelope operation", () => {
it.each([
["success", { ok: true, value: [{ id: "item-1", name: "First" }] }],