Files
clean-architecture-frontend…/src/adapters/http/http-effect-certainty.ts
T
DongHyeonka f8a492a6ad fix(http): 문제 응답 분류기 실패를 진단 reason으로 남긴다 (03-05)
문제
기능 패키지의 classifyProblem이 throw하거나 집합 밖 값을 돌려주면
classifyProblemEffect는 MAYBE_APPLIED + contractRuntimeFailure: true를
돌려준다. 주석과 설계서(closed-deep-design.md:650)는 이것을 "contract
runtime failure로 기록한다"고 적지만, 실행기는 .effect만 쓰고 플래그를
버린다. 그래서 분류기가 throw한 409와 분류기가 정말 MAYBE_APPLIED라고
답한 409의 관측 기록·진단이 요청 id 말고 똑같다. 또 이 안전 기본값을
NOT_APPLIED로 바꿔도(변이 M5) 영역 테스트가 하나도 실패하지 않는다.

고른 방법
- HttpExecutionObservation에 선택 필드 diagnosticReason을 더한다. 타입은
  닫힌 집합 HttpDiagnosticReason이고 지금 값은 CLASSIFIER_FAILED 하나다.
  문제 응답 admission이 명령의 contractRuntimeFailure를 이 값으로 바꾸고,
  finish()가 관측 기록에 싣는다.
- 조립 지점의 projector는 이 값을 diagnostics에만 reason으로 더한다
  (reason은 이미 허용 목록의 taxonomy 키). telemetry 속성은 그대로다.
- 효과는 계속 MAYBE_APPLIED다. 재시도 판단에 쓰는 certainty는 건드리지
  않았다.

버린 대안
- 리뷰 문서 문구대로 terminalReason을 CLASSIFIER_FAILED로 바꾸기:
  terminalReason은 "sink로 나가지 않는 내부 라벨"(VD-07 5-1)이고, 문제
  응답에서는 certainty 값이 그대로 terminalReason이 되며 재시도 차단
  조건(certainty !== "MAYBE_APPLIED")에도 쓰인다. 값을 바꾸면 그 이중
  차단이 하나로 줄고, projector가 문자열을 걸러 내야 한다. 별도 닫힌
  타입 필드가 의도가 더 잘 보인다.
- 플래그와 주석 문장을 지우기(리뷰의 두 번째 안): 운영자가 "결과 불명"이
  분류기 결함 때문인지 구분할 수단이 계속 없다.

위험·한계
- classifyStatus(401·403·429) 분류기의 throw는 지금처럼 MAYBE_APPLIED만
  내고 reason을 남기지 않는다. 그 함수는 기록을 주장하지 않아 이번 범위에서
  뺐다.
- 공개 타입은 추가만 했다(관측 선택 필드 1개, 배럴 type export 1개).
- VD-07 5-1에 reason 전달 규칙을 적었다.

검증
- RED(수정 전): tests/integration/http-execution-v3-observability.test.ts
  "keeps MAYBE_APPLIED and records a failed problem classifier in
  diagnostics only (03-05)" 실패. 기대 reason "CLASSIFIER_FAILED", 실제
  undefined.
- GREEN: 같은 파일 7/7 통과. 변이 M5(catch를 NOT_APPLIED로)를 다시 넣으면
  이 테스트가 실패하는 것을 확인하고 원복했다.
- 회귀: run-vitest tests/integration tests/features/reference-feature
  tests/unit/http-execution-v3.test.ts 30 files / 302 tests 통과.
  tsc app/test/node rc=0. 바꾼 파일 eslint rc=0.
  check-adapter-inventory PASS.
- 미실행: check:architecture(pnpm 스크립트 필요).

Refs: docs/reviews/2026-11-01-maturity-review/03-adapters-http-state.md
2026-11-01 22:42:44 +09:00

168 lines
4.6 KiB
TypeScript

import type {
CommandEffectDescriptor,
CommandEffectClassification,
} from "../../contracts/external-contract-runtime.ts";
/**
* §8.7–§8.9. Mutation effect certainty.
*
* The frontend never infers "not applied" from an HTTP status alone. Anything
* observed after the request was dispatched but before a classified terminal
* response is `MAYBE_APPLIED`, which forbids automatic resend.
*/
export type MutationEffectCertainty =
| "NOT_STARTED"
| "NOT_APPLIED"
| "MAYBE_APPLIED"
| "APPLIED_CONFIRMED";
export type PhysicalAttemptState =
| "NOT_STARTED"
| "PREPARING"
| "READY_TO_SEND"
| "DISPATCHED"
| "RESPONSE_HEADERS"
| "READING_BODY"
| "VALIDATING"
| "MAPPING_READY"
| "SETTLED";
/**
* `READY_TO_SEND` is recorded immediately before entering the `fetch()`
* invocation expression and `DISPATCHED` immediately after the promise is
* returned. A synchronous throw therefore leaves the attempt `NOT_STARTED`.
*/
export function certaintyForAbandonedAttempt(
state: PhysicalAttemptState,
isCommand: boolean,
): MutationEffectCertainty {
if (!isCommand) return "NOT_STARTED";
switch (state) {
case "NOT_STARTED":
case "PREPARING":
case "READY_TO_SEND":
return "NOT_STARTED";
default:
return "MAYBE_APPLIED";
}
}
/**
* §8.7. The conservative certainty lattice for one logical execution.
*
* `PhysicalAttemptState` describes only the attempt in flight. A new retry that
* has not been sent yet must never lower what an earlier attempt already
* established, so the executor joins observations into a monotonic accumulator.
*/
const CERTAINTY_RANK: Readonly<Record<MutationEffectCertainty, number>> =
Object.freeze({
NOT_STARTED: 0,
NOT_APPLIED: 1,
MAYBE_APPLIED: 2,
APPLIED_CONFIRMED: 3,
});
export function joinMutationEffectCertainty(
current: MutationEffectCertainty,
observed: MutationEffectCertainty,
): MutationEffectCertainty {
return CERTAINTY_RANK[observed] > CERTAINTY_RANK[current]
? observed
: current;
}
export type ProblemEffectInput<Problem> = Readonly<{
status: number;
problem: Problem;
descriptor: CommandEffectDescriptor<Problem> | null;
}>;
export type ProblemEffectOutcome = Readonly<{
effect: MutationEffectCertainty;
contractRuntimeFailure: boolean;
}>;
const CLASSIFICATIONS: ReadonlySet<CommandEffectClassification> = new Set([
"NOT_APPLIED",
"APPLIED_CONFIRMED",
"MAYBE_APPLIED",
]);
/**
* §4.4. The classifier is package-owned and pure. A throw or an unrecognised
* return value fails safe to `MAYBE_APPLIED` and is recorded as a contract
* runtime failure rather than being silently treated as "not applied": the
* executor turns `contractRuntimeFailure` into the observation's
* `diagnosticReason: "CLASSIFIER_FAILED"` (03-05).
*/
export function classifyProblemEffect<Problem>(
input: ProblemEffectInput<Problem>,
): ProblemEffectOutcome {
if (!input.descriptor) {
// A read operation carries no command effect; there is nothing to apply.
return Object.freeze({
effect: "NOT_STARTED" as const,
contractRuntimeFailure: false,
});
}
let classification: CommandEffectClassification;
try {
classification = input.descriptor.classifyProblem({
status: input.status,
problem: input.problem,
});
} catch {
return Object.freeze({
effect: "MAYBE_APPLIED" as const,
contractRuntimeFailure: true,
});
}
if (!CLASSIFICATIONS.has(classification)) {
return Object.freeze({
effect: "MAYBE_APPLIED" as const,
contractRuntimeFailure: true,
});
}
return Object.freeze({
effect: classification,
contractRuntimeFailure: false,
});
}
/**
* D-2. A dispatched command answered 401, 403 or 429 is `MAYBE_APPLIED` unless
* the package classifies that status as `NOT_APPLIED`. Any other answer, or a
* throw, fails safe to `MAYBE_APPLIED`.
*/
export function classifyStatusEffect<Problem>(
descriptor: CommandEffectDescriptor<Problem> | null,
status: 401 | 403 | 429,
abandoned: MutationEffectCertainty,
): MutationEffectCertainty {
if (abandoned !== "MAYBE_APPLIED" || !descriptor?.classifyStatus) {
return abandoned;
}
try {
return descriptor.classifyStatus(status) === "NOT_APPLIED"
? "NOT_APPLIED"
: "MAYBE_APPLIED";
} catch {
return "MAYBE_APPLIED";
}
}
/** §8.10. Certainty to UI intent. The copy itself is owned by the i18n catalog. */
export function projectCertaintyToUi(
certainty: MutationEffectCertainty,
): "RETRYABLE" | "CHECK_STATUS" | "SUCCESS" {
switch (certainty) {
case "APPLIED_CONFIRMED":
return "SUCCESS";
case "MAYBE_APPLIED":
return "CHECK_STATUS";
default:
return "RETRYABLE";
}
}