From 5c0b37e39e1368be4d3451fbb5592dcb265f64c5 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:15:20 +0900 Subject: [PATCH] =?UTF-8?q?fix(contracts)!:=20=EC=93=B0=EA=B8=B0=20?= =?UTF-8?q?=EB=92=A4=EC=97=90=EB=8F=84=20=EB=82=98=EC=98=A4=EB=8A=94=20?= =?UTF-8?q?=ED=94=8C=EB=9E=AB=ED=8F=BC=20code=EB=A5=BC=20=EC=93=B0?= =?UTF-8?q?=EA=B8=B0=20=EC=A0=84=20=EA=B1=B0=EC=A0=88=EB=A1=9C=20=EC=A0=81?= =?UTF-8?q?=EC=A7=80=20=EB=AA=BB=ED=95=98=EA=B2=8C=20=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 commandEffect.refusedBeforeWrite의 조립 검사는 code 문법, 멱등성 접두사, 중복, Envelope 여부만 본다. 계약 문서 6.1절은 BAD_PARAMETER(어느 층이든 IllegalArgumentException), MAPPING_FAILED(멱등성 응답 직렬화는 action 뒤), DB_* 8개, LOCK_ACQUISITION_TIMEOUT, fileserver code를 "쓰기 뒤 가능"으로 적는다. 이 code를 목록에 적어도 조립이 통과하고, 그 code로 온 400·409·422가 NOT_APPLIED가 된다. 쓰기 뒤에 난 실패를 사용자가 다시 저장하면 새 키나 키 없는 새 요청이 나가 같은 항목이 둘 생길 수 있다(리뷰 실험 X2: 네 code가 조립을 통과하고 모두 NOT_APPLIED). 고른 방법 6.1절의 "쓰기 뒤 가능" 플랫폼 code를 src/contracts/external-contract-runtime.ts에 PLATFORM_CODES_POSSIBLY_AFTER_WRITE로 두고, assertRefusedBeforeWrite가 그 code의 선언을 6.1절을 이유로 거절한다. 실행기의 fail-close(조립 없이 부른 경우)도 같은 목록을 무시한다. 목록을 adapters가 아니라 contracts에 둔 것은 조립 검사가 adapters를 import할 수 없기 때문이다(리뷰 문서의 최소 개선은 backend-envelope.ts에 두라고 했다). backend-contract-pin.test.ts가 계약 문서 6.1절 표의 "쓰기 뒤 가능" 행을 읽어 목록과 양방향으로 대조한다. 참조 도메인 code와 web-advanced patch code는 엔드포인트가 단계를 정하므로 테스트의 예외 목록에 적고 선언할 수 있게 둔다. 버린 대안 - 매뉴얼 문장만 둔다(현상 유지): 폼을 막는 code를 넣고 싶어지는 바로 그 자리에 통제가 없다. - 업무 code 접두사 규칙(_로 시작하는 code만 허용): 다운스트림 code 이름을 강제해 과하다. 위험·한계 - 이미 이 code를 적은 다운스트림 계약은 부팅에서 조립이 실패한다. 의도한 실패다. - 6.1절 표에 플랫폼 code가 더해지면 목록도 같이 고쳐야 한다. 대조 테스트가 알린다. 백엔드가 code를 더한 것은 pin을 올릴 때 6.1절을 다시 읽어야 안다. - 업무 code를 잘못 선언하는 것은 여전히 막지 못한다(기능 작성자의 판단). - 대조 테스트는 계약 문서를 읽으므로, 문서를 복사하지 않는 기능 제거 드릴(FE-GATE-020의 optional-recipe·browser-file-storage·realtime)에서는 돌지 않는다. `scripts/lib/removal-fixture.ts`의 문서 테스트 목록에 `tests/unit/backend-contract-pin.test.ts`를 더했다. 저장소 자신의 test:unit은 그대로 돌린다. 검증 desktop batch에서 확인: node scripts/run-vitest.ts run tests/unit/external-contract-runtime.test.ts tests/unit/backend-envelope.test.ts tests/unit/backend-contract-pin.test.ts corepack pnpm test:optional-recipe-removal BREAKING CHANGE: refusedBeforeWrite에 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(PLATFORM_CODES_POSSIBLY_AFTER_WRITE)를 적으면 composeContractContributions가 거절한다. 그 code를 목록에서 지운다. 그 code의 실패는 결과 불명으로 남는다. Refs: 1105/03-01 --- .../backend-api-and-server-state-contract.md | 7 +++ docs/manual/02-decision-tables.md | 1 + docs/manual/reference/errors.md | 1 + scripts/lib/removal-fixture.ts | 2 + src/adapters/http/backend-envelope.ts | 5 +- src/contracts/external-contract-runtime.ts | 48 +++++++++++++++++- tests/unit/backend-contract-pin.test.ts | 50 +++++++++++++++++++ tests/unit/backend-envelope.test.ts | 13 +++++ tests/unit/external-contract-runtime.test.ts | 12 +++++ 9 files changed, 137 insertions(+), 2 deletions(-) diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index 2e2fe977..b3a57096 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -343,6 +343,13 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐 - 위 표의 code(`VALIDATION_FAILED` 등)는 적어도 표의 status 규칙을 따른다. `IDEMPOTENT_*`·`IDEMPOTENCY_*`는 적을 수 없다. 계약 조립이 거절하고, 실행기도 무시한다. 409 `IDEMPOTENT_IN_FLIGHT`의 앞선 요청은 적용될 수 있기 때문이다. +- 위 표에서 "쓰기 뒤 가능"인 플랫폼 code(`BAD_PARAMETER`, `MAPPING_FAILED`, `DB_*` 8개, + `LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다(1105/03-01). 계약 조립이 + 거절하고 실행기도 무시한다. 목록은 `src/contracts/external-contract-runtime.ts`의 + `PLATFORM_CODES_POSSIBLY_AFTER_WRITE`이고, `tests/unit/backend-contract-pin.test.ts`가 + 이 표의 "쓰기 뒤 가능" 행과 대조한다. 참조 도메인 code와 web-advanced patch code는 + 엔드포인트가 단계를 정하므로 그 엔드포인트를 확인한 기능 작성자가 적을 수 있다. 이 표에 + "쓰기 뒤 가능" 플랫폼 code를 더하면 그 목록도 같은 변경에서 고친다. - `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에는 적을 수 없다. 실행기가 백엔드 code를 읽지 않는다. - 판정은 `src/adapters/http/backend-envelope.ts` `envelopeFailureEffect`, 조립 검사는 diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index e36381f1..55c30c46 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -182,6 +182,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 - 짝 백엔드 `new-feature.sh`가 만든 create는 이름을 트랜잭션 전에 검사하고 400 `_INVALID`를 준다(백엔드 `Create__Feature__UseCase.java.tmpl`). 이 code는 적는다. 예: 기능 `worklog`이면 `refusedBeforeWrite: ["WORKLOG_INVALID"]`. - 고르는 기준: 백엔드 코드에서 그 code를 던지는 곳이 모두 쓰기(트랜잭션, 외부 호출) 전인지 확인했을 때만 적는다. 확인하지 못했으면 적지 않는다. 쓰기 뒤에도 나오는 code를 적으면 결과 불명 요청을 새 키로 다시 보내 중복이 생길 수 있다. - 적을 수 없는 code: `IDEMPOTENT_*`, `IDEMPOTENCY_*`. 멱등성 응답은 백엔드 표가 정한다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...`로 거부한다. `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에 적어도 거부한다(`refusedBeforeWrite needs responseEnvelope ENVELOPE_V1 ...`). + - 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(`BAD_PARAMETER`, `MAPPING_FAILED`, `DB_UNIQUE_VIOLATION` 등 `DB_*`, `LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다. 폼을 막는 400 `BAD_PARAMETER`나 409 `DB_UNIQUE_VIOLATION`은 어느 층에서든, 트랜잭션 안에서도 나온다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...; contract 6.1 reads this platform code as possibly raised after the write`로 거부한다. - 거절 이유를 필드 옆에 보이려면 `mapProblem`이 그 code를 `VALIDATION_REJECTED`와 필드 목록으로 돌려준다. 선언 없이 `mapProblem`만 두면 필드 오류는 보이지만 저장 버튼은 꺼진 채다. **503 `IDEMPOTENCY_UNAVAILABLE`는 `NOT_APPLIED`로 분류하지 않는다.** diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index 5ba0d59e..39d28c98 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -103,6 +103,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `/: KEYED commands require a recovery descriptor` | `KEYED`인데 `commandRecovery`가 없다 | V3 `commandRecovery` | | `/: is a read; its retrySemantics is SAFE or IDEMPOTENT, not <값>` | 읽기에 `KEYED`나 `NEVER`를 적었다 | V3 `retrySemantics`. 재시도를 막으려면 `frontend.retryBudget: 0` | | `/: command operations require a command effect descriptor` | 쓰기에 `commandEffect`가 없다 | V3 `commandEffect` | +| `/: refusedBeforeWrite cannot declare ; contract 6.1 reads this platform code as possibly raised after the write` | `commandEffect.refusedBeforeWrite`에 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(`BAD_PARAMETER`, `DB_*` 등)를 적었다 | 그 code를 목록에서 지운다. 그 실패는 결과 불명으로 남는다([02 결정표 4절](../02-decision-tables.md#4-결과-불명)) | | `/: read operations carry no command descriptors` | GET에 `commandEffect`·`commandRecovery`를 적었다 | 둘 다 `null` | | `/: responseEnvelope NONE, but in the same contribution reads ENVELOPE_V1; ...` | 한 계약 기여 안에서 operation 하나만 응답 모양이 다르다. 손으로 더한 operation에 `responseEnvelope` 줄을 빠뜨린 경우다 | 그 operation에 `responseEnvelope: "ENVELOPE_V1" as const`를 적는다. 정말 다른 백엔드면 기여를 나눈다 | | `: package version must be exact SemVer` | 버전 범위(`^1.2.0`)나 형식 오류 | `_CONTRACT_PACKAGE.version` | diff --git a/scripts/lib/removal-fixture.ts b/scripts/lib/removal-fixture.ts index efbbf9b3..9aa9bc80 100644 --- a/scripts/lib/removal-fixture.ts +++ b/scripts/lib/removal-fixture.ts @@ -70,6 +70,8 @@ export const REMOVAL_FIXTURE_DOCUMENT_TARGETS = Object.freeze([ export const REMOVAL_FIXTURE_DOCUMENT_TESTS = Object.freeze([ "tests/unit/changelog-review-ids.test.ts", "tests/unit/documentation-readiness.test.ts", + // 1105/03-01. Reads the 6.1 table of the frontend contract document. + "tests/unit/backend-contract-pin.test.ts", ] as const); /** The tests a fixture copied from `copyTargets` cannot run. */ diff --git a/src/adapters/http/backend-envelope.ts b/src/adapters/http/backend-envelope.ts index b959cb40..7d9d28f8 100644 --- a/src/adapters/http/backend-envelope.ts +++ b/src/adapters/http/backend-envelope.ts @@ -4,6 +4,7 @@ import { type FailureKind, type ValidationIssue, } from "../../contracts/errors.ts"; +import { PLATFORM_CODES_POSSIBLY_AFTER_WRITE } from "../../contracts/external-contract-runtime.ts"; import { z } from "../../contracts/zod.ts"; /** @@ -312,7 +313,8 @@ export function unknownEffectReason( * (`commandEffect.refusedBeforeWrite`). Composition already refuses an * idempotency code in that list; this is the runtime's own fail-close for an * executor called without composition. The table's own codes keep its status - * rule. + * rule. 1105/03-01. So do the platform codes contract 6.1 reads as possibly + * raised after the write. */ function declaredBeforeWrite( code: string, @@ -322,6 +324,7 @@ function declaredBeforeWrite( declared !== undefined && !Object.hasOwn(REFUSED_BEFORE_WRITE, code) && !/^IDEMPOTEN(?:T|CY)_/.test(code) && + !PLATFORM_CODES_POSSIBLY_AFTER_WRITE.includes(code) && declared.includes(code) ); } diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index f89f2e18..77327a9a 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -166,7 +166,10 @@ export interface CommandEffectDescriptor { * carries one of these codes is `NOT_APPLIED`, so the next save takes a new * key. Every code not listed stays `MAYBE_APPLIED`. Idempotency codes * (`IDEMPOTENT_*`, `IDEMPOTENCY_*`) are the backend table's to decide, and - * composition refuses them here. Composition installs a copy of the list. + * composition refuses them here, as it refuses the platform codes contract + * 6.1 reads as possibly after the write (1105/03-01, + * `PLATFORM_CODES_POSSIBLY_AFTER_WRITE`). Composition installs a copy of + * the list. */ readonly refusedBeforeWrite?: readonly string[]; } @@ -613,6 +616,44 @@ const BACKEND_ERROR_CODE = /^[A-Z0-9_]{1,64}$/; */ const IDEMPOTENCY_CODE = /^IDEMPOTEN(?:T|CY)_/; +/** + * 1105/03-01. The paired backend's platform codes that contract 6.1 + * (docs/architecture/backend-api-and-server-state-contract.md) reads as + * possibly raised after the write: `IllegalArgumentException` from any layer, + * the mappers (the idempotency response codec runs after the action), the + * persistence adapter's SQL and JPA failures, the distributed lock and the + * fileserver module. Their stage is the template's knowledge, not the + * feature's, so no operation may declare them as refused before its write. + * Business codes stay the feature author's to declare. + * tests/unit/backend-contract-pin.test.ts holds this list to the 6.1 table. + */ +export const PLATFORM_CODES_POSSIBLY_AFTER_WRITE: readonly string[] = + Object.freeze([ + "BAD_PARAMETER", + "MAPPING_FAILED", + "DB_SERIALIZATION_FAILURE", + "DB_DEADLOCK", + "DB_LOCK_TIMEOUT", + "DB_NULL_VIOLATION", + "DB_FK_VIOLATION", + "DB_UNIQUE_VIOLATION", + "DB_CHECK_VIOLATION", + "DB_OPTIMISTIC_CONFLICT", + "LOCK_ACQUISITION_TIMEOUT", + "BAD_REQUEST", + "FILE_ALREADY_EXISTS", + "FILE_NOT_READY", + "UPLOAD_OFFSET_MISMATCH", + "CONCURRENT_MODIFICATION", + "INTEGRITY_MISMATCH", + "MALWARE_DETECTED", + "INVALID_PATH", + "PATH_OUTSIDE_NAMESPACE", + ]); +const PLATFORM_CODE_AFTER_WRITE: ReadonlySet = new Set( + PLATFORM_CODES_POSSIBLY_AFTER_WRITE, +); + function assertRefusedBeforeWrite( contract: InstalledHttpContract["contract"], label: string, @@ -639,6 +680,11 @@ function assertRefusedBeforeWrite( `${label}: refusedBeforeWrite cannot declare ${code}; the backend's idempotency answers are decided by its own table`, ); } + if (PLATFORM_CODE_AFTER_WRITE.has(code)) { + fail( + `${label}: refusedBeforeWrite cannot declare ${code}; contract 6.1 reads this platform code as possibly raised after the write`, + ); + } if (seen.has(code)) fail(`${label}: refusedBeforeWrite repeats ${code}`); seen.add(code); } diff --git a/tests/unit/backend-contract-pin.test.ts b/tests/unit/backend-contract-pin.test.ts index 7bd9051b..df4f0983 100644 --- a/tests/unit/backend-contract-pin.test.ts +++ b/tests/unit/backend-contract-pin.test.ts @@ -9,6 +9,7 @@ import { maybeAppliedAnswerRows, refusedBeforeWriteRows, } from "../../src/adapters/http/backend-envelope.ts"; +import { PLATFORM_CODES_POSSIBLY_AFTER_WRITE } from "../../src/contracts/external-contract-runtime.ts"; /** * 1103/12-06. The paired backend's contract is pinned in a file a machine @@ -141,3 +142,52 @@ describe("paired backend contract pin", () => { } }); }); + +/** + * 1105/03-01. The codes of the contract 6.1 table rows whose stage is "쓰기 뒤 + * 가능" (possibly after the write), read from the document the pin names + * (docs/architecture/backend-api-and-server-state-contract.md). Because this + * file reads that document, the removal drills that copy no documents leave + * it out (REMOVAL_FIXTURE_DOCUMENT_TESTS in scripts/lib/removal-fixture.ts). + */ +function codesPossiblyAfterWrite(): ReadonlySet { + const text = readFileSync(pin.frontend.contractDocument, "utf8"); + const section = text.split("### 6.1 ")[1]?.split(/\n#{2,3} /u)[0] ?? ""; + const codes = new Set(); + for (const line of section.split("\n")) { + const cells = line.split("|").map((cell) => cell.trim()); + if (!line.startsWith("|") || cells[3] !== "쓰기 뒤 가능") continue; + for (const [, code = ""] of (cells[1] ?? "").matchAll(/`([A-Z0-9_]+)`/gu)) { + codes.add(code); + } + } + return codes; +} + +/** + * Rows of that table whose stage the endpoint decides: the reference domain's + * codes and web-advanced's patch codes ("부르는 코드가 단계를 정한다"). A + * feature author who checked the endpoint may declare them. + */ +const FEATURE_DECIDED_CODES: readonly string[] = [ + "WORKLOG_INVALID", + "POSTER_INVALID_STATE", + "POSTER_IMAGE_REQUIRED", + "WORKLOG_CONFLICT", + "POSTER_ALREADY_EXISTS", + "POSTER_IMAGE_ALREADY_PUBLISHED", + "PATCH_REJECTED", + "PATCH_TEST_FAILED", +]; + +describe("platform codes no operation may declare as refused before its write", () => { + it("are the 6.1 table's possibly-after-write codes outside the feature-decided rows", () => { + const table61 = codesPossiblyAfterWrite(); + for (const code of FEATURE_DECIDED_CODES) { + expect(table61.has(code), code).toBe(true); + } + expect([...PLATFORM_CODES_POSSIBLY_AFTER_WRITE].sort()).toEqual( + [...table61].filter((code) => !FEATURE_DECIDED_CODES.includes(code)).sort(), + ); + }); +}); diff --git a/tests/unit/backend-envelope.test.ts b/tests/unit/backend-envelope.test.ts index 36695dbc..6e2f6344 100644 --- a/tests/unit/backend-envelope.test.ts +++ b/tests/unit/backend-envelope.test.ts @@ -101,6 +101,19 @@ describe("backend Envelope failure table", () => { ); }); + // 1105/03-01. The runtime's own fail-close for an executor called without + // composition: a platform code 6.1 reads as possibly after the write + // stays maybe applied, declared or not. + it.each([ + [400, "BAD_PARAMETER"], + [400, "MAPPING_FAILED"], + [409, "DB_UNIQUE_VIOLATION"], + [409, "LOCK_ACQUISITION_TIMEOUT"], + [422, "INTEGRITY_MISMATCH"], + ] as const)("keeps a declared platform code %i %s maybe applied", (status, code) => { + expect(envelopeFailureEffect(status, { code }, [code])).toBe("MAYBE_APPLIED"); + }); + it("does not reach statuses outside 400, 409 and 422", () => { expect(envelopeFailureEffect(500, { code: "WORKLOG_INVALID" }, declared)).toBeUndefined(); expect(envelopeFailureEffect(503, { code: "REQUEST_TIMEOUT" }, ["REQUEST_TIMEOUT"])).toBe( diff --git a/tests/unit/external-contract-runtime.test.ts b/tests/unit/external-contract-runtime.test.ts index 564be7e6..cfcaf99d 100644 --- a/tests/unit/external-contract-runtime.test.ts +++ b/tests/unit/external-contract-runtime.test.ts @@ -283,6 +283,18 @@ describe("declared pre-write refusals", () => { ); }); + // 1105/03-01. Contract 6.1 reads these platform codes as possibly raised + // after the write. Declared, a 400 or 409 that came after a write would read + // as not applied and the next save would be a new request. + it.each(["BAD_PARAMETER", "MAPPING_FAILED", "DB_UNIQUE_VIOLATION", "LOCK_ACQUISITION_TIMEOUT"])( + "refuses to declare the platform code %s, which 6.1 reads as possibly after the write", + (code) => { + expect(reasonFor(["TEST_ENTITY_INVALID", code])).toBe( + `test-feature/TEST_CREATE_ENTITY: refusedBeforeWrite cannot declare ${code}; contract 6.1 reads this platform code as possibly raised after the write`, + ); + }, + ); + it("refuses a list on an operation that does not read the Envelope", () => { expect(reasonFor(["TEST_ENTITY_INVALID"], "NONE")).toBe( "test-feature/TEST_CREATE_ENTITY: refusedBeforeWrite needs responseEnvelope ENVELOPE_V1; without it classifyProblem decides",