From 99baed97ea9215d08525998d48fec35ca31317d5 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 19 Nov 2026 01:21:34 +0900 Subject: [PATCH] =?UTF-8?q?test(scale):=20=EA=B7=B9=ED=95=9C=20=EA=B7=9C?= =?UTF-8?q?=EB=AA=A8=20=EC=A6=9D=EA=B0=80=EC=9C=A8=EC=9D=84=20=EB=B2=BD?= =?UTF-8?q?=EC=8B=9C=EA=B3=84=20=EB=8C=80=EC=8B=A0=20=EC=9E=85=EB=A0=A5=20?= =?UTF-8?q?=EC=9D=BD=EA=B8=B0=20=ED=9A=9F=EC=88=98=EB=A1=9C=20=EC=9E=B0?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: `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가 잡았다. --- .../extreme-scale-registry.test.ts | 244 ++++++++++++------ 1 file changed, 168 insertions(+), 76 deletions(-) diff --git a/tests/platform/cardinality/extreme-scale-registry.test.ts b/tests/platform/cardinality/extreme-scale-registry.test.ts index 84e7de93..f7737647 100644 --- a/tests/platform/cardinality/extreme-scale-registry.test.ts +++ b/tests/platform/cardinality/extreme-scale-registry.test.ts @@ -1,4 +1,4 @@ -import { performance } from "node:perf_hooks"; +import { types } from "node:util"; import { describe, expect, it } from "vitest"; @@ -7,59 +7,141 @@ import { selectCompiledProductFeatures, } from "../../../src/contracts/product-features.ts"; import { composeUniqueRecord } from "../../../src/platform/cardinality/compose-unique-record.ts"; -import { assertLinearOrBetter } from "../../../src/platform/cardinality/growth-regression.ts"; +import { + assertLinearOrBetter, + type GrowthSample, +} from "../../../src/platform/cardinality/growth-regression.ts"; /* - * This file runs in merge gates on CPUs nobody chose (FE-GATE-005 coverage and - * the pr scale tier), so it asserts only what holds on any CPU: how a cost - * grows from 10k to 100k entries, and how a registry lookup compares with a - * plain-object lookup timed in the same process. Absolute timings belong to - * check:scale:baseline, which compares them only on the CPU that recorded + * 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 MEASUREMENT_RUNS = 3; const MAX_COMPOSE_GROWTH_RATIO = 30; -/** Registry lookups against plain-object lookups on the same 100k keys. */ -const MAX_LOOKUP_OVERHEAD_RATIO = 3; +/** 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: 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 = 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( + counter: ReadCounter, + small: () => Result, + large: () => Result, + maxRatio: number, +): GrowthRun { + 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>[] { return Array.from({ length: count }, (_, index) => ({ [`key-${index}`]: index })); } -function elapsedMs(action: () => void, repetitions: number): number { - const startedAt = performance.now(); - for (let repetition = 0; repetition < repetitions; repetition += 1) action(); - return (performance.now() - startedAt) / repetitions; -} - -/** - * Per-call cost of `left` and `right`, timed in alternating runs so both see - * the same background load. `leftRepetitions` makes the 10k side do as much - * work per run as the 100k side: on a shared core a 10ms run can finish inside - * one scheduler slice while a 100ms run waits behind other processes, which - * reads as steeper growth than the code has. Other processes and GC pauses only - * ever add time, so each side keeps its fastest run (check:scale:baseline reads - * growth from minMs for the same reason). - */ -function timeAlternately( - left: () => void, - right: () => void, - leftRepetitions = 1, -): Readonly<{ leftMs: number; rightMs: number }> { - left(); - right(); - let leftMs = Number.POSITIVE_INFINITY; - let rightMs = Number.POSITIVE_INFINITY; - for (let run = 0; run < MEASUREMENT_RUNS; run += 1) { - leftMs = Math.min(leftMs, elapsedMs(left, leftRepetitions)); - rightMs = Math.min(rightMs, elapsedMs(right, 1)); - } - return Object.freeze({ leftMs, rightMs }); +function countedRecords( + count: number, + counter: ReadCounter, +): readonly Readonly>[] { + return counted( + syntheticRecords(count).map((record) => counted(record, counter)), + counter, + ); } function lookupChecksum(registry: Readonly>): number { @@ -72,20 +154,26 @@ function lookupChecksum(registry: Readonly>): number { describe("extreme-scale registry composition", () => { it("keeps 10k -> 100k composition growth below a quadratic regression budget", () => { - const smallRecords = syntheticRecords(SMALL_REGISTRY_SIZE); - const largeRecords = syntheticRecords(LARGE_REGISTRY_SIZE); + 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 { leftMs: smallMs, rightMs: largeMs } = timeAlternately( + const { + series: [small, large], + results: [smallRegistry, largeRegistry], + } = readGrowth( + counter, () => compose(smallRecords), () => compose(largeRecords), - SIZE_RATIO, + MAX_COMPOSE_GROWTH_RATIO, ); - const growthRatio = largeMs / Math.max(smallMs, 1); - expect(Object.keys(compose(smallRecords))).toHaveLength(SMALL_REGISTRY_SIZE); - expect(Object.keys(compose(largeRecords))).toHaveLength(LARGE_REGISTRY_SIZE); - expect(growthRatio).toBeLessThan(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", () => { @@ -94,30 +182,35 @@ describe("extreme-scale registry composition", () => { const plain: Record = {}; for (const record of records) Object.assign(plain, record); - const { leftMs: registryMs, rightMs: plainMs } = timeAlternately( - () => lookupChecksum(registry), - () => lookupChecksum(plain), - ); + // `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)); - expect(registryMs / plainMs).toBeLessThan(MAX_LOOKUP_OVERHEAD_RATIO); }); }); -function membershipInput(size: number) { - const compiled = Array.from({ length: size }, (_, index) => - Object.freeze({ featureId: `feature-${index.toString().padStart(6, "0")}` }), +function membershipInput(size: number, counter: ReadCounter) { + const ids = Array.from( + { length: size }, + (_, index) => `feature-${index.toString().padStart(6, "0")}`, ); - const declared = compiled - .filter((_, index) => index % 10 === 0) - .map((feature) => feature.featureId) - .join(","); - const compiledIds = compiled.map((feature) => feature.featureId); - const installedIds = selectCompiledProductFeatures(compiled, declared).map( - (feature) => feature.featureId, + 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), @@ -126,24 +219,23 @@ function membershipInput(size: number) { describe("extreme-scale product feature membership", () => { it("selects and resolves 100k feature ids with near-linear growth from 10k", () => { - const small = membershipInput(SMALL_REGISTRY_SIZE); - const large = membershipInput(LARGE_REGISTRY_SIZE); - const selection = timeAlternately(small.select, large.select, SIZE_RATIO); - const resolution = timeAlternately(small.resolve, large.resolve, SIZE_RATIO); - const statuses = large.resolve(); + 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(large.select()).toHaveLength(LARGE_REGISTRY_SIZE / 10); + 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, ); - assertLinearOrBetter([ - { n: SMALL_REGISTRY_SIZE, cost: selection.leftMs }, - { n: LARGE_REGISTRY_SIZE, cost: selection.rightMs }, - ]); - assertLinearOrBetter([ - { n: SMALL_REGISTRY_SIZE, cost: resolution.leftMs }, - { n: LARGE_REGISTRY_SIZE, cost: resolution.rightMs }, - ]); + // 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 }); }); }); -- 2.54.0