Files
clean-architecture-frontend…/tests/component/application-query.test.tsx
T
DongHyeonka 1fa5f3e237 fix(query)!: 제품 mutation 훅이 raw 입력을 받지 않게 한다 (1101/08-03)
문제: 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
2026-11-03 00:53:16 +09:00

1171 lines
39 KiB
TypeScript

// @vitest-environment jsdom
import { act, renderHook, waitFor } from "@testing-library/react";
import { renderToString } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
import {
type ApplicationResult,
useApplicationMutation,
} from "../../src/presentation/adapters/query/application-query.ts";
import { createFailure } from "../../src/contracts/errors.ts";
import { MUTATION_COORDINATOR_BOUNDS } from "../../src/contracts/server-state.ts";
import {
RESOURCE_INVALIDATION_TOPIC,
queryClient,
scopeSnapshot,
wrapper,
} from "./application-query-fixture.tsx";
import { useLegacyApplicationMutation } from "../helpers/legacy-application-query-harness.ts";
describe("application mutation reconciliation bridge", () => {
it.each([
["NOT_STARTED", ["existing"], 0, null],
["NOT_APPLIED", ["existing"], 0, null],
["APPLIED_CONFIRMED", ["existing", "created"], 1, null],
[
"MAYBE_APPLIED",
["existing", "created"],
0,
"mutation-effect-unknown",
],
] as const)(
"settles an optimistic failure with %s certainty",
async (effect, expectedData, expectedInvalidations, expectedIndicator) => {
const client = queryClient();
const key = ["resource", `certainty-${effect}`];
client.setQueryData(key, ["existing"]);
const invalidateQueries = vi.spyOn(client, "invalidateQueries");
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect,
});
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
execute: async () => ({ ok: false, error: failure }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let outcome: ApplicationResult<string> | undefined;
await act(async () => {
outcome = await hook.result.current.submit("created");
});
expect(outcome).toMatchObject({
ok: false,
error: { kind: failure.kind, effect },
});
expect(client.getQueryData(key)).toEqual([...expectedData]);
expect(invalidateQueries).toHaveBeenCalledTimes(expectedInvalidations);
expect(hook.result.current.state.indicator).toBe(expectedIndicator);
if (effect === "MAYBE_APPLIED") {
expect(outcome).toMatchObject({
ok: false,
error: { retryable: false, action: "contact-support" },
});
expect(hook.result.current.state.overlay).toMatchObject({
mutationEffectUnknown: true,
mutationPending: false,
mutationConflict: false,
});
}
if (effect === "APPLIED_CONFIRMED") {
expect(outcome).toMatchObject({
ok: false,
error: { retryable: false, action: "none" },
});
}
},
);
it("keeps an applied-confirmed layer committed when invalidation fails", async () => {
const client = queryClient();
const key = ["resource", "applied-invalidation-failure"];
client.setQueryData(key, ["base"]);
const invalidateQueries = vi
.spyOn(client, "invalidateQueries")
.mockImplementation(async () => {
expect(client.getQueryData(key)).toEqual(["base", "created"]);
throw new Error("refresh failed");
});
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "APPLIED_CONFIRMED",
});
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
definitionId: "legacy-applied-invalidation-failure-v1",
execute: async () => ({ ok: false, error: failure }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let outcome: ApplicationResult<string> | undefined;
await act(async () => {
outcome = await hook.result.current.submit("created");
});
expect(outcome).toMatchObject({
ok: false,
error: {
effect: "APPLIED_CONFIRMED",
retryable: false,
action: "none",
},
});
expect(invalidateQueries).toHaveBeenCalledOnce();
expect(client.getQueryData(key)).toEqual(["base", "created"]);
});
it("treats a command failure with missing effect certainty as maybe applied", async () => {
const client = queryClient();
const key = ["resource", "missing-effect"];
client.setQueryData(key, ["existing"]);
const invalidateQueries = vi.spyOn(client, "invalidateQueries");
const failure = createFailure("SERVER_FAILURE", "CREATE", 0);
const execute = vi.fn(async () => ({ ok: false as const, error: failure }));
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
execute,
invalidate: [RESOURCE_INVALIDATION_TOPIC],
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let outcome: ApplicationResult<string> | undefined;
await act(async () => {
outcome = await hook.result.current.submit("created");
});
expect(execute).toHaveBeenCalledOnce();
expect(outcome).toMatchObject({
ok: false,
error: {
effect: "MAYBE_APPLIED",
retryable: false,
action: "contact-support",
},
});
expect(client.getQueryData(key)).toEqual(["existing", "created"]);
expect(invalidateQueries).not.toHaveBeenCalled();
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
});
it.each([
["APPLIED", ["existing", "created"], 1],
["NOT_APPLIED", ["existing"], 0],
] as const)(
"reconciles an unknown optimistic effect as %s exactly once",
async (resolution, expectedData, expectedInvalidations) => {
const client = queryClient();
const scope = scopeSnapshot();
const key = ["resource", `reconcile-${resolution}`];
client.setQueryData(key, ["existing"]);
const invalidateQueries = vi.spyOn(client, "invalidateQueries");
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: `reconcile-${resolution}-v1`,
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
execute: async () => ({ ok: false, error: failure }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
await act(() => hook.result.current.submit("created"));
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() => hook.result.current.reconcileUnknownEffect(resolution));
await act(() =>
hook.result.current.reconcileUnknownEffect(
resolution === "APPLIED" ? "NOT_APPLIED" : "APPLIED",
),
);
expect(client.getQueryData(key)).toEqual([...expectedData]);
expect(invalidateQueries).toHaveBeenCalledTimes(expectedInvalidations);
expect(hook.result.current.state.indicator).toBeNull();
},
);
it("reconciles parallel unknown effects without losing either lease", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const key = ["resource", "parallel-unknown"];
client.setQueryData(key, ["base"]);
const invalidateQueries = vi.spyOn(client, "invalidateQueries");
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const resolvers: Array<(value: ApplicationResult<string>) => void> = [];
const execute = vi.fn(
(_input: string) =>
new Promise<ApplicationResult<string>>((resolve) => {
resolvers.push(resolve);
}),
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "parallel-unknown-v1",
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "ALLOW_PARALLEL",
scope,
execute,
invalidate: [RESOURCE_INVALIDATION_TOPIC],
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let first: Promise<ApplicationResult<string>> | undefined;
let second: Promise<ApplicationResult<string>> | undefined;
act(() => {
first = hook.result.current.submit("created");
second = hook.result.current.submit("created");
});
await waitFor(() => expect(resolvers).toHaveLength(2));
act(() => resolvers[0]?.({ ok: false, error: failure }));
if (!first) throw new Error("expected first mutation");
await act(() => first);
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
act(() => resolvers[1]?.({ ok: false, error: failure }));
if (!second) throw new Error("expected second mutation");
await act(() => second);
expect(client.getQueryData(key)).toEqual(["base", "created", "created"]);
await act(() => hook.result.current.reconcileUnknownEffect("NOT_APPLIED"));
expect(client.getQueryData(key)).toEqual(["base", "created"]);
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() => hook.result.current.reconcileUnknownEffect("APPLIED"));
expect(client.getQueryData(key)).toEqual(["base", "created"]);
expect(invalidateQueries).toHaveBeenCalledOnce();
expect(hook.result.current.state.indicator).toBeNull();
});
it("closes an unknown optimistic effect safely after scope expiry", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const key = ["resource", "expired-unknown"];
client.setQueryData(key, ["existing"]);
const invalidateQueries = vi.spyOn(client, "invalidateQueries");
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "expired-unknown-v1",
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
execute: async () => ({ ok: false, error: failure }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
await act(() => hook.result.current.submit("created"));
scope.fence();
await act(() => hook.result.current.reconcileUnknownEffect("APPLIED"));
expect(client.getQueryState(key)).toBeUndefined();
expect(invalidateQueries).not.toHaveBeenCalled();
expect(hook.result.current.state.indicator).toBeNull();
});
it("reconciles a legacy unknown effect without an optimistic layer", async () => {
const client = queryClient();
const invalidateQueries = vi.spyOn(client, "invalidateQueries");
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
definitionId: "legacy-no-layer-reconcile-v1",
execute: async () => ({ ok: false, error: failure }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
}),
{ wrapper: wrapper(client) },
);
await act(() => hook.result.current.submit("created"));
expect(invalidateQueries).not.toHaveBeenCalled();
await act(() => hook.result.current.reconcileUnknownEffect("APPLIED"));
expect(invalidateQueries).toHaveBeenCalledOnce();
expect(hook.result.current.state.indicator).toBeNull();
});
it("preserves a later legacy commit when an earlier unknown effect is not applied", async () => {
const client = queryClient();
const key = ["resource", "legacy-ordered-unknown"];
client.setQueryData(key, ["base"]);
const uncertainFailure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const resolvers = new Map<
string,
(value: ApplicationResult<string>) => void
>();
const execute = vi.fn(
(input: string) =>
new Promise<ApplicationResult<string>>((resolve) => {
resolvers.set(input, resolve);
}),
);
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
definitionId: "legacy-active-after-unknown-v1",
duplicatePolicy: "ALLOW_PARALLEL",
execute,
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let first: Promise<ApplicationResult<string>> | undefined;
let second: Promise<ApplicationResult<string>> | undefined;
act(() => {
first = hook.result.current.submit("first");
second = hook.result.current.submit("second");
});
await waitFor(() => expect(resolvers.size).toBe(2));
act(() =>
resolvers.get("first")?.({ ok: false, error: uncertainFailure }),
);
if (!first) throw new Error("expected first mutation");
await act(() => first);
act(() =>
resolvers.get("second")?.({ ok: true, value: "second" }),
);
if (!second) throw new Error("expected second mutation");
await act(() => second);
expect(client.getQueryData(key)).toEqual(["base", "first", "second"]);
await act(() => hook.result.current.reconcileUnknownEffect("NOT_APPLIED"));
expect(client.getQueryData(key)).toEqual(["base", "second"]);
});
it("keeps a newer submit pending while reconciling an older unknown effect", async () => {
const client = queryClient();
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
let completeSecond: (value: ApplicationResult<string>) => void = () => {};
const execute = vi.fn((input: string) =>
input === "first"
? Promise.resolve({ ok: false as const, error: failure })
: new Promise<ApplicationResult<string>>((resolve) => {
completeSecond = resolve;
}),
);
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
definitionId: "legacy-active-after-unknown-no-layer-v1",
duplicatePolicy: "ALLOW_PARALLEL",
execute,
}),
{ wrapper: wrapper(client) },
);
await act(() => hook.result.current.submit("first"));
let second: Promise<ApplicationResult<string>> | undefined;
act(() => {
second = hook.result.current.submit("second");
});
await waitFor(() => expect(execute).toHaveBeenCalledTimes(2));
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() => hook.result.current.reconcileUnknownEffect("NOT_APPLIED"));
expect(hook.result.current.state.indicator).toBe("mutation-pending");
completeSecond({ ok: true, value: "second" });
if (!second) throw new Error("expected second mutation");
await act(() => second);
await waitFor(() => expect(hook.result.current.state.indicator).toBeNull());
});
it("serializes reconciliation so a double action cannot settle the next intent", async () => {
const client = queryClient();
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
let finishInvalidation: () => void = () => {};
const invalidation = new Promise<void>((resolve) => {
finishInvalidation = resolve;
});
vi.spyOn(client, "invalidateQueries").mockImplementation(
async () => invalidation,
);
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
definitionId: "legacy-applied-double-action-v1",
duplicatePolicy: "ALLOW_PARALLEL",
execute: async () => ({ ok: false, error: failure }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
}),
{ wrapper: wrapper(client) },
);
await act(async () => {
await Promise.all([
hook.result.current.submit("first"),
hook.result.current.submit("second"),
]);
});
let firstResolution: Promise<void> | undefined;
let duplicateResolution: Promise<void> | undefined;
act(() => {
firstResolution = hook.result.current.reconcileUnknownEffect("APPLIED");
duplicateResolution = hook.result.current.reconcileUnknownEffect(
"NOT_APPLIED",
);
});
await expect(duplicateResolution).resolves.toBeUndefined();
expect(hook.result.current.state.indicator).toBe("mutation-pending");
finishInvalidation();
if (!firstResolution) throw new Error("expected reconciliation");
await act(() => firstResolution);
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() => hook.result.current.reconcileUnknownEffect("NOT_APPLIED"));
expect(hook.result.current.state.indicator).toBeNull();
});
it("keeps the next intent unresolved after a synchronous not-applied double action", async () => {
const client = queryClient();
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
definitionId: "legacy-not-applied-double-action-v1",
duplicatePolicy: "ALLOW_PARALLEL",
execute: async () => ({ ok: false, error: failure }),
}),
{ wrapper: wrapper(client) },
);
await act(async () => {
await Promise.all([
hook.result.current.submit("first"),
hook.result.current.submit("second"),
]);
});
let firstResolution: Promise<void> | undefined;
let duplicateResolution: Promise<void> | undefined;
act(() => {
firstResolution = hook.result.current.reconcileUnknownEffect(
"NOT_APPLIED",
);
duplicateResolution = hook.result.current.reconcileUnknownEffect(
"APPLIED",
);
});
await expect(duplicateResolution).resolves.toBeUndefined();
if (!firstResolution) throw new Error("expected reconciliation");
await act(() => firstResolution);
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() => hook.result.current.reconcileUnknownEffect("NOT_APPLIED"));
expect(hook.result.current.state.indicator).toBeNull();
});
it("clears every stale-scope unknown effect without touching new data", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const key = ["resource", "scope-unknown-queue"];
client.setQueryData(key, ["base"]);
const invalidateQueries = vi.spyOn(client, "invalidateQueries");
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "scope-unknown-queue-v1",
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "ALLOW_PARALLEL",
scope,
execute: async () => ({ ok: false, error: failure }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
await act(async () => {
await Promise.all([
hook.result.current.submit("created"),
hook.result.current.submit("created"),
]);
});
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
act(() => scope.fence());
await waitFor(() => expect(hook.result.current.state.indicator).toBeNull());
expect(client.getQueryState(key)).toBeUndefined();
client.setQueryData(key, ["new-generation"]);
await act(() => hook.result.current.reconcileUnknownEffect("APPLIED"));
expect(client.getQueryData(key)).toEqual(["new-generation"]);
expect(invalidateQueries).not.toHaveBeenCalled();
});
it("restores a bound unknown-effect head after controller remount", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const key = ["resource", "durable-unknown"];
client.setQueryData(key, ["base"]);
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const mutationOptions = {
definitionId: "durable-unknown-v1",
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE" as const,
scope,
execute: vi.fn(async () => ({ ok: false as const, error: failure })),
invalidate: [] as const,
optimistic: {
queryKey: key,
update: (previous: unknown, input: string) => [
...(previous as string[]),
input,
],
},
};
const first = renderHook(
() => useApplicationMutation<string, string>(mutationOptions),
{ wrapper: wrapper(client) },
);
await act(() => first.result.current.submit("created"));
expect(first.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
first.unmount();
const remounted = renderHook(
() => useApplicationMutation<string, string>(mutationOptions),
{ wrapper: wrapper(client) },
);
expect(remounted.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() =>
remounted.result.current.reconcileUnknownEffect("NOT_APPLIED"),
);
expect(client.getQueryData(key)).toEqual(["base"]);
expect(remounted.result.current.state.indicator).toBeNull();
expect(mutationOptions.execute).toHaveBeenCalledOnce();
});
it("restores a non-optimistic legacy unknown effect by stable definition after remount", async () => {
const client = queryClient();
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const mutationOptions = {
definitionId: "legacy-durable-create-v1",
execute: vi.fn(async () => ({ ok: false as const, error: failure })),
};
const first = renderHook(
() => useLegacyApplicationMutation<string, string>(mutationOptions),
{ wrapper: wrapper(client) },
);
await act(() => first.result.current.submit("created"));
expect(first.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
first.unmount();
const remounted = renderHook(
() => useLegacyApplicationMutation<string, string>(mutationOptions),
{ wrapper: wrapper(client) },
);
expect(remounted.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() =>
remounted.result.current.reconcileUnknownEffect("NOT_APPLIED"),
);
expect(remounted.result.current.state.indicator).toBeNull();
expect(mutationOptions.execute).toHaveBeenCalledOnce();
});
it("does not allocate unknown-effect channels for abandoned server renders", async () => {
const client = queryClient();
const selectedScopes = Array.from(
{ length: MUTATION_COORDINATOR_BOUNDS.activeDefinitionsPerRuntime },
(_, index) => scopeSnapshot(1, `server-render-scope-${index}`),
);
function AbandonedMutation({ index }: Readonly<{ index: number }>) {
useApplicationMutation<string, string>({
definitionId: `server-render-abandoned-${index}`,
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope: selectedScopes[index]!,
execute: async (input) => ({ ok: true, value: input }),
invalidate: [],
});
return null;
}
const ServerWrapper = wrapper(client);
renderToString(
<ServerWrapper>
{selectedScopes.map((_, index) => (
<AbandonedMutation key={index} index={index} />
))}
</ServerWrapper>,
);
const scope = scopeSnapshot(1, "committed-after-server-render");
const execute = vi.fn(async (input: string) => ({
ok: true as const,
value: input,
}));
const committed = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "committed-after-server-render",
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
await expect(committed.result.current.submit("created")).resolves.toEqual({
ok: true,
value: "created",
});
expect(execute).toHaveBeenCalledOnce();
});
it("isolates channels when a reused fingerprint advances generation", async () => {
const client = queryClient();
const firstScope = scopeSnapshot(1, "reused-scope-fingerprint");
const secondScope = scopeSnapshot(2, "reused-scope-fingerprint");
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const definition = {
definitionId: "generation-channel-v1",
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE" as const,
invalidate: [] as const,
};
const first = renderHook(
() =>
useApplicationMutation<string, string>({
...definition,
scope: firstScope,
execute: async () => ({ ok: false, error: failure }),
}),
{ wrapper: wrapper(client) },
);
await act(() => first.result.current.submit("first"));
expect(first.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
const secondExecute = vi.fn(async () => ({
ok: true as const,
value: "second",
}));
const second = renderHook(
() =>
useApplicationMutation<string, string>({
...definition,
scope: secondScope,
execute: secondExecute,
}),
{ wrapper: wrapper(client) },
);
expect(second.result.current.state.indicator).toBeNull();
await expect(second.result.current.submit("second")).resolves.toEqual({
ok: true,
value: "second",
});
expect(secondExecute).toHaveBeenCalledOnce();
expect(first.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
});
it("isolates unrelated non-optimistic legacy controllers", async () => {
const client = queryClient();
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const first = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
definitionId: "legacy-isolation-first-v1",
execute: async () => ({ ok: false, error: failure }),
}),
{ wrapper: wrapper(client) },
);
const second = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
definitionId: "legacy-isolation-second-v1",
execute: async (input) => ({ ok: true, value: input }),
}),
{ wrapper: wrapper(client) },
);
await act(() => first.result.current.submit("first"));
expect(first.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
expect(second.result.current.state.indicator).toBeNull();
await act(() => second.result.current.reconcileUnknownEffect("APPLIED"));
expect(first.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
});
it("fails closed when identical bound metadata is mounted with a different scope owner", async () => {
const client = queryClient();
const firstScope = scopeSnapshot(1, "same-owner-fingerprint");
const secondScope = scopeSnapshot(1, "same-owner-fingerprint");
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const definition = {
definitionId: "scope-owner-channel-v1",
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE" as const,
invalidate: [] as const,
};
const first = renderHook(
() =>
useApplicationMutation<string, string>({
...definition,
scope: firstScope,
execute: async () => ({ ok: false, error: failure }),
}),
{ wrapper: wrapper(client) },
);
await act(() => first.result.current.submit("first"));
const secondExecute = vi.fn(async () => ({
ok: true as const,
value: "second",
}));
const second = renderHook(
() =>
useApplicationMutation<string, string>({
...definition,
scope: secondScope,
execute: secondExecute,
}),
{ wrapper: wrapper(client) },
);
expect(second.result.current.state.indicator).toBeNull();
await expect(second.result.current.submit("second")).resolves.toMatchObject({
ok: false,
error: {
kind: "IDENTITY_INTERN_LIMIT_EXCEEDED",
code: "UNKNOWN_EFFECT_CHANNEL_LIMIT_EXCEEDED",
effect: "NOT_STARTED",
},
});
expect(secondExecute).not.toHaveBeenCalled();
expect(first.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
});
it("releases empty unmounted channels after their active mutation settles", async () => {
const client = queryClient();
const firstScope = scopeSnapshot(1, "release-owner-fingerprint");
const secondScope = scopeSnapshot(1, "release-owner-fingerprint");
let resolveFirst: (value: ApplicationResult<string>) => void = () => {};
const definition = {
definitionId: "release-channel-v1",
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "ALLOW_PARALLEL" as const,
invalidate: [] as const,
};
const first = renderHook(
() =>
useApplicationMutation<string, string>({
...definition,
scope: firstScope,
execute: () =>
new Promise((resolve) => {
resolveFirst = resolve;
}),
}),
{ wrapper: wrapper(client) },
);
let pending: Promise<ApplicationResult<string>> | undefined;
act(() => {
pending = first.result.current.submit("created");
});
await waitFor(() =>
expect(first.result.current.state.indicator).toBe("mutation-pending"),
);
first.unmount();
resolveFirst({ ok: true, value: "created" });
if (!pending) throw new Error("expected active mutation");
await act(() => pending);
const execute = vi.fn(async () => ({
ok: true as const,
value: "after-release",
}));
const afterRelease = renderHook(
() =>
useApplicationMutation<string, string>({
...definition,
scope: secondScope,
execute,
}),
{ wrapper: wrapper(client) },
);
await expect(afterRelease.result.current.submit("created")).resolves.toEqual({
ok: true,
value: "after-release",
});
expect(execute).toHaveBeenCalledOnce();
});
it("enforces the active intent bound across all QueryClient channels", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const never = () => new Promise<ApplicationResult<string>>(() => {});
const options = (definitionId: string) => ({
definitionId,
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "ALLOW_PARALLEL" as const,
scope,
execute: never,
invalidate: [] as const,
});
const first = renderHook(
() => useApplicationMutation<string, string>(options("bound-a")),
{ wrapper: wrapper(client) },
);
const second = renderHook(
() => useApplicationMutation<string, string>(options("bound-b")),
{ wrapper: wrapper(client) },
);
const half = MUTATION_COORDINATOR_BOUNDS.activeIntentsTotal / 2;
act(() => {
for (let index = 0; index < half; index += 1) {
void first.result.current.submit("same-input");
void second.result.current.submit("same-input");
}
});
await expect(first.result.current.submit("same-input")).resolves.toMatchObject({
ok: false,
error: {
kind: "IDENTITY_INTERN_LIMIT_EXCEEDED",
code: "UNKNOWN_EFFECT_CHANNEL_LIMIT_EXCEEDED",
effect: "NOT_STARTED",
},
});
act(() => scope.fence());
});
it("reconciles parallel unknown effects in submit order after reverse completion", async () => {
const client = queryClient();
const key = ["resource", "reverse-completion"];
client.setQueryData(key, ["base"]);
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const resolvers = new Map<
string,
(value: ApplicationResult<string>) => void
>();
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
duplicatePolicy: "ALLOW_PARALLEL",
execute: (input) =>
new Promise((resolve) => {
resolvers.set(input, resolve);
}),
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let first: Promise<ApplicationResult<string>> | undefined;
let second: Promise<ApplicationResult<string>> | undefined;
act(() => {
first = hook.result.current.submit("first");
second = hook.result.current.submit("second");
});
await waitFor(() => expect(resolvers.size).toBe(2));
act(() => resolvers.get("second")?.({ ok: false, error: failure }));
if (!second) throw new Error("expected second mutation");
await act(() => second);
expect(hook.result.current.state.indicator).toBe("mutation-pending");
act(() => resolvers.get("first")?.({ ok: false, error: failure }));
if (!first) throw new Error("expected first mutation");
await act(() => first);
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() => hook.result.current.reconcileUnknownEffect("NOT_APPLIED"));
expect(client.getQueryData(key)).toEqual(["base", "second"]);
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() => hook.result.current.reconcileUnknownEffect("APPLIED"));
expect(client.getQueryData(key)).toEqual(["base", "second"]);
expect(hook.result.current.state.indicator).toBeNull();
});
it("removes committed old-scope data when scope fences during reconciliation invalidation", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const key = ["resource", "reconcile-fence-race"];
client.setQueryData(key, ["base"]);
let finishInvalidation: () => void = () => {};
const invalidation = new Promise<void>((resolve) => {
finishInvalidation = resolve;
});
const invalidateQueries = vi
.spyOn(client, "invalidateQueries")
.mockImplementation(async () => invalidation);
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "MAYBE_APPLIED",
});
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "reconcile-fence-race-v1",
definitionVersion: 1,
operationId: "CREATE",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
execute: async () => ({ ok: false, error: failure }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
await act(() => hook.result.current.submit("created"));
let reconciliation: Promise<void> | undefined;
act(() => {
reconciliation = hook.result.current.reconcileUnknownEffect("APPLIED");
});
await waitFor(() => expect(invalidateQueries).toHaveBeenCalledOnce());
act(() => scope.fence());
finishInvalidation();
if (!reconciliation) throw new Error("expected reconciliation");
await act(() => reconciliation);
expect(client.getQueryState(key)).toBeUndefined();
expect(hook.result.current.state.indicator).toBeNull();
});
it.each(["NOT_APPLICABLE", undefined] as const)(
"treats %s conflict effect certainty as unknown without conflict retry",
async (effect) => {
const client = queryClient();
const key = ["resource", `ambiguous-conflict-${String(effect)}`];
client.setQueryData(key, ["base"]);
const conflict = createFailure("CONFLICT", "CREATE", 0, {
...(effect ? { effect } : {}),
});
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
execute: async () => ({ ok: false, error: conflict }),
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let outcome: ApplicationResult<string> | undefined;
await act(async () => {
outcome = await hook.result.current.submit("created");
});
expect(outcome).toMatchObject({
ok: false,
error: {
effect: "MAYBE_APPLIED",
retryable: false,
action: "contact-support",
},
});
expect(client.getQueryData(key)).toEqual(["base", "created"]);
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
},
);
});