From 4da046683f582caaaa9eeb163a44bfecf5be4e12 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 1 Nov 2026 22:17:26 +0900 Subject: [PATCH] =?UTF-8?q?fix(http):=20=EC=A0=84=EC=86=A1=20=EC=A0=84=20?= =?UTF-8?q?=EA=B1=B0=EC=A0=88=EC=9D=98=20=EC=9B=90=EC=9D=B8=EC=9D=84=20?= =?UTF-8?q?=EC=A7=84=EB=8B=A8=EC=97=90=20=EB=82=A8=EA=B8=B0=EA=B3=A0=20?= =?UTF-8?q?=EC=97=B0=EA=B2=B0=20=EC=8B=A4=EC=88=98=EB=A5=BC=20=EA=B5=AC?= =?UTF-8?q?=EB=B6=84=ED=95=9C=EB=8B=A4=20(03-02)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 전송 전 실패가 네 곳에서 원인 없는 위반 FINAL_REQUEST_INVARIANT_FAILED 하나로 바뀐다. 입력 검증 실패, 요청 조립 실패 10종(PATH_PLACEHOLDER_MISSING 등), 최종 불변식 실패 12종, 미설치 계약이다. 바인딩은 이 위반과 MISSING_IDEMPOTENCY_KEY·UNEXPECTED_IDEMPOTENCY_KEY를 모두 VALIDATION_REJECTED로 바꿔 "서버가 입력값을 받아들이지 않았습니다"를 띄운다. 그래서 경로 placeholder 오타나 mutation 정책과 계약의 불일치 같은 개발자 연결 실수가 사용자 입력 문제처럼 보이고, 진단에는 원인이 없다. 미설치 계약은 실행기를 거치지 않아 진단이 0건이다. 또 마감이 시도별 budget 읽기와 최종 불변식 검사 사이에 끝나면 DEADLINE_EXPIRED도 같은 위반이 되어, 시간 초과가 "입력 거절"로 보인다(P-03-05). 고른 방법 - HttpContractViolation에 선택 필드 reason(닫힌 집합 HttpRequestRejectionReason)을 더한다. 실행기의 세 거절 지점이 refusedRequest(reason)로 위반을 만들고, finish()가 그 reason을 관측의 diagnosticReason으로 옮긴다. projector는 03-05에서 만든 경로대로 diagnostics에만 reason을 싣는다. telemetry는 error_kind 그대로다. - 최종 불변식의 DEADLINE_EXPIRED는 budget 읽기 분기와 똑같이 TRANSPORT_FAILURE/TIMEOUT으로 끝낸다(P-03-05). - 바인딩은 사용자가 입력을 바꿔 고칠 수 있는 거절(INPUT_INVALID, PATH_VALUE_INVALID, QUERY_TOO_LARGE, URL_TOO_LARGE, REQUEST_BODY_TOO_LARGE)과 reason 없는 거절만 VALIDATION_REJECTED로 둔다. 나머지 reason과 멱등 키 위반은 UNKNOWN_CLIENT_FAILURE(문의 행동, "요청을 처리할 수 없습니다.")로 낸다. V2 client가 미등록 operation을 같은 종류로 내는 것과 맞췄다. - 미설치 계약 분기는 같은 projector로 관측 1건(reason CONTRACT_NOT_INSTALLED)을 직접 남긴다. 버린 대안 - 새 FailureKind 추가: 오류 레지스트리·i18n 카탈로그·화면 분기를 다 바꿔야 한다. 이미 있는 UNKNOWN_CLIENT_FAILURE가 "클라이언트 결함, 문의"라는 같은 뜻이고 V2에서 같은 상황에 쓰고 있다. - 리뷰 예시대로 MAPPING_CONTRACT_VIOLATION으로 내기: 문구가 "서버 응답을 화면 데이터로 바꾸지 못했습니다"라 응답이 없는 전송 전 실패와 맞지 않는다. - 사용자 입력 쪽을 reason별 Record로 망라하기: 컴파일 시 분류를 강제하지만 20여 줄이 는다. 새 reason은 기본으로 클라이언트 결함이 되는 쪽이 안전하므로 입력 쪽 5개만 Set으로 적었다. - terminalReason에 원인을 싣기(리뷰 문구): 03-05와 같은 이유로 버렸다. 위험·한계 - 동작 변경: 멱등 키 위반과 연결 실수가 VALIDATION_REJECTED에서 UNKNOWN_CLIENT_FAILURE로 바뀐다. 폼은 필드 오류 대신 "unavailable" 상태 안내를 띄운다. 기존 계약 테스트의 기대값을 이에 맞게 바꿨다. - 입력 검증 실패(INPUT_INVALID)는 리뷰 문구("입력 크기 초과만")와 달리 VALIDATION_REJECTED로 남겼다. 입력 validator의 거절은 사용자 입력 문제다. - reason 없는 FINAL_REQUEST_INVARIANT_FAILED(다른 실행기 구현)는 기존대로 VALIDATION_REJECTED다. - AppFailure.code는 지금처럼 위반 종류다. 원인 코드는 진단에만 있다. - 공개 타입은 추가만 했다(위반 선택 필드 1개, 진단 reason 집합 확장). - validator가 throw하는 경우(VALIDATOR_RUNTIME_FAILURE → SCHEMA_MISMATCH, "서버 응답 데이터가…" 문구)는 이번 범위가 아니라 그대로다. - 미설치 계약 거절도 다른 CONTRACT_VIOLATION처럼 api.request.failed telemetry 1건을 낸다(VD-07 규칙 5). - 화면: 정상 상태는 그대로이고 위 실패에서만 문구가 바뀐다. 시각 골든은 다시 찍지 않았다. 검증 - RED(수정 전): - http-execution-v3-observability "names a refused request's assembly cause in diagnostics only (03-02)": violation.reason 없음. - 같은 파일 "ends a deadline that expires at the final invariant check as a timeout (P-03-05)": TRANSPORT_FAILURE 기대, 실제 CONTRACT_VIOLATION. - feature-http-binding 계약 테스트 5건: PATH_PLACEHOLDER_MISSING, CONTRACT_NOT_INSTALLED, HEADER_NOT_ALLOWED, MISSING_IDEMPOTENCY_KEY, UNEXPECTED_IDEMPOTENCY_KEY가 VALIDATION_REJECTED로 나옴. - runtime-adapters-auth-profile "is refused without a fetch and leaves one diagnostic naming the cause": reason 없음, 진단 0건. - GREEN: 세 파일 38/38 통과. - 회귀: run-vitest tests/unit tests/integration tests/component tests/features tests/contract tests/runtime-schema(pnpm을 언급하는 파일 13개 제외) 227 files 중 226 통과, 2354/2355. 실패 1건은 provider-guardian-transaction의 ENOSPC(inotify watcher 한도, 이 머신의 다른 실행 때문)로 HTTP와 무관하다. 제외했던 http-scenario-evidence는 pnpm을 띄우지 않아 따로 돌렸고 14/14 통과. tsc app/test/node rc=0. 바꾼 파일 eslint rc=0. check-adapter-inventory PASS. verify-documentation-readiness PASS_SCOPED. - 미실행: check:architecture(pnpm 스크립트 필요), 번들 크기 측정. Refs: docs/reviews/2026-11-01-maturity-review/03-adapters-http-state.md --- ...D-07-diagnostics-and-telemetry-exporter.md | 8 +- src/adapters/http/feature-http-binding.ts | 36 +++++-- src/adapters/http/http-execution-v3.ts | 76 ++++++++++---- src/bootstrap/runtime-adapters.ts | 26 ++++- .../feature-http-binding.test.ts | 27 +++-- .../http-execution-v3-observability.test.ts | 98 +++++++++++++++++++ .../runtime-adapters-auth-profile.test.ts | 40 ++++++++ 7 files changed, 275 insertions(+), 36 deletions(-) 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", + }); + }); +});