test(scale): 극한 규모 증가율을 벽시계 대신 입력 읽기 횟수로 잰다 #62
@@ -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 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 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<Record<string, number>>[] {
|
||||
return counted(
|
||||
syntheticRecords(count).map((record) => counted(record, counter)),
|
||||
counter,
|
||||
);
|
||||
}
|
||||
|
||||
function lookupChecksum(registry: Readonly<Record<string, number>>): number {
|
||||
@@ -72,20 +154,26 @@ function lookupChecksum(registry: Readonly<Record<string, number>>): 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<string, number> = {};
|
||||
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 });
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user