From 1fa5f3e23783232e0a725beab7b9036c060bf6df Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 00:49:58 +0900 Subject: [PATCH] =?UTF-8?q?fix(query)!:=20=EC=A0=9C=ED=92=88=20mutation=20?= =?UTF-8?q?=ED=9B=85=EC=9D=B4=20raw=20=EC=9E=85=EB=A0=A5=EC=9D=84=20?= =?UTF-8?q?=EB=B0=9B=EC=A7=80=20=EC=95=8A=EA=B2=8C=20=ED=95=9C=EB=8B=A4=20?= =?UTF-8?q?(1101/08-03)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: useApplicationMutation이 BoundMutation과 함께 raw LegacyMutationOptions({ execute, definitionId })도 공개 overload로 받는다. raw 쓰기는 intent가 없어 Idempotency-Key 없이 나가고, scope 세대 확인과 측정 profile을 건너뛴다. 결과 불명 뒤 resendUnknownEffect()는 null이라 샘플 폼을 복사하면 "같은 요청으로 다시 보내기"를 눌러도 아무 일이 없고 새 제출도 막힌다. tsc·eslint·depcruise 어느 것도 기능 코드의 raw 사용을 막지 않는다. 고른 방법(결정대로): - 공개 useApplicationMutation에서 raw overload를 뺀다. 남은 공개 시그니처는 BoundMutation 하나다. 런타임 LEGACY 분기는 그대로 둔다. - raw로 쓰인 테스트 24곳(3파일)은 tests/helpers/legacy-application- query-harness.ts의 useLegacyApplicationMutation으로 옮긴다. harness는 명시적 cast로만 그 분기에 닿는다. 단언은 한 줄도 바꾸지 않았다. - 타입 fixture: application-mutation-admission 테스트에 제품 훅에 raw 입력을 넘기는 @ts-expect-error를 둔다. raw overload가 돌아오면 tsconfig.test.json 검사가 TS2578로 실패한다. - raw query({ queryKey, execute })는 남긴다. 먼저 확인했다: raw query는 세션이 바뀐 뒤 이전 사용자의 결과를 보이지 않는다. FENCED에서 ServerStateScopeProvider가 하위 트리를 내리고, READY는 이전 QueryClient를 비우고 세대 key로 새 QueryClient를 붙인 뒤에 온다. 늦게 온 이전 응답은 버려진 client에 쓰인다. 이 동작을 server-state-generation-provider 테스트로 고정했고, 생성 저장소가 같은 client를 비우지 않고 다시 쓰게 바꾸면 이 테스트가 실패한다(변이 확인). 시그니처 JSDoc에 "scope·측정 profile 없이 도는 읽기 경로"와 provider 밖에서는 훅이 막지 않는다는 위험을 적었다. - typescript-state-and-data-flow.md 4.3의 raw 예시를 bound 정의로 바꾼다. 버린 대안: raw query까지 제거 — 다운스트림 memento의 raw query 12곳이 깨지는데 읽기는 다시 보내도 부작용이 없어 얻는 안전이 작다. 현상 유지 — 쓰기 경로의 중복 생성과 동작하지 않는 재전송이 남는다. 런타임 LEGACY 분기 제거 — legacy 전용 테스트 4건의 단언이 바뀌어 "같은 단언 유지"를 못 지킨다. 별도 tests/fixtures/typecheck + CI 명령 — package.json, gates.json, contract-baseline.json, 명령 수를 고정한 테스트까지 바꾸고 다른 수정과 baseline 해시가 충돌한다. 같은 tsc 검사를 기존 check:types:test 게이트가 돈다. 위험·한계: 공개 계약 변경(BREAKING). 런타임에는 raw 분기가 남아 cast로 여전히 닿는다(타입으로만 막음). LegacyMutationOptions 타입은 harness가 쓰도록 application-query.ts에서 export한다(배럴에는 없음). raw query는 ServerStateGenerationProvider 밖에서 쓰면 세션 보호가 없다. 검증: - RED: 원래 훅(raw overload 있음)으로 tsc -p tsconfig.test.json → "error TS2578: Unused '@ts-expect-error' directive." - GREEN: tsc app·test·node 통과. tests/component 35 files 229 tests 통과(옮긴 테스트 포함). tests/unit·component·features·contract· runtime-schema·architecture·scripts·integration(security-followup- archive 제외, pnpm 사용) 256 files 중 3 files 4 tests가 부하(load avg 32)에서 실패했고 세 파일을 3회 다시 돌려 모두 통과(78/78). eslint (바꾼 파일) 통과. - 다운스트림(읽기만): memento 10곳, tech-log 34곳 모두 bound. 깨지는 제품 호출 0곳. 두 repo의 tests/component 템플릿 소유 테스트 3파일은 raw 호출이 있어 harness와 함께 동기화해야 한다. BREAKING CHANGE: useApplicationMutation이 raw { execute, definitionId } 입력을 받지 않는다. BoundMutation(definitionId, definitionVersion, operationId, requiresIdempotencyKey, owner, duplicatePolicy, scope, invalidate, execute(input, { signal, intent }))을 넘긴다. scope는 useServerStateScope()에서 얻는다. Refs: docs/reviews/2026-11-01-maturity-review/08-presentation.md 08-03 --- .../typescript-state-and-data-flow.md | 18 +++- .../adapters/query/application-query.ts | 32 ++++++- .../application-mutation-admission.test.tsx | 28 +++++- ...ication-mutation-optimistic-cache.test.tsx | 16 ++-- tests/component/application-query.test.tsx | 29 +++--- .../server-state-generation-provider.test.tsx | 96 +++++++++++++++++++ .../legacy-application-query-harness.ts | 22 +++++ 7 files changed, 207 insertions(+), 34 deletions(-) create mode 100644 tests/helpers/legacy-application-query-harness.ts diff --git a/docs/architecture/typescript-state-and-data-flow.md b/docs/architecture/typescript-state-and-data-flow.md index 9e77d838..ae7df761 100644 --- a/docs/architecture/typescript-state-and-data-flow.md +++ b/docs/architecture/typescript-state-and-data-flow.md @@ -322,15 +322,29 @@ export function useResourcesQuery(input: ListResourcesInput) { ```ts export function useCreateResourceMutation() { const application = useApplication(); + const scope = useServerStateScope(); return useApplicationMutation({ - execute: (command: CreateResourceCommand) => - application.resources.create(command), + definitionId: "resource-create-v1", + definitionVersion: 1, + operationId: "CREATE_RESOURCE", + requiresIdempotencyKey: true, + owner: RESOURCE_FEATURE_ID, + duplicatePolicy: "REJECT_WHILE_ACTIVE", invalidate: [RESOURCE_INVALIDATION_TOPIC], + scope, + execute: (command: CreateResourceCommand, context) => + application.resources.create(command, context), }); } ``` +`useApplicationMutation`은 bound 정의(`BoundMutation`)만 받는다(1101/08-03). +`{ execute }`만 넘기는 raw 형태는 멱등 키와 scope 확인 없이 쓰기를 보내고 +결과 불명 뒤 "다시 보내기"가 아무것도 하지 않아 타입에서 막는다. 실제 정의는 +`src/features/reference-feature/presentation/use-reference-feature.ts`의 +`REFERENCE_CREATE_MUTATION_POLICY`를 본다. + 기본 mutation은 navigation만으로 취소됐다고 가정하지 않는다. 서버 작업의 취소가 안전한 operation만 controller가 보관한 `AbortController`와 명시적 cancel action을 사용한다. idempotency key는 UI 입력으로 받지 않고 application use case가 diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts index aa87347f..49ca0c1a 100644 --- a/src/presentation/adapters/query/application-query.ts +++ b/src/presentation/adapters/query/application-query.ts @@ -60,6 +60,19 @@ class ApplicationQueryError extends Error { } } +/** + * Prefer a `BoundQuery` (`bindQuery`). + * + * The raw `{ queryKey, execute }` form is a read path that runs without a + * scope and without a measurement profile: no generation check around + * `execute`, no result-size limit, default stale and gc times, and a key that + * carries no scope fingerprint. It does not show the previous session's answer + * only because `ServerStateGenerationProvider` unmounts it on FENCED and mounts + * it again on the next generation's empty QueryClient + * (`server-state-generation-provider.test.tsx`). Outside that provider nothing + * in this hook fences it. Kept for reads only (1101/08-03): a read can be sent + * again without side effects; a raw write cannot. + */ export function useApplicationQuery( options: | BoundQuery @@ -207,7 +220,12 @@ type LegacyMutationBase = Readonly<{ currentData?: unknown; }>; -type LegacyMutationOptions = LegacyMutationBase & +/** + * 1101/08-03. Raw mutation input: no scope, no intent, no `Idempotency-Key`, + * and `resendUnknownEffect()` resolves to `null`. `useApplicationMutation` + * rejects it; only the test harness passes it, by cast. + */ +export type LegacyMutationOptions = LegacyMutationBase & ( | Readonly<{ /** Stable logical identity required to retain an unknown effect across remounts. */ @@ -282,12 +300,18 @@ const LEGACY_OPTIMISTIC_SCOPE = Object.freeze({ isCurrent: () => true, }); +/** + * Takes a bound definition only (1101/08-03): the binding supplies the scope + * check, the intent and its `Idempotency-Key`, so a resend after an unknown + * result sends the same key. + */ export function useApplicationMutation( options: BoundMutation, ): ApplicationMutationController; -export function useApplicationMutation( - options: LegacyMutationOptions, -): ApplicationMutationController; +// 1101/08-03. The raw (LEGACY) shape below is no longer a public overload. The +// runtime branch stays so `tests/helpers/legacy-application-query-harness.ts` +// keeps its assertions; reaching it takes an explicit cast. Removing the +// branch changes those tests and is a separate step. export function useApplicationMutation( options: BoundMutation | LegacyMutationOptions, ): ApplicationMutationController { diff --git a/tests/component/application-mutation-admission.test.tsx b/tests/component/application-mutation-admission.test.tsx index d569e635..2ddfabfa 100644 --- a/tests/component/application-mutation-admission.test.tsx +++ b/tests/component/application-mutation-admission.test.tsx @@ -19,6 +19,7 @@ import { scopeSnapshot, wrapper, } from "./application-query-fixture.tsx"; +import { useLegacyApplicationMutation } from "../helpers/legacy-application-query-harness.ts"; describe("application mutation intent admission", () => { it("retains optimistic data when execute throws after dispatch begins", async () => { @@ -27,7 +28,7 @@ describe("application mutation intent admission", () => { client.setQueryData(key, ["base"]); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ execute: async () => { throw new Error("private transport defect"); }, @@ -232,7 +233,7 @@ describe("application mutation intent admission", () => { })); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ definitionId: "legacy-raw-path-v1", execute, }), @@ -245,6 +246,23 @@ describe("application mutation intent admission", () => { expect(createIntent).not.toHaveBeenCalled(); }); + // 1101/08-03. Type fixture, checked by `tsc -p tsconfig.test.json`: if the + // product hook takes a raw executor again, the directive below is unused + // (TS2578) and the type check fails. Only the harness reaches that path. + it("rejects a raw executor on the product hook at compile time", () => { + const raw = { + definitionId: "raw-product-call-v1", + execute: async (input: string) => ({ ok: true as const, value: input }), + }; + const useRawProductMutation = () => + useApplicationMutation( + // @ts-expect-error a raw executor is not a BoundMutation. + raw, + ); + + expect(useRawProductMutation).toBeTypeOf("function"); + }); + it("rejects a duplicate submit by default while one is active", async () => { const client = queryClient(); let complete: (value: ApplicationResult) => void = () => {}; @@ -256,7 +274,7 @@ describe("application mutation intent admission", () => { ); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ definitionId: "legacy-duplicate-rejection-v1", execute, }), @@ -294,7 +312,7 @@ describe("application mutation intent admission", () => { ); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ // §11.2: joining is opt-in. The default is REJECT_WHILE_ACTIVE. duplicatePolicy: "JOIN_IDENTICAL", execute, @@ -349,7 +367,7 @@ describe("application mutation intent admission", () => { ); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ definitionId: "legacy-parallel-distinct-inputs-v1", execute, currentData: true, diff --git a/tests/component/application-mutation-optimistic-cache.test.tsx b/tests/component/application-mutation-optimistic-cache.test.tsx index eca908bd..1d2297ca 100644 --- a/tests/component/application-mutation-optimistic-cache.test.tsx +++ b/tests/component/application-mutation-optimistic-cache.test.tsx @@ -3,16 +3,14 @@ import { act, renderHook } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; -import { - type ApplicationResult, - useApplicationMutation, -} from "../../src/presentation/adapters/query/application-query.ts"; +import type { ApplicationResult } from "../../src/presentation/adapters/query/application-query.ts"; import { createFailure } from "../../src/contracts/errors.ts"; import { RESOURCE_INVALIDATION_TOPIC, queryClient, wrapper, } from "./application-query-fixture.tsx"; +import { useLegacyApplicationMutation } from "../helpers/legacy-application-query-harness.ts"; describe("application mutation optimistic cache lifecycle", () => { it("cancels an in-flight query before taking the optimistic snapshot", async () => { @@ -37,7 +35,7 @@ describe("application mutation optimistic cache lifecycle", () => { })); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ execute, currentData: ["existing"], optimistic: { queryKey: key, update }, @@ -76,7 +74,7 @@ describe("application mutation optimistic cache lifecycle", () => { ); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ execute: async () => ({ ok: true, value: "created" }), invalidate: [RESOURCE_INVALIDATION_TOPIC], currentData: ["existing"], @@ -110,7 +108,7 @@ describe("application mutation optimistic cache lifecycle", () => { })); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ execute, currentData: ["existing"], optimistic: { @@ -150,7 +148,7 @@ describe("application mutation optimistic cache lifecycle", () => { }); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ execute: async () => ({ ok: false, error: failure }), currentData: true, optimistic: { @@ -180,7 +178,7 @@ describe("application mutation optimistic cache lifecycle", () => { }); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ execute: async () => ({ ok: false, error: conflict }), invalidate: [RESOURCE_INVALIDATION_TOPIC], currentData: client.getQueryData(key), diff --git a/tests/component/application-query.test.tsx b/tests/component/application-query.test.tsx index e32e8ed0..41e88027 100644 --- a/tests/component/application-query.test.tsx +++ b/tests/component/application-query.test.tsx @@ -16,6 +16,7 @@ import { scopeSnapshot, wrapper, } from "./application-query-fixture.tsx"; +import { useLegacyApplicationMutation } from "../helpers/legacy-application-query-harness.ts"; describe("application mutation reconciliation bridge", () => { it.each([ @@ -40,7 +41,7 @@ describe("application mutation reconciliation bridge", () => { }); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ execute: async () => ({ ok: false, error: failure }), invalidate: [RESOURCE_INVALIDATION_TOPIC], currentData: client.getQueryData(key), @@ -102,7 +103,7 @@ describe("application mutation reconciliation bridge", () => { }); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ definitionId: "legacy-applied-invalidation-failure-v1", execute: async () => ({ ok: false, error: failure }), invalidate: [RESOURCE_INVALIDATION_TOPIC], @@ -144,7 +145,7 @@ describe("application mutation reconciliation bridge", () => { const execute = vi.fn(async () => ({ ok: false as const, error: failure })); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ execute, invalidate: [RESOURCE_INVALIDATION_TOPIC], currentData: client.getQueryData(key), @@ -353,7 +354,7 @@ describe("application mutation reconciliation bridge", () => { }); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ definitionId: "legacy-no-layer-reconcile-v1", execute: async () => ({ ok: false, error: failure }), invalidate: [RESOURCE_INVALIDATION_TOPIC], @@ -388,7 +389,7 @@ describe("application mutation reconciliation bridge", () => { ); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ definitionId: "legacy-active-after-unknown-v1", duplicatePolicy: "ALLOW_PARALLEL", execute, @@ -442,7 +443,7 @@ describe("application mutation reconciliation bridge", () => { ); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ definitionId: "legacy-active-after-unknown-no-layer-v1", duplicatePolicy: "ALLOW_PARALLEL", execute, @@ -483,7 +484,7 @@ describe("application mutation reconciliation bridge", () => { ); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ definitionId: "legacy-applied-double-action-v1", duplicatePolicy: "ALLOW_PARALLEL", execute: async () => ({ ok: false, error: failure }), @@ -527,7 +528,7 @@ describe("application mutation reconciliation bridge", () => { }); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ definitionId: "legacy-not-applied-double-action-v1", duplicatePolicy: "ALLOW_PARALLEL", execute: async () => ({ ok: false, error: failure }), @@ -678,7 +679,7 @@ describe("application mutation reconciliation bridge", () => { execute: vi.fn(async () => ({ ok: false as const, error: failure })), }; const first = renderHook( - () => useApplicationMutation(mutationOptions), + () => useLegacyApplicationMutation(mutationOptions), { wrapper: wrapper(client) }, ); @@ -689,7 +690,7 @@ describe("application mutation reconciliation bridge", () => { first.unmount(); const remounted = renderHook( - () => useApplicationMutation(mutationOptions), + () => useLegacyApplicationMutation(mutationOptions), { wrapper: wrapper(client) }, ); expect(remounted.result.current.state.indicator).toBe( @@ -824,7 +825,7 @@ describe("application mutation reconciliation bridge", () => { }); const first = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ definitionId: "legacy-isolation-first-v1", execute: async () => ({ ok: false, error: failure }), }), @@ -832,7 +833,7 @@ describe("application mutation reconciliation bridge", () => { ); const second = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ definitionId: "legacy-isolation-second-v1", execute: async (input) => ({ ok: true, value: input }), }), @@ -1021,7 +1022,7 @@ describe("application mutation reconciliation bridge", () => { >(); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ duplicatePolicy: "ALLOW_PARALLEL", execute: (input) => new Promise((resolve) => { @@ -1132,7 +1133,7 @@ describe("application mutation reconciliation bridge", () => { }); const hook = renderHook( () => - useApplicationMutation({ + useLegacyApplicationMutation({ execute: async () => ({ ok: false, error: conflict }), currentData: client.getQueryData(key), optimistic: { diff --git a/tests/component/server-state-generation-provider.test.tsx b/tests/component/server-state-generation-provider.test.tsx index 4b198f65..f966dba7 100644 --- a/tests/component/server-state-generation-provider.test.tsx +++ b/tests/component/server-state-generation-provider.test.tsx @@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest"; import { createServerStateScopeRuntime } from "../../src/adapters/query-cache/server-state-scope-runtime.ts"; import { createServerStateGenerationStore } from "../../src/bootstrap/server-state-generation-store.ts"; +import { useApplicationQuery } from "../../src/presentation/adapters/query/application-query.ts"; import { ServerStateGenerationProvider } from "../../src/presentation/adapters/query/server-state-generation-provider.tsx"; describe("server-state generation provider", () => { @@ -77,4 +78,99 @@ describe("server-state generation provider", () => { scope.dispose(); store.dispose(); }); + + // 1101/08-03. A raw query has no scope check of its own. It still never + // shows the previous identity's answer: FENCED unmounts it, and READY + // mounts it again on the next generation's empty QueryClient. + it("never shows a raw query's previous-session answer after a session change", async () => { + const { store, scope, notifySession } = generationRuntime(); + const answers: ((value: string) => void)[] = []; + function RawProbe() { + const query = useApplicationQuery({ + queryKey: ["raw-profile"], + execute: () => + new Promise((resolve) => { + answers.push((value) => resolve({ ok: true, value })); + }), + }); + return
{query.data ?? "no-data"}
; + } + const view = render( + scope-transition} + > + + , + ); + + // Signed in as the first user: the answer is cached and shown. + await waitFor(() => expect(answers).toHaveLength(1)); + act(() => answers[0]?.("first-user-cached")); + expect(await view.findByText("first-user-cached")).toBeVisible(); + + // A refetch starts, then the session changes before it answers. + act(() => { + void store.getSnapshot().queryClient.refetchQueries(); + }); + await waitFor(() => expect(answers).toHaveLength(2)); + act(() => notifySession()); + await waitFor(() => expect(scope.getPhase()).toBe("READY")); + await waitFor(() => expect(answers).toHaveLength(3)); + + // The first user's late answer arrives while the next one is loading. + act(() => answers[1]?.("first-user-late")); + expect(await view.findByText("no-data")).toBeVisible(); + expect(view.container).not.toHaveTextContent("first-user"); + + act(() => answers[2]?.("second-user")); + expect(await view.findByText("second-user")).toBeVisible(); + + scope.dispose(); + store.dispose(); + }); }); + +const unusedMutationIntentFactory = Object.freeze({ + create(): never { + throw new Error("mutation intent is unused by this provider test"); + }, +}); + +function generationRuntime() { + const store = createServerStateGenerationStore(() => { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + }); + return { + queryClient, + queryInvalidation: { + invalidate: async () => {}, + beginMutation: () => ({ release: async () => {} }), + resetLocal: async () => { + await queryClient.cancelQueries(); + queryClient.clear(); + }, + dispose() {}, + }, + crossContextStatus: () => "DEGRADED_LOCAL_ONLY" as const, + }; + }); + let sessionListener: () => void = () => {}; + let token = 0; + const scope = createServerStateScopeRuntime({ + session: { + subscribe(listener) { + sessionListener = listener; + return () => {}; + }, + }, + queryInvalidation: { resetLocal: () => store.resetCurrent() }, + activateNextGeneration: () => store.activateNext(), + tokenFactory: () => + `scope-generation-raw-${String(token++).padStart(4, "0")}`, + }); + return { store, scope, notifySession: () => sessionListener() }; +} diff --git a/tests/helpers/legacy-application-query-harness.ts b/tests/helpers/legacy-application-query-harness.ts new file mode 100644 index 00000000..64a9283d --- /dev/null +++ b/tests/helpers/legacy-application-query-harness.ts @@ -0,0 +1,22 @@ +import type { BoundMutation } from "../../src/contracts/server-state.ts"; +import { + type LegacyMutationOptions, + useApplicationMutation, +} from "../../src/presentation/adapters/query/application-query.ts"; + +/** + * 1101/08-03. Test-only door to the raw (LEGACY) mutation path. + * + * The product hook takes a bound definition only. Its runtime still has the + * raw branch, so the tests that pin that branch run it through this cast. A + * raw write sends no Idempotency-Key and its resend resolves to `null`; no + * product code may reach it ("rejects a raw executor on the product hook at + * compile time" in `tests/component/application-mutation-admission.test.tsx`). + */ +export function useLegacyApplicationMutation( + options: LegacyMutationOptions, +) { + return useApplicationMutation( + options as unknown as BoundMutation, + ); +}