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
This commit is contained in:
DongHyeonka
2026-11-01 22:42:44 +09:00
parent 5e6be9a92f
commit f8a492a6ad
6 changed files with 112 additions and 2 deletions
@@ -45,7 +45,11 @@ vendor 결정 전에는 안전한 기본값이 아니다.
`operation`, `outcome`, `error_kind`, `http_status_group`,
`attempt_count_bucket`, `duration_bucket`만 사용한다. diagnostics에만
`correlation_id`(서버가 돌려준 `x-correlation-id`, 없으면 실행이 보낸 요청 ID)를
더한다. telemetry에는 넣지 않는다(03-03, `createHttpObservationProjector`). raw attempt count,
더한다. telemetry에는 넣지 않는다(03-03, `createHttpObservationProjector`).
실행이 observation의 `diagnosticReason`(닫힌 집합 `HttpDiagnosticReason`)을
남기면 diagnostics에만 `reason`으로 더한다. 지금 값은 기능 패키지의
`classifyProblem`이 throw하거나 집합 밖 값을 돌려줘 효과를 `MAYBE_APPLIED`로
떨어뜨린 `CLASSIFIER_FAILED` 하나다(03-05). raw attempt count,
duration, status, URL, intent, key, input identity와 내부 `terminalReason`은
sink로 나가지 않는다. effect certainty가 운영상 필요해지면 `effect_certainty`
key와 닫힌 value policy를 contract·fixture·이 ADR에 동시에 추가한 뒤에만
+3 -1
View File
@@ -92,7 +92,9 @@ const CLASSIFICATIONS: ReadonlySet<CommandEffectClassification> = new Set([
/**
* §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".
* 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>,
+21
View File
@@ -283,8 +283,22 @@ export type HttpExecutionObservation = Readonly<{
* projection never forwards it to diagnostics or telemetry.
*/
terminalReason: string;
/**
* 03-05. A client-side defect the outcome alone cannot show, from a closed
* set. Diagnostics carry it as `reason`; telemetry never does (VD-07).
*/
diagnosticReason?: HttpDiagnosticReason;
}>;
/**
* Closed set behind `HttpExecutionObservation.diagnosticReason`.
*
* - `CLASSIFIER_FAILED`: the package `classifyProblem` threw or answered
* outside the closed classification set, so the effect fell back to
* `MAYBE_APPLIED` (03-05).
*/
export type HttpDiagnosticReason = "CLASSIFIER_FAILED";
/**
* The outcome is the single authority for the observed error kind. The terminal
* reason only distinguishes an internal runtime failure from a transport
@@ -590,6 +604,7 @@ export function createContractHttpExecutor(
const finish = (
outcome: HttpExecutionOutcome<WireOutput, Problem>,
terminalReason: string,
diagnosticReason?: HttpDiagnosticReason,
): HttpExecutionOutcome<WireOutput, Problem> => {
disposeLifetime();
try {
@@ -607,6 +622,7 @@ export function createContractHttpExecutor(
durationMs: Math.max(0, now() - startedAt),
effect: outcome.effect,
terminalReason,
...(diagnosticReason === undefined ? {} : { diagnosticReason }),
...(terminalCancellation === null
? {}
: { cancellationOwner: terminalCancellation }),
@@ -1070,6 +1086,7 @@ export function createContractHttpExecutor(
effect,
}) as HttpExecutionOutcome<WireOutput, Problem>),
outcome.certainty,
outcome.diagnosticReason,
);
} finally {
clearTimeout(deadlineTimer);
@@ -1144,6 +1161,7 @@ type AdmissionOutcome<Value, Problem> = Readonly<{
certainty: string;
retryHint: boolean;
retryAfterMs: number | null;
diagnosticReason?: HttpDiagnosticReason;
}>;
/**
@@ -1612,6 +1630,9 @@ async function admitProblem<Input, WireOutput, Problem>(
certainty: effect,
retryHint: retryable && effect !== "MAYBE_APPLIED",
retryAfterMs: metadata.retryAfterMs ?? null,
...(isCommand && classification.contractRuntimeFailure
? { diagnosticReason: "CLASSIFIER_FAILED" as const }
: {}),
});
}
+1
View File
@@ -12,6 +12,7 @@ export {
type ContractHttpExecutorDependencies,
type HttpContractViolation,
type HttpContractViolationKind,
type HttpDiagnosticReason,
type HttpEffectCertainty,
type HttpExecutionContext,
type HttpExecutionObservation,
+4
View File
@@ -251,6 +251,10 @@ export function createHttpObservationProjector(
...(observation.correlationId === undefined
? {}
: { correlation_id: observation.correlationId }),
// 03-05. A closed client-defect code; diagnostics only.
...(observation.diagnosticReason === undefined
? {}
: { reason: observation.diagnosticReason }),
},
});
} catch {
@@ -210,6 +210,84 @@ describe("V3 HTTP observability projection", () => {
expect(JSON.stringify(sinks.telemetry)).not.toContain("server-ref-7");
});
/**
* 03-05. A package problem classifier that throws, or answers outside the
* closed set, fails safe to MAYBE_APPLIED. Diagnostics must still tell that
* apart from a classifier that really answered MAYBE_APPLIED; telemetry stays
* on `error_kind` alone.
*/
it("keeps MAYBE_APPLIED and records a failed problem classifier in diagnostics only (03-05)", async () => {
async function runWithClassifier(classifyProblem: () => unknown) {
const sinks = recordingSinks();
const contract = {
...TEST_CREATE_HTTP_CONTRACT,
contract: {
...TEST_CREATE_HTTP_CONTRACT.contract,
commandEffect: {
...TEST_CREATE_HTTP_CONTRACT.contract.commandEffect!,
classifyProblem,
} as NonNullable<
typeof TEST_CREATE_HTTP_CONTRACT.contract.commandEffect
>,
},
};
const outcome = await createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
fetcher: (async () =>
Response.json(
{ type: "about:blank", title: "conflict", status: 409 },
{ status: 409 },
)) as unknown as typeof fetch,
observe: sinks.projector,
}).execute(
contract,
{ name: "Created" },
{
routeId: ROUTE_ID,
scope: scopeSnapshot(),
intent: Object.freeze({
intentId: "intent-1",
operationId: "TEST_CREATE_ENTITY",
canonicalInputIdentity: "opaque-input-identity",
idempotencyKey: "key-1",
createdAtMonotonicMs: 1,
}),
},
);
expect(sinks.diagnostics).toHaveLength(1);
expect(projectDiagnosticRecord(sinks.diagnostics[0]!).success).toBe(true);
expect(sinks.telemetry).toHaveLength(1);
return {
kind: outcome.kind,
effect: outcome.effect,
reason: sinks.diagnostics[0]?.context?.reason,
telemetryKeys: Object.keys(sinks.telemetry[0]?.attributes ?? {}),
};
}
const answered = await runWithClassifier(() => "MAYBE_APPLIED");
const thrown = await runWithClassifier(() => {
throw new Error("package classifier defect");
});
const unknownAnswer = await runWithClassifier(() => "NOT_STARTED");
expect(answered).toMatchObject({
kind: "PROBLEM",
effect: "MAYBE_APPLIED",
reason: undefined,
});
for (const failed of [thrown, unknownAnswer]) {
expect(failed).toMatchObject({
kind: "PROBLEM",
effect: "MAYBE_APPLIED",
reason: "CLASSIFIER_FAILED",
});
expect(failed.telemetryKeys).toEqual(answered.telemetryKeys);
}
});
it("keeps a never-sent unauthenticated request out of telemetry (03-07)", async () => {
const sinks = recordingSinks();
const fetcher = vi.fn();