diff --git a/docs/architecture/decisions/VD-07-diagnostics-and-telemetry-exporter.md b/docs/architecture/decisions/VD-07-diagnostics-and-telemetry-exporter.md index fe3fac79..d46e64bb 100644 --- a/docs/architecture/decisions/VD-07-diagnostics-and-telemetry-exporter.md +++ b/docs/architecture/decisions/VD-07-diagnostics-and-telemetry-exporter.md @@ -47,9 +47,13 @@ vendor 결정 전에는 안전한 기본값이 아니다. `correlation_id`(서버가 돌려준 `x-correlation-id`, 없으면 실행이 보낸 요청 ID)를 더한다. telemetry에는 넣지 않는다(03-03, `createHttpObservationProjector`). 실행이 observation의 `diagnosticReason`(닫힌 집합 `HttpDiagnosticReason`)을 - 남기면 diagnostics에만 `reason`으로 더한다. 지금 값은 기능 패키지의 + 남기면 diagnostics에만 `reason`으로 더한다. 값은 둘 중 하나다. 기능 패키지의 `classifyProblem`이 throw하거나 집합 밖 값을 돌려줘 효과를 `MAYBE_APPLIED`로 - 떨어뜨린 `CLASSIFIER_FAILED` 하나다(03-05). raw attempt count, + 떨어뜨린 `CLASSIFIER_FAILED`(03-05), 그리고 전송 전에 거절한 요청의 원인 + `HttpRequestRejectionReason`(입력 검증 실패, 요청 조립 실패, 최종 불변식 실패, + 미설치 계약 `CONTRACT_NOT_INSTALLED`, 03-02)이다. 미설치 계약은 실행기를 + 거치지 않으므로 조립 지점이 같은 projector로 관측 1건을 직접 남긴다. + raw attempt count, duration, status, URL, intent, key, input identity와 내부 `terminalReason`은 sink로 나가지 않는다. effect certainty가 운영상 필요해지면 `effect_certainty` key와 닫힌 value policy를 contract·fixture·이 ADR에 동시에 추가한 뒤에만 diff --git a/src/adapters/http/feature-http-binding.ts b/src/adapters/http/feature-http-binding.ts index 51b060a9..ca1c483e 100644 --- a/src/adapters/http/feature-http-binding.ts +++ b/src/adapters/http/feature-http-binding.ts @@ -14,7 +14,9 @@ import { import type { MutationIntent } from "../../contracts/mutation-intent.ts"; import type { ExecutionContext } from "../../platform/execution/execution-context.ts"; import type { + HttpContractViolation, HttpExecutionOutcome, + HttpRequestRejectionReason, SafeResponseMetadata, } from "./http-execution-v3.ts"; @@ -426,7 +428,7 @@ function projectOutcome( }); } return failure( - failureKindForViolation(outcome.violation.kind), + failureKindForViolation(outcome.violation), operationId, outcome.violation.kind, { @@ -442,13 +444,21 @@ function isServerFailureStatus(status: number): boolean { return status >= 500 || status === 408 || status === 425; } -function failureKindForViolation( - violation: Extract< - HttpExecutionOutcome, - { kind: "CONTRACT_VIOLATION" } - >["violation"]["kind"], -): FailureKind { - switch (violation) { +/** + * 03-02. Pre-dispatch refusals the user can fix by changing what they entered. + * Every other refusal reason is a wiring defect in this client, and a refusal + * without a reason keeps the input reading it always had. + */ +const USER_INPUT_REJECTIONS: ReadonlySet = new Set([ + "INPUT_INVALID", + "PATH_VALUE_INVALID", + "QUERY_TOO_LARGE", + "URL_TOO_LARGE", + "REQUEST_BODY_TOO_LARGE", +]); + +function failureKindForViolation(violation: HttpContractViolation): FailureKind { + switch (violation.kind) { case "CONTENT_TYPE_MISMATCH": return "CONTENT_TYPE_MISMATCH"; case "RESPONSE_TOO_LARGE": @@ -465,10 +475,18 @@ function failureKindForViolation( case "VALIDATOR_RUNTIME_FAILURE": return "SCHEMA_MISMATCH"; // Rejected before dispatch: the request, not the server answer, was wrong. + // 03-02. Only input the user can change is "input rejected"; a client + // wiring defect (contract not installed, path template and projection + // disagree, intent policy disagrees with the contract) cannot be fixed by + // the user, the same reading as the V2 client's OPERATION_NOT_REGISTERED. case "FINAL_REQUEST_INVARIANT_FAILED": + return violation.reason === undefined || + USER_INPUT_REJECTIONS.has(violation.reason) + ? "VALIDATION_REJECTED" + : "UNKNOWN_CLIENT_FAILURE"; case "MISSING_IDEMPOTENCY_KEY": case "UNEXPECTED_IDEMPOTENCY_KEY": - return "VALIDATION_REJECTED"; + return "UNKNOWN_CLIENT_FAILURE"; default: return "ENVELOPE_MISMATCH"; } diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index 70857e25..5db17aa3 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -24,6 +24,8 @@ import { projectRequest, type CredentialAdmissionFailure, type CredentialPatchOutcome, + type FinalInvariantFailure, + type RequestProjectionFailure, } from "./http-contract-bridge.ts"; import { INSTALLED_REST_AUTH_PROFILES, @@ -101,8 +103,26 @@ export type HttpContractViolationKind = export type HttpContractViolation = Readonly<{ kind: HttpContractViolationKind; operation: "REQUEST" | "RESPONSE" | "VALIDATION" | "MAPPING"; + /** + * 03-02. Why a `FINAL_REQUEST_INVARIANT_FAILED` request was refused before + * dispatch. Absent on every other violation. + */ + reason?: HttpRequestRejectionReason; }>; +/** + * 03-02. Closed set of pre-dispatch refusal causes: the input validator said + * no (`INPUT_INVALID`), the request could not be assembled, a final invariant + * failed, or the composition root holds no contract for the operation + * (`CONTRACT_NOT_INSTALLED`). A deadline or scope fence at the final check is + * not a refusal; it ends as a timeout or a fence. + */ +export type HttpRequestRejectionReason = + | "INPUT_INVALID" + | "CONTRACT_NOT_INSTALLED" + | RequestProjectionFailure + | Exclude; + export type HttpEffectCertainty = | "NOT_APPLICABLE" | "NOT_STARTED" @@ -296,8 +316,12 @@ export type HttpExecutionObservation = Readonly<{ * - `CLASSIFIER_FAILED`: the package `classifyProblem` threw or answered * outside the closed classification set, so the effect fell back to * `MAYBE_APPLIED` (03-05). + * - an `HttpRequestRejectionReason`: copied from the refused request's + * violation (03-02). */ -export type HttpDiagnosticReason = "CLASSIFIER_FAILED"; +export type HttpDiagnosticReason = + | "CLASSIFIER_FAILED" + | HttpRequestRejectionReason; /** * The outcome is the single authority for the observed error kind. The terminal @@ -607,6 +631,12 @@ export function createContractHttpExecutor( diagnosticReason?: HttpDiagnosticReason, ): HttpExecutionOutcome => { disposeLifetime(); + // 03-02. A refused request carries its cause on the violation itself. + const recordedReason = + diagnosticReason ?? + (outcome.kind === "CONTRACT_VIOLATION" + ? outcome.violation.reason + : undefined); try { const status = observationStatus(outcome); const correlationId = responseCorrelation(outcome) ?? sentRequestId; @@ -622,7 +652,9 @@ export function createContractHttpExecutor( durationMs: Math.max(0, now() - startedAt), effect: outcome.effect, terminalReason, - ...(diagnosticReason === undefined ? {} : { diagnosticReason }), + ...(recordedReason === undefined + ? {} + : { diagnosticReason: recordedReason }), ...(terminalCancellation === null ? {} : { cancellationOwner: terminalCancellation }), @@ -698,11 +730,7 @@ export function createContractHttpExecutor( } if (validated.outcome === "INVALID") { return finish( - violation( - "FINAL_REQUEST_INVARIANT_FAILED", - "REQUEST", - preDispatchEffect(isCommand), - ), + refusedRequest("INPUT_INVALID", preDispatchEffect(isCommand)), "NOT_STARTED", ); } @@ -714,11 +742,7 @@ export function createContractHttpExecutor( ); if (!projected.ok) { return finish( - violation( - "FINAL_REQUEST_INVARIANT_FAILED", - "REQUEST", - preDispatchEffect(isCommand), - ), + refusedRequest(projected.failure, preDispatchEffect(isCommand)), "NOT_STARTED", ); } @@ -945,14 +969,16 @@ export function createContractHttpExecutor( if (invariantFailure) { clearTimeout(deadlineTimer); lifetimeController.signal.removeEventListener("abort", forwardLifetime); + // P-03-05. The deadline can run out between the budget read above and + // this check. Nothing was sent and the request is not wrong: end it + // exactly as the budget read does. + if (invariantFailure === "DEADLINE_EXPIRED") { + return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT"); + } return finish( invariantFailure === "SCOPE_FENCED" ? scopeFenced(logicalPreDispatchEffect()) - : violation( - "FINAL_REQUEST_INVARIANT_FAILED", - "REQUEST", - logicalPreDispatchEffect(), - ), + : refusedRequest(invariantFailure, logicalPreDispatchEffect()), "NOT_STARTED", ); } @@ -1677,6 +1703,22 @@ function violation( }); } +/** 03-02. A request refused before dispatch, with its cause. */ +function refusedRequest( + reason: HttpRequestRejectionReason, + effect: HttpEffectCertainty, +): HttpExecutionOutcome { + return Object.freeze({ + kind: "CONTRACT_VIOLATION" as const, + violation: Object.freeze({ + kind: "FINAL_REQUEST_INVARIANT_FAILED" as const, + operation: "REQUEST" as const, + reason, + }), + effect, + }); +} + function scopeFenced( effect: HttpEffectCertainty, ): HttpExecutionOutcome { diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 29883ad3..161449c4 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -490,6 +490,10 @@ export async function createRuntimeAdapters( location.reload(); }, }); + const observeHttpExecution = createHttpObservationProjector({ + diagnostics, + telemetry, + }); const contractHttp = createContractHttpExecutor({ baseUrl: config.API_BASE_URL, maxRetryAttempts: config.MAX_RETRY_ATTEMPTS, @@ -543,7 +547,7 @@ export async function createRuntimeAdapters( return Object.freeze({ kind: "UNAVAILABLE" as const }); } }, - observe: createHttpObservationProjector({ diagnostics, telemetry }), + observe: observeHttpExecution, }); // 15-01. Filled one feature at a time as feature runtimes load; an // operation of a feature that has not loaded resolves to nothing and is @@ -555,14 +559,32 @@ export async function createRuntimeAdapters( operation.contract.operationId, ); if (!installed) { - return Object.freeze({ + // 03-02. Refused before the executor runs, so this path leaves the + // one diagnostic every V3 execution leaves itself, with the cause. + const refused = Object.freeze({ kind: "CONTRACT_VIOLATION" as const, effect: "NOT_STARTED" as const, violation: Object.freeze({ kind: "FINAL_REQUEST_INVARIANT_FAILED" as const, operation: "REQUEST" as const, + reason: "CONTRACT_NOT_INSTALLED" as const, }), }); + observeHttpExecution( + Object.freeze({ + routeId: executionContext.routeId, + operationId: operation.contract.operationId, + diagnosticsOperation: operation.frontend.diagnosticsOperation, + outcome: refused.kind, + errorKind: refused.violation.kind, + attemptCount: 0, + durationMs: 0, + effect: refused.effect, + terminalReason: "NOT_STARTED", + diagnosticReason: refused.violation.reason, + }), + ); + return refused; } // composeContractContributions deliberately snapshots every installed // contract. Runtime authority is therefore the validated registry entry, diff --git a/tests/contract/reusable-capability/feature-http-binding.test.ts b/tests/contract/reusable-capability/feature-http-binding.test.ts index c9ddbe14..22bbf86c 100644 --- a/tests/contract/reusable-capability/feature-http-binding.test.ts +++ b/tests/contract/reusable-capability/feature-http-binding.test.ts @@ -188,19 +188,34 @@ describe("feature HTTP binding", () => { expect(result.error.code).toBe("MAPPING_INVARIANT_REJECTED"); }); + /** + * 03-02. A request refused before dispatch is never a server answer. Only an + * input the user can change is "input rejected"; a wiring defect in this + * client (contract not installed, path template and projection disagree, + * mutation intent disagrees with the contract) is a client failure. + */ it.each([ - "FINAL_REQUEST_INVARIANT_FAILED", - "MISSING_IDEMPOTENCY_KEY", - "UNEXPECTED_IDEMPOTENCY_KEY", + ["FINAL_REQUEST_INVARIANT_FAILED", undefined, "VALIDATION_REJECTED"], + ["FINAL_REQUEST_INVARIANT_FAILED", "INPUT_INVALID", "VALIDATION_REJECTED"], + ["FINAL_REQUEST_INVARIANT_FAILED", "PATH_VALUE_INVALID", "VALIDATION_REJECTED"], + ["FINAL_REQUEST_INVARIANT_FAILED", "QUERY_TOO_LARGE", "VALIDATION_REJECTED"], + ["FINAL_REQUEST_INVARIANT_FAILED", "URL_TOO_LARGE", "VALIDATION_REJECTED"], + ["FINAL_REQUEST_INVARIANT_FAILED", "REQUEST_BODY_TOO_LARGE", "VALIDATION_REJECTED"], + ["FINAL_REQUEST_INVARIANT_FAILED", "PATH_PLACEHOLDER_MISSING", "UNKNOWN_CLIENT_FAILURE"], + ["FINAL_REQUEST_INVARIANT_FAILED", "CONTRACT_NOT_INSTALLED", "UNKNOWN_CLIENT_FAILURE"], + ["FINAL_REQUEST_INVARIANT_FAILED", "HEADER_NOT_ALLOWED", "UNKNOWN_CLIENT_FAILURE"], + ["MISSING_IDEMPOTENCY_KEY", undefined, "UNKNOWN_CLIENT_FAILURE"], + ["UNEXPECTED_IDEMPOTENCY_KEY", undefined, "UNKNOWN_CLIENT_FAILURE"], ] as const)( - "does not report the request-side violation %s as a server envelope mismatch", - async (violationKind) => { + "reports the request-side violation %s (%s) as %s, never as a server answer", + async (violationKind, reason, expectedKind) => { const scripted = scriptedExecutor( Object.freeze({ kind: "CONTRACT_VIOLATION" as const, violation: Object.freeze({ kind: violationKind, operation: "REQUEST" as const, + ...(reason === undefined ? {} : { reason }), }), effect: "NOT_APPLICABLE" as const, }), @@ -213,7 +228,7 @@ describe("feature HTTP binding", () => { expect(result).toMatchObject({ ok: false, - error: { kind: "VALIDATION_REJECTED", code: violationKind }, + error: { kind: expectedKind, code: violationKind }, }); }, ); diff --git a/tests/integration/http-execution-v3-observability.test.ts b/tests/integration/http-execution-v3-observability.test.ts index 47129fa0..183d40a6 100644 --- a/tests/integration/http-execution-v3-observability.test.ts +++ b/tests/integration/http-execution-v3-observability.test.ts @@ -288,6 +288,104 @@ describe("V3 HTTP observability projection", () => { } }); + /** + * 03-02 (E6c). A path template and a `projectRequest` that disagree are + * refused before dispatch. The cause reaches diagnostics, not telemetry. + */ + it("names a refused request's assembly cause in diagnostics only (03-02)", async () => { + const sinks = recordingSinks(); + const fetcher = vi.fn(); + const mismatched = { + ...TEST_LIST_HTTP_CONTRACT, + contract: { + ...TEST_LIST_HTTP_CONTRACT.contract, + pathTemplate: "/api/test-entities/{id}", + projectRequest: () => + Object.freeze({ + pathValues: Object.freeze({ entityId: "entity-1" }), + queryEntries: Object.freeze([]), + body: null, + }), + }, + }; + + const outcome = await createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 0, + attachCredentials: () => ({ kind: "READY" as const, headers: {} }), + fetcher: fetcher as unknown as typeof fetch, + observe: sinks.projector, + }).execute( + mismatched, + { limit: 5 }, + { routeId: ROUTE_ID, scope: scopeSnapshot() }, + ); + + expect(fetcher).not.toHaveBeenCalled(); + expect(outcome).toMatchObject({ + kind: "CONTRACT_VIOLATION", + effect: "NOT_APPLICABLE", + violation: { + kind: "FINAL_REQUEST_INVARIANT_FAILED", + reason: "PATH_PLACEHOLDER_MISSING", + }, + }); + expect(sinks.diagnostics).toHaveLength(1); + expect(sinks.diagnostics[0]?.context).toMatchObject({ + error_kind: "FINAL_REQUEST_INVARIANT_FAILED", + reason: "PATH_PLACEHOLDER_MISSING", + }); + expect(projectDiagnosticRecord(sinks.diagnostics[0]!).success).toBe(true); + expect(JSON.stringify(sinks.telemetry)).not.toContain( + "PATH_PLACEHOLDER_MISSING", + ); + }); + + /** + * 03-02 / P-03-05 (E3). The deadline can run out between the attempt's + * budget read and the final invariant check. Nothing was sent and nothing is + * wrong with the request: it is a timeout, like the budget read itself. + */ + it("ends a deadline that expires at the final invariant check as a timeout (P-03-05)", async () => { + let clockReads = 0; + let jumpAtRead = Number.POSITIVE_INFINITY; + const monotonicNow = () => { + clockReads += 1; + return clockReads >= jumpAtRead ? 1_000_000 : 0; + }; + const run = (fetcher: typeof fetch) => + createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 0, + attachCredentials: () => ({ kind: "READY" as const, headers: {} }), + fetcher, + monotonicNow, + }).execute( + TEST_LIST_HTTP_CONTRACT, + { limit: 5 }, + { routeId: ROUTE_ID, scope: scopeSnapshot() }, + ); + + // Probe: the last clock read before fetch is the final invariant check's + // deadline read, because nothing else reads the clock in between. + let readsBeforeFetch = 0; + await run((async () => { + readsBeforeFetch = clockReads; + return Response.json([]); + }) as unknown as typeof fetch); + + clockReads = 0; + jumpAtRead = readsBeforeFetch; + const fetcher = vi.fn(); + const outcome = await run(fetcher as unknown as typeof fetch); + + expect(fetcher).not.toHaveBeenCalled(); + expect(outcome).toMatchObject({ + kind: "TRANSPORT_FAILURE", + failure: { kind: "TIMEOUT" }, + }); + }); + it("keeps a never-sent unauthenticated request out of telemetry (03-07)", async () => { const sinks = recordingSinks(); const fetcher = vi.fn(); diff --git a/tests/unit/runtime-adapters-auth-profile.test.ts b/tests/unit/runtime-adapters-auth-profile.test.ts index 9f83f368..a6a80531 100644 --- a/tests/unit/runtime-adapters-auth-profile.test.ts +++ b/tests/unit/runtime-adapters-auth-profile.test.ts @@ -355,3 +355,43 @@ describe("09-01 credentialed operations keep failing closed", () => { ); }); }); + +/** + * 03-02. An operation no loaded feature contributed is refused before the + * executor runs. That refusal must still leave the one diagnostic every V3 + * execution leaves, with the cause, so it is not invisible in the buffer. + */ +describe("03-02 an operation the registry does not hold", () => { + it("is refused without a fetch and leaves one diagnostic naming the cause", async () => { + const { http, fetcher, adapters } = await compose("demo"); + const completed = () => + adapters.outputPorts.diagnostics + .entries() + .filter((entry) => entry.eventId === "http.request.completed"); + const before = completed().length; + + const outcome = await http.execute( + fixture.withProfile(TEST_LIST_HTTP_CONTRACT, "TEST_NOT_INSTALLED", "ANONYMOUS"), + { limit: 1 }, + { routeId: "TEST_ROUTE" }, + ); + + expect(outcome).toMatchObject({ + kind: "CONTRACT_VIOLATION", + effect: "NOT_STARTED", + violation: { + kind: "FINAL_REQUEST_INVARIANT_FAILED", + reason: "CONTRACT_NOT_INSTALLED", + }, + }); + expect(fetcher).not.toHaveBeenCalled(); + expect(completed()).toHaveLength(before + 1); + expect(completed().at(-1)?.context).toMatchObject({ + route_id: "TEST_ROUTE", + operation_id: "TEST_NOT_INSTALLED", + outcome: "CONTRACT_VIOLATION", + error_kind: "FINAL_REQUEST_INVARIANT_FAILED", + reason: "CONTRACT_NOT_INSTALLED", + }); + }); +});