Files
clean-architecture-frontend…/scripts/lib/lab-performance.ts
DongHyeonka 81701add7e feat(perf): lab이 기능 라우트 첫 진입을 재고 500 ms 예산으로 판정한다
문제: lab(FE-GATE-026)은 플랫폼 구성 화면(EXAMPLES_PLATFORM) 하나만 잰다.
이 화면은 기능 코드를 받지 않아 기능을 더해도 수치가 거의 그대로다
(146 → 154 ms). 기능 라우트는 처음 들어갈 때 context 라우트 모듈과 기능
실행부를 받고, 그다음 페이지 청크를 받는 두 번의 요청 묶음을 거친다.
lab 조건에서 EXAMPLES_UI 첫 진입은 중앙값 406 ms(403~410, 리뷰 15-R1)로
대상 화면의 2.7배인데 어느 게이트도 재지 않는다. 다운스트림의 화면은
모두 기능 라우트다.

고른 방법:
- labFeatureRoute(scripts/lib/lab-performance.ts): 설치된 기능이 가진,
  세션 없이 열리는 첫 내비게이션 라우트. 템플릿에서는 EXAMPLES_UI다.
  없으면 null이고 lab은 measured: false로 남기고 판정하지 않는다.
- lab은 run마다 `/`에서 그 라우트의 내비게이션 링크를 눌러 heading까지를
  같은 페이지 시계로 잰다(새 cold context). metrics.featureRouteInteractionMs
  (중앙값), context.sampling.featureRoute(표본, owner)에 남긴다. 기존 대상
  라우트와 그 예산(200 ms)은 그대로라 회귀 비교가 이어진다.
- 예산 config/performance/budgets.json lab.featureRouteInteractionMs = 500 ms.
  측정 406 ms(8a44226, i5-10400F, lab 조건)를 통과시키고, 지금 둘째 요청
  묶음 크기(약 100 ms, 클릭 뒤 98~204 ms)의 왕복이 하나 더 붙으면 넘는다.
  lab 자가 검사 fixture에 feature-route-over-threshold를 더해 이 예산이
  실패할 수 있음을 매번 확인한다.
- 단위 테스트: 라우트 선택 규칙, 설치된 레지스트리에서의 선택, 커밋된
  예산이 406 ms는 통과·516 ms는 실패·null은 판정 제외.
버린 대안:
- 두 요청 묶음을 하나로 줄이기(진입한 URL의 페이지 청크를 context 라우트
  모듈과 같이 받기): 페이지 청크 이름이 context 라우트 모듈 안의 lazy()에만
  있어, 첫 묶음에서 받으려면 초기 청크의 라우트 선언이 페이지 로더를 가져야
  한다. 선언 모양·생성기·초기 JS를 바꾸는 일이라 이 커밋에서 하지 않았다
  (결정 대기, performance-evidence.md에 적음).
- 처음에는 기록만 하기: 기록만 하면 늘어도 아무도 모른다. 측정값이 있으니
  예산을 같이 둔다.
- 라우트별 예산 표: 다운스트림이 채워야 하는 표가 는다.

위험·한계: 예산 여유가 94 ms(23%)라 lab 호스트가 지금보다 20% 이상 느리면
기능 라우트 판정이 흔들릴 수 있다(0929/11-04 lab 부하 가드는 여전히 없음).
FE-GATE-026 시간이 run마다 cold navigation 하나(약 2~3초) 늘어 5회면
+10~15초다. 생성 기능의 목록 라우트는 session-required라 lab 대상이 되지
않는다. 기능 라우트의 heading은 계약 `title`과 같은 글자로 찾는다(대상
라우트와 같은 방식). CHANGELOG의 "기능 라우트 첫 진입은 어느 게이트도
재지 않는다" 제한 문장은 이 커밋에서 고치지 않았다(오케스트레이터 몫).

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/lab-performance.test.ts
tests/unit/performance-budgets.test.ts
corepack pnpm build && corepack pnpm test:performance -- --runs=5
(featureRoute EXAMPLES_UI 중앙값이 500 ms 안인지, 표본 기록)

Refs: 1105/15-04
2026-11-06 01:23:48 +09:00

134 lines
4.2 KiB
TypeScript

/**
* 11-07. The pieces of the lab performance gate (`scripts/test-performance.ts`)
* that decide what is measured and whether the numbers can be trusted.
*/
export const DEFAULT_LAB_PORT = 4173;
export const DEFAULT_LAB_RUNS = 5;
/**
* `vite preview` arguments. Without `--strictPort` vite moved to the next free
* port when the requested one was taken, and the gate measured whatever server
* already listened there.
*/
export function previewArguments(port: number): readonly string[] {
return [
"pnpm",
"preview",
"--host",
"127.0.0.1",
"--port",
String(port),
"--strictPort",
];
}
/**
* 1105/15-05. Playwright starts Chromium with `--hide-scrollbars`, so the lab
* measured layout shift in a browser without the classic scrollbar most
* Windows and Linux desktops draw. A first render that made one appear
* moved the header 15 px and the lab reported CLS 0. The lab runs with
* scrollbars, as those users see the page.
*/
export function labBrowserLaunchOptions(): { ignoreDefaultArgs: string[] } {
return { ignoreDefaultArgs: ["--hide-scrollbars"] };
}
export type LabRoute = Readonly<{
routeId: string;
path: string;
access: "public" | "session-required";
title: string;
navigationLabel: string | null;
navigationOrder: number | null;
}>;
/**
* 1105/15-04. The feature route the lab times next to its platform target:
* the first one in the navigation that an installed feature owns and a
* visitor without a session can open. The platform target loads no feature
* code, so its number stayed flat while a feature route's first entry (the
* context route module, then the page chunk) took 2.7 times as long and no
* gate measured it. `null` when no installed feature has such a route; the
* lab then records that it measured none.
*/
export function labFeatureRoute(
routes: readonly LabRoute[],
owners: Readonly<Record<string, string>>,
): LabRoute | null {
const candidates = routes.filter(
(route) =>
owners[route.routeId] !== undefined &&
route.access === "public" &&
route.navigationLabel !== null &&
route.navigationOrder !== null,
);
candidates.sort((left, right) => left.navigationOrder! - right.navigationOrder!);
return candidates[0] ?? null;
}
export type SampleSummary = Readonly<{
median: number;
min: number;
max: number;
samples: readonly number[];
}>;
export function summarizeSamples(samples: readonly number[]): SampleSummary {
if (samples.length === 0) throw new RangeError("no samples to summarize");
const sorted = [...samples].sort((left, right) => left - right);
const middle = Math.floor(sorted.length / 2);
const median =
sorted.length % 2 === 1
? sorted[middle]!
: (sorted[middle - 1]! + sorted[middle]!) / 2;
return Object.freeze({
median,
min: sorted[0]!,
max: sorted.at(-1)!,
samples: Object.freeze([...samples]),
});
}
/** Fails when anything already answers where the preview server will listen. */
export async function assertPortUnused(
baseUrl: string,
fetchImpl: typeof fetch = fetch,
): Promise<void> {
let answered = false;
try {
await fetchImpl(baseUrl, { signal: AbortSignal.timeout(1_000) });
answered = true;
} catch {
// Nothing is listening: the expected state.
}
if (answered) {
throw new Error(
`${baseUrl} already answers before the preview server starts; another server holds the port.`,
);
}
}
/**
* Compares the release the server actually serves with the local build that
* is being measured, so the numbers belong to that build.
*/
export async function assertServedRelease(
baseUrl: string,
expected: Readonly<{ buildId: string; releaseId: string }>,
fetchImpl: typeof fetch = fetch,
): Promise<void> {
const response = await fetchImpl(new URL("/release-manifest.json", baseUrl), {
cache: "no-store",
});
const served = response.ok
? ((await response.json()) as Partial<Record<"buildId" | "releaseId", unknown>>)
: {};
if (served.buildId !== expected.buildId || served.releaseId !== expected.releaseId) {
throw new Error(
`${baseUrl} serves build ${String(served.buildId)}/${String(served.releaseId)}, ` +
`not the measured ${expected.buildId}/${expected.releaseId}.`,
);
}
}