Files
clean-architecture-frontend…/tests/platform/cardinality/extreme-scale-registry.test.ts
DongHyeonka 99baed97ea
frontend-quality-gates / merge / static checks (pull_request) Successful in 1m20s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 5m6s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / main / self-tests and removal drills (pull_request) Skipped
frontend-quality-gates / merge / tests (pull_request) Successful in 10m56s
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
test(scale): 극한 규모 증가율을 벽시계 대신 입력 읽기 횟수로 잰다
문제: `extreme-scale-registry.test.ts`는 1만→10만 증가를 벽시계 두 점의
비율로 잰다. 선형 코드라도 10만 쪽만 캐시 미스와 GC를 더 치러, 부하가
걸린 desktop의 test:coverage 안에서 지수 1.53(11-13, 장부 7번 줄)과
1.51(11-19, #60 갱신의 merge 단계 FE-GATE-020)로 「near-linear growth」가
실패했다. 같은 파일의 합성 증가 비율(30배)과 조회 비교(3배)도 같은
벽시계 비율이다.

방법: 세 단언을 실행마다 같은 값이 나오는 측정으로 바꾼다.
- 증가율 두 시험: 입력 배열·레코드·feature 객체를 Proxy로 감싸 읽기와
  키 나열 횟수를 센다. built-in(map, includes, spread, new Set,
  Object.entries)이 하는 읽기도 잡힌다. 문턱은 그대로다(합성 30배,
  membership 지수 1.5 = `assertLinearOrBetter` 기본값). 센 값이 입력 크기
  이상인지도 단언해 계수기가 끊기면 빈 통과가 되지 않게 한다.
- 1만·10만 쪽을 한 번씩만 돌리고, 길이·상태 단언은 그 결과에 한다.
  10만 쪽은 읽기가 1만 쪽의 문턱 배수를 넘는 순간 멈추고 그 이유로
  실패한다. 멈춘 뒤는 어차피 실패라 판정은 같고, n² 회귀가 Proxy를 거쳐
  한 시간 넘게 읽은 뒤에야 job 시한으로 끝나는 것을 막는다.
- 조회 비교: registry가 Proxy가 아니고, 프로토타입이 Object.prototype이나
  null이고, 10만 키가 모두 자기 data property인지 본다. 이 조건이면
  `registry[key]`는 plain object 조회와 같은 엔진 연산이다. checksum
  비교는 그대로 둔다.
판정 함수 `growth-regression.ts`는 바꾸지 않는다.
버린 대안: 반복 표본의 중앙값. 10만 쪽이 느린 것은 캐시·GC의 계통 차이라
중앙값으로도 문턱 근처에 남는다(메모리 부하에서 지수 1.56~2.03).

위험·한계: 세기는 코드가 만든 복사본을 다시 훑는 회귀를 못 본다(복사본은
plain string이다). 그 몫은 같은 FE-GATE-005의 pr scale tier
(`run-composition-scale.ts` S0~S2, 시간 중앙값)가 잡는다. 다만 비교 한 번이
포인터 비교뿐인 재탐색(지역 id 목록 위 indexOf 중복 검사)은 그 tier의
1천 표본이 잡음 바닥 근처라 잡는 run과 놓치는 run이 갈린다. tier가 10만을
재기 전까지 받아들이는 빈칸으로 파일 주석에 적었다. 입력 재탐색 n²
회귀는 실패까지 오래 걸린다(실제 크기 resolve includes 63초, indexOf 중복
검사 653초). 이 파일이 FE-GATE-005에서 두 번 돌아 그 두 배다.

검증(desktop, 12코어):
- merge 단계(이 트리, CI=true): FE-GATE-001~013·020 14개 rc=0
- 한 파일 coverage 모드, 부하 아래 반복:
  - 고치기 전: CPU 부하(busy loop 12개) 0/20 실패, 메모리 대역 부하
    (256 MB 배열을 훑는 node 12개) 19/20 실패(지수 1.56~2.03, 가장 긴
    시험 10.4초)
  - 고친 뒤: CPU 부하 20/20, 메모리 부하 30/30 통과(가장 긴 시험 4.5초).
    이 반복과 변이는 lint 수정(`{ cause: error }`) 한 줄 전 트리에서 돌았다.
- 변이(1천→1만, resolve 둘은 실제 크기도): 입력 재탐색(resolve의
  includes·indexOf 중복 검사, 합성의 앞 레코드 재탐색)과 registry
  Proxy·프로토타입 사슬은 이 파일이 실패로 잡는다. select의 지역 복사본
  includes·indexOf와 spread 누적은 이 파일이 못 보고 pr scale tier가
  잡았다.
2026-11-19 03:16:52 +09:00

242 lines
9.5 KiB
TypeScript

import { types } from "node:util";
import { describe, expect, it } from "vitest";
import {
resolveProductFeatures,
selectCompiledProductFeatures,
} from "../../../src/contracts/product-features.ts";
import { composeUniqueRecord } from "../../../src/platform/cardinality/compose-unique-record.ts";
import {
assertLinearOrBetter,
type GrowthSample,
} from "../../../src/platform/cardinality/growth-regression.ts";
/*
* This file runs in merge gates on CPUs nobody chose and under whatever load
* the runner carries (FE-GATE-005 coverage and the pr scale tier, the
* FE-GATE-020 removal drill), so it asserts only what comes out the same on
* every run. Growth from 10k to 100k entries is counted, not timed: how many
* times the code reads its input. A wall-clock ratio read the linear code here
* as super-linear on a loaded desktop, because the 100k side pays for cache
* misses and GC that the 10k side does not (docs/ledger/flaky-tests.jsonl).
*
* Counting sees a rescan of an input, such as `installedIds.includes(id)` in a
* loop over the compiled ids. It cannot see a rescan of a copy the code made
* itself, because the copy holds plain strings. Timed growth of the same three
* functions runs in scripts/scale/run-composition-scale.ts (the pr scale tier,
* median of several samples up to 10k), which catches such a rescan when its
* per-step cost clears that tier's noise floor at 1k. A rescan of a copy that
* costs only a pointer compare per step, such as an indexOf duplicate check
* over a local id list, sits near that floor, so the tier catches it on some
* runs and not on others, and this file never sees it: an accepted gap until
* that tier also times 100k. Absolute timings stay in check:scale:baseline,
* which compares them only on the CPU that recorded
* config/scale/benchmark-baseline.json.
*/
const SMALL_REGISTRY_SIZE = 10_000;
const LARGE_REGISTRY_SIZE = 100_000;
const SIZE_RATIO = LARGE_REGISTRY_SIZE / SMALL_REGISTRY_SIZE;
const LOOKUP_OPERATIONS = 200_000;
const MAX_COMPOSE_GROWTH_RATIO = 30;
/** The `assertLinearOrBetter` default, named so the read limit can use it. */
const MAX_MEMBERSHIP_EXPONENT = 1.5;
type ReadCounter = { reads: number; limit: number };
/** Thrown from a counting Proxy once its reads pass `ReadCounter.limit`. */
class ReadLimitReached extends Error {}
/**
* `target` behind a Proxy that counts every property read and key listing,
* including the ones built-ins make on it (map, filter, includes, spread,
* `new Set`, Object.entries). The count depends only on the code path.
*/
function counted<Target extends object>(target: Target, counter: ReadCounter): Target {
const read = () => {
counter.reads += 1;
if (counter.reads > counter.limit) throw new ReadLimitReached();
};
return new Proxy(target, {
get(object, key, receiver) {
read();
return Reflect.get(object, key, receiver);
},
getOwnPropertyDescriptor(object, key) {
read();
return Reflect.getOwnPropertyDescriptor(object, key);
},
has(object, key) {
read();
return Reflect.has(object, key);
},
ownKeys(object) {
read();
return Reflect.ownKeys(object);
},
});
}
function newReadCounter(): ReadCounter {
return { reads: 0, limit: Number.POSITIVE_INFINITY };
}
type GrowthRun<Result> = Readonly<{
series: readonly [GrowthSample, GrowthSample];
results: readonly [Result, Result];
}>;
/**
* Runs `small` at 10k, then `large` at 100k, once each, and returns their
* input reads as a growth series together with what they returned, so the
* caller checks those results instead of reading the inputs again.
*
* The 100k run stops as soon as its reads pass `maxRatio` times the 10k
* reads, where the caller's growth judgment fails anyway, and the test fails
* there with that reason. Without the stop a quadratic regression would read
* through the Proxy for most of an hour before any assertion ran.
*/
function readGrowth<Result>(
counter: ReadCounter,
small: () => Result,
large: () => Result,
maxRatio: number,
): GrowthRun<Result> {
counter.reads = 0;
const smallResult = small();
const smallReads = counter.reads;
counter.reads = 0;
counter.limit = smallReads * maxRatio;
try {
const largeResult = large();
return {
series: [
{ n: SMALL_REGISTRY_SIZE, cost: smallReads },
{ n: LARGE_REGISTRY_SIZE, cost: counter.reads },
],
results: [smallResult, largeResult],
};
} catch (error) {
if (!(error instanceof ReadLimitReached)) throw error;
throw new Error(
`super-linear growth: input reads at n=${LARGE_REGISTRY_SIZE} passed ` +
`${maxRatio.toFixed(1)}x the ${smallReads} reads at n=${SMALL_REGISTRY_SIZE} ` +
"and the count was stopped there",
{ cause: error },
);
} finally {
counter.limit = Number.POSITIVE_INFINITY;
}
}
function syntheticRecords(count: number): readonly Readonly<Record<string, number>>[] {
return Array.from({ length: count }, (_, index) => ({ [`key-${index}`]: index }));
}
function countedRecords(
count: number,
counter: ReadCounter,
): readonly Readonly<Record<string, number>>[] {
return counted(
syntheticRecords(count).map((record) => counted(record, counter)),
counter,
);
}
function lookupChecksum(registry: Readonly<Record<string, number>>): number {
let checksum = 0;
for (let index = 0; index < LOOKUP_OPERATIONS; index += 1) {
checksum += registry[`key-${index % LARGE_REGISTRY_SIZE}`] ?? -1;
}
return checksum;
}
describe("extreme-scale registry composition", () => {
it("keeps 10k -> 100k composition growth below a quadratic regression budget", () => {
const counter = newReadCounter();
const smallRecords = countedRecords(SMALL_REGISTRY_SIZE, counter);
const largeRecords = countedRecords(LARGE_REGISTRY_SIZE, counter);
const compose = (records: typeof smallRecords) =>
composeUniqueRecord(records, () => "synthetic registry");
const {
series: [small, large],
results: [smallRegistry, largeRegistry],
} = readGrowth(
counter,
() => compose(smallRecords),
() => compose(largeRecords),
MAX_COMPOSE_GROWTH_RATIO,
);
expect(Object.keys(smallRegistry)).toHaveLength(SMALL_REGISTRY_SIZE);
expect(Object.keys(largeRegistry)).toHaveLength(LARGE_REGISTRY_SIZE);
// Every record is read, so the count covers the work being judged.
expect(small.cost).toBeGreaterThanOrEqual(SMALL_REGISTRY_SIZE);
expect(large.cost / small.cost).toBeLessThan(MAX_COMPOSE_GROWTH_RATIO);
});
it("keeps lookups on a 100k-entry registry as cheap as on a plain object", () => {
const records = syntheticRecords(LARGE_REGISTRY_SIZE);
const registry = composeUniqueRecord(records, () => "synthetic registry");
const plain: Record<string, number> = {};
for (const record of records) Object.assign(plain, record);
// `registry[key]` is the same engine lookup as `plain[key]` exactly when
// the registry is an ordinary object holding every key as its own data
// property: no Proxy trap, no getter, no chain of prototypes to walk.
// Timing the two lookups side by side measured the CPU, not the registry.
expect(types.isProxy(registry)).toBe(false);
expect([Object.prototype, null]).toContain(Object.getPrototypeOf(registry));
const descriptors = Object.values(Object.getOwnPropertyDescriptors(registry));
expect(descriptors).toHaveLength(LARGE_REGISTRY_SIZE);
expect(descriptors.filter((descriptor) => !("value" in descriptor))).toEqual([]);
const checksum = lookupChecksum(registry);
expect(checksum).toBeGreaterThan(0);
expect(checksum).toBe(lookupChecksum(plain));
});
});
function membershipInput(size: number, counter: ReadCounter) {
const ids = Array.from(
{ length: size },
(_, index) => `feature-${index.toString().padStart(6, "0")}`,
);
const installed = ids.filter((_, index) => index % 10 === 0);
const compiled = counted(
ids.map((featureId) => counted(Object.freeze({ featureId }), counter)),
counter,
);
const compiledIds = counted(ids, counter);
const installedIds = counted(installed, counter);
const declared = installed.join(",");
return {
select: () => selectCompiledProductFeatures(compiled, declared),
resolve: () => resolveProductFeatures(compiledIds, installedIds),
};
}
describe("extreme-scale product feature membership", () => {
it("selects and resolves 100k feature ids with near-linear growth from 10k", () => {
const counter = newReadCounter();
const small = membershipInput(SMALL_REGISTRY_SIZE, counter);
const large = membershipInput(LARGE_REGISTRY_SIZE, counter);
const maxRatio = SIZE_RATIO ** MAX_MEMBERSHIP_EXPONENT;
const selection = readGrowth(counter, small.select, large.select, maxRatio);
const resolution = readGrowth(counter, small.resolve, large.resolve, maxRatio);
const statuses = resolution.results[1];
expect(selection.results[1]).toHaveLength(LARGE_REGISTRY_SIZE / 10);
expect(statuses).toHaveLength(LARGE_REGISTRY_SIZE);
expect(statuses.filter((status) => status.state === "ACTIVE")).toHaveLength(
LARGE_REGISTRY_SIZE / 10,
);
// Every compiled feature is read, so the count covers the work being judged.
expect(selection.series[0].cost).toBeGreaterThanOrEqual(SMALL_REGISTRY_SIZE);
expect(resolution.series[0].cost).toBeGreaterThanOrEqual(SMALL_REGISTRY_SIZE);
assertLinearOrBetter(selection.series, { maxExponent: MAX_MEMBERSHIP_EXPONENT });
assertLinearOrBetter(resolution.series, { maxExponent: MAX_MEMBERSHIP_EXPONENT });
});
});