From 5d0f8454c6a8a4daae0df15f08ce0b32a107467b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:24:09 +0900 Subject: [PATCH] =?UTF-8?q?test(http):=20Envelope=20=ED=8C=90=EC=A0=95=20?= =?UTF-8?q?=EA=B2=BD=EA=B3=84=EC=99=80=20=EC=B2=98=EB=A6=AC=20=EC=A4=91=20?= =?UTF-8?q?409=20=EB=AC=B4=EC=9E=AC=EC=A0=84=EC=86=A1=EC=9D=84=20=EA=B3=A0?= =?UTF-8?q?=EC=A0=95=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 Envelope 실패 판정 표(backend-envelope.ts)와 실행기의 실패 Envelope 처리는 커버리지가 100%인데 경계 다섯 곳이 테스트에 걸리지 않는다. 표의 code를 다른 status로 보내는 행, 표 밖 422, 게이트웨이 408·425, 응답 한도보다 크고 64 KiB보다 작은 실패 본문, JSON이 아닌 실패 본문이 없다. 그래서 변이 H14(=M6, status 대조 제거)·H45(표 밖 422를 분류기로)·H15 (408·425 제거)·H23(실패 한도를 64 KiB 고정)·H10b(실패 media type 검사 제거)가 살아남았다. 처리 중 409를 자동 재전송하게 바꾼 변이 M7도 살아남았다. Envelope 표 테스트는 재시도 예산이 0이라 재전송을 볼 수 없었다. 같은 문서의 이월 항목 둘도 그대로다. 결과 불명 동안 입력 identity를 잡는 네 줄(M1, 0929/03-06)과 반사 correlation 문법 검사(M3, 1101/03-06)를 지워도 테스트가 통과한다. 고른 방법 - tests/unit/backend-envelope.test.ts: envelopeFailureEffect· idempotencyRefusalReason·envelopeFailureReading을 status × code 표로 직접 부른다. - envelope 통합 테스트: LENIENT 묶음에 422 INTEGRITY_MISMATCH 한 행, 한도를 넘는 실패 Envelope와 text/plain 실패 본문(네이티브 Response), retryBudget 1인 KEYED가 409 IDEMPOTENT_IN_FLIGHT에 한 번만 보내는 행. - 결과 불명 입력이 두 칸짜리 identity 레지스트리에서 밀려나지 않는지, 문법 밖 반사 id가 보낸 id로 바뀌는지를 각각 한 건씩 더한다. 위험·한계 테스트만 더했다. 동작은 바꾸지 않았다. 검증 - 변이 8종(H14·H45·H15·H23·H10b·M7·M1·M3)을 하나씩 넣고 관련 테스트를 돌렸다. 모두 새 테스트에서 실패하고, 되돌리면 통과한다. - check:types, lint 통과. 바뀐 4파일 83건 통과. Refs: docs/reviews/2026-11-03-maturity-review/10-tests-fast-layers.md 10-02 Refs: docs/reviews/2026-11-03-maturity-review/03-adapters-http-state.md 03-08 --- .../application-mutation-admission.test.tsx | 26 ++++++- .../http-execution-v3-envelope.test.ts | 73 +++++++++++++++++++ .../http-execution-v3-observability.test.ts | 35 +++++++++ tests/unit/backend-envelope.test.ts | 62 ++++++++++++++++ 4 files changed, 194 insertions(+), 2 deletions(-) create mode 100644 tests/unit/backend-envelope.test.ts diff --git a/tests/component/application-mutation-admission.test.tsx b/tests/component/application-mutation-admission.test.tsx index 5f386dc6..380c6e7e 100644 --- a/tests/component/application-mutation-admission.test.tsx +++ b/tests/component/application-mutation-admission.test.tsx @@ -393,11 +393,12 @@ describe("application mutation intent admission", () => { }); describe("unknown-effect replay (D-1)", () => { - function replayScope() { + function replayScope(maxEntries?: number) { let token = 0; return { ...scopeSnapshot(), identities: createRuntimeIdentityRegistry({ + ...(maxEntries === undefined ? {} : { maxEntries }), tokenFactory: () => `replay-identity-token-${String(++token).padStart(4, "0")}`, }), }; @@ -405,6 +406,7 @@ describe("application mutation intent admission", () => { function renderKeyedCreate( outcomes: ApplicationResult[], + maxIdentities?: number, ) { const client = queryClient(); const intents: MutationIntent[] = []; @@ -419,7 +421,7 @@ describe("application mutation intent admission", () => { return outcomes.shift() ?? { ok: true, value: input }; }, ); - const scope = replayScope(); + const scope = replayScope(maxIdentities); const hook = renderHook( () => useApplicationMutation({ @@ -478,6 +480,26 @@ describe("application mutation intent admission", () => { ); }); + // 0929/03-06. The unknown request leases its input identity, so a full + // identity registry evicts other inputs first and the same input saved + // later still finds the unknown request and its key. + it("keeps the unknown input's identity when the identity registry is full", async () => { + const { hook, intents } = renderKeyedCreate([unknown], 2); + await act(() => hook.result.current.submit("same-input")); + // A two-entry registry: the third input evicts the oldest unleased one. + await act(() => hook.result.current.submit("second-input")); + await act(() => hook.result.current.submit("third-input")); + + await act(() => hook.result.current.submit("same-input")); + + expect(intents.map((intent) => intent.idempotencyKey)).toEqual([ + "key-1", + "key-2", + "key-3", + "key-1", + ]); + }); + it("resends the unknown head request with its original key", async () => { const { hook, intents, execute } = renderKeyedCreate([unknown, unknown]); await act(() => hook.result.current.submit("resent-input")); diff --git a/tests/integration/http-execution-v3-envelope.test.ts b/tests/integration/http-execution-v3-envelope.test.ts index 39d217c8..ade862e8 100644 --- a/tests/integration/http-execution-v3-envelope.test.ts +++ b/tests/integration/http-execution-v3-envelope.test.ts @@ -574,6 +574,17 @@ describe("V3 Envelope verdicts follow the backend's refusal table", () => { effect: "MAYBE_APPLIED", }); + // 1103/10-02. Fileserver writes the record before it answers this 422. + answer( + "post", + "/api/envelope-items", + failure("INTEGRITY_MISMATCH", "VALIDATION", false), + { status: 422 }, + ); + await expect(v3CreateFailure(conflict)).resolves.toMatchObject({ + effect: "MAYBE_APPLIED", + }); + // A 404 is the package's to classify. answer("post", "/api/envelope-items", failure("NOT_FOUND", "NOT_FOUND", false), { status: 404, @@ -665,6 +676,22 @@ describe("KEYED resend on the backend's pre-execution refusal", () => { expect(keys).toEqual([KEY, KEY]); }); + // 1103/10-02 (03-08 M7). A same-key request that is still running is the + // user's to resend after Retry-After; the executor does not wait on it. + it("does not resend a 409 IDEMPOTENT_IN_FLIGHT on its own", async () => { + const { outcome, keys } = await run([ + () => + HttpResponse.json(failure("IDEMPOTENT_IN_FLIGHT", "CONFLICT", true), { + status: 409, + headers: { "Retry-After": "2" }, + }), + created, + ]); + + expect(outcome).toMatchObject({ kind: "PROBLEM", effect: "MAYBE_APPLIED" }); + expect(keys).toEqual([KEY]); + }); + it("does not resend a 503 the backend did not mark as a pre-execution refusal", async () => { const { outcome, keys } = await run([ () => @@ -679,6 +706,52 @@ describe("KEYED resend on the backend's pre-execution refusal", () => { }); }); +// 1103/10-02. A failure Envelope is read under the operation's own response +// limit and media type, not only the problem ceiling. Native Responses: MSW +// never settles a cancel() on a body it is still streaming. +describe("failure Envelope admission bounds", () => { + const conflictBody = (details?: JsonBodyType) => + JSON.stringify(failure("RESOURCE_CONFLICT", "CONFLICT", false, details)); + + it("refuses a failure Envelope above the operation's response limit", async () => { + // Over the operation's 2 KiB, well under the 64 KiB problem ceiling. + const body = conflictBody({ note: "n".repeat(LIST_LIMIT) }); + expect(body.length).toBeGreaterThan(LIST_LIMIT); + expect(body.length).toBeLessThan(16 * 1024); + const fetcher = (async () => + new Response(body, { + status: 409, + headers: { "content-type": "application/json" }, + })) as typeof fetch; + + await expect( + v3CreateFailure(createFeatureHttpBinding(v3Executor(fetcher), OPERATIONS)), + ).resolves.toMatchObject({ + kind: "SCHEMA_MISMATCH", + code: "PROBLEM_SCHEMA_INVALID", + httpStatus: 409, + effect: "MAYBE_APPLIED", + }); + }); + + it("refuses a failure Envelope that is not sent as JSON", async () => { + const fetcher = (async () => + new Response(conflictBody(), { + status: 409, + headers: { "content-type": "text/plain" }, + })) as typeof fetch; + + await expect( + v3CreateFailure(createFeatureHttpBinding(v3Executor(fetcher), OPERATIONS)), + ).resolves.toMatchObject({ + kind: "CONTENT_TYPE_MISMATCH", + code: "CONTENT_TYPE_MISMATCH", + httpStatus: 409, + effect: "MAYBE_APPLIED", + }); + }); +}); + describe("shared MSW scenarios for an Envelope operation", () => { it.each([ ["success", { ok: true, value: [{ id: "item-1", name: "First" }] }], diff --git a/tests/integration/http-execution-v3-observability.test.ts b/tests/integration/http-execution-v3-observability.test.ts index 183d40a6..4f95fc14 100644 --- a/tests/integration/http-execution-v3-observability.test.ts +++ b/tests/integration/http-execution-v3-observability.test.ts @@ -210,6 +210,41 @@ describe("V3 HTTP observability projection", () => { expect(JSON.stringify(sinks.telemetry)).not.toContain("server-ref-7"); }); + // 1101/03-06. A reflected id outside the request id grammar (a proxy's + // text, an overlong value) is not what the server logged: the sent id + // stands in for it, in the outcome and in diagnostics. + it.each([ + ["a value with spaces and markup", "proxy ref"], + ["an overlong value", "r".repeat(129)], + ])("drops a reflected correlation id that is %s", async (_label, reflected) => { + const sinks = recordingSinks(); + const outcome = await createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 0, + attachCredentials: () => ({ kind: "READY" as const, headers: {} }), + createRequestId: () => "sent-request-1", + fetcher: (async () => + new Response(null, { + status: 503, + headers: { "x-correlation-id": reflected }, + })) as unknown as typeof fetch, + observe: sinks.projector, + }).execute( + TEST_LIST_HTTP_CONTRACT, + { limit: 5 }, + { routeId: ROUTE_ID, scope: scopeSnapshot() }, + ); + + expect("metadata" in outcome ? outcome.metadata : undefined).not.toHaveProperty( + "correlationReference", + ); + expect(outcome.sentRequestId).toBe("sent-request-1"); + expect(sinks.diagnostics[0]?.context).toMatchObject({ + correlation_id: "sent-request-1", + }); + expect(JSON.stringify(sinks.diagnostics)).not.toContain(reflected); + }); + /** * 03-05. A package problem classifier that throws, or answers outside the * closed set, fails safe to MAYBE_APPLIED. Diagnostics must still tell that diff --git a/tests/unit/backend-envelope.test.ts b/tests/unit/backend-envelope.test.ts new file mode 100644 index 00000000..fa09e59a --- /dev/null +++ b/tests/unit/backend-envelope.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; + +import { + envelopeFailureEffect, + envelopeFailureReading, + idempotencyRefusalReason, +} from "../../src/adapters/http/backend-envelope.ts"; + +/** + * 1103/10-02. The backend's refusal table, read status by status. The + * integration test sends each table code with its own status; these rows pin + * the edges it does not reach: a table code under another status, a 422 + * outside the table, and the gateway statuses that keep the server-failure + * kind. + */ +describe("backend Envelope failure table", () => { + it.each([ + [400, "VALIDATION_FAILED", undefined], + [400, "IDEMPOTENCY_KEY_INVALID", "IDEMPOTENCY_KEY_RULE_MISMATCH"], + [422, "IDEMPOTENT_REQUEST_MISMATCH", "IDEMPOTENT_REQUEST_MISMATCH"], + ] as const)("reads %i %s as refused before the write", (status, code, reason) => { + expect(envelopeFailureEffect(status, { code })).toBe("NOT_APPLIED"); + expect(idempotencyRefusalReason(code, status)).toBe(reason); + }); + + // The table names a status and a code together. The same code under + // another status is not the refusal the backend documents. + it.each([ + [409, "VALIDATION_FAILED"], + [422, "VALIDATION_FAILED"], + [400, "IDEMPOTENT_REQUEST_MISMATCH"], + [409, "IDEMPOTENT_REQUEST_MISMATCH"], + [422, "IDEMPOTENCY_KEY_INVALID"], + ] as const)("reads a table code under another status (%i %s) as maybe applied", (status, code) => { + expect(envelopeFailureEffect(status, { code })).toBe("MAYBE_APPLIED"); + expect(idempotencyRefusalReason(code, status)).toBeUndefined(); + }); + + it.each([ + [400, "BAD_PARAMETER"], + [409, "IDEMPOTENT_IN_FLIGHT"], + [409, "RESOURCE_CONFLICT"], + // A 422 outside the table stays with the backend's verdict, never with a + // package that reads every 422 as refused (fileserver writes first). + [422, "INTEGRITY_MISMATCH"], + ] as const)("keeps %i %s, outside the table, maybe applied", (status, code) => { + expect(envelopeFailureEffect(status, { code })).toBe("MAYBE_APPLIED"); + }); + + it("leaves a status the table does not speak for to the package", () => { + expect(envelopeFailureEffect(404, { code: "NOT_FOUND" })).toBeUndefined(); + }); + + it.each([408, 425, 500, 502, 503, 504])( + "reads a gateway %i as a server failure, not a client one", + (status) => { + expect(envelopeFailureReading(status, { code: "GATEWAY_REFUSED" }).kind).toBe( + "SERVER_FAILURE", + ); + }, + ); +});