diff --git a/config/scale/feature-shape-growth.json b/config/scale/feature-shape-growth.json new file mode 100644 index 00000000..2a28b36e --- /dev/null +++ b/config/scale/feature-shape-growth.json @@ -0,0 +1,210 @@ +{ + "schemaVersion": 1, + "measuredAt": "2026-09-27T04:03:00.821Z", + "command": "node scripts/scale/measure-feature-shape-growth.ts --sizes=0,25,100 --repeats=2", + "environment": { + "node": "24.14.0", + "platform": "linux", + "arch": "x64", + "cpuModel": "Intel(R) Core(TM) i5-10400F CPU @ 2.90GHz", + "logicalCpus": 12, + "availableParallelism": 12, + "typescript": "Version 7.0.2", + "vite": "vite/8.1.5 linux-x64 node-v24.14.0" + }, + "sourceFeature": "src/features/reference-feature", + "runs": [ + { + "repeat": 1, + "addedFeatures": 0, + "routes": 10, + "tsc": { + "passed": true, + "firstError": null, + "files": 840, + "types": 284678, + "symbols": 802946, + "instantiations": 712089, + "memoryKb": 520454, + "wallMs": 3408 + }, + "build": { + "wallMs": 1208, + "initialJavascriptFiles": 13, + "initialJavascriptGzipBytes": 200001, + "lazyJavascriptFiles": 14, + "lazyJavascriptGzipBytes": 24938 + }, + "loadBefore": [ + 25.05, + 16.88, + 7.75 + ], + "loadAfter": [ + 26.4, + 17.3, + 7.93 + ] + }, + { + "repeat": 2, + "addedFeatures": 0, + "routes": 10, + "tsc": { + "passed": true, + "firstError": null, + "files": 840, + "types": 284678, + "symbols": 802946, + "instantiations": 712089, + "memoryKb": 520395, + "wallMs": 3930 + }, + "build": { + "wallMs": 1526, + "initialJavascriptFiles": 13, + "initialJavascriptGzipBytes": 200001, + "lazyJavascriptFiles": 14, + "lazyJavascriptGzipBytes": 24938 + }, + "loadBefore": [ + 26.4, + 17.3, + 7.93 + ], + "loadAfter": [ + 27.65, + 17.71, + 8.12 + ] + }, + { + "repeat": 1, + "addedFeatures": 25, + "routes": 110, + "tsc": { + "passed": true, + "firstError": null, + "files": 1366, + "types": 1055723, + "symbols": 2831441, + "instantiations": 3579093, + "memoryKb": 1422337, + "wallMs": 8121 + }, + "build": { + "wallMs": 1676, + "initialJavascriptFiles": 39, + "initialJavascriptGzipBytes": 274493, + "lazyJavascriptFiles": 165, + "lazyJavascriptGzipBytes": 171638 + }, + "loadBefore": [ + 27.65, + 17.71, + 8.12 + ], + "loadAfter": [ + 27.17, + 17.93, + 8.29 + ] + }, + { + "repeat": 2, + "addedFeatures": 25, + "routes": 110, + "tsc": { + "passed": true, + "firstError": null, + "files": 1366, + "types": 1055723, + "symbols": 2831441, + "instantiations": 3579093, + "memoryKb": 1422431, + "wallMs": 8714 + }, + "build": { + "wallMs": 2140, + "initialJavascriptFiles": 39, + "initialJavascriptGzipBytes": 274493, + "lazyJavascriptFiles": 165, + "lazyJavascriptGzipBytes": 171638 + }, + "loadBefore": [ + 27.17, + 17.93, + 8.29 + ], + "loadAfter": [ + 27.55, + 18.46, + 8.62 + ] + }, + { + "repeat": 1, + "addedFeatures": 100, + "routes": 410, + "tsc": { + "passed": true, + "firstError": null, + "files": 2941, + "types": 3349868, + "symbols": 8940533, + "instantiations": 12157304, + "memoryKb": 4195900, + "wallMs": 31315 + }, + "build": { + "wallMs": 6010, + "initialJavascriptFiles": 114, + "initialJavascriptGzipBytes": 490658, + "lazyJavascriptFiles": 615, + "lazyJavascriptGzipBytes": 704938 + }, + "loadBefore": [ + 27.43, + 18.59, + 8.71 + ], + "loadAfter": [ + 29.72, + 20.12, + 9.64 + ] + }, + { + "repeat": 2, + "addedFeatures": 100, + "routes": 410, + "tsc": { + "passed": true, + "firstError": null, + "files": 2941, + "types": 3349868, + "symbols": 8940533, + "instantiations": 12157304, + "memoryKb": 4195704, + "wallMs": 43234 + }, + "build": { + "wallMs": 3702, + "initialJavascriptFiles": 114, + "initialJavascriptGzipBytes": 490658, + "lazyJavascriptFiles": 615, + "lazyJavascriptGzipBytes": 704938 + }, + "loadBefore": [ + 29.72, + 20.12, + 9.64 + ], + "loadAfter": [ + 35.75, + 22.97, + 11.09 + ] + } + ] +} diff --git a/docs/reviews/2026-09-23-extreme-scale-acceptance.md b/docs/reviews/2026-09-23-extreme-scale-acceptance.md index f62aba3c..b12c2e43 100644 --- a/docs/reviews/2026-09-23-extreme-scale-acceptance.md +++ b/docs/reviews/2026-09-23-extreme-scale-acceptance.md @@ -8,7 +8,7 @@ Plan bundle: `docs/reviews/2026-09-23-extreme-scale-frontend-plan-bundle/`. One | 2 | Composition does not contain known quadratic accumulation patterns. | 완료 | `src/platform/cardinality/compose-unique-record.ts`; `tests/platform/cardinality/compose-unique-record.test.ts`; `tests/platform/cardinality/extreme-scale-registry.test.ts`; growth gate `scripts/scale/run-composition-scale.ts` + `src/platform/cardinality/growth-regression.ts` (`tests/scale/composition-scale.test.ts`, `tests/scale/growth-regression.test.ts`, artifact `artifacts/scale/main/composition-s0-s2.json`); stored-baseline gate `pnpm check:scale:baseline` (`config/scale/benchmark-baseline.json`) | | 3 | Membership checks on scale-sensitive paths use appropriate indexed structures. | 완료 | `src/contracts/product-features.ts` (`Set` membership); `tests/unit/product-features.test.ts`; `tests/features/product-features-scale.test.ts`; 100k selection/resolution in `tests/platform/cardinality/extreme-scale-registry.test.ts`; workloads `product-feature-selection`/`product-feature-resolution` in `scripts/scale/composition-workloads.ts` | | 4 | Concrete imports across unrelated features fail architecture checks. | 완료 | `.dependency-cruiser.json` rules `features-do-not-import-other-features`, `contexts-do-not-import-other-contexts`; rejected fixtures `tests/fixtures/architecture/dependency-graph/cross-boundary/`; assertions in `scripts/check-architecture.ts`; `pnpm check:architecture` | -| 5 | Context/app cardinality ceilings are explicit and testable. | 완료 | `src/platform/cardinality/cardinality-budget.ts`; `src/contexts/bounded-context-module.ts`; `src/apps/deployable-app-module.ts`; `tests/architecture/topology-cardinality.test.ts`; `tests/architecture/module-hierarchy.test.ts`; `tests/platform/cardinality/cardinality-budget.test.ts` | +| 5 | Context/app cardinality ceilings are explicit and testable. | 완료 | `src/platform/cardinality/cardinality-budget.ts`; `src/contexts/bounded-context-module.ts`; `src/apps/deployable-app-module.ts`; `tests/architecture/topology-cardinality.test.ts`; `tests/architecture/module-hierarchy.test.ts`; `tests/platform/cardinality/cardinality-budget.test.ts`. The ceilings are declared limits, not a measured capacity: see "Growth inside one app" below (11-04) | | 6 | An unchanged local app does not grow materially when global logical topology grows toward S3/S4 fixtures. | 완료 | (1) Ownership source: `src/apps/template-app/app-module.ts`, `src/contexts/reference-context/context-module.ts`, `FEATURE_CONTEXT_ID`. (2) Production projection: `scripts/generate-product-feature-index.ts` selects one app (`--app=`/`PRODUCT_APP_ID`) → `src/.generated/{product-feature-index,product-context-index,product-app}.ts` → `src/apps/template-app.ts`. (3) S0→S4 invariant: `tests/scale/global-local-independence.test.ts` — S0/S1/S2 real on-disk repos through the generator command (identical generated files, sha256 and reachable source graph); S0→S4 through the same `selectAppIndexes` (identical feature/context ids, route roots, generated files, hashes and compile-input paths; only App A's declarations read at 1M), pinned to the filesystem source by an equivalence test. (4) Build-input gate: `scripts/check-app-build-input.ts` (`pnpm check:app-build-input`, and `check:app-build-input:bundle` on the fresh production bundle), negative fixtures in `tests/architecture/app-build-input.test.ts` | | 7 | Initial routing is hierarchical/lazy rather than a product-wide flat feature table. | 완료 | `src/platform/routing/context-route-module.ts`; `src/presentation/routes/app-router.tsx` (`ContextRouteGateway`); `tests/platform/routing/context-route-module.test.ts`; `tests/architecture/context-lazy-loading.test.ts`; `tests/features/reference-feature/installed-context-routing.test.ts` | | 8 | User interactions carry bounded request, retry, concurrency, cancellation, and deadline semantics. | 완료 | `src/platform/execution/execution-context.ts`; `src/platform/traffic/{request-budget,concurrency-budget,traffic-budget}.ts`; `src/platform/resilience/{retry-budget,deadline}.ts`; enforcement in `src/adapters/http/http-execution-v3.ts`; operation policy `HttpExecutionPolicy.traffic` (`src/contracts/external-contract-runtime.ts`); `tests/platform/traffic/http-budget-integration.test.ts`; `tests/platform/traffic/traffic-amplification.test.ts`; `pnpm check:traffic` | @@ -24,6 +24,30 @@ Plan bundle: `docs/reviews/2026-09-23-extreme-scale-frontend-plan-bundle/`. One Overall: **완료** — every spec §54 criterion is `완료`. +## Growth inside one app (11-04) + +The rows above show that one app does not change when the *global* topology grows. What one app costs as its *own* feature count grows is measured separately, with copies of the real reference feature: `scripts/scale/measure-feature-shape-growth.ts` copies `src/features/reference-feature` N times with every feature-owned identifier renamed (feature id, routes, operations, schemas, query namespace, invalidation topic, messages), into contexts of 200 features each, and proves that the copies compose (the registries throw at module evaluation on any duplicate). The baseline is `config/scale/feature-shape-growth.json`, re-created with `node scripts/scale/measure-feature-shape-growth.ts --sizes=0,25,100 --repeats=2 --write` and checked by `tests/unit/feature-shape-growth.test.ts`. + +Measured 2026-09-27, two runs per size, Intel i5-10400F (12 logical CPUs), Node 24.14.0, TypeScript 7.0.2, Vite 8.1.5. Load average 25–30 during the runs (other agents were building in parallel), so wall times are upper bounds; counts and bytes are identical in both runs. + +| Added features | Routes | tsc instantiations | tsc memory | tsc wall (run 1 / 2) | vite build wall | Initial JS files / gzip | Lazy JS files / gzip | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 0 | 10 | 712,089 | 0.5 GB | 3.4 s / 3.9 s | 1.2 s / 1.5 s | 13 / 200,001 B | 14 / 24,938 B | +| 25 | 110 | 3,579,093 | 1.4 GB | 8.1 s / 8.7 s | 1.7 s / 2.1 s | 39 / 274,493 B | 165 / 171,638 B | +| 100 | 410 | 12,157,304 | 4.2 GB | 31.3 s / 43.2 s | 6.0 s / 3.7 s | 114 / 490,658 B | 615 / 704,938 B | + +What this means for the declared ceilings (`CONTEXT_MAX_FEATURES = 200`, `src/contexts/reference-context/context-module.ts:10`; `APP_MAX_CONTEXTS = 20`, `src/apps/template-app/app-module.ts:7`): + +| Growth axis | Verified | Condition | Not verified | +| --- | --- | --- | --- | +| Typecheck of one app | Linear, about 115k instantiations and 37 MB of tsc memory per feature, up to 100 features | Reference-shaped features, `tsconfig.app.json`, the host above | 200 features (one full context) and beyond; 4,000 (20 × 200) would need on the order of 150 GB by the same slope | +| Production build | Completes at 100 features in seconds | Same | Beyond 100 | +| Initial JavaScript | Grows by about 2.9 KB gzip and one file per feature: every installed feature's contracts and module load at boot | Same | — the initial budget (204,800 B, `config/performance/budgets.json`) (about 196.5 KB used by `check:bundle`) is exceeded after about three more reference-shaped features, far below the context ceiling | +| Lazy JavaScript | About 6.8 KB gzip and six files per feature, every file far below the 120 KiB lazy-chunk budget | Same | Download cost of many lazy files | +| Routes | 4 per feature, composed without conflict | Same | Router matching cost at runtime | + +So the ceilings bound the *count*; they are not a verified capacity. The practical limit of one app today is the initial JavaScript budget, then typecheck memory. 400 features were not measured (D-18 makes it optional; at the observed slope a run needs about 16 GB of tsc memory). + ## Executable evidence (supported runtime) Re-run on Node **v24.11.0** / pnpm 11.17.0 inside the `workmachine` container (whose default Node v22.23.2 is below `engines.node`): diff --git a/scripts/scale/measure-feature-shape-growth.ts b/scripts/scale/measure-feature-shape-growth.ts new file mode 100644 index 00000000..dba1ec0e --- /dev/null +++ b/scripts/scale/measure-feature-shape-growth.ts @@ -0,0 +1,257 @@ +import { spawnSync } from "node:child_process"; +import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { availableParallelism, cpus, loadavg, tmpdir } from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { gzipSync } from "node:zlib"; + +import { classifyViteJavascript } from "../lib/classify-vite-bundle.ts"; +import { linkFixtureNodeModules } from "../lib/fixture-node-modules.ts"; +import { parseTscExtendedDiagnostics, type TscDiagnostics } from "./collect-tsc-diagnostics.ts"; + +/** + * 11-04 (D-18). Cost of one app as its feature count grows, measured with + * features shaped like the real one: `src/features/reference-feature` copied N + * times with every feature-owned identifier renamed (feature id, route ids and + * paths, API operations, schemas, query namespace, invalidation topic, + * messages). The copies live in contexts of their own (200 features each, the + * context ceiling) so the reference context is unchanged. + * + * For each N the script runs the product generator, `tsc --extendedDiagnostics` + * over tsconfig.app.json and `vite build`, and records compiler counts, wall + * times and initial/lazy JavaScript gzip bytes. Deterministic counts repeat + * exactly; times depend on the host, so the CPU and load average are recorded + * next to them. A typecheck that fails (for example TS2590, a union too complex + * to represent) is recorded as a result with its first error. + * + * node scripts/scale/measure-feature-shape-growth.ts [--sizes=0,25,100] [--repeats=2] [--write] + * + * `--write` stores the result as config/scale/feature-shape-growth.json. + */ +export const FEATURE_SHAPE_BASELINE_PATH = "config/scale/feature-shape-growth.json"; + +const SOURCE_FEATURE = "src/features/reference-feature"; +const FEATURES_PER_CONTEXT = 200; +const BUILD_INPUTS = [ + "src", + "public", + "index.html", + "package.json", + "vite.config.ts", + "tsconfig.base.json", + "tsconfig.app.json", + "scripts/lib/vite-module-inventory.ts", +] as const; +// Platform-owned names that only happen to contain "reference". +const PLATFORM_TOKENS = [ + "REFERENCE_EXTERNAL_BEARER", + "REFERENCE_FEATURE_V1", + "supportReference", +] as const; + +/** Renames every feature-owned identifier of the reference feature for copy `id`. */ +export function renameReferenceFeature( + text: string, + id: string, + context: Readonly<{ id: string; routeRoot: string }>, +): string { + const upper = id.toUpperCase(); + let renamed = text; + PLATFORM_TOKENS.forEach((token, index) => { + renamed = renamed.replaceAll(token, `\u0000${index}\u0000`); + }); + renamed = renamed + .replaceAll("/examples/reference-resources", `/${context.routeRoot}/${id}-resources`) + .replaceAll("qinv.01k10f7m3w9p6r2c8v5n4x", `qinv.shape.${id}`) + .replaceAll("NoRequest", `${upper}NoRequest`) + .replaceAll("reference-context", context.id) + .replaceAll("REFERENCE", upper) + .replaceAll("Reference", upper) + .replaceAll("reference", id); + PLATFORM_TOKENS.forEach((token, index) => { + renamed = renamed.replaceAll(`\u0000${index}\u0000`, token); + }); + return renamed; +} + +async function copyRenamed(from: string, to: string, rename: (text: string) => string) { + await mkdir(to, { recursive: true }); + for (const entry of await readdir(from, { withFileTypes: true })) { + const source = path.join(from, entry.name); + const target = path.join(to, rename(entry.name)); + if (entry.isDirectory()) await copyRenamed(source, target, rename); + else await writeFile(target, rename(await readFile(source, "utf8"))); + } +} + +async function createFixture(features: number): Promise { + const root = await mkdtemp(path.join(tmpdir(), `feature-shape-${features}-`)); + for (const input of BUILD_INPUTS) { + await mkdir(path.dirname(path.join(root, input)), { recursive: true }); + await cp(path.resolve(input), path.join(root, input), { recursive: true }); + } + await rm(path.join(root, "src/.generated"), { recursive: true, force: true }); + await linkFixtureNodeModules(root); + for (let index = 0; index < features; index += 1) { + const contextNumber = Math.floor(index / FEATURES_PER_CONTEXT); + const context = { id: `shape-context-${contextNumber}`, routeRoot: `shape-${contextNumber}` }; + if (index % FEATURES_PER_CONTEXT === 0) { + const contextFile = path.join(root, "src/contexts", context.id, "context-module.ts"); + await mkdir(path.dirname(contextFile), { recursive: true }); + await writeFile( + contextFile, + `export const CONTEXT_MODULE_ID = "${context.id}";\n` + + `export const CONTEXT_APP_ID = "template-app";\n` + + `export const CONTEXT_ROUTE_PATH = "${context.routeRoot}/*";\n` + + `export const CONTEXT_MAX_FEATURES = ${FEATURES_PER_CONTEXT};\n`, + ); + } + const id = `s${String(index).padStart(3, "0")}`; + await copyRenamed( + path.resolve(SOURCE_FEATURE), + path.join(root, "src/features", `${id}-feature`), + (text) => renameReferenceFeature(text, id, context), + ); + } + return root; +} + +function run( + command: string, + args: readonly string[], + cwd: string, + options: Readonly<{ allowFailure?: boolean }> = {}, +) { + const started = performance.now(); + const result = spawnSync(command, args, { + cwd, + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + }); + const ms = Math.round(performance.now() - started); + if (result.status !== 0 && !(options.allowFailure && result.stdout.includes("Instantiations:"))) { + throw new Error( + `${path.basename(command)} ${args.join(" ")} failed in ${cwd}:\n${(result.stdout + result.stderr).slice(0, 4_000)}`, + ); + } + return { ms, passed: result.status === 0, stdout: result.stdout }; +} + +const load = () => loadavg().map((value) => Math.round(value * 100) / 100); + +async function javascriptGzipBytes(root: string, files: readonly string[]) { + let bytes = 0; + for (const file of files) bytes += gzipSync(await readFile(path.join(root, "dist", file))).byteLength; + return bytes; +} + +async function measureOnce(root: string, features: number) { + const loadBefore = load(); + run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root); + // The composed registries throw at module evaluation on a duplicate route, + // operation, schema, namespace or message key: prove the copies compose. + const contracts = (await import( + `${pathToFileURL(path.join(root, "src/features/installed-feature-contracts.ts")).href}?features=${features}` + )) as typeof import("../../src/features/installed-feature-contracts.ts"); + const routes = Object.keys(contracts.ROUTE_REGISTRY).length; + const tsc = run( + path.resolve("node_modules/.bin/tsc"), + ["--project", path.join(root, "tsconfig.app.json"), "--noEmit", "--extendedDiagnostics"], + root, + // A type error is a result here (the typecheck stops scaling), not a crash. + { allowFailure: true }, + ); + await rm(path.join(root, "dist"), { recursive: true, force: true }); + const build = run(path.resolve("node_modules/.bin/vite"), ["build", "--logLevel", "error"], root); + const manifest = JSON.parse(await readFile(path.join(root, "dist/.vite/manifest.json"), "utf8")); + const javascript = classifyViteJavascript(manifest); + const diagnostics: TscDiagnostics = parseTscExtendedDiagnostics(tsc.stdout); + return { + addedFeatures: features, + routes, + tsc: { + passed: tsc.passed, + firstError: tsc.stdout.split("\n").find((line) => line.includes("error TS")) ?? null, + files: diagnostics.files, + types: diagnostics.types, + symbols: diagnostics.symbols, + instantiations: diagnostics.instantiations, + memoryKb: diagnostics.memoryKb ?? null, + wallMs: tsc.ms, + }, + build: { + wallMs: build.ms, + initialJavascriptFiles: javascript.initialFiles.length, + initialJavascriptGzipBytes: await javascriptGzipBytes(root, javascript.initialFiles), + lazyJavascriptFiles: javascript.lazyFiles.length, + lazyJavascriptGzipBytes: await javascriptGzipBytes(root, javascript.lazyFiles), + }, + loadBefore, + loadAfter: load(), + }; +} + +function version(bin: string): string { + const result = spawnSync(path.resolve("node_modules/.bin", bin), ["--version"], { encoding: "utf8" }); + return (result.stdout ?? "").trim(); +} + +async function main(): Promise { + const argument = (name: string) => + process.argv.find((entry) => entry.startsWith(`--${name}=`))?.slice(name.length + 3); + const sizes = (argument("sizes") ?? "0,25,100").split(",").map(Number); + const repeats = Number(argument("repeats") ?? "2"); + if (!sizes.every((size) => Number.isSafeInteger(size) && size >= 0) || !(repeats >= 1)) { + throw new TypeError("--sizes must be nonnegative integers and --repeats at least 1"); + } + const runs = []; + for (const features of sizes) { + const root = await createFixture(features); + try { + for (let repeat = 1; repeat <= repeats; repeat += 1) { + const measured = await measureOnce(root, features); + runs.push({ repeat, ...measured }); + process.stdout.write( + `features +${features} (repeat ${repeat}): routes=${measured.routes} ` + + `instantiations=${measured.tsc.instantiations} tsc=${measured.tsc.wallMs}ms ` + + `build=${measured.build.wallMs}ms initial=${measured.build.initialJavascriptGzipBytes}B ` + + `lazy=${measured.build.lazyJavascriptGzipBytes}B load=${measured.loadBefore.join("/")}` + + `${measured.tsc.passed ? "" : ` typecheck FAILED: ${measured.tsc.firstError}`}\n`, + ); + // Compiler results repeat exactly; a failed typecheck costs minutes and + // gigabytes again for no new information. + if (!measured.tsc.passed) break; + } + } finally { + await rm(root, { recursive: true, force: true }); + } + } + const cpu = cpus(); + const result = { + schemaVersion: 1, + measuredAt: new Date().toISOString(), + command: `node scripts/scale/measure-feature-shape-growth.ts --sizes=${sizes.join(",")} --repeats=${repeats}`, + environment: { + node: process.versions.node, + platform: process.platform, + arch: process.arch, + cpuModel: cpu[0]?.model.trim() ?? "unknown", + logicalCpus: cpu.length, + availableParallelism: availableParallelism(), + typescript: version("tsc"), + vite: version("vite"), + }, + sourceFeature: SOURCE_FEATURE, + runs, + }; + const output = process.argv.includes("--write") + ? FEATURE_SHAPE_BASELINE_PATH + : "artifacts/scale/feature-shape-growth.json"; + await mkdir(path.dirname(output), { recursive: true }); + await writeFile(output, `${JSON.stringify(result, null, 2)}\n`); + process.stdout.write(`feature-shape growth: ${output}\n`); +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + await main(); +} diff --git a/tests/unit/feature-shape-growth.test.ts b/tests/unit/feature-shape-growth.test.ts new file mode 100644 index 00000000..fffc0b52 --- /dev/null +++ b/tests/unit/feature-shape-growth.test.ts @@ -0,0 +1,103 @@ +import { readFile } from "node:fs/promises"; + +import { describe, expect, it } from "vitest"; + +import { + FEATURE_SHAPE_BASELINE_PATH, + renameReferenceFeature, +} from "../../scripts/scale/measure-feature-shape-growth.ts"; + +/** + * 11-04 (D-18). The scale evidence used to come from stub features that only + * differ by name, so the cost of one app growing towards its declared ceiling + * (20 contexts x 200 features) was never measured. The committed baseline is a + * measurement with copies of the real reference feature. + */ +const context = { id: "shape-context-0", routeRoot: "shape-0" } as const; + +type Run = Readonly<{ + addedFeatures: number; + routes: number; + tsc: Readonly<{ passed: boolean; instantiations: number; wallMs: number }>; + build: Readonly<{ + wallMs: number; + initialJavascriptGzipBytes: number; + lazyJavascriptFiles: number; + }>; + loadBefore: readonly number[]; +}>; + +describe("feature-shape growth measurement (11-04)", () => { + it("renames every feature-owned identifier of a reference copy", () => { + const source = [ + 'featureId: "reference-feature"', + 'path: "/examples/reference-resources/:id"', + "REFERENCE_RESOURCE_LIST", + "ReferenceResourcePage", + 'contextId: "reference-context"', + 'topic: "qinv.01k10f7m3w9p6r2c8v5n4x"', + "NoRequest", + ].join("\n"); + + const renamed = renameReferenceFeature(source, "s007", context); + + expect(renamed).not.toMatch(/reference/iu); + expect(renamed).toContain('featureId: "s007-feature"'); + expect(renamed).toContain('path: "/shape-0/s007-resources/:id"'); + expect(renamed).toContain("S007_RESOURCE_LIST"); + expect(renamed).toContain("S007ResourcePage"); + expect(renamed).toContain('contextId: "shape-context-0"'); + expect(renamed).toContain('topic: "qinv.shape.s007"'); + expect(renamed).toContain("S007NoRequest"); + }); + + it("keeps platform-owned names that only contain the word", () => { + const source = + "REFERENCE_EXTERNAL_BEARER REFERENCE_FEATURE_V1 supportReference"; + + expect(renameReferenceFeature(source, "s001", context)).toBe(source); + }); + + it("commits a baseline measured at 25 and 100 real-shape features, twice each", async () => { + const baseline = JSON.parse( + await readFile(FEATURE_SHAPE_BASELINE_PATH, "utf8"), + ) as Readonly<{ + environment: Readonly>; + runs: readonly Run[]; + }>; + expect(baseline.environment).toMatchObject({ + cpuModel: expect.any(String), + logicalCpus: expect.any(Number), + }); + + const bySize = (size: number) => + baseline.runs.filter((run) => run.addedFeatures === size); + const [origin] = bySize(0); + expect(origin?.tsc.passed).toBe(true); + for (const size of [25, 100]) { + const runs = bySize(size); + // A failed typecheck is the result and is not repeated. + expect(runs.length).toBeGreaterThanOrEqual(runs[0]?.tsc.passed ? 2 : 1); + for (const run of runs) { + // Every copy contributes the reference feature's own routes. + expect((run.routes - origin!.routes) % size).toBe(0); + expect(run.routes).toBeGreaterThan(origin!.routes); + expect(run.build.lazyJavascriptFiles).toBeGreaterThan( + origin!.build.lazyJavascriptFiles, + ); + expect(run.loadBefore).toHaveLength(3); + } + // Compiler counts are deterministic; only times vary with the host. + expect(new Set(runs.map((run) => run.tsc.instantiations)).size).toBe(1); + } + }); + + it("states in the acceptance matrix what the ceilings rest on", async () => { + const acceptance = await readFile( + "docs/reviews/2026-09-23-extreme-scale-acceptance.md", + "utf8", + ); + expect(acceptance).toContain(FEATURE_SHAPE_BASELINE_PATH); + expect(acceptance).toMatch(/\| Growth axis \| Verified \| Condition \| Not verified \|/u); + }); +});