Merge pull request 'refactor: 도메인 확장에 유지보수 쉬운 구조로 변경' (#1) from refactor/domain-scalable into main
This commit was merged in pull request #1.
This commit is contained in:
@@ -204,6 +204,54 @@
|
||||
"pathNot": "^src/adapters/[^/]+/index\\.ts$|^src/adapters/[^/]+/[^/]+/index\\.ts$"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "features-do-not-import-other-features",
|
||||
"comment": "A feature may depend on shared contracts/ports, but never on another feature concrete implementation.",
|
||||
"severity": "error",
|
||||
"from": {
|
||||
"path": "^src/features/([^/]+)/"
|
||||
},
|
||||
"to": {
|
||||
"path": "^src/features/[^/]+/",
|
||||
"pathNot": "^src/features/$1/"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "contexts-do-not-import-other-contexts",
|
||||
"comment": "A bounded context may compose its own features and shared platform contracts, but not another context concrete implementation.",
|
||||
"severity": "error",
|
||||
"from": {
|
||||
"path": "^src/contexts/([^/]+)/"
|
||||
},
|
||||
"to": {
|
||||
"path": "^src/contexts/[^/]+/",
|
||||
"pathNot": "^src/contexts/$1/"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "observability-vendors-live-behind-adapters",
|
||||
"comment": "Spec §24. Features, platform, application, domain, contracts and presentation emit observability only through the provider-neutral TelemetryPort. A vendor telemetry SDK may be imported only by an adapter-side transport under src/adapters.",
|
||||
"severity": "error",
|
||||
"from": {
|
||||
"path": "^src/",
|
||||
"pathNot": "^src/adapters/"
|
||||
},
|
||||
"to": {
|
||||
"path": "^(@sentry|@datadog|@opentelemetry|@newrelic|newrelic|@honeycombio|@bugsnag|bugsnag-js|@rollbar|rollbar|logrocket|@logrocket|@amplitude|posthog-js|mixpanel-browser|@segment|@elastic/apm-rum|@grafana/faro-web-sdk|@microsoft/applicationinsights-web)(/|$)"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "platform-kernel-is-product-neutral",
|
||||
"comment": "Spec §4. src/platform holds product-neutral primitives (budgets, execution, telemetry pipeline, validation, error envelopes). It never reaches up into a concrete feature, context, adapter, bootstrap or presentation module. Routing composes deployable-app descriptors by type and is the one named exception.",
|
||||
"severity": "error",
|
||||
"from": {
|
||||
"path": "^src/platform/",
|
||||
"pathNot": "^src/platform/routing/"
|
||||
},
|
||||
"to": {
|
||||
"path": "^src/(features|contexts|apps|adapters|bootstrap|presentation|application)/"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "no-circular-dependencies",
|
||||
"severity": "error",
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
$ node scripts/check-architecture.ts
|
||||
Static import graph: 330 modules, 984 dependencies, all imports resolved
|
||||
Architecture graph fixtures: 16 regression checks PASS
|
||||
TypeScript-only source policy: PASS (src, scripts, tests, .storybook, recipes; no fixture exceptions)
|
||||
Architecture fixtures: allowed PASS, 9 forbidden rejected
|
||||
@@ -0,0 +1 @@
|
||||
$ tsc --project tsconfig.app.json
|
||||
@@ -0,0 +1 @@
|
||||
$ tsc --project tsconfig.test.json
|
||||
@@ -0,0 +1,20 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/unit/http-retry-lifecycle.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 4[2mms[22m[39m
|
||||
[32m✓[39m tests/unit/realtime/bounded-polling-policy.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/unit/realtime/realtime-reconnect-policy.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/unit/retry-policy.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/unit/realtime/bounded-poll-coordinator.test.ts [2m([22m[2m16 tests[22m[2m)[22m[32m 25[2mms[22m[39m
|
||||
[32m✓[39m tests/unit/realtime/live-poll-handoff-coordinator.test.ts [2m([22m[2m13 tests[22m[2m)[22m[32m 71[2mms[22m[39m
|
||||
[32m✓[39m tests/unit/resumable-upload-runtime.test.ts [2m([22m[2m18 tests[22m[2m)[22m[32m 87[2mms[22m[39m
|
||||
[32m✓[39m tests/unit/realtime/realtime-reconnect-coordinator.test.ts [2m([22m[2m25 tests[22m[2m)[22m[32m 32[2mms[22m[39m
|
||||
[32m✓[39m tests/unit/tanstack-cache-coordinator.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 168[2mms[22m[39m
|
||||
[32m✓[39m tests/unit/resumable-upload-runtime-teardown.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 163[2mms[22m[39m
|
||||
[32m✓[39m tests/unit/realtime/stream-coordinator.test.ts [2m([22m[2m36 tests[22m[2m)[22m[33m 625[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m11 passed[39m[22m[90m (11)[39m
|
||||
[2m Tests [22m [1m[32m138 passed[39m[22m[90m (138)[39m
|
||||
[2m Start at [22m 08:27:14
|
||||
[2m Duration [22m 1.40s[2m (transform 1.56s, setup 3.50s, import 2.09s, tests 1.19s, environment 2ms)[22m
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
contract set: 0 package(s) sha256:ad6aab71fea6a9ff87cbd170b984b339965afc90d85bb57f87801c9e0c020da2
|
||||
vite v8.1.5 building client environment for production...
|
||||
[2K
|
||||
transforming...✓ 2113 modules transformed.
|
||||
rendering chunks...
|
||||
computing gzip size...
|
||||
dist/index.html 1.12 kB │ gzip: 0.45 kB
|
||||
dist/.vite/manifest.json 8.11 kB │ gzip: 1.04 kB
|
||||
dist/.vite/module-inventory.json 21.94 kB │ gzip: 3.15 kB
|
||||
dist/assets/index-C0p5zoj4.css 39.62 kB │ gzip: 8.51 kB
|
||||
dist/assets/installed-contract-contributions-CFHdeDEf.js 0.16 kB │ gzip: 0.15 kB
|
||||
dist/assets/not-found-page-CHQA5rw5.js 0.45 kB │ gzip: 0.30 kB
|
||||
dist/assets/reference-resource-status-page-t3RWROLD.js 0.51 kB │ gzip: 0.45 kB
|
||||
dist/assets/use-reference-failure-action-BYb2UYeT.js 0.57 kB │ gzip: 0.37 kB
|
||||
dist/assets/session-provider-CIR3Mmin.js 0.60 kB │ gzip: 0.39 kB
|
||||
dist/assets/application-provider-_OkSTAcq.js 0.61 kB │ gzip: 0.34 kB
|
||||
dist/assets/reference-resource-page-1-Q0DGen.js 1.21 kB │ gzip: 0.77 kB
|
||||
dist/assets/reference-resource-detail-page-D5mbWw2a.js 1.23 kB │ gzip: 0.72 kB
|
||||
dist/assets/async-state-CfvFHl3I.js 1.53 kB │ gzip: 0.49 kB
|
||||
dist/assets/auth-example-page-htVwyPYW.js 1.78 kB │ gzip: 0.94 kB
|
||||
dist/assets/context-routes-CEM0c3Wb.js 1.80 kB │ gzip: 0.70 kB
|
||||
dist/assets/server-state-DQADfngu.js 2.24 kB │ gzip: 0.90 kB
|
||||
dist/assets/home-page-a_jMrdst.js 2.37 kB │ gzip: 1.27 kB
|
||||
dist/assets/state-gallery-page-CunviFji.js 2.70 kB │ gzip: 1.22 kB
|
||||
dist/assets/reference-resource-form-page-BHq_gRJf.js 2.77 kB │ gzip: 1.50 kB
|
||||
dist/assets/installed-feature-contracts-DgTAlLr2.js 4.52 kB │ gzip: 1.43 kB
|
||||
dist/assets/ui-gallery-page-Ru0CrH32.js 8.09 kB │ gzip: 2.90 kB
|
||||
dist/assets/platform-overview-page-BgxC-c_W.js 11.90 kB │ gzip: 4.08 kB
|
||||
dist/assets/route-input-DpW3PpRj.js 19.72 kB │ gzip: 6.27 kB
|
||||
dist/assets/use-reference-feature-DkrwJNPz.js 23.75 kB │ gzip: 8.06 kB
|
||||
dist/assets/preload-helper-ChbRSsLi.js 101.06 kB │ gzip: 27.93 kB
|
||||
dist/assets/design-system-Bd1NzELd.js 213.52 kB │ gzip: 65.78 kB
|
||||
dist/assets/index-zhAbJ8ef.js 294.86 kB │ gzip: 91.72 kB
|
||||
|
||||
✓ built in 361ms
|
||||
runtime config: local profile written to dist/config.json (APP_ENV=local, AUTH_MODE=demo)
|
||||
service worker mode null: skipping worker build
|
||||
@@ -0,0 +1,2 @@
|
||||
app build input: app=template-app contexts=1 features=1 generatedImports=1 bundle=1 feature dirs PASS
|
||||
$ node scripts/check-app-build-input.ts --require-bundle
|
||||
@@ -0,0 +1,2 @@
|
||||
app build input: app=template-app contexts=1 features=1 generatedImports=1 bundle=not checked PASS
|
||||
$ node scripts/check-app-build-input.ts
|
||||
@@ -0,0 +1,5 @@
|
||||
Static import graph: 363 modules, 1043 dependencies, all imports resolved
|
||||
Architecture graph fixtures: 16 regression checks PASS
|
||||
TypeScript-only source policy: PASS (src, scripts, tests, .storybook, recipes; no fixture exceptions)
|
||||
Architecture fixtures: allowed PASS, 9 forbidden rejected
|
||||
$ node scripts/check-architecture.ts
|
||||
@@ -0,0 +1,2 @@
|
||||
Diagnostics contract: 8 diagnostics and 5 telemetry producers PASS
|
||||
$ node scripts/check-diagnostics.ts
|
||||
@@ -0,0 +1 @@
|
||||
$ node scripts/generate-product-feature-index.ts --check
|
||||
@@ -0,0 +1,23 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-port.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 8[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/redact-telemetry.test.ts [2m([22m[2m14 tests[22m[2m)[22m[32m 17[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-buffer.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 22[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/validation/validation-budget.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-deduplicator.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 13[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/observability-boundaries.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 142[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/errors/platform-errors.test.ts [2m([22m[2m16 tests[22m[2m)[22m[32m 23[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/trace-context.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 63[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/validation/bounded-json.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 107[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/errors/app-error.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/errors/failure-boundary.test.tsx [2m([22m[2m4 tests[22m[2m)[22m[32m 55[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-pipeline.test.ts [2m([22m[2m9 tests[22m[2m)[22m[33m 785[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m bounds network sends during a repeated error storm [33m 718[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m12 passed[39m[22m[90m (12)[39m
|
||||
[2m Tests [22m [1m[32m99 passed[39m[22m[90m (99)[39m
|
||||
[2m Start at [22m 13:29:27
|
||||
[2m Duration [22m 1.58s[2m (transform 1.38s, setup 3.81s, import 1.84s, tests 1.25s, environment 902ms)[22m
|
||||
|
||||
$ node scripts/run-vitest.ts run tests/platform/errors tests/platform/validation tests/platform/telemetry tests/architecture/observability-boundaries.test.ts --reporter=default
|
||||
@@ -0,0 +1,2 @@
|
||||
Registry governance: 11 registries PASS; compatibility=breaking
|
||||
$ node scripts/check-registries.ts
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/release/release-coherence.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/release/release-mismatch-recovery.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 14[2mms[22m[39m
|
||||
[32m✓[39m tests/release/old-asset-reachability.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 8[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/release/cache-policy.test.ts [2m([22m[2m5 tests[22m[2m)[22m[32m 39[2mms[22m[39m
|
||||
[32m✓[39m tests/release/release-matrix.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 48[2mms[22m[39m
|
||||
[32m✓[39m tests/release/mixed-replica.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 69[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m6 passed[39m[22m[90m (6)[39m
|
||||
[2m Tests [22m [1m[32m43 passed[39m[22m[90m (43)[39m
|
||||
[2m Start at [22m 13:29:30
|
||||
[2m Duration [22m 914ms[2m (transform 1.31s, setup 1.45s, import 2.18s, tests 187ms, environment 1ms)[22m
|
||||
|
||||
$ node scripts/run-vitest.ts run tests/platform/release tests/release --reporter=default
|
||||
@@ -0,0 +1,3 @@
|
||||
request fan-out: 77 files scanned, 0 per-row dispatches PASS
|
||||
request fan-out fixtures: forbidden 3 rejected in 3 files, allowed 0 violations PASS
|
||||
$ node scripts/check-request-fanout.ts && node scripts/check-request-fanout.ts --fixture
|
||||
@@ -0,0 +1,4 @@
|
||||
compatibility: structural=true compiler=true timing=true
|
||||
axes: absolute 28 (ok), growth 8 (ok), relative 16 compiler + 12 timing
|
||||
scale baseline gate: PASSED (artifacts/scale/baseline-comparison.json)
|
||||
$ node scripts/scale/check-scale-baseline.ts
|
||||
@@ -0,0 +1,10 @@
|
||||
PASSED main:architecture-topology (3173ms)
|
||||
PASSED main:traffic-budgets (1489ms)
|
||||
PASSED main:scale-units (2433ms)
|
||||
PASSED main:composition-s0-s1 (91ms)
|
||||
PASSED main:composition-s0-s2 (232ms)
|
||||
PASSED main:composition-scale-suite (941ms)
|
||||
PASSED main:typescript-diagnostics (1543ms)
|
||||
PASSED main:baseline-regression (1739ms)
|
||||
scale tier main: PASSED (artifacts/scale/main/summary.json)
|
||||
$ node scripts/scale/run-scale-profile.ts main
|
||||
@@ -0,0 +1,14 @@
|
||||
PASSED nightly:architecture-topology (3175ms)
|
||||
PASSED nightly:traffic-budgets (1393ms)
|
||||
PASSED nightly:scale-units (2435ms)
|
||||
PASSED nightly:composition-s0-s1 (90ms)
|
||||
PASSED nightly:composition-s0-s2 (226ms)
|
||||
PASSED nightly:composition-scale-suite (861ms)
|
||||
PASSED nightly:typescript-diagnostics (1552ms)
|
||||
PASSED nightly:baseline-regression (1750ms)
|
||||
PASSED nightly:topology-s3-s4 (6995ms)
|
||||
PASSED nightly:telemetry-storm (3703ms)
|
||||
PASSED nightly:session-cycles (1703ms)
|
||||
PASSED nightly:browser-soak (121407ms)
|
||||
scale tier nightly: PASSED (artifacts/scale/nightly/summary.json)
|
||||
$ node scripts/scale/run-scale-profile.ts nightly
|
||||
@@ -0,0 +1,6 @@
|
||||
PASSED pr:architecture-topology (4307ms)
|
||||
PASSED pr:traffic-budgets (1446ms)
|
||||
PASSED pr:scale-units (2377ms)
|
||||
PASSED pr:composition-s0-s1 (87ms)
|
||||
scale tier pr: PASSED (artifacts/scale/pr/summary.json)
|
||||
$ node scripts/scale/run-scale-profile.ts pr
|
||||
@@ -0,0 +1,13 @@
|
||||
PASSED release:release-coherence (1123ms)
|
||||
PASSED release:architecture-topology (3142ms)
|
||||
PASSED release:traffic-budgets (1432ms)
|
||||
PASSED release:scale-units (2318ms)
|
||||
PASSED release:composition-s0-s1 (95ms)
|
||||
PASSED release:composition-s0-s2 (235ms)
|
||||
PASSED release:composition-scale-suite (843ms)
|
||||
PASSED release:typescript-diagnostics (1499ms)
|
||||
PASSED release:baseline-regression (1820ms)
|
||||
PASSED release:topology-s3-s4 (7137ms)
|
||||
PASSED release:telemetry-storm (3364ms)
|
||||
scale tier release: PASSED (artifacts/scale/release/summary.json)
|
||||
$ node scripts/scale/run-scale-profile.ts release
|
||||
@@ -0,0 +1,19 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/cardinality/cardinality-budget.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/compose-unique-record.test.ts [2m([22m[2m2 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/context-lazy-loading.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/routing/context-route-module.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/topology-cardinality.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 13[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/extreme-scale-registry.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 2363[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps 10k -> 100k composition growth below a quadratic regression budget [33m 391[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps one million lookups bounded on a 100k-entry runtime registry [33m 1515[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m selects and resolves 100k feature ids within the membership budget [33m 455[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m6 passed[39m[22m[90m (6)[39m
|
||||
[2m Tests [22m [1m[32m21 passed[39m[22m[90m (21)[39m
|
||||
[2m Start at [22m 13:29:21
|
||||
[2m Duration [22m 2.94s[2m (transform 231ms, setup 1.63s, import 305ms, tests 2.41s, environment 1ms)[22m
|
||||
|
||||
$ node scripts/run-vitest.ts run tests/architecture/topology-cardinality.test.ts tests/architecture/context-lazy-loading.test.ts tests/platform/cardinality tests/platform/routing --reporter=default
|
||||
@@ -0,0 +1,21 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/traffic/request-budget.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 17[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/resilience/retry-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/resilience/deadline.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/concurrency-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/execution/execution-context.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-budget.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/operation-traffic-policy.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-fanout.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 49[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-deduplication.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 47[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/http-budget-integration.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 130[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-amplification.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 391[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m11 passed[39m[22m[90m (11)[39m
|
||||
[2m Tests [22m [1m[32m69 passed[39m[22m[90m (69)[39m
|
||||
[2m Start at [22m 13:29:25
|
||||
[2m Duration [22m 1.34s[2m (transform 858ms, setup 4.17s, import 1.44s, tests 690ms, environment 2ms)[22m
|
||||
|
||||
$ node scripts/run-vitest.ts run tests/platform/execution tests/platform/traffic tests/platform/resilience --reporter=default
|
||||
@@ -0,0 +1 @@
|
||||
$ tsc --project tsconfig.app.json
|
||||
@@ -0,0 +1 @@
|
||||
$ tsc --project tsconfig.test.json
|
||||
@@ -0,0 +1,7 @@
|
||||
$ corepack pnpm check:types:app && corepack pnpm check:types:node && corepack pnpm check:types:test && corepack pnpm check:types:recipes && corepack pnpm check:types:web-worker && corepack pnpm check:types:service-worker
|
||||
$ tsc --project tsconfig.app.json
|
||||
$ tsc --project tsconfig.node.json
|
||||
$ tsc --project tsconfig.test.json
|
||||
$ node scripts/check-optional-recipe-types.ts
|
||||
$ tsc --project tsconfig.web-worker.json
|
||||
$ tsc --project tsconfig.service-worker.json
|
||||
@@ -0,0 +1 @@
|
||||
$ eslint src scripts tests recipes .storybook vite.config.ts vitest.config.ts playwright*.config.ts --max-warnings=0
|
||||
@@ -0,0 +1,23 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/scripts/generate-product-feature-index.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 41[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-deduplication.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 54[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-fanout.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 56[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/request-fanout.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 194[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-request-deduplication.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 50[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-request-fanout.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 68[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/app-build-input.test.ts [2m([22m[2m4 tests[22m[2m)[22m[33m 2380[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m accepts the production generator's output and an app-local bundle [33m 771[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a generator regression that imports every discovered feature [33m 673[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a production bundle that contains another app's feature [33m 643[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/global-local-independence.test.ts [2m([22m[2m7 tests[22m[2m)[22m[33m 7755[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps App A's generated indexes and reachable source graph identical from S0 to S2 on disk [33m 5260[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m selects another app from the same repository without App A's features [33m 982[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m8 passed[39m[22m[90m (8)[39m
|
||||
[2m Tests [22m [1m[32m43 passed[39m[22m[90m (43)[39m
|
||||
[2m Start at [22m 13:29:12
|
||||
[2m Duration [22m 8.30s[2m (transform 919ms, setup 1.94s, import 1.61s, tests 10.60s, environment 1ms)[22m
|
||||
|
||||
$ node scripts/run-vitest.ts run tests/scale/global-local-independence.test.ts tests/architecture/app-build-input.test.ts tests/architecture/request-fanout.test.ts tests/platform/traffic/request-fanout.test.ts tests/platform/traffic/request-deduplication.test.ts tests/features/reference-feature/reference-request-fanout.test.ts tests/features/reference-feature/reference-request-deduplication.test.ts tests/scripts/generate-product-feature-index.test.ts --reporter=default
|
||||
@@ -0,0 +1,55 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/architecture/app-build-input.test.ts [2m([22m[2m4 tests[22m[2m)[22m[33m 9429[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m accepts the production generator's output and an app-local bundle [33m 1340[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a generator regression that imports every discovered feature [33m 5122[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a production bundle that contains another app's feature [33m 2464[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/extreme-scale-registry.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 3975[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps 10k -> 100k composition growth below a quadratic regression budget [33m 634[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps one million lookups bounded on a 100k-entry runtime registry [33m 2331[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m selects and resolves 100k feature ids within the membership budget [33m 1007[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-pipeline.test.ts [2m([22m[2m9 tests[22m[2m)[22m[33m 1077[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m bounds network sends during a repeated error storm [33m 961[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-amplification.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 558[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps physical requests bounded when every dispatch fails [33m 307[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/request-fanout.test.ts [2m([22m[2m4 tests[22m[2m)[22m[33m 344[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m finds no per-row dispatch in feature code or application use cases [33m 330[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/observability-boundaries.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 235[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/http-budget-integration.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 133[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/validation/bounded-json.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 140[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/trace-context.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 82[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/errors/failure-boundary.test.tsx [2m([22m[2m4 tests[22m[2m)[22m[32m 87[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-fanout.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 75[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-deduplication.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 74[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/release/cache-policy.test.ts [2m([22m[2m5 tests[22m[2m)[22m[32m 40[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/errors/platform-errors.test.ts [2m([22m[2m16 tests[22m[2m)[22m[32m 19[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-buffer.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 20[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/redact-telemetry.test.ts [2m([22m[2m14 tests[22m[2m)[22m[32m 14[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-budget.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/release/release-mismatch-recovery.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 12[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/topology-cardinality.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-deduplicator.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/concurrency-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/execution/execution-context.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 12[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-budget.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 8[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/validation/validation-budget.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/operation-traffic-policy.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/routing/context-route-module.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/release/release-coherence.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 13[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/compose-unique-record.test.ts [2m([22m[2m2 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-port.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/resilience/retry-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/errors/app-error.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/cardinality-budget.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/context-lazy-loading.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/resilience/deadline.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/module-hierarchy.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m35 passed[39m[22m[90m (35)[39m
|
||||
[2m Tests [22m [1m[32m223 passed[39m[22m[90m (223)[39m
|
||||
[2m Start at [22m 13:29:32
|
||||
[2m Duration [22m 33.44s[2m (transform 977ms, setup 7.36s, import 2.52s, tests 16.46s, environment 1.01s)[22m
|
||||
|
||||
JUNIT report written to /shared/codebase/clean-architecture-frontend-template/artifacts/tests/platform.xml
|
||||
$ node scripts/run-vitest.ts run tests/platform tests/architecture --no-file-parallelism --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/platform.xml
|
||||
@@ -0,0 +1,30 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/features/reference-feature/reference-error.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 102[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-telemetry.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 55[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-http-problem-mapping.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 12[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-request-deduplication.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 112[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-request-fanout.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 189[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-traffic-policy.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/installed-context-routing.test.ts [2m([22m[2m2 tests[22m[2m)[22m[32m 108[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-contract.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 35[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/feature-module.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-http-gateway.test.ts [2m([22m[2m2 tests[22m[2m)[22m[32m 8[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-installed-executor.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-diagnostics.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 81[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-runtime-composition.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 201[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-production-vertical.test.tsx [2m([22m[2m1 test[22m[2m)[22m[33m 1243[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m traverses bootstrap, router, application, HTTP schema/mapper and query cache [33m 1237[2mms[22m[39m
|
||||
[32m✓[39m tests/features/reference-feature/reference-page.test.tsx [2m([22m[2m11 tests[22m[2m)[22m[33m 3248[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m mounts list and detail keys under the installed governed namespace [33m 1035[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m renders backend forbidden even when the client access hint allowed entry [33m 423[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m deduplicates create, preserves input and surfaces a conflict [33m 584[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m15 passed[39m[22m[90m (15)[39m
|
||||
[2m Tests [22m [1m[32m54 passed[39m[22m[90m (54)[39m
|
||||
[2m Start at [22m 13:30:06
|
||||
[2m Duration [22m 7.80s[2m (transform 13.26s, setup 7.90s, import 20.03s, tests 5.42s, environment 2.84s)[22m
|
||||
|
||||
JUNIT report written to /shared/codebase/clean-architecture-frontend-template/artifacts/tests/reference-feature.xml
|
||||
$ node scripts/run-vitest.ts run tests/features/reference-feature --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/reference-feature.xml --passWithNoTests
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/cardinality/cardinality-budget.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/compose-unique-record.test.ts [2m([22m[2m2 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/module-hierarchy.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/context-lazy-loading.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/routing/context-route-module.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/topology-cardinality.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/observability-boundaries.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 97[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/request-fanout.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 206[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/extreme-scale-registry.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 2005[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps 10k -> 100k composition growth below a quadratic regression budget [33m 407[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps one million lookups bounded on a 100k-entry runtime registry [33m 1229[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m selects and resolves 100k feature ids within the membership budget [33m 366[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/app-build-input.test.ts [2m([22m[2m4 tests[22m[2m)[22m[33m 2215[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m accepts the production generator's output and an app-local bundle [33m 714[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a generator regression that imports every discovered feature [33m 626[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a production bundle that contains another app's feature [33m 613[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m10 passed[39m[22m[90m (10)[39m
|
||||
[2m Tests [22m [1m[32m34 passed[39m[22m[90m (34)[39m
|
||||
[2m Start at [22m 13:30:24
|
||||
[2m Duration [22m 2.82s[2m (transform 645ms, setup 2.94s, import 949ms, tests 4.57s, environment 2ms)[22m
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
compatibility: structural=true compiler=true timing=true
|
||||
axes: absolute 28 (ok), growth 8 (ok), relative 16 compiler + 12 timing
|
||||
scale baseline gate: PASSED (artifacts/scale/main/baseline-regression.json)
|
||||
@@ -0,0 +1,5 @@
|
||||
PASS registry-composition:growth (exponents 0.00)
|
||||
PASS product-feature-selection:growth (exponents 0.00)
|
||||
PASS product-feature-resolution:growth (exponents 0.00)
|
||||
PASS context-hierarchy-composition:growth (exponents 0.00)
|
||||
composition scale artifact: /shared/codebase/clean-architecture-frontend-template/artifacts/scale/main/composition-s0-s1.json
|
||||
@@ -0,0 +1,5 @@
|
||||
PASS registry-composition:growth (exponents 0.00, 0.64)
|
||||
PASS product-feature-selection:growth (exponents 0.00, 0.83)
|
||||
PASS product-feature-resolution:growth (exponents 0.00, 0.83)
|
||||
PASS context-hierarchy-composition:growth (exponents 0.00, 0.34)
|
||||
composition scale artifact: /shared/codebase/clean-architecture-frontend-template/artifacts/scale/main/composition-s0-s2.json
|
||||
@@ -0,0 +1,11 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/scale/tsc-diagnostics-parser.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/composition-scale.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 232[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m2 passed[39m[22m[90m (2)[39m
|
||||
[2m Tests [22m [1m[32m9 passed[39m[22m[90m (9)[39m
|
||||
[2m Start at [22m 13:30:31
|
||||
[2m Duration [22m 596ms[2m (transform 94ms, setup 326ms, import 114ms, tests 239ms, environment 0ms)[22m
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/scale/growth-regression.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/traffic/retry-after-jitter.test.ts [2m([22m[2m5 tests[22m[2m)[22m[32m 38[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/traffic/amplification-metrics.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/benchmark.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 8[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/synthetic-topology.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 8[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/scale-baseline.test.ts [2m([22m[2m11 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/traffic/failure-scenarios.test.ts [2m([22m[2m5 tests[22m[2m)[22m[33m 1420[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m bounds physical requests when all upstream calls fail [33m 896[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m7 passed[39m[22m[90m (7)[39m
|
||||
[2m Tests [22m [1m[32m46 passed[39m[22m[90m (46)[39m
|
||||
[2m Start at [22m 13:30:29
|
||||
[2m Duration [22m 2.04s[2m (transform 695ms, setup 1.76s, import 808ms, tests 1.50s, environment 1ms)[22m
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/resilience/deadline.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 4[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-budget.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/resilience/retry-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/concurrency-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-budget.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/execution/execution-context.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/operation-traffic-policy.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-fanout.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 59[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-deduplication.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 47[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/http-budget-integration.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 124[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-amplification.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 379[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m11 passed[39m[22m[90m (11)[39m
|
||||
[2m Tests [22m [1m[32m69 passed[39m[22m[90m (69)[39m
|
||||
[2m Start at [22m 13:30:27
|
||||
[2m Duration [22m 1.13s[2m (transform 1.01s, setup 3.62s, import 1.55s, tests 663ms, environment 2ms)[22m
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
tsc app: files=827 types=279186 instantiations=700415
|
||||
PASS tsc:types (exponents 0.84, 0.96)
|
||||
PASS tsc:symbols (exponents 0.51, 0.80)
|
||||
PASS tsc:instantiations (exponents 0.97, 0.99)
|
||||
tsc diagnostics artifact: /shared/codebase/clean-architecture-frontend-template/artifacts/scale/main/typescript-diagnostics.json
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/cardinality/compose-unique-record.test.ts [2m([22m[2m2 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/cardinality-budget.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/module-hierarchy.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/context-lazy-loading.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/routing/context-route-module.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 8[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/topology-cardinality.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 13[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/observability-boundaries.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 109[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/request-fanout.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 151[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/extreme-scale-registry.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 1946[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps 10k -> 100k composition growth below a quadratic regression budget [33m 378[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps one million lookups bounded on a 100k-entry runtime registry [33m 1201[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m selects and resolves 100k feature ids within the membership budget [33m 365[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/app-build-input.test.ts [2m([22m[2m4 tests[22m[2m)[22m[33m 2219[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m accepts the production generator's output and an app-local bundle [33m 671[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a generator regression that imports every discovered feature [33m 648[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a production bundle that contains another app's feature [33m 649[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m10 passed[39m[22m[90m (10)[39m
|
||||
[2m Tests [22m [1m[32m34 passed[39m[22m[90m (34)[39m
|
||||
[2m Start at [22m 13:30:41
|
||||
[2m Duration [22m 2.82s[2m (transform 580ms, setup 3.20s, import 787ms, tests 4.47s, environment 2ms)[22m
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
compatibility: structural=true compiler=true timing=true
|
||||
axes: absolute 28 (ok), growth 8 (ok), relative 16 compiler + 12 timing
|
||||
scale baseline gate: PASSED (artifacts/scale/nightly/baseline-regression.json)
|
||||
@@ -0,0 +1,12 @@
|
||||
browser soak: passed classification=stable samples=24 cycles=2012
|
||||
PASS cycles (2012 >= 200)
|
||||
PASS post-warmup samples (18 >= 3)
|
||||
PASS navigation (0 failures)
|
||||
PASS heap slope (stable)
|
||||
PASS listeners (stable, delta 2)
|
||||
PASS timers (delta 0, max 2)
|
||||
PASS in-flight settles (final 0, max 0)
|
||||
PASS storage growth (keys 0, bytes 0)
|
||||
PASS backend failure exercised (68 settled visits, 479 API requests, 24 telemetry events)
|
||||
PASS request amplification (479 requests / 336 visits)
|
||||
PASS telemetry rate (max 14/min, 24 posts, 24 events)
|
||||
@@ -0,0 +1,5 @@
|
||||
PASS registry-composition:growth (exponents 0.00)
|
||||
PASS product-feature-selection:growth (exponents 0.00)
|
||||
PASS product-feature-resolution:growth (exponents 0.00)
|
||||
PASS context-hierarchy-composition:growth (exponents 0.00)
|
||||
composition scale artifact: /shared/codebase/clean-architecture-frontend-template/artifacts/scale/nightly/composition-s0-s1.json
|
||||
@@ -0,0 +1,5 @@
|
||||
PASS registry-composition:growth (exponents 0.00, 0.64)
|
||||
PASS product-feature-selection:growth (exponents 0.00, 0.85)
|
||||
PASS product-feature-resolution:growth (exponents 0.00, 0.83)
|
||||
PASS context-hierarchy-composition:growth (exponents 0.00, 0.34)
|
||||
composition scale artifact: /shared/codebase/clean-architecture-frontend-template/artifacts/scale/nightly/composition-s0-s2.json
|
||||
@@ -0,0 +1,11 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/scale/tsc-diagnostics-parser.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/composition-scale.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 191[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m2 passed[39m[22m[90m (2)[39m
|
||||
[2m Tests [22m [1m[32m9 passed[39m[22m[90m (9)[39m
|
||||
[2m Start at [22m 13:30:48
|
||||
[2m Duration [22m 514ms[2m (transform 78ms, setup 296ms, import 81ms, tests 197ms, environment 0ms)[22m
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/scale/traffic/retry-after-jitter.test.ts [2m([22m[2m5 tests[22m[2m)[22m[32m 34[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/traffic/amplification-metrics.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/benchmark.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 8[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/growth-regression.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/synthetic-topology.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 8[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/scale-baseline.test.ts [2m([22m[2m11 tests[22m[2m)[22m[32m 14[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/traffic/failure-scenarios.test.ts [2m([22m[2m5 tests[22m[2m)[22m[33m 1453[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m bounds physical requests when all upstream calls fail [33m 896[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m7 passed[39m[22m[90m (7)[39m
|
||||
[2m Tests [22m [1m[32m46 passed[39m[22m[90m (46)[39m
|
||||
[2m Start at [22m 13:30:45
|
||||
[2m Duration [22m 2.07s[2m (transform 436ms, setup 1.74s, import 563ms, tests 1.53s, environment 1ms)[22m
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/scale/session/network-flap.test.ts [2m([22m[2m2 tests[22m[2m)[22m[33m 324[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/session/long-session.test.ts [2m([22m[2m1 test[22m[2m)[22m[33m 921[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m returns timers, listeners, leases, buffers and cache entries to a stable bound [33m 919[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m2 passed[39m[22m[90m (2)[39m
|
||||
[2m Tests [22m [1m[32m3 passed[39m[22m[90m (3)[39m
|
||||
[2m Start at [22m 13:31:03
|
||||
[2m Duration [22m 1.37s[2m (transform 228ms, setup 296ms, import 363ms, tests 1.24s, environment 0ms)[22m
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-port.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-deduplicator.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-buffer.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 15[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/redact-telemetry.test.ts [2m([22m[2m14 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/trace-context.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 43[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/telemetry/telemetry-pipeline.test.ts [2m([22m[2m9 tests[22m[2m)[22m[33m 669[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m bounds network sends during a repeated error storm [33m 609[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/telemetry/telemetry-storm.test.ts [2m([22m[2m4 tests[22m[2m)[22m[33m 2882[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m does not turn 100000 identical failures into 100000 sends [33m 748[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m bounds sends and buffer when a storm has many distinct fingerprints [33m 2099[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m7 passed[39m[22m[90m (7)[39m
|
||||
[2m Tests [22m [1m[32m52 passed[39m[22m[90m (52)[39m
|
||||
[2m Start at [22m 13:30:59
|
||||
[2m Duration [22m 3.35s[2m (transform 427ms, setup 1.75s, import 534ms, tests 3.64s, environment 1ms)[22m
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/cardinality/extreme-scale-registry.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 1822[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps 10k -> 100k composition growth below a quadratic regression budget [33m 313[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps one million lookups bounded on a 100k-entry runtime registry [33m 1163[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m selects and resolves 100k feature ids within the membership budget [33m 345[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/global-local-independence.test.ts [2m([22m[2m7 tests[22m[2m)[22m[33m 6311[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps App A's generated indexes and reachable source graph identical from S0 to S2 on disk [33m 4764[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m selects another app from the same repository without App A's features [33m 583[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m2 passed[39m[22m[90m (2)[39m
|
||||
[2m Tests [22m [1m[32m10 passed[39m[22m[90m (10)[39m
|
||||
[2m Start at [22m 13:30:52
|
||||
[2m Duration [22m 6.64s[2m (transform 87ms, setup 327ms, import 80ms, tests 8.13s, environment 0ms)[22m
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/traffic/concurrency-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/resilience/deadline.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 4[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-budget.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/resilience/retry-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-budget.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 8[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/execution/execution-context.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/operation-traffic-policy.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-fanout.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 41[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-deduplication.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 40[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/http-budget-integration.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 121[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-amplification.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 316[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m11 passed[39m[22m[90m (11)[39m
|
||||
[2m Tests [22m [1m[32m69 passed[39m[22m[90m (69)[39m
|
||||
[2m Start at [22m 13:30:44
|
||||
[2m Duration [22m 1.04s[2m (transform 890ms, setup 3.40s, import 1.40s, tests 570ms, environment 2ms)[22m
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
tsc app: files=827 types=279186 instantiations=700415
|
||||
PASS tsc:types (exponents 0.84, 0.96)
|
||||
PASS tsc:symbols (exponents 0.51, 0.80)
|
||||
PASS tsc:instantiations (exponents 0.97, 0.99)
|
||||
tsc diagnostics artifact: /shared/codebase/clean-architecture-frontend-template/artifacts/scale/nightly/typescript-diagnostics.json
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/architecture/module-hierarchy.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 14[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/topology-cardinality.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 37[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/observability-boundaries.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 210[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/context-lazy-loading.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 18[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/cardinality-budget.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 22[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/compose-unique-record.test.ts [2m([22m[2m2 tests[22m[2m)[22m[32m 12[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/routing/context-route-module.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/request-fanout.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 234[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/extreme-scale-registry.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 2791[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps 10k -> 100k composition growth below a quadratic regression budget [33m 721[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps one million lookups bounded on a 100k-entry runtime registry [33m 1649[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m selects and resolves 100k feature ids within the membership budget [33m 420[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/app-build-input.test.ts [2m([22m[2m4 tests[22m[2m)[22m[33m 2872[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m accepts the production generator's output and an app-local bundle [33m 996[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a generator regression that imports every discovered feature [33m 897[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a production bundle that contains another app's feature [33m 723[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m10 passed[39m[22m[90m (10)[39m
|
||||
[2m Tests [22m [1m[32m34 passed[39m[22m[90m (34)[39m
|
||||
[2m Start at [22m 13:30:15
|
||||
[2m Duration [22m 3.81s[2m (transform 625ms, setup 4.78s, import 1.11s, tests 6.22s, environment 2ms)[22m
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
PASS registry-composition:growth (exponents 0.00)
|
||||
PASS product-feature-selection:growth (exponents 0.00)
|
||||
PASS product-feature-resolution:growth (exponents 0.00)
|
||||
PASS context-hierarchy-composition:growth (exponents 0.00)
|
||||
composition scale artifact: /shared/codebase/clean-architecture-frontend-template/artifacts/scale/pr/composition-s0-s1.json
|
||||
@@ -0,0 +1,17 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/scale/traffic/amplification-metrics.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/growth-regression.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/traffic/retry-after-jitter.test.ts [2m([22m[2m5 tests[22m[2m)[22m[32m 38[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/benchmark.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/synthetic-topology.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/scale-baseline.test.ts [2m([22m[2m11 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/traffic/failure-scenarios.test.ts [2m([22m[2m5 tests[22m[2m)[22m[33m 1429[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m bounds physical requests when all upstream calls fail [33m 919[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m7 passed[39m[22m[90m (7)[39m
|
||||
[2m Tests [22m [1m[32m46 passed[39m[22m[90m (46)[39m
|
||||
[2m Start at [22m 13:30:21
|
||||
[2m Duration [22m 2.02s[2m (transform 485ms, setup 1.52s, import 646ms, tests 1.51s, environment 1ms)[22m
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/traffic/request-budget.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/resilience/deadline.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/concurrency-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/resilience/retry-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/execution/execution-context.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-budget.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/operation-traffic-policy.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-fanout.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 44[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-deduplication.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 40[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/http-budget-integration.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 127[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-amplification.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 328[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m11 passed[39m[22m[90m (11)[39m
|
||||
[2m Tests [22m [1m[32m69 passed[39m[22m[90m (69)[39m
|
||||
[2m Start at [22m 13:30:20
|
||||
[2m Duration [22m 1.09s[2m (transform 1.03s, setup 3.64s, import 1.52s, tests 590ms, environment 2ms)[22m
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/cardinality/compose-unique-record.test.ts [2m([22m[2m2 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/context-lazy-loading.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/routing/context-route-module.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/cardinality-budget.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/module-hierarchy.test.ts [2m([22m[2m1 test[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/topology-cardinality.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 12[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/observability-boundaries.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 101[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/request-fanout.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 155[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/cardinality/extreme-scale-registry.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 1941[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps 10k -> 100k composition growth below a quadratic regression budget [33m 383[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps one million lookups bounded on a 100k-entry runtime registry [33m 1177[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m selects and resolves 100k feature ids within the membership budget [33m 379[2mms[22m[39m
|
||||
[32m✓[39m tests/architecture/app-build-input.test.ts [2m([22m[2m4 tests[22m[2m)[22m[33m 2191[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m accepts the production generator's output and an app-local bundle [33m 659[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a generator regression that imports every discovered feature [33m 635[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m rejects a production bundle that contains another app's feature [33m 660[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m10 passed[39m[22m[90m (10)[39m
|
||||
[2m Tests [22m [1m[32m34 passed[39m[22m[90m (34)[39m
|
||||
[2m Start at [22m 13:33:08
|
||||
[2m Duration [22m 2.80s[2m (transform 512ms, setup 3.13s, import 681ms, tests 4.43s, environment 2ms)[22m
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
compatibility: structural=true compiler=true timing=true
|
||||
axes: absolute 28 (ok), growth 8 (ok), relative 16 compiler + 12 timing
|
||||
scale baseline gate: PASSED (artifacts/scale/release/baseline-regression.json)
|
||||
@@ -0,0 +1,5 @@
|
||||
PASS registry-composition:growth (exponents 0.00)
|
||||
PASS product-feature-selection:growth (exponents 0.00)
|
||||
PASS product-feature-resolution:growth (exponents 0.00)
|
||||
PASS context-hierarchy-composition:growth (exponents 0.00)
|
||||
composition scale artifact: /shared/codebase/clean-architecture-frontend-template/artifacts/scale/release/composition-s0-s1.json
|
||||
@@ -0,0 +1,5 @@
|
||||
PASS registry-composition:growth (exponents 0.00, 0.65)
|
||||
PASS product-feature-selection:growth (exponents 0.00, 0.90)
|
||||
PASS product-feature-resolution:growth (exponents 0.00, 0.85)
|
||||
PASS context-hierarchy-composition:growth (exponents 0.00, 0.44)
|
||||
composition scale artifact: /shared/codebase/clean-architecture-frontend-template/artifacts/scale/release/composition-s0-s2.json
|
||||
@@ -0,0 +1,11 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/scale/tsc-diagnostics-parser.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/composition-scale.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 186[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m2 passed[39m[22m[90m (2)[39m
|
||||
[2m Tests [22m [1m[32m9 passed[39m[22m[90m (9)[39m
|
||||
[2m Start at [22m 13:33:15
|
||||
[2m Duration [22m 494ms[2m (transform 86ms, setup 297ms, import 80ms, tests 193ms, environment 0ms)[22m
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/release/release-coherence.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 8[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/release/release-mismatch-recovery.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 14[2mms[22m[39m
|
||||
[32m✓[39m tests/release/old-asset-reachability.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/release/cache-policy.test.ts [2m([22m[2m5 tests[22m[2m)[22m[32m 29[2mms[22m[39m
|
||||
[32m✓[39m tests/release/release-matrix.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 39[2mms[22m[39m
|
||||
[32m✓[39m tests/release/mixed-replica.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 67[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m6 passed[39m[22m[90m (6)[39m
|
||||
[2m Tests [22m [1m[32m43 passed[39m[22m[90m (43)[39m
|
||||
[2m Start at [22m 13:33:06
|
||||
[2m Duration [22m 780ms[2m (transform 1.11s, setup 1.22s, import 1.79s, tests 163ms, environment 1ms)[22m
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/scale/traffic/amplification-metrics.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/growth-regression.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/traffic/retry-after-jitter.test.ts [2m([22m[2m5 tests[22m[2m)[22m[32m 27[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/benchmark.test.ts [2m([22m[2m4 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/synthetic-topology.test.ts [2m([22m[2m8 tests[22m[2m)[22m[32m 13[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/scale-baseline.test.ts [2m([22m[2m11 tests[22m[2m)[22m[32m 11[2mms[22m[39m
|
||||
[32m✓[39m tests/scale/traffic/failure-scenarios.test.ts [2m([22m[2m5 tests[22m[2m)[22m[33m 1362[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m bounds physical requests when all upstream calls fail [33m 874[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m7 passed[39m[22m[90m (7)[39m
|
||||
[2m Tests [22m [1m[32m46 passed[39m[22m[90m (46)[39m
|
||||
[2m Start at [22m 13:33:12
|
||||
[2m Duration [22m 1.96s[2m (transform 513ms, setup 1.59s, import 672ms, tests 1.44s, environment 1ms)[22m
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/scale/telemetry/telemetry-storm.test.ts [2m([22m[2m4 tests[22m[2m)[22m[33m 2705[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m does not turn 100000 identical failures into 100000 sends [33m 672[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m bounds sends and buffer when a storm has many distinct fingerprints [33m 1998[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m1 passed[39m[22m[90m (1)[39m
|
||||
[2m Tests [22m [1m[32m4 passed[39m[22m[90m (4)[39m
|
||||
[2m Start at [22m 13:33:26
|
||||
[2m Duration [22m 3.01s[2m (transform 58ms, setup 146ms, import 52ms, tests 2.71s, environment 0ms)[22m
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/scale/global-local-independence.test.ts [2m([22m[2m7 tests[22m[2m)[22m[33m 6484[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m keeps App A's generated indexes and reachable source graph identical from S0 to S2 on disk [33m 4707[2mms[22m[39m
|
||||
[33m[2m✓[22m[39m selects another app from the same repository without App A's features [33m 646[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m1 passed[39m[22m[90m (1)[39m
|
||||
[2m Tests [22m [1m[32m7 passed[39m[22m[90m (7)[39m
|
||||
[2m Start at [22m 13:33:19
|
||||
[2m Duration [22m 6.79s[2m (transform 53ms, setup 145ms, import 49ms, tests 6.48s, environment 0ms)[22m
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
|
||||
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.10 [39m[90m/shared/codebase/clean-architecture-frontend-template[39m
|
||||
|
||||
[32m✓[39m tests/platform/traffic/request-budget.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/concurrency-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 10[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/resilience/retry-budget.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 5[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/resilience/deadline.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 6[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-budget.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/execution/execution-context.test.ts [2m([22m[2m10 tests[22m[2m)[22m[32m 13[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/operation-traffic-policy.test.ts [2m([22m[2m7 tests[22m[2m)[22m[32m 7[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-fanout.test.ts [2m([22m[2m6 tests[22m[2m)[22m[32m 47[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/request-deduplication.test.ts [2m([22m[2m3 tests[22m[2m)[22m[32m 50[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/http-budget-integration.test.ts [2m([22m[2m9 tests[22m[2m)[22m[32m 121[2mms[22m[39m
|
||||
[32m✓[39m tests/platform/traffic/traffic-amplification.test.ts [2m([22m[2m3 tests[22m[2m)[22m[33m 331[2mms[22m[39m
|
||||
|
||||
[2m Test Files [22m [1m[32m11 passed[39m[22m[90m (11)[39m
|
||||
[2m Tests [22m [1m[32m69 passed[39m[22m[90m (69)[39m
|
||||
[2m Start at [22m 13:33:11
|
||||
[2m Duration [22m 1.08s[2m (transform 940ms, setup 3.62s, import 1.46s, tests 603ms, environment 2ms)[22m
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
tsc app: files=827 types=279186 instantiations=700415
|
||||
PASS tsc:types (exponents 0.84, 0.96)
|
||||
PASS tsc:symbols (exponents 0.51, 0.80)
|
||||
PASS tsc:instantiations (exponents 0.97, 0.99)
|
||||
tsc diagnostics artifact: /shared/codebase/clean-architecture-frontend-template/artifacts/scale/release/typescript-diagnostics.json
|
||||
@@ -96,6 +96,14 @@
|
||||
"compatibilityWindow": "Existing valid envelopes continue to decode; invalid values fail closed.",
|
||||
"rollback": "Remove the required codec field and runtime codec dispatch together.",
|
||||
"owner": "frontend-platform"
|
||||
},
|
||||
{
|
||||
"changeId": "FE-REG-ERROR:QUERY_CACHE_FAILURE:telemetryEvent:field-changed",
|
||||
"versionBump": "Error taxonomy observability references became the closed union of registered diagnostic and telemetry event ids (extreme-scale Phase 4 ledger, 2026-09-23).",
|
||||
"migration": "QUERY_CACHE_FAILURE pointed at the unregistered event id query.cache.failed; it now references the registered cache.operation.failed diagnostic event that the query cache adapter actually emits.",
|
||||
"compatibilityWindow": "No wire, storage or runtime-config format changes: the old id was never emitted by any producer, so no consumer could observe it.",
|
||||
"rollback": "Restore the previous telemetryEvent string on QUERY_CACHE_FAILURE in src/contracts/errors.ts and widen ErrorObservationEvent back to string.",
|
||||
"owner": "frontend-platform"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"environment": {
|
||||
"nodeMajor": 24,
|
||||
"platform": "linux",
|
||||
"arch": "x64",
|
||||
"cpuModel": "Intel(R) Core(TM) i5-10400F CPU @ 2.90GHz",
|
||||
"cpuCount": 12,
|
||||
"typescript": "7.0.2"
|
||||
},
|
||||
"metrics": {
|
||||
"timing": [
|
||||
{
|
||||
"workload": "context-hierarchy-composition",
|
||||
"profile": "S0",
|
||||
"cardinality": 100,
|
||||
"medianMs": 0.025,
|
||||
"minMs": 0.022
|
||||
},
|
||||
{
|
||||
"workload": "context-hierarchy-composition",
|
||||
"profile": "S1",
|
||||
"cardinality": 1000,
|
||||
"medianMs": 0.115,
|
||||
"minMs": 0.111
|
||||
},
|
||||
{
|
||||
"workload": "context-hierarchy-composition",
|
||||
"profile": "S2",
|
||||
"cardinality": 10000,
|
||||
"medianMs": 1.208,
|
||||
"minMs": 1.086
|
||||
},
|
||||
{
|
||||
"workload": "product-feature-resolution",
|
||||
"profile": "S0",
|
||||
"cardinality": 100,
|
||||
"medianMs": 0.028,
|
||||
"minMs": 0.02
|
||||
},
|
||||
{
|
||||
"workload": "product-feature-resolution",
|
||||
"profile": "S1",
|
||||
"cardinality": 1000,
|
||||
"medianMs": 0.177,
|
||||
"minMs": 0.173
|
||||
},
|
||||
{
|
||||
"workload": "product-feature-resolution",
|
||||
"profile": "S2",
|
||||
"cardinality": 10000,
|
||||
"medianMs": 3.404,
|
||||
"minMs": 3.316
|
||||
},
|
||||
{
|
||||
"workload": "product-feature-selection",
|
||||
"profile": "S0",
|
||||
"cardinality": 100,
|
||||
"medianMs": 0.045,
|
||||
"minMs": 0.043
|
||||
},
|
||||
{
|
||||
"workload": "product-feature-selection",
|
||||
"profile": "S1",
|
||||
"cardinality": 1000,
|
||||
"medianMs": 0.261,
|
||||
"minMs": 0.246
|
||||
},
|
||||
{
|
||||
"workload": "product-feature-selection",
|
||||
"profile": "S2",
|
||||
"cardinality": 10000,
|
||||
"medianMs": 3.149,
|
||||
"minMs": 3.042
|
||||
},
|
||||
{
|
||||
"workload": "registry-composition",
|
||||
"profile": "S0",
|
||||
"cardinality": 100,
|
||||
"medianMs": 0.046,
|
||||
"minMs": 0.043
|
||||
},
|
||||
{
|
||||
"workload": "registry-composition",
|
||||
"profile": "S1",
|
||||
"cardinality": 1000,
|
||||
"medianMs": 0.269,
|
||||
"minMs": 0.244
|
||||
},
|
||||
{
|
||||
"workload": "registry-composition",
|
||||
"profile": "S2",
|
||||
"cardinality": 10000,
|
||||
"medianMs": 2.634,
|
||||
"minMs": 2.209
|
||||
}
|
||||
],
|
||||
"compiler": [
|
||||
{
|
||||
"fixture": "app",
|
||||
"files": 824,
|
||||
"types": 278300,
|
||||
"symbols": 794961,
|
||||
"instantiations": 699730
|
||||
},
|
||||
{
|
||||
"fixture": "local-100",
|
||||
"files": 158,
|
||||
"types": 6413,
|
||||
"symbols": 20267,
|
||||
"instantiations": 8573
|
||||
},
|
||||
{
|
||||
"fixture": "local-25",
|
||||
"files": 83,
|
||||
"types": 1995,
|
||||
"symbols": 9978,
|
||||
"instantiations": 2222
|
||||
},
|
||||
{
|
||||
"fixture": "local-400",
|
||||
"files": 458,
|
||||
"types": 24113,
|
||||
"symbols": 61442,
|
||||
"instantiations": 33998
|
||||
}
|
||||
]
|
||||
},
|
||||
"approval": {
|
||||
"owner": "frontend-platform",
|
||||
"reason": "Initial extreme-scale benchmark baseline (composition S0-S2, tsc app + local 25/100/400), 2026-09-23",
|
||||
"approvedAt": "2026-09-23T10:44:14.787Z",
|
||||
"metricsDigest": "97bcf7620a1fac46a44fcd4e7f611c05fc2024ed023454ef4fc340c44912bda1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
# Clean Architecture Frontend Template — Domain Scale / High Traffic / Horizontal Scaling Review
|
||||
|
||||
- Review date: 2026-09-23
|
||||
- Repository: `/shared/codebase/clean-architecture-frontend-template`
|
||||
- Review baseline: `origin/main` `ebea300` (`2026-09-20 13:47:27 +0900`)
|
||||
- Source modification: 없음
|
||||
- Scope: 대용량 트래픽, feature/domain 100→1,000→10,000 확장, 문제 인식이 코드에 드러나는 구조, 클라우드 수평 확장
|
||||
|
||||
## 0. Baseline 주의사항
|
||||
|
||||
현재 로컬 `main`은 `91ae42a` Initial commit에 머물러 있고 `origin/main`보다 235 commit 뒤에 있다. 현재 working tree의 `src/`, `tests/`, `dist/`, `artifacts/` 등은 untracked 상태이므로 그 상태를 최신 템플릿으로 간주하면 잘못된 리뷰가 된다.
|
||||
|
||||
따라서 이번 검토는 working tree를 변경하지 않고 `origin/main`을 `/tmp/clean-architecture-frontend-template-review-20260923`에 별도 archive로 전개한 뒤 수행했다. `git fetch origin --prune`으로 확인했을 때 `origin/main`은 `ebea300`으로 동일했다.
|
||||
|
||||
## 1. 결론
|
||||
|
||||
현재 구조는 **클린 아키텍처 경계, 브라우저 상태 격리, HTTP 실패/재시도 정책, 배포 release coherence**는 상당히 강하다. 특히 다음은 좋은 방향이다.
|
||||
|
||||
- feature 내부를 `domain / application / adapters / presentation / contracts`로 분리한다.
|
||||
- application input은 module augmentation으로 feature가 자기 계약을 등록한다.
|
||||
- presentation이 직접 `fetch`, storage, concrete adapter를 사용하지 못하게 lint/architecture rule을 둔다.
|
||||
- Query 기본 retry를 끄고 HTTP retry를 idempotency/replay semantics와 full jitter로 제한한다.
|
||||
- API response와 boot JSON의 크기/deadline을 bounded contract로 표현한다.
|
||||
- route owner, query invalidation topic/namespace/edge, schema/mapper owner가 코드에 드러난다.
|
||||
- static hosting은 immutable asset + no-store config/manifest + release/build identity validation을 사용한다.
|
||||
|
||||
그러나 **100→1,000→10,000 feature/domain 확장성** 기준으로는 현재 그대로 끝난 구조가 아니다.
|
||||
|
||||
핵심 문제는 다음 네 가지다.
|
||||
|
||||
1. feature 설치를 위해 여러 중앙 파일을 수정해야 한다.
|
||||
2. feature 간 직접 의존을 원천적으로 막는 규칙이 없다.
|
||||
3. 일부 registry/product composition이 O(N²)이다.
|
||||
4. 모든 feature contract/route metadata가 하나의 정적 TypeScript/SPA graph에 들어간다.
|
||||
|
||||
따라서 현재 구조는 **100개 정도의 bounded feature까지는 개선을 전제로 유지 가능**, **1,000개부터는 중앙 composition 구조를 바꾸지 않으면 유지보수와 startup/build cost가 문제**, **10,000개를 한 SPA의 flat registry로 수용하는 모델은 적합하지 않다**고 판단한다.
|
||||
|
||||
## 2. 좋은 점 — 문제가 코드에서 드러나는 부분
|
||||
|
||||
### 2.1 Feature capability가 compile-time dependency로 드러난다
|
||||
|
||||
`ApplicationFeatureInputs`와 `FeatureIndexedDbRepositories`는 빈 interface를 두고 feature가 module augmentation으로 자기 input/repository를 등록한다.
|
||||
|
||||
이 방식의 장점은 새로운 feature가 `indexedDb` 같은 capability를 요구하면 composition root가 그것을 공급하지 않는 한 타입 수준에서 닫히지 않는다는 점이다.
|
||||
|
||||
예를 들어 `local-draft-feature`는 `needs: ["indexedDb"]`를 선언한다. 현재 production adapter catalog에는 reference feature만 설치되어 있어 `createRuntimeAdapters()`는 `{ http: contractOperations }`만 공급한다. 향후 local draft를 실제 catalog에 넣으면 `indexedDb` capability wiring이 빠졌다는 사실이 composition boundary에서 드러나게 된다.
|
||||
|
||||
이는 서버에서 연관관계 비용을 숨기지 않는 것과 유사하게, **feature가 어떤 인프라 capability를 요구하는지 코드에서 숨길 수 없게 한다**는 점에서 좋다.
|
||||
|
||||
### 2.2 Network fan-out의 일부 위험이 contract에 올라와 있다
|
||||
|
||||
HTTP operation에는 다음이 명시돼 있다.
|
||||
|
||||
- idempotency / replay policy
|
||||
- retry policy
|
||||
- deadline ceiling
|
||||
- request/response schema
|
||||
- success status
|
||||
- response media type
|
||||
- `maxResponseBytes`
|
||||
- mapper와 `maxOutputItems`
|
||||
|
||||
즉 "그냥 fetch한다"가 아니라 네트워크 요청의 비용과 실패 의미가 operation contract에 올라와 있다.
|
||||
|
||||
또 QueryClient 기본값은 `retry: false`, mutation도 `retry: false`이고 HTTP 계층에서만 retry authority를 가진다. HTTP retry는 safe/idempotent semantics, bounded attempt, exponential full jitter, Retry-After ceiling을 사용한다. 장애 시 브라우저 전체가 무제한 재시도로 서버를 더 압박하는 구조를 피하고 있다.
|
||||
|
||||
### 2.3 Browser-local state와 hosting instance state가 분리돼 있다
|
||||
|
||||
TanStack Query client, generation store, session integration, local/session storage, cross-context invalidation은 브라우저 runtime에서 생성된다. frontend hosting instance 메모리에 사용자 session/cache를 저장하는 구조가 아니다.
|
||||
|
||||
따라서 **동일한 release artifact를 제공하는 stateless web origin replica를 늘리는 것 자체는 application correctness를 깨지 않는다.**
|
||||
|
||||
### 2.4 Release coherence가 코드와 운영 계약 양쪽에 있다
|
||||
|
||||
배포 계약은 다음을 강제한다.
|
||||
|
||||
- hashed assets: `public, max-age=31536000, immutable`
|
||||
- HTML: `no-cache`
|
||||
- runtime config / release manifest: `no-store`
|
||||
- runtime config의 build id 검증
|
||||
- release manifest의 build/config/release/contract identity 검증
|
||||
- immutable `releases/<releaseId>/` tuple 생성 후 active pointer 전환
|
||||
|
||||
따라서 replica A와 B가 서로 다른 자산을 제멋대로 섞어 제공하는 상황을 단순한 "배포 문제"로 방치하지 않고 boot failure로 드러낼 기반이 있다.
|
||||
|
||||
## 3. P0 — Registry composition 일부가 O(N²)이다
|
||||
|
||||
### 3.1 `installed-feature-contracts.ts` route composition
|
||||
|
||||
현재 패턴:
|
||||
|
||||
```ts
|
||||
INSTALLED_FEATURE_CONTRACTS.reduce(
|
||||
(registry, contract) => ({ ...registry, ...contract.routes }),
|
||||
{ ...PLATFORM_ROUTE_REGISTRY },
|
||||
)
|
||||
```
|
||||
|
||||
매 iteration마다 이전 registry 전체를 다시 copy한다. feature 수와 route 수가 늘어날수록 누적 copy가 커진다.
|
||||
|
||||
합성 benchmark는 feature마다 route 1개인 최소 조건으로 측정했다.
|
||||
|
||||
| feature 수 | 현재 route spread reduce | 선형 Object.assign 조합 |
|
||||
|---:|---:|---:|
|
||||
| 100 | 0.46 ms | 0.06 ms |
|
||||
| 1,000 | 92.94 ms | 0.24 ms |
|
||||
| 5,000 | 3,769.40 ms | 0.54 ms |
|
||||
| 10,000 | 16,527.58 ms | 1.20 ms |
|
||||
|
||||
이 benchmark는 Node 22에서 수행한 synthetic microbenchmark이며 실제 browser boot time 그 자체는 아니다. 그러나 증가 형태가 O(N²)인지 확인하기에는 충분하다.
|
||||
|
||||
**개선:** mutable local accumulator에 중복 검증을 하면서 한 번만 assign한 뒤 마지막에 freeze한다. Schema/API/mapper registry가 이미 이 방식에 가깝다.
|
||||
|
||||
### 3.2 `product-features.ts`의 반복 `includes()`
|
||||
|
||||
다음 로직도 큰 N에서 O(N²)이다.
|
||||
|
||||
- requested feature 검증: `compiledIds.includes(id)`
|
||||
- selection: `requested.includes(feature.featureId)`
|
||||
- status resolve: `installedIds.includes(featureId)`
|
||||
|
||||
10,000 feature synthetic 결과:
|
||||
|
||||
- selection: 약 441.87 ms
|
||||
- status resolve: 약 218.93 ms
|
||||
- `Set` 기반 status resolve: 약 1.68 ms
|
||||
|
||||
**개선:** membership query는 composition 시작 시 `Set`으로 변환한다.
|
||||
|
||||
### 3.3 runtime/contract contribution filter도 동일하다
|
||||
|
||||
`installed-feature-runtimes.tsx`, `installed-contract-contributions.ts`가 `INSTALLED_PRODUCT_FEATURE_IDS.includes(...)`로 filter한다.
|
||||
|
||||
10,000 feature synthetic filter는 약 122.58 ms였다. 이것 역시 `Set`으로 바꾸면 선형화할 수 있다.
|
||||
|
||||
## 4. P0 — Feature 하나 추가할 때 중앙 파일이 너무 많이 바뀐다
|
||||
|
||||
현재 `reference-feature`는 feature directory 밖에서 다음 중앙 파일에 직접 import된다.
|
||||
|
||||
1. `installed-product-manifest.ts`
|
||||
2. `installed-feature-adapters.ts`
|
||||
3. `installed-feature-runtimes.tsx`
|
||||
4. `installed-feature-messages.ts`
|
||||
5. `installed-contract-contributions.ts`
|
||||
|
||||
`installed-feature-contracts.ts`는 product manifest에서 파생되므로 개선됐지만, feature 설치를 "한 번 선언"하는 상태까지는 아니다.
|
||||
|
||||
`test-sample-removal.ts`도 reference feature를 제거하는 fixture를 만들 때 위 중앙 파일들을 각각 empty variant로 교체한다. 즉 테스트 자체가 현재의 multi-touch installation cost를 증명한다.
|
||||
|
||||
feature 10개에서는 문제가 작다. 100개부터는 merge hotspot이 되고, 1,000개에서는 사람이 central catalog를 직접 유지하는 방식이 실질적으로 유지 불가능해진다.
|
||||
|
||||
**개선 방향:** feature 하나가 하나의 `FeatureModuleDescriptor`를 소유하게 한다.
|
||||
|
||||
예:
|
||||
|
||||
```ts
|
||||
export const FEATURE = defineFeatureModule({
|
||||
id,
|
||||
contracts,
|
||||
adapterContribution,
|
||||
runtimeContribution,
|
||||
messages,
|
||||
contractContributions,
|
||||
});
|
||||
```
|
||||
|
||||
그리고 중앙 catalog는 사람이 5곳을 편집하는 방식이 아니라 **build-time generated static index** 하나로 만든다.
|
||||
|
||||
중요한 점은 runtime string으로 임의 `import()` 하는 plugin system을 만들자는 뜻이 아니다. 현재 보안/공급망 철학을 유지하면서 build 단계에서 명시적인 static module map을 생성하면 된다.
|
||||
|
||||
## 5. P0 — Cross-feature dependency가 기본 금지되어 있지 않다
|
||||
|
||||
현재 architecture rules는 각 feature 내부의 layer 방향은 잘 막는다.
|
||||
|
||||
예:
|
||||
|
||||
- feature domain → application/adapters/presentation 금지
|
||||
- feature application → adapters/presentation 금지
|
||||
- feature presentation → concrete adapter 금지
|
||||
- feature adapters → presentation 금지
|
||||
|
||||
하지만 **feature A → feature B 자체를 금지하는 일반 규칙은 없다.**
|
||||
|
||||
따라서 예를 들어:
|
||||
|
||||
```text
|
||||
features/order/application
|
||||
-> features/member/application
|
||||
-> features/payment/domain
|
||||
```
|
||||
|
||||
같은 concrete cross-feature edge가 생겨도 layer rule만 만족하면 통과할 여지가 있다.
|
||||
|
||||
이게 서버의 `OneToMany` 비유와 가장 가까운 핵심 문제다. feature 수가 커질 때 진짜 위험한 것은 파일 수 자체가 아니라 **feature fan-out이 코드 어디서든 조용히 증가하는 것**이다.
|
||||
|
||||
**권장 invariant:**
|
||||
|
||||
```text
|
||||
src/features/A/** -> src/features/B/** 기본 금지 (A != B)
|
||||
```
|
||||
|
||||
공유가 필요하면 다음 중 하나로 문제를 명시적으로 승격한다.
|
||||
|
||||
- `src/contracts`의 stable contract
|
||||
- `src/application/ports`의 platform/application capability
|
||||
- 별도 orchestration/workflow feature
|
||||
- 명시적 public facade package
|
||||
|
||||
즉 cross-domain 의존이 필요할 때 개발자가 "그냥 import"로 해결하지 못하게 해야 한다. 이것이 코드에서 문제를 조기에 인식하게 만드는 frontend 쪽 핵심 장치다.
|
||||
|
||||
## 6. P1 — Build-time feature selection이 bundle graph를 줄이지 않는다
|
||||
|
||||
`installed-product-manifest.ts` 주석도 이미 이를 명확히 적고 있다.
|
||||
|
||||
`VITE_PRODUCT_FEATURES`는 installed registry에서는 feature를 제외하지만 static import 자체는 제거하지 않는다.
|
||||
|
||||
따라서 feature가 1,000/10,000개까지 늘면 "비활성 feature는 runtime에서 안 쓰니까 괜찮다"고 볼 수 없다. TypeScript compiler, Vite/Rollup graph, registry metadata, schema/codec import가 영향을 받는다.
|
||||
|
||||
페이지 component는 `React.lazy()`로 route chunk 분리가 되어 있어 좋은 편이다. 그러나 feature contract/runtime contribution의 상위 graph는 여전히 정적이다.
|
||||
|
||||
**개선:** product별 build input에서 필요한 feature set만 대상으로 static index를 생성한다. 모든 제품이 모든 domain source를 compiler graph에 반드시 넣어야 하는 구조를 피한다.
|
||||
|
||||
## 7. P1 — 10,000 route를 flat router에 한 번에 넣는 모델은 부적절하다
|
||||
|
||||
`AppRouter`는 boot 시:
|
||||
|
||||
```ts
|
||||
Object.values(ROUTE_REGISTRY).map(...)
|
||||
```
|
||||
|
||||
으로 모든 route에 대한 `RouteObject`를 생성한다.
|
||||
|
||||
선형이라도 10,000 route가 하나의 browser application에 동시에 존재해야 하는 이유부터 다시 검토해야 한다.
|
||||
|
||||
대규모에서는 다음 계층이 적합하다.
|
||||
|
||||
```text
|
||||
Product Router
|
||||
-> Bounded Context / Domain Router
|
||||
-> Feature Router
|
||||
-> Page Route
|
||||
```
|
||||
|
||||
상위 prefix에서 domain group을 선택하고 해당 group의 runtime/route table을 lazy-load한다. "10,000개를 더 빠르게 flat map"하는 것보다 **애초에 한 browser boot가 10,000개를 알 필요가 없게 하는 것**이 중요하다.
|
||||
|
||||
## 8. P1 — Global TypeScript augmentation registry도 무한 확장 대상으로 보면 안 된다
|
||||
|
||||
`ApplicationFeatureInputs` module augmentation은 수십~수백 feature에서는 타입 안전성이 좋다. 그러나 10,000개 feature key가 한 interface에 합쳐지는 구조는 TypeScript compiler의 symbol/type graph도 함께 키운다.
|
||||
|
||||
따라서 1,000+ bounded context를 실제 목표로 한다면 global interface 하나보다 package/context 단위 typed registry를 만들고 product composition 시 합치는 것이 낫다.
|
||||
|
||||
즉 runtime complexity뿐 아니라 **compile-time complexity도 budget 대상**이어야 한다.
|
||||
|
||||
## 9. P1 — Message catalog는 아직 feature contribution 모델과 어긋난다
|
||||
|
||||
`installed-feature-messages.ts`는 `REFERENCE_MESSAGE_CATALOGS`를 직접 import하고 locale object에 spread한다.
|
||||
|
||||
다른 contract/runtime/adapter가 contribution 방식으로 이동한 것에 비해 i18n은 reference-specific central wiring이 남아 있다.
|
||||
|
||||
feature가 늘수록 message catalog도 `FeatureModuleDescriptor.messages` 같은 feature-owned contribution으로 통합해야 한다.
|
||||
|
||||
## 10. 대용량 트래픽 관점
|
||||
|
||||
### 강점
|
||||
|
||||
1. **Static asset offload 가능**
|
||||
- content-hashed immutable asset이라 CDN/cache 효과를 최대화하기 좋다.
|
||||
2. **Query retry 기본 OFF**
|
||||
- React Query가 별도로 재시도하고 HTTP client가 또 재시도하는 이중 증폭을 피한다.
|
||||
3. **HTTP retry authority 중앙화**
|
||||
- safe/idempotent semantics만 retry한다.
|
||||
- full jitter가 있다.
|
||||
- Retry-After ceiling이 있다.
|
||||
4. **bounded payload**
|
||||
- response byte limit, mapper output limit, boot JSON size limit이 있다.
|
||||
5. **scope fencing / cancellation**
|
||||
- session/state generation 전환 중 stale request가 새 scope를 오염시키지 않도록 한다.
|
||||
6. **cache invalidation edge 명시**
|
||||
- namespace/topic/edge가 registry에 올라와 있어 mutation 영향 범위를 코드로 추적할 수 있다.
|
||||
|
||||
### 추가로 코드 invariant로 올릴 것
|
||||
|
||||
대용량 서비스에서 backend의 N+1과 비슷한 frontend 문제는 "list 1건을 렌더링할 때 item 수만큼 detail request"가 발생하는 query waterfall/fan-out이다.
|
||||
|
||||
현재 `presentation -> direct fetch`는 막혀 있지만, application use case가 여러 operation을 item 단위로 반복 호출하는 것은 별도 invariant가 없다.
|
||||
|
||||
권장:
|
||||
|
||||
- collection operation은 pagination/cursor와 최대 page size를 contract로 갖게 한다.
|
||||
- list rendering을 위해 item별 network request를 만드는 API를 기본 금지한다.
|
||||
- relation/detail이 필요하면 backend bulk/read-model endpoint를 요구한다.
|
||||
- 한 user action에서 발생 가능한 physical request count에 budget/evidence를 둔다.
|
||||
- integration test에서 "N개의 row → N개의 request"가 생기면 fail하도록 request-count assertion을 둔다.
|
||||
|
||||
이렇게 해야 성능 문제가 production APM에서 처음 보이는 것이 아니라 코드/테스트 단계에서 드러난다.
|
||||
|
||||
## 11. 클라우드 instance 수평 확장 관점
|
||||
|
||||
### Application code 판정
|
||||
|
||||
**replica-safe 방향이다.**
|
||||
|
||||
frontend hosting instance에 다음이 없다.
|
||||
|
||||
- 사용자별 HttpSession
|
||||
- process-local authenticated session authority
|
||||
- process-local query cache shared by users
|
||||
- process-local mutation state
|
||||
|
||||
중요한 mutable state는 browser runtime에 있다. 따라서 static origin을 1→N replica로 늘려도 특정 replica affinity/sticky session을 요구하지 않는다.
|
||||
|
||||
### 반드시 지켜야 하는 infra 조건
|
||||
|
||||
다만 frontend repo만 보고 "어떤 클라우드 배포에서도 무조건 안전"이라고 할 수는 없다. 다음이 깨지면 replica 수를 늘릴수록 mixed release 확률이 올라간다.
|
||||
|
||||
1. 모든 replica가 동일 immutable release artifact를 제공해야 한다.
|
||||
2. HTML active pointer 전환은 release tuple 기준으로 원자적이어야 한다.
|
||||
3. `/config.json`, `/release-manifest.json`은 `no-store` 계약을 지켜야 한다.
|
||||
4. hashed asset은 release 간 overwrite하지 않아야 한다.
|
||||
5. load balancer/CDN이 다른 release의 HTML/config/manifest를 혼합하지 않아야 한다.
|
||||
6. rolling deployment 중 old/new release가 동시에 살아도 old HTML이 참조하는 old hashed asset은 계속 접근 가능해야 한다.
|
||||
|
||||
현재 코드와 문서는 build/release mismatch를 fail-close하도록 잘 구성돼 있다. 다음 단계는 infra repo에서 실제 CDN/LB/origin 설정이 이 계약을 만족하는지 별도로 검증하는 것이다.
|
||||
|
||||
## 12. 목표 구조
|
||||
|
||||
권장 구조는 다음과 같다.
|
||||
|
||||
```text
|
||||
src/features/<feature>/
|
||||
domain/
|
||||
application/
|
||||
contracts/
|
||||
adapters/
|
||||
presentation/
|
||||
feature-module.ts # feature-owned 단일 descriptor
|
||||
|
||||
.generated/
|
||||
product-feature-index.ts # build-time 생성
|
||||
|
||||
bootstrap/
|
||||
compose-product.ts # generic composition only
|
||||
```
|
||||
|
||||
핵심 invariant:
|
||||
|
||||
```text
|
||||
Feature -> Platform Contract 허용
|
||||
Feature -> Application Port 허용
|
||||
Feature A -> Feature B concrete 금지
|
||||
Presentation -> Fetch/Storage 금지 (이미 존재)
|
||||
Adapter -> Presentation 금지 (이미 존재)
|
||||
Registry composition O(N)
|
||||
Route/domain loading hierarchical + lazy
|
||||
Runtime user state browser-owned / external authority
|
||||
Hosting replica stateless
|
||||
```
|
||||
|
||||
## 13. 추가해야 할 검증 Gate
|
||||
|
||||
### Gate A — cross-feature dependency
|
||||
|
||||
다른 feature directory로의 direct import가 하나라도 생기면 CI fail.
|
||||
|
||||
### Gate B — composition complexity
|
||||
|
||||
100 / 1,000 / 10,000 synthetic feature descriptors를 생성해 다음을 측정한다.
|
||||
|
||||
- product selection
|
||||
- contract registry composition
|
||||
- route registry composition
|
||||
- feature input composition
|
||||
- route group creation
|
||||
|
||||
절대 숫자는 CI runner baseline을 먼저 측정해 결정하되, N 증가에 대해 quadratic regression이 발생하면 실패하게 한다.
|
||||
|
||||
### Gate C — central touchpoint count
|
||||
|
||||
새 feature fixture를 추가할 때 feature directory + generated index 외의 production 파일을 사람이 수정해야 하면 fail.
|
||||
|
||||
목표: **feature 추가 시 central handwritten file 수정 0개 또는 1개**.
|
||||
|
||||
### Gate D — cross-domain request fan-out
|
||||
|
||||
대표 collection page에서 data cardinality가 증가해도 request count가 선형 증가하지 않는지 integration test로 검증한다.
|
||||
|
||||
### Gate E — build/typecheck scale
|
||||
|
||||
100/1,000 feature fixture에서 TypeScript typecheck memory/time과 production build time을 기록한다. runtime만 빠르고 compiler가 수십 분 걸리는 구조도 scale-ready가 아니다.
|
||||
|
||||
### Gate F — replica release coherence
|
||||
|
||||
서로 다른 old/new frontend replica를 둔 fixture에서 LB가 요청을 교차 분배해도:
|
||||
|
||||
- coherent release는 정상 boot
|
||||
- mixed config/manifest/build는 명시적 boot failure
|
||||
- old hashed asset은 계속 200
|
||||
- 새 active pointer 전환 후 reload loop가 발생하지 않음
|
||||
|
||||
을 검증한다.
|
||||
|
||||
## 14. 규모별 판정
|
||||
|
||||
| 규모 | 현재 구조 판정 | 이유 |
|
||||
|---|---|---|
|
||||
| 100 feature/domain | 개선 전제 사용 가능 | layer/capability 경계는 좋지만 중앙 5-file wiring이 merge hotspot이 됨 |
|
||||
| 1,000 | 현재 그대로는 부적합 | O(N²) composition, central catalogs, compiler graph, flat route registry 부담이 커짐 |
|
||||
| 10,000 | 구조 변경 필요 | 하나의 SPA가 모든 feature/route/typed registry를 flat하게 아는 모델 자체가 맞지 않음 |
|
||||
|
||||
## 15. 우선순위
|
||||
|
||||
### P0
|
||||
|
||||
1. route registry의 repeated object spread 제거
|
||||
2. product/runtime selection의 `includes()` membership을 `Set`으로 변경
|
||||
3. feature 설치를 단일 descriptor + generated product index로 변경
|
||||
4. cross-feature concrete import 금지 rule 추가
|
||||
|
||||
### P1
|
||||
|
||||
5. route를 bounded-context 단위 hierarchical/lazy composition으로 변경
|
||||
6. i18n을 feature-owned contribution으로 통합
|
||||
7. 100/1,000/10,000 synthetic scale gate 추가
|
||||
8. request fan-out / waterfall budget test 추가
|
||||
9. TypeScript/build scale evidence 추가
|
||||
|
||||
### P2
|
||||
|
||||
10. 실제 cloud infra에서 multi-replica mixed-release test 수행
|
||||
11. CDN/LB/active-pointer/cache header가 repo의 release contract와 일치하는지 검증
|
||||
|
||||
## 16. 검증 메모
|
||||
|
||||
- `origin/main`: `ebea300`, fetch 후 동일
|
||||
- direct `tsc --project tsconfig.app.json`: PASS
|
||||
- direct `tsc --project tsconfig.test.json`: PASS
|
||||
- `dependency-cruiser`: TypeScript 7 미지원으로 0 module을 보고하므로 이번 리뷰의 architecture evidence로 사용하지 않음
|
||||
- 전체 `pnpm check:*`는 현재 Coka host Node 22와 repo engine 요구 Node 24 불일치 및 snapshot node_modules 정합성 때문에 수행하지 않음
|
||||
- benchmark는 synthetic microbenchmark이며 production browser latency 수치로 해석하지 않음
|
||||
|
||||
## Final assessment
|
||||
|
||||
이 템플릿은 "대충 layer만 나눈 frontend"는 아니다. 네트워크, browser capability, release identity, invalidation, retry, runtime state의 위험을 계약과 gate로 끌어올리는 방향은 좋다.
|
||||
|
||||
다음 단계의 핵심은 **도메인이 늘어날 때 생기는 coupling과 cardinality 자체도 같은 방식으로 코드에 드러내는 것**이다.
|
||||
|
||||
서버에서 `OneToMany`를 사용하지 않아 관계 fan-out을 숨기지 않는 것과 같은 철학을 frontend에 적용한다면 가장 중요한 규칙은 다음 두 줄이다.
|
||||
|
||||
```text
|
||||
Feature A -> Feature B concrete import 금지
|
||||
Unbounded feature/route/request fan-out 금지
|
||||
```
|
||||
|
||||
그리고 이 두 규칙을 사람의 리뷰 규칙이 아니라 architecture gate와 scale test로 고정해야 한다.
|
||||
@@ -0,0 +1,46 @@
|
||||
# Extreme-scale frontend architecture — acceptance matrix (spec §54)
|
||||
|
||||
Plan bundle: `docs/reviews/2026-09-23-extreme-scale-frontend-plan-bundle/`. One row per acceptance criterion. Status is `완료` or `아직 더 봐야댐`. Each `완료` row names the executable evidence.
|
||||
|
||||
| # | Acceptance criterion (spec §54) | Status | Evidence |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | Adding a normal feature does not require editing a collection of central handwritten installation registries. | 완료 | `scripts/generate-product-feature-index.ts` → `src/.generated/product-feature-index.ts`, `src/.generated/product-context-index.ts`; `tests/features/feature-installation-surface.test.ts`; `tests/scripts/generate-product-feature-index.test.ts`; `pnpm check:feature-index`; `pnpm test:sample-removal` |
|
||||
| 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` |
|
||||
| 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` |
|
||||
| 9 | Representative collections do not create frontend N+1 request fan-out. | 완료 | Policy (spec §41 implementation note): paginated bulk read, page ≤ 100 by contract (not raised). `tests/platform/traffic/request-fanout.test.ts`, `tests/features/reference-feature/reference-request-fanout.test.ts`: 10/50/100/1,000-row collections load a page with 1 request; full 1,000-row walk ≤ ceil(N/100)+1 requests; single oversized response rejected within 1 request. Coalescing: `tests/platform/traffic/request-deduplication.test.ts`. Source gate: `scripts/check-request-fanout.ts` (`pnpm check:request-fanout`; forbidden/allowed fixtures in `tests/fixtures/architecture/request-fanout/`, `tests/architecture/request-fanout.test.ts`) |
|
||||
| 10 | Errors remain local and typed without constructing a global union of all feature errors. | 완료 | `src/platform/errors/app-error.ts`; `src/platform/errors/platform-errors.ts`; `src/adapters/http/platform-error-mapping.ts`; `src/features/reference-feature/application/reference-error.ts`; `tests/features/reference-feature/reference-error.test.ts`; `tests/architecture/observability-boundaries.test.ts` |
|
||||
| 11 | External data is validated at trust boundaries with bounded payload/structure cost. | 완료 | `src/platform/validation/{validation-budget,bounded-json}.ts`; structure-before-mapping in `src/adapters/http/http-execution-v3.ts`; existing byte ceilings `src/adapters/http/bounded-body-reader.ts`; `src/contracts/validation-issues.ts`; `tests/platform/validation/*.test.ts` |
|
||||
| 12 | Feature code emits observability through a platform port rather than vendor SDKs. | 완료 | `src/platform/telemetry/telemetry-port.ts`; capability `telemetry` in `src/features/feature-adapter-contribution.ts`; reference emission `src/features/reference-feature/application/reference-feature-api.ts`; collector transport `src/adapters/telemetry/feature-telemetry.ts`; rule `observability-vendors-live-behind-adapters` in `.dependency-cruiser.json`; `tests/architecture/observability-boundaries.test.ts`; `tests/features/reference-feature/reference-telemetry.test.ts` |
|
||||
| 13 | Telemetry is redacted, deduplicated, sampled, buffered, and rate-limited with bounded memory. | 완료 | `src/platform/telemetry/{redact-telemetry,telemetry-fingerprint,telemetry-deduplicator,telemetry-sampler,telemetry-buffer,telemetry-pipeline}.ts`; `tests/platform/telemetry/*.test.ts`; `tests/scale/telemetry/telemetry-storm.test.ts` |
|
||||
| 14 | Telemetry failure does not fail business behavior. | 완료 | `tests/platform/telemetry/telemetry-pipeline.test.ts` (transport throw/reject); `tests/platform/telemetry/telemetry-port.test.ts` (`failOpenTelemetryPort`); `tests/features/reference-feature/reference-telemetry.test.ts`; collector outage in `tests/scale/telemetry/telemetry-storm.test.ts` |
|
||||
| 15 | Failure boundaries prevent one feature/context from unnecessarily collapsing unrelated UI. | 완료 | `src/platform/errors/{scoped-error-boundary,feature-error-boundary,context-error-boundary}.tsx`; wiring in `src/presentation/routes/app-router.tsx`; `tests/platform/errors/failure-boundary.test.tsx` |
|
||||
| 16 | Spike and sustained-load tests detect request, retry, telemetry, and memory amplification. | 완료 | `tests/scale/traffic/*`, `tests/scale/telemetry/telemetry-storm.test.ts`, `tests/scale/session/*`; real Chromium soak `scripts/scale/browser-soak.ts` against the fresh build with telemetry on and a 503 API: 2,012 cycles, heap/listeners/timers/storage stable, 0 in-flight at end, 1.43 API requests per reference visit (≤ 3), telemetry ≤ 14 posts/min (≤ 40), checks in `artifacts/scale/nightly/browser-soak.json`; evaluator tests `tests/scale/browser-soak.contract.test.ts`; skipped ⇒ tier `incomplete` (non-zero). Platform telemetry adapter now send-rate limited (`src/adapters/telemetry/best-effort-telemetry.ts`, tests in `tests/unit/telemetry.test.ts`) |
|
||||
| 17 | Multi-replica release tests verify fail-closed coherence and old-asset reachability. | 완료 | `src/platform/release/release-coherence.ts` (delegated to by `src/bootstrap/load-runtime-config.ts`, `src/bootstrap/load-release-manifest.ts`); `src/platform/release/release-mismatch-recovery.ts` + `src/bootstrap/boot-release-recovery.ts`; `tests/platform/release/*.test.ts`; `tests/release/{old-asset-reachability,mixed-replica,release-matrix}.test.ts`; `pnpm check:release-coherence` |
|
||||
|
||||
Overall: **완료** — every spec §54 criterion is `완료`.
|
||||
|
||||
## 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`):
|
||||
|
||||
```
|
||||
PATH=$PWD/.tmp/node24/bin:$PATH corepack pnpm run verify:extreme-scale
|
||||
```
|
||||
|
||||
Record `artifacts/quality/extreme-scale-gates.json` (logs in `artifacts/quality/extreme-scale-gates/`): status `passed`, **24/24 gates, 552 tests passed, 0 failed** — `check:feature-index`, `check:types:app`, `check:types:test`, `check:types`, `lint`, `check:architecture`, `check:app-build-input`, `check:request-fanout`, `check:registries`, `check:diagnostics`, `test:extreme-scale:focused`, `check:topology`, `check:traffic`, `check:observability`, `check:release-coherence`, `test:platform`, `test:reference-feature`, `check:scale:pr`, `check:scale:main`, `check:scale:baseline`, `build`, `check:app-build-input:bundle`, `check:scale:nightly`, `check:scale:release`.
|
||||
|
||||
The same record carries 12 evidence checks, all passed: nightly/release summaries and the soak, baseline comparison and bundle inventory were regenerated by this run; tier summaries have `environment.nodeMajor == 24`, status `passed` and no skipped step; the soak is `passed`; the baseline comparison is `passed` on all three axes (absolute ceiling, relative regression, growth shape) with a timing-compatible environment (an incompatible one is `incomplete`, never passed); and the source digest (`source.digest`, 1,048 files) did not change while the gates ran. On an unsupported Node the runner writes `not-executed` and exits 2.
|
||||
|
||||
Also on Node v24.11.0 in the container: `test:sample-removal` PASS (13 checks, no fixture IDs); coverage suite 217 files / 2,314 tests PASS; risk coverage 362/362 modules, 80 thresholds PASS.
|
||||
|
||||
## Notes that do not change a row
|
||||
|
||||
- Behavior changes worth review: `retryDelayFor()` now treats `Retry-After` as a floor plus bounded jitter (spec §13.3); a boot-time release mismatch now performs at most one automatic reload per mismatch key before showing the boot error shell (spec §45).
|
||||
- Fixed while closing coverage: `src/contracts/diagnostics.ts` rejected its own bounded bucket labels `51+`/`5+`; admitted finite-set values are now projected as-is.
|
||||
- Stored baseline and relative regression gate: `config/scale/benchmark-baseline.json` (approved, digest-checked) + `scripts/scale/{scale-baseline,check-scale-baseline}.ts`, run by `pnpm check:scale:baseline` and the `baseline-regression` step of the main/nightly/release tiers; logic tested in `tests/scale/scale-baseline.test.ts`. Compiler counts must stay within +10% and need re-approval on a compiler change; timings must stay within 2.5x (1 ms noise floor) and are enforced only on a timing-compatible machine (same Node major, platform/arch, CPU model), otherwise reported as advisory. Re-approve with `SCALE_BASELINE_OWNER=… SCALE_BASELINE_REASON=… pnpm update:scale-baseline`.
|
||||
- Host-checkout-only failures (not reproduced in the container run above): tests that need a git-tracked `src/` inventory (`tests/integration/security-followup-archive.test.ts`, `tests/system/ci-runner/ci-artifact-contract.test.ts`) and `check:adapter-inventory`; Playwright `*.spec.ts` files are not vitest suites.
|
||||
@@ -0,0 +1,190 @@
|
||||
# Extreme-scale frontend implementation baseline
|
||||
|
||||
## Live baseline
|
||||
|
||||
- Verified source baseline: `origin/main` `ebea300e4ffd9ef9312d3982b44ccda2fc3fea2c`.
|
||||
- Local branch remains the user-owned initial branch and was not reset because the worktree already contained untracked project files.
|
||||
- Missing baseline files were materialized with `git archive origin/main | tar --skip-old-files -x`; existing files were preserved byte-for-byte.
|
||||
- Host during implementation: Node `v22.23.2`, pnpm `11.17.0`.
|
||||
- Repository engine requests Node `>=24.11.0 <25.0.0`; checks executed on this host therefore retain an engine warning.
|
||||
- `tsconfig.app.json` passed before production edits.
|
||||
|
||||
## Verified scale-sensitive baseline paths
|
||||
|
||||
- `src/features/installed-product-manifest.ts` directly imported the reference feature contract.
|
||||
- `src/features/installed-feature-adapters.ts` directly imported the reference adapter contribution.
|
||||
- `src/features/installed-feature-runtimes.tsx` directly imported the reference runtime contribution and used installed-id membership filtering.
|
||||
- `src/features/installed-feature-messages.ts` directly imported the reference message catalogs.
|
||||
- `src/features/installed-contract-contributions.ts` directly imported the reference contract contribution and used installed-id membership filtering.
|
||||
- `src/features/installed-feature-contracts.ts` composed routes and route-runtime contracts with repeated accumulator object spread inside `reduce()`.
|
||||
- `src/contracts/product-features.ts` used repeated array `includes()` membership checks.
|
||||
- `src/presentation/routes/app-router.tsx` flattened `Object.values(ROUTE_REGISTRY)` into boot-time route objects.
|
||||
- `.dependency-cruiser.json` had feature-local layer rules but no generic Feature-A -> Feature-B or Context-A -> Context-B concrete import prohibition.
|
||||
|
||||
## Live-path ruling
|
||||
|
||||
The supplied plan names `src/features/product-features.ts`; the verified live implementation is `src/contracts/product-features.ts`. The live path is used throughout implementation. The live reference feature id is `reference-feature`; example ids such as `reference` in the plan are treated as illustrative and do not replace the existing contract id.
|
||||
|
||||
## 2026-09-23 Phase 2 continuation ledger
|
||||
|
||||
### Execution environment
|
||||
|
||||
- Continuation checks ran with Node `v24.11.0` from the verified host-local Node 24.11.0 binary path; no Node installation files were added to the repository.
|
||||
- The existing working tree was preserved. No reset, clean, checkout, rebase, merge, commit, or push was performed.
|
||||
|
||||
### Phase 2-B — 완료
|
||||
|
||||
- `tests/platform/cardinality/extreme-scale-registry.test.ts` was executed before modification and passed 3/3 tests against the existing O(N) production composition path.
|
||||
- The scale gate now performs one warm-up plus three measured runs and compares the median instead of relying on one timing sample.
|
||||
- Registry composition validates 10k -> 100k relative growth with a generous hard ceiling.
|
||||
- Runtime registry lookup validates 100k entries with 1,000,000 repeated lookups.
|
||||
- Product feature selection and installed/active resolution validate 100k feature ids.
|
||||
- Related cardinality/routing/product-feature regression: 7 files, 28 tests PASS.
|
||||
|
||||
### Phase 2-C — 완료
|
||||
|
||||
- Context route loading remains lazy and is now single-flight per context.
|
||||
- A successful context route composition is frozen and cached; later entries reuse the same route array.
|
||||
- A failed lazy load clears only the in-flight promise so the next entry can retry.
|
||||
- `ContextRouteGateway` no longer clones the already-frozen route array after each context load.
|
||||
- Generator regression verifies that feature executable route modules are emitted as dynamic imports behind one context loader, not as boot-time static imports.
|
||||
- Focused lazy-composition regression: 3 files, 9 tests PASS.
|
||||
|
||||
### Phase 2-D — 완료
|
||||
|
||||
- The topology gate now proves with a generic 20-context app that app boot constructs context gateways without executing any context route loader.
|
||||
- Entering one context executes only that context loader; re-entry reuses the cached result.
|
||||
- The test contains no concrete product feature id, so the physical feature-removal fixture remains valid.
|
||||
- `check:topology` includes this boot/lazy regression permanently.
|
||||
|
||||
### Phase 2-E / Phase 2-F — 완료
|
||||
|
||||
- Topology capacity remains covered at 100 / 1k / 10k / 100k / 1M feature tiers using partition math rather than materializing one million executable feature objects.
|
||||
- The 100k registry / 1,000,000 lookup scale gate is part of the same topology CI gate.
|
||||
- Latest `check:topology`: 6 files, 21 tests PASS.
|
||||
|
||||
### Required gates after Phase 2
|
||||
|
||||
- `check:types:app`: PASS.
|
||||
- `check:types:test`: PASS.
|
||||
- `check:feature-index`: PASS.
|
||||
- `check:architecture`: 329 modules, 979 dependencies, all imports resolved; 16 graph regression checks PASS; allowed fixture PASS; 9 forbidden fixtures rejected.
|
||||
- `test:sample-removal`: 13/13 checks PASS, no fixture ids.
|
||||
- Sample-removal coverage run: 168 test files PASS, 1604 passed, 3 skipped.
|
||||
- Sample-removal risk coverage: 307/307 production modules PASS, 76 thresholds.
|
||||
- Sample-removal fixture architecture: 308 modules, 897 dependencies, 16 graph regression checks PASS, 9 forbidden fixtures rejected.
|
||||
|
||||
Phase 2 status: **완료**.
|
||||
|
||||
## 2026-09-23 Phase 3 continuation ledger
|
||||
|
||||
### Phase 3 — logging / diagnostics cardinality — 완료
|
||||
|
||||
- Every diagnostic context key now has an explicit cardinality class: `bounded`, `taxonomy`, `topology`, `deployment`, or `request`.
|
||||
- `correlation_id` is explicitly request-cardinality and remains diagnostics-only; `check:diagnostics` rejects any request-cardinality key added to telemetry dimensions.
|
||||
- Route/operation ids are topology-cardinality and are bounded by the deployed topology rather than raw URL/user values.
|
||||
- Outcome, HTTP status group, attempt count, duration, component boundary, and queue size are validated as bounded dimensions rather than arbitrary safe strings.
|
||||
- Existing source-controlled error/reason taxonomies remain distinct from request-cardinality identifiers.
|
||||
- Focused diagnostics/telemetry regression: 5 files, 33 tests PASS.
|
||||
- `check:diagnostics`: 8 diagnostic producers and 5 telemetry producers PASS.
|
||||
- `check:types:app`: PASS.
|
||||
- `check:types:test`: PASS.
|
||||
- `check:architecture`: 329 modules, 979 dependencies, 16 graph regression checks PASS, 9 forbidden fixtures rejected.
|
||||
|
||||
Phase 3 status: **완료**.
|
||||
|
||||
## 2026-09-23 Phase 4 continuation ledger
|
||||
|
||||
### Phase 4 — error taxonomy / validation — 완료
|
||||
|
||||
- Validation issue projection is centralized in `src/contracts/validation-issues.ts`.
|
||||
- Failure handling admits at most 50 projected issues, scans at most 200 candidates, and rejects issue paths longer than 120 characters or codes longer than 80 characters.
|
||||
- `createFailure()`, legacy HTTP schema projection, and installed runtime schema codec projection use the same bounded issue policy.
|
||||
- A Feature codec can no longer return an unbounded validation issue array through the runtime schema registry.
|
||||
- Error taxonomy observability references are no longer free-form strings: `ErrorObservationEvent` is the union of registered diagnostic and telemetry event ids.
|
||||
- The stale `QUERY_CACHE_FAILURE -> query.cache.failed` reference was corrected to the registered `cache.operation.failed` event.
|
||||
- Focused error/schema regression: 4 files, 27 tests PASS.
|
||||
- `check:types:app`: PASS.
|
||||
- `check:types:test`: PASS.
|
||||
- `check:architecture`: 330 modules, 984 dependencies, 16 graph regression checks PASS, 9 forbidden fixtures rejected.
|
||||
|
||||
Phase 4 status: **완료**.
|
||||
|
||||
## 2026-09-23 plan-bundle continuation ledger (Phases 2–5 of `2026-09-23-extreme-scale-frontend-plan-bundle`)
|
||||
|
||||
The ledger sections above track the earlier numbering. This section maps the remaining work onto the bundle's five plans. Phase 1 (topology/composition) was verified complete before starting (`check:feature-index`, `check:architecture`, `check:topology`, both type checks PASS; no spread accumulators, no `includes()` membership, no `REFERENCE_*` in installed central files).
|
||||
|
||||
### Execution environment
|
||||
|
||||
- Node `v24.14.0`; pnpm scripts run with `pnpm_config_verify_deps_before_run=false` because pnpm's deps-status check tried to purge `node_modules` without a TTY. No dependency was installed or changed.
|
||||
- Project files written by the previous in-container (root) session were re-owned to uid 1000 so the host user could edit them; contents were not changed.
|
||||
|
||||
### Phase 2 — execution/traffic — 완료
|
||||
|
||||
- `src/platform/execution/execution-context.ts`, `src/platform/traffic/{request-budget,concurrency-budget,traffic-budget,request-fanout}.ts`, `src/platform/resilience/{retry-budget,deadline}.ts`.
|
||||
- `HttpExecutionPolicy.traffic` (optional, validated, snapshotted) in `src/contracts/external-contract-runtime.ts`; reference operations declare it.
|
||||
- V3 executor enforces: cancellation → remaining interaction deadline → request budget → cancellable concurrency lease → dispatch → shared retry budget; operations without an interaction get a bounded implicit one (`DEFAULT_OPERATION_TRAFFIC_BUDGET`). Existing HTTP suites unchanged and green.
|
||||
- `check:traffic`: 11 files PASS.
|
||||
|
||||
### Phase 3 — errors/validation/telemetry — 완료
|
||||
|
||||
- `src/platform/errors/*` (envelope, platform kinds, scoped/feature/context boundaries wired in `ContextRouteGateway`), `src/adapters/http/platform-error-mapping.ts`, feature-local `reference-error.ts`.
|
||||
- `src/platform/validation/*`; structure-before-mapping in V3 response admission.
|
||||
- `src/platform/telemetry/*` (port, redaction, fingerprint, dedup, sampler, buffer, fail-open pipeline, trace context); `telemetry` feature capability; bootstrap composes `createFeatureTelemetry`; reference feature emits `reference.load.failed`.
|
||||
- `.dependency-cruiser.json`: `observability-vendors-live-behind-adapters`, `platform-kernel-is-product-neutral`.
|
||||
- `check:observability`: 12 files PASS.
|
||||
|
||||
### Phase 4 — scale/chaos/soak — 완료
|
||||
|
||||
- `tests/scale/**`, `scripts/scale/**`, `src/platform/cardinality/growth-regression.ts`.
|
||||
- Retry-After now a floor plus bounded jitter (`src/adapters/http/http-retry-lifecycle.ts`), found by the jitter regression.
|
||||
- Tiers: `check:scale:pr`, `check:scale:main`, `check:scale:nightly` (includes a 120 s real-Chromium soak: stable), `check:scale:release` — all PASS; summaries in `artifacts/scale/<tier>/summary.json`.
|
||||
|
||||
### Phase 5 — release coherence — 완료
|
||||
|
||||
- `docs/reviews/2026-09-23-release-coherence-baseline.md`; `src/platform/release/{release-coherence,release-mismatch-recovery}.ts`; both boot loaders delegate identity checks; `src/bootstrap/boot-release-recovery.ts` + `main.tsx` allow one reload per mismatch key via registered session key `RELEASE_MISMATCH_RECOVERY`.
|
||||
- `tests/platform/release/*`, `tests/release/*` (R10/R11 fixtures, mixed replicas, matrix, no reload loop); `check:release-coherence` PASS.
|
||||
|
||||
### Gaps from the earlier session closed here
|
||||
|
||||
- `check:registries` failed on `FE-REG-ERROR:QUERY_CACHE_FAILURE:telemetryEvent:field-changed`; evidence added to `config/contracts/registry-change-evidence.json`.
|
||||
- `check:types` (node project) failed on parameter properties in `src/platform/cardinality/cardinality-budget.ts` and a narrowed comparison in `scripts/check-diagnostics.ts`; both fixed.
|
||||
- Risk coverage failed on `src/contracts/diagnostics.ts`; the new tests exposed that bounded buckets `51+`/`5+` were rejected by the free-form safe-string pattern, fixed in the projection.
|
||||
|
||||
### Final verification
|
||||
|
||||
- PASS: `check:feature-index`, `check:architecture`, `check:topology`, `check:traffic`, `check:observability`, `check:release-coherence`, `check:scale:{pr,main,nightly,release}`, `check:types`, `check:registries`, `check:diagnostics`, `check:ci`, `lint`, `test:platform`, `test:reference-feature`.
|
||||
- Coverage suite (runtime-schema, unit, contract, component, integration, reference-feature, platform): 217 files / 2307 tests PASS; risk coverage 359/359 modules, 80 thresholds PASS.
|
||||
- `test:sample-removal`: typecheck, architecture, registries, residue and CI checks PASS inside the removal fixture; its unit/coverage stages stop only on `tests/integration/security-followup-archive.test.ts`.
|
||||
- Environment-only failures (not caused by this work): tests requiring a git-tracked `src/` inventory (`tests/integration/security-followup-archive.test.ts`, `tests/system/ci-runner/ci-artifact-contract.test.ts`) and `check:adapter-inventory`; this checkout tracks 1 file.
|
||||
|
||||
Acceptance matrix: `docs/reviews/2026-09-23-extreme-scale-acceptance.md` — all 17 spec §54 criteria `완료`.
|
||||
|
||||
### Follow-up — stored benchmark baseline and relative regression gate — 완료
|
||||
|
||||
- Baseline: `config/scale/benchmark-baseline.json` — environment (Node 24, linux/x64, i5-10400F ×12, TypeScript 7.0.2), 12 composition timings (4 workloads × S0/S1/S2, median and best-of-9) and 4 compiler fixtures (app + local 25/100/400: files/types/symbols/instantiations), approval owner/reason/time and a sha256 digest of the metrics.
|
||||
- Compatibility check (`scripts/scale/scale-baseline.ts`): structural (schema, digest, coverage of every measured workload/fixture) → must pass; compiler (same TypeScript) → a change fails and requires re-approval; timing (same Node major, platform/arch, CPU model) → otherwise timing is advisory and skipped.
|
||||
- Relative gate: compiler counts ≤ baseline × 1.10; best-observed timing ≤ max(baseline × 2.5, baseline + 1 ms).
|
||||
- Commands: `check:scale:baseline`, `update:scale-baseline` (requires `SCALE_BASELINE_OWNER`/`SCALE_BASELINE_REASON`); step `baseline-regression` in `check:scale:{main,nightly,release}`; `tests/scale/scale-baseline.test.ts` (9 tests) in the PR tier.
|
||||
- Verification: gate PASS 4/4 consecutive runs (closest metric at 0.91 of its limit — compiler counts equal to baseline); `check:types`, `lint`, `check:architecture`, `check:ci`, `check:scale:{pr,main,release}` PASS.
|
||||
- Master plan Final Verification: all 14 items checked.
|
||||
|
||||
### Follow-up — 2026-09-23 re-verification findings — 완료
|
||||
|
||||
The re-verification ("아직 더 봐야댐") raised three blockers; each is closed with executable evidence.
|
||||
|
||||
1. **Gates not executed on Node 22.** New `pnpm verify:extreme-scale` (`scripts/verify-extreme-scale.ts`) runs all 18 cited gates under the current Node and records `artifacts/quality/extreme-scale-gates.json`; on an unsupported Node it records `not-executed` and exits 2. Re-run inside `workmachine` with the repository-local Node 24.11.0 first on PATH: 18/18 PASS, including `check:scale:nightly` with a real Chromium soak (Playwright headless shell provided via `PLAYWRIGHT_BROWSERS_PATH=.tmp/ms-playwright`; all shared libraries resolved in the container) and a timing-compatible `check:scale:baseline`. `test:sample-removal` PASS (13 checks); coverage 217 files / 2308 tests; risk coverage 362/362.
|
||||
2. **S4 proof not linked to production discovery.** The generator now discovers ownership declarations (`src/apps/<app>/app-module.ts` → `src/contexts/<context>/context-module.ts` → `FEATURE_CONTEXT_ID`) and emits indexes for exactly one selected app (`--app=`/`PRODUCT_APP_ID`, or the single declared app), including `src/.generated/product-app.ts`, which `src/apps/template-app.ts` consumes. Context route root and budget moved from the feature to the context declaration. `tests/scale/global-local-independence.test.ts` runs the production generator command on real S0/S1/S2 on-disk repositories (identical outputs and reachable source graph for App A) and the same `selectAppIndexes` at S3/S4 over a declaration source proven equivalent to the filesystem one; the removal drill now also removes the sample context.
|
||||
3. **N+1 at 1,000 rows only proven by rejection.** Fan-out tests now load 10/100/1,000-row paginated collections successfully with one request per page (≤ ceil(N/100)+1 for a full walk); the single-oversized-response rejection remains a separate bounded-rejection case.
|
||||
|
||||
Also: a tier with a skipped step is now `incomplete` and exits non-zero; the soak fails on `insufficient-data` and records the soaked build identity and browser version.
|
||||
|
||||
### Follow-up — second re-verification (production-path rigor) — 완료
|
||||
|
||||
- Build-input regression gate: `scripts/check-app-build-input.ts` checks the generated indexes (and, after a fresh build, the production module inventory) contain only features owned by the built app; negative fixtures cover an "import every discovered feature" regression and a foreign module in the bundle.
|
||||
- S0→S4 invariant extended to generated-file sha256 and compile-input paths through `selectAppIndexes`; on-disk S0–S2 also compares hashes.
|
||||
- Baseline gate now evaluates absolute ceilings, relative regression and growth shape; a timing-incompatible environment yields `incomplete` (non-zero), not `passed`.
|
||||
- N+1: supported page cardinalities 10/50/100 plus 1,000-row collections; spec §41 carries the policy note; `check:request-fanout` AST gate with forbidden/allowed fixtures.
|
||||
- Browser soak v2: cycles, navigation verification, listener/timer/storage deltas, in-flight settle, request amplification and telemetry rate against a 503 API with telemetry enabled; non-vacuity required. Found and fixed: the platform-event telemetry adapter had no send-rate limit (now 20/min, bounded queue, page-exit flush may exceed once).
|
||||
- `verify:extreme-scale` records pnpm version, node major, a source digest (checked unchanged across the run), per-gate test counts and artifact-freshness checks.
|
||||
- Result: 24/24 gates, 552 tests, 12/12 evidence checks on Node v24.11.0 in the container; removal drill 13/13; coverage 2,314 tests; risk coverage 362/362.
|
||||
+715
@@ -0,0 +1,715 @@
|
||||
# Error, Validation, Telemetry, and Failure Boundary Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` or `superpowers:executing-plans` to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Make errors, external validation, observability, and UI failure containment maintainable at extreme domain/traffic scale without global unions/registries or telemetry amplification.
|
||||
|
||||
**Architecture:** Platform code owns generic envelopes and enforcement; features own concrete domain errors, validation schemas/contracts, message mappings, and telemetry payloads. External data is bounded before expensive parsing/mapping. Telemetry passes through a provider-neutral port and bounded pipeline: redact -> fingerprint -> deduplicate -> sample -> bounded buffer -> batch/rate-limit -> transport. Failure boundaries align with app/context/feature ownership.
|
||||
|
||||
**Tech Stack:** TypeScript, current runtime schema system, React Error Boundary mechanism/current router, current HTTP contract layer, provider-neutral telemetry adapter.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-09-23-extreme-scale-frontend-architecture-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- No global union of all feature errors or telemetry payloads.
|
||||
- Feature code cannot import Sentry/Datadog/vendor SDK APIs directly.
|
||||
- Telemetry failure cannot fail business behavior.
|
||||
- Buffers, dedup tables, rate windows, payloads, collection size, depth, and string length are bounded.
|
||||
- Access tokens, refresh tokens, authorization, cookies, passwords, and equivalent secrets are never emitted.
|
||||
- Validation at frontend trust boundaries does not replace backend validation.
|
||||
- Do not commit/merge/reset/discard repository changes.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. An unknown error type must still be represented without extending a global union.
|
||||
2. A huge/deep malformed payload must be rejected within configured structural limits.
|
||||
3. Repeated identical browser errors must not produce proportional telemetry network calls.
|
||||
4. Telemetry transport failure must not reject the business operation.
|
||||
5. A feature render failure must not collapse unrelated context/app UI.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Define the platform error envelope
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/errors/app-error.ts`
|
||||
- Test: `tests/platform/errors/app-error.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `AppError`
|
||||
- `ErrorCategory`
|
||||
- `ErrorSeverity`
|
||||
- `Retryability`
|
||||
- `isAppError()`
|
||||
|
||||
- [ ] **Step 1: Write the failing structural test**
|
||||
|
||||
```ts
|
||||
it("recognizes feature-owned errors through the platform envelope", () => {
|
||||
const error = {
|
||||
kind: "payment.declined",
|
||||
category: "domain",
|
||||
severity: "warning",
|
||||
retryability: "never",
|
||||
} as const;
|
||||
|
||||
expect(isAppError(error)).toBe(true);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/errors/app-error.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement the generic envelope**
|
||||
|
||||
```ts
|
||||
export type ErrorCategory =
|
||||
| "transport"
|
||||
| "contract"
|
||||
| "validation"
|
||||
| "domain"
|
||||
| "application"
|
||||
| "platform";
|
||||
|
||||
export type ErrorSeverity = "info" | "warning" | "error" | "critical";
|
||||
export type Retryability = "never" | "safe" | "policy";
|
||||
|
||||
export interface AppError {
|
||||
readonly kind: string;
|
||||
readonly category: ErrorCategory;
|
||||
readonly severity: ErrorSeverity;
|
||||
readonly retryability: Retryability;
|
||||
}
|
||||
```
|
||||
|
||||
Do not create a union enumerating all feature `kind` literals.
|
||||
|
||||
- [ ] **Step 4: Run test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/errors/app-error.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Normalize platform/transport errors at the adapter boundary
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/errors/platform-errors.ts`
|
||||
- Modify: current HTTP executor/transport error mapper from Phase 2
|
||||
- Test: `tests/platform/errors/platform-errors.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces concrete platform errors for network unavailable, timeout, cancellation, oversized response, invalid transport response, and traffic-budget exhaustion.
|
||||
|
||||
- [ ] **Step 1: Write a mapper test**
|
||||
|
||||
```ts
|
||||
it("maps an abort caused by interaction cancellation to request.cancelled", () => {
|
||||
const error = mapTransportFailure(abortError(), { deadlineExpired: false });
|
||||
|
||||
expect(error).toMatchObject({
|
||||
kind: "request.cancelled",
|
||||
category: "transport",
|
||||
retryability: "never",
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/errors/platform-errors.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement stable machine-readable platform kinds**
|
||||
|
||||
Use stable kinds such as:
|
||||
- `network.unavailable`
|
||||
- `request.timeout`
|
||||
- `request.cancelled`
|
||||
- `response.too-large`
|
||||
- `response.invalid`
|
||||
- `traffic.budget-exceeded`
|
||||
|
||||
- [ ] **Step 4: Run HTTP/error tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/errors tests --testNamePattern="http|transport"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Prove feature-local domain errors need no global union
|
||||
|
||||
**Files:**
|
||||
- Create: `src/features/reference-feature/application/reference-error.ts`
|
||||
- Test: `tests/features/reference-feature/reference-error.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `AppError`.
|
||||
- Produces `ReferenceError` local union only.
|
||||
|
||||
- [ ] **Step 1: Write the local type/runtime test**
|
||||
|
||||
```ts
|
||||
type ReferenceError =
|
||||
| {
|
||||
readonly kind: "reference.not-found";
|
||||
readonly category: "domain";
|
||||
readonly severity: "warning";
|
||||
readonly retryability: "never";
|
||||
}
|
||||
| {
|
||||
readonly kind: "reference.conflict";
|
||||
readonly category: "domain";
|
||||
readonly severity: "warning";
|
||||
readonly retryability: "never";
|
||||
};
|
||||
|
||||
it("keeps concrete error kinds feature-local", () => {
|
||||
const error: ReferenceError = {
|
||||
kind: "reference.not-found",
|
||||
category: "domain",
|
||||
severity: "warning",
|
||||
retryability: "never",
|
||||
};
|
||||
|
||||
expect(isAppError(error)).toBe(true);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run TypeScript/test checks**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/features/reference-feature/reference-error.test.ts
|
||||
pnpm exec tsc --project tsconfig.app.json --noEmit
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Scan against global mega-union creation**
|
||||
|
||||
```bash
|
||||
rg -n 'Global(Application)?Error|AllFeatureErrors|InstalledFeatureErrors' src
|
||||
```
|
||||
|
||||
Expected: no global feature-error union.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Add validation budget primitives
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/validation/validation-budget.ts`
|
||||
- Test: `tests/platform/validation/validation-budget.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces `ValidationBudget` and finite-value validation.
|
||||
|
||||
- [ ] **Step 1: Write failing finite-bound tests**
|
||||
|
||||
```ts
|
||||
it("rejects unbounded validation configuration", () => {
|
||||
expect(() =>
|
||||
defineValidationBudget({
|
||||
maxBytes: Infinity,
|
||||
maxItems: 1_000,
|
||||
maxDepth: 20,
|
||||
maxStringLength: 32_768,
|
||||
}),
|
||||
).toThrow(/maxBytes/);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/validation/validation-budget.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement**
|
||||
|
||||
```ts
|
||||
export interface ValidationBudget {
|
||||
readonly maxBytes: number;
|
||||
readonly maxItems: number;
|
||||
readonly maxDepth: number;
|
||||
readonly maxStringLength: number;
|
||||
}
|
||||
```
|
||||
|
||||
All values must be finite positive safe integers.
|
||||
|
||||
- [ ] **Step 4: Run test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/validation/validation-budget.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Enforce size before parse and structure before mapping
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/validation/bounded-json.ts`
|
||||
- Modify: current bounded body reader/HTTP response parsing path
|
||||
- Test: `tests/platform/validation/bounded-json.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces `parseBoundedJson(text, budget)` or equivalent integration with existing body reader.
|
||||
|
||||
- [ ] **Step 1: Write oversized-input test**
|
||||
|
||||
```ts
|
||||
it("rejects oversized input before JSON.parse is invoked", () => {
|
||||
const parse = vi.spyOn(JSON, "parse");
|
||||
const payload = "x".repeat(101);
|
||||
|
||||
expect(() =>
|
||||
parseBoundedJson(payload, {
|
||||
maxBytes: 100,
|
||||
maxItems: 10,
|
||||
maxDepth: 10,
|
||||
maxStringLength: 100,
|
||||
}),
|
||||
).toThrow(/too-large/i);
|
||||
|
||||
expect(parse).not.toHaveBeenCalled();
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add depth/array/string tests**
|
||||
|
||||
```ts
|
||||
it("rejects arrays above maxItems", () => {
|
||||
expect(() => validateJsonStructure([1, 2, 3], { ...BUDGET, maxItems: 2 }))
|
||||
.toThrow(/items/i);
|
||||
});
|
||||
```
|
||||
|
||||
Add analogous explicit tests for `maxDepth` and `maxStringLength`.
|
||||
|
||||
- [ ] **Step 3: Implement iterative bounded structural traversal**
|
||||
|
||||
Use an explicit stack/queue rather than unbounded recursive descent so adversarial nesting cannot overflow the JS call stack.
|
||||
|
||||
- [ ] **Step 4: Integrate with existing response contract**
|
||||
|
||||
Existing `maxResponseBytes` remains the transport-size ceiling; `ValidationBudget` controls parsed structure.
|
||||
|
||||
- [ ] **Step 5: Run validation/HTTP tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/validation tests --testNamePattern="response|schema"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Define provider-neutral telemetry event and port
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/telemetry/telemetry-event.ts`
|
||||
- Create: `src/platform/telemetry/telemetry-port.ts`
|
||||
- Test: `tests/platform/telemetry/telemetry-port.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `TelemetryEvent<TPayload>`
|
||||
- `TelemetryPort.emit(event): void | Promise<void>`
|
||||
|
||||
- [ ] **Step 1: Write the compile/runtime test**
|
||||
|
||||
```ts
|
||||
it("accepts feature-owned payloads through a generic envelope", async () => {
|
||||
const seen: TelemetryEvent<unknown>[] = [];
|
||||
const port: TelemetryPort = {
|
||||
emit(event) {
|
||||
seen.push(event);
|
||||
},
|
||||
};
|
||||
|
||||
await port.emit({
|
||||
kind: "reference.load.failed",
|
||||
severity: "error",
|
||||
contextId: "reference",
|
||||
featureId: "reference",
|
||||
interactionId: "i-1",
|
||||
payload: { reason: "timeout" },
|
||||
});
|
||||
|
||||
expect(seen).toHaveLength(1);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/telemetry/telemetry-port.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement only the common envelope**
|
||||
|
||||
No Sentry/Datadog/vendor type appears in these interfaces.
|
||||
|
||||
- [ ] **Step 4: Run test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/telemetry/telemetry-port.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Implement telemetry redaction before buffering
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/telemetry/redact-telemetry.ts`
|
||||
- Test: `tests/platform/telemetry/redact-telemetry.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces `redactTelemetryPayload()`.
|
||||
|
||||
- [ ] **Step 1: Write secret-removal tests**
|
||||
|
||||
```ts
|
||||
it.each([
|
||||
"password",
|
||||
"authorization",
|
||||
"cookie",
|
||||
"accessToken",
|
||||
"refreshToken",
|
||||
])("redacts %s recursively", (secretKey) => {
|
||||
const input = { nested: { [secretKey]: "secret", safe: "ok" } };
|
||||
const result = redactTelemetryPayload(input);
|
||||
|
||||
expect(JSON.stringify(result)).not.toContain("secret");
|
||||
expect(result).toMatchObject({ nested: { safe: "ok" } });
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/telemetry/redact-telemetry.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement bounded recursive/iterative sanitizer**
|
||||
|
||||
Do not preserve prototypes or execute getters from untrusted payloads. Cap traversal using the telemetry payload structural budget.
|
||||
|
||||
- [ ] **Step 4: Run test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/telemetry/redact-telemetry.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Implement deterministic fingerprinting and bounded deduplication
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/telemetry/telemetry-fingerprint.ts`
|
||||
- Create: `src/platform/telemetry/telemetry-deduplicator.ts`
|
||||
- Test: `tests/platform/telemetry/telemetry-deduplicator.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `fingerprintTelemetryEvent()`
|
||||
- `TelemetryDeduplicator(maxEntries, windowMs)`
|
||||
|
||||
- [ ] **Step 1: Write repeated-error test**
|
||||
|
||||
```ts
|
||||
it("collapses repeated identical failures into one active fingerprint entry", () => {
|
||||
const dedup = new TelemetryDeduplicator({ maxEntries: 100, windowMs: 60_000 });
|
||||
|
||||
for (let i = 0; i < 10_000; i += 1) {
|
||||
dedup.record(FINGERPRINT, i);
|
||||
}
|
||||
|
||||
expect(dedup.size).toBe(1);
|
||||
expect(dedup.count(FINGERPRINT)).toBe(10_000);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add capacity test**
|
||||
|
||||
```ts
|
||||
it("never retains more than maxEntries fingerprints", () => {
|
||||
const dedup = new TelemetryDeduplicator({ maxEntries: 2, windowMs: 60_000 });
|
||||
dedup.record("a", 1);
|
||||
dedup.record("b", 2);
|
||||
dedup.record("c", 3);
|
||||
|
||||
expect(dedup.size).toBe(2);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement bounded LRU/window eviction**
|
||||
|
||||
- [ ] **Step 4: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/telemetry/telemetry-deduplicator.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 9: Implement deterministic sampling and bounded buffer
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/telemetry/telemetry-sampler.ts`
|
||||
- Create: `src/platform/telemetry/telemetry-buffer.ts`
|
||||
- Test: `tests/platform/telemetry/telemetry-buffer.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces deterministic sampling by interaction/trace key and bounded event/byte buffer.
|
||||
|
||||
- [ ] **Step 1: Write deterministic sampling test**
|
||||
|
||||
```ts
|
||||
it("makes the same sampling decision for the same stable key", () => {
|
||||
const sampler = createDeterministicSampler({ rate: 0.1 });
|
||||
|
||||
expect(sampler.keep("interaction-123")).toBe(sampler.keep("interaction-123"));
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Write bounded buffer test**
|
||||
|
||||
```ts
|
||||
it("never exceeds event or byte ceilings", () => {
|
||||
const buffer = createTelemetryBuffer({
|
||||
maxEvents: 2,
|
||||
maxBytes: 1_024,
|
||||
});
|
||||
|
||||
buffer.push(infoEvent("a"));
|
||||
buffer.push(infoEvent("b"));
|
||||
buffer.push(criticalEvent("c"));
|
||||
|
||||
expect(buffer.size).toBeLessThanOrEqual(2);
|
||||
expect(buffer.bytes).toBeLessThanOrEqual(1_024);
|
||||
expect(buffer.items.some((item) => item.severity === "critical")).toBe(true);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement severity-aware drop policy**
|
||||
|
||||
Lowest-priority events are evicted/dropped first; buffer growth is never used as backpressure.
|
||||
|
||||
- [ ] **Step 4: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/telemetry/telemetry-buffer.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 10: Implement rate-limited fail-open telemetry pipeline
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/telemetry/telemetry-pipeline.ts`
|
||||
- Test: `tests/platform/telemetry/telemetry-pipeline.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes redaction, fingerprinting, dedup, sampler, buffer, provider transport.
|
||||
- Produces `TelemetryPipeline.emit()` that never throws into business behavior.
|
||||
|
||||
- [ ] **Step 1: Write transport-failure test**
|
||||
|
||||
```ts
|
||||
it("does not reject business flow when telemetry transport fails", async () => {
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: {
|
||||
async send() {
|
||||
throw new Error("collector unavailable");
|
||||
},
|
||||
},
|
||||
budget: TEST_TELEMETRY_BUDGET,
|
||||
});
|
||||
|
||||
await expect(pipeline.emit(TEST_EVENT)).resolves.toBeUndefined();
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Write storm-bound test**
|
||||
|
||||
```ts
|
||||
it("bounds network sends during a repeated error storm", async () => {
|
||||
const send = vi.fn().mockResolvedValue(undefined);
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: { send },
|
||||
budget: { ...TEST_TELEMETRY_BUDGET, maxSendsPerMinute: 10 },
|
||||
});
|
||||
|
||||
for (let i = 0; i < 100_000; i += 1) {
|
||||
await pipeline.emit(REPEATED_ERROR);
|
||||
}
|
||||
|
||||
await pipeline.flush();
|
||||
expect(send.mock.calls.length).toBeLessThanOrEqual(10);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement the fixed pipeline order**
|
||||
|
||||
```text
|
||||
redact
|
||||
fingerprint
|
||||
deduplicate
|
||||
sample
|
||||
buffer
|
||||
rate limit
|
||||
batch
|
||||
transport
|
||||
```
|
||||
|
||||
Every internal exception is swallowed or converted to an internal dropped-event counter; it never rejects the business caller.
|
||||
|
||||
- [ ] **Step 4: Run telemetry tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/telemetry
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 11: Add trace/correlation propagation to execution and transport
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/telemetry/trace-context.ts`
|
||||
- Modify: `src/platform/execution/execution-context.ts`
|
||||
- Modify: current HTTP request header builder
|
||||
- Test: `tests/platform/telemetry/trace-context.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces stable interaction/trace context and valid `traceparent`/correlation metadata according to the existing server contract.
|
||||
|
||||
- [ ] **Step 1: Write propagation test**
|
||||
|
||||
```ts
|
||||
it("propagates one interaction trace identity to child requests", () => {
|
||||
const context = testExecutionContext({ interactionId: "i-1", traceId: VALID_TRACE_ID });
|
||||
|
||||
const a = buildRequestHeaders(context);
|
||||
const b = buildRequestHeaders(context);
|
||||
|
||||
expect(a.get("traceparent")).toBe(b.get("traceparent"));
|
||||
expect(a.get("x-correlation-id")).toBe("i-1");
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED and then implement**
|
||||
|
||||
Use existing header conventions if the repository already defines them; do not introduce duplicate competing correlation headers.
|
||||
|
||||
- [ ] **Step 3: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/telemetry/trace-context.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 12: Align React failure boundaries with ownership boundaries
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/errors/feature-error-boundary.tsx`
|
||||
- Create: `src/platform/errors/context-error-boundary.tsx`
|
||||
- Modify: context/feature route composition from Phase 1
|
||||
- Test: `tests/platform/errors/failure-boundary.test.tsx`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces feature- and context-scoped render containment.
|
||||
|
||||
- [ ] **Step 1: Write the isolation test**
|
||||
|
||||
```tsx
|
||||
it("keeps sibling feature UI mounted when one feature throws during render", () => {
|
||||
render(
|
||||
<ContextErrorBoundary>
|
||||
<FeatureErrorBoundary featureId="broken">
|
||||
<ThrowsOnRender />
|
||||
</FeatureErrorBoundary>
|
||||
<div>healthy-feature</div>
|
||||
</ContextErrorBoundary>,
|
||||
);
|
||||
|
||||
expect(screen.getByText("healthy-feature")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("feature-fallback-broken")).toBeInTheDocument();
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
Run the repository's existing React test command for this file.
|
||||
|
||||
- [ ] **Step 3: Implement scoped boundaries**
|
||||
|
||||
Feature fallback contains feature-local render failures; context boundary is the next escalation. Do not add an ErrorBoundary around every leaf component.
|
||||
|
||||
- [ ] **Step 4: Run UI/router tests**
|
||||
|
||||
Run the existing React/router test suite.
|
||||
|
||||
---
|
||||
|
||||
### Task 13: Close Phase 3 with global-union/vendor-import/boundedness gates
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/architecture/observability-boundaries.test.ts`
|
||||
- Modify: `.dependency-cruiser.json`
|
||||
- Modify: `package.json`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces `check:observability`.
|
||||
|
||||
- [ ] **Step 1: Add architecture prohibition for vendor SDKs in feature code**
|
||||
|
||||
Dependency rule:
|
||||
|
||||
```text
|
||||
src/features/**
|
||||
X
|
||||
@sentry/*
|
||||
@datadog/*
|
||||
vendor telemetry SDK package names present in package.json
|
||||
```
|
||||
|
||||
Only platform adapter code may import configured observability vendors.
|
||||
|
||||
- [ ] **Step 2: Add a source scan test against global mega unions**
|
||||
|
||||
```ts
|
||||
it("does not define installed/global unions of all feature errors or telemetry payloads", async () => {
|
||||
const source = await readProductionSources();
|
||||
expect(source).not.toMatch(/AllFeatureErrors|GlobalFeatureErrors|AllTelemetryEvents/);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add script**
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"check:observability": "vitest run tests/platform/errors tests/platform/validation tests/platform/telemetry tests/architecture/observability-boundaries.test.ts"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run Phase 3 verification**
|
||||
|
||||
```bash
|
||||
pnpm run check:architecture
|
||||
pnpm run check:observability
|
||||
pnpm exec tsc --project tsconfig.app.json --noEmit
|
||||
pnpm exec tsc --project tsconfig.test.json --noEmit
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Phase decision**
|
||||
|
||||
**완료** only if concrete errors remain local, validation cost is bounded, telemetry is provider-neutral/bounded/fail-open, secrets are redacted, and feature/context render failures are isolated. Otherwise **아직 더 봐야댐**.
|
||||
+594
@@ -0,0 +1,594 @@
|
||||
# Execution Context and Traffic Resilience Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` or `superpowers:executing-plans` to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Make every user interaction carry bounded physical-request, retry, concurrency, cancellation, and deadline semantics so spike traffic and slow/failing backends cannot cause unbounded client-side amplification.
|
||||
|
||||
**Architecture:** `ExecutionContext` is created once per user/application interaction and passed through application/adapter boundaries. `TrafficBudget` is immutable configuration; mutable counters/leases are interaction-local runtime state. Retry consumes a shared interaction budget, concurrency uses cancellable leases, and every physical request uses the remaining interaction deadline rather than restarting independent timeouts.
|
||||
|
||||
**Tech Stack:** TypeScript, current HTTP operation executor, AbortController, current retry/idempotency implementation, TanStack Query integration points.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-09-23-extreme-scale-frontend-architecture-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- No unbounded retry, request fan-out, concurrency, waiting queue, or timeout reset.
|
||||
- Existing idempotency/replay-safety semantics remain authoritative.
|
||||
- Retry budget is interaction-scoped, not request-scoped.
|
||||
- Cancellation propagates to queue waits, in-flight transport, retry delay, and dedup waiters.
|
||||
- Telemetry integration is deferred to Phase 3 but event hooks must not require vendor SDKs.
|
||||
- Do not commit/merge/reset/discard repository changes.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. Two failing requests in the same interaction compete for one shared retry budget.
|
||||
2. An aborted interaction releases all concurrency leases and waiting queue entries.
|
||||
3. A retry started late cannot extend the original interaction deadline.
|
||||
4. Collection cardinality growth must not create proportional physical requests.
|
||||
5. Safe/idempotent retry rules from the current HTTP layer must remain intact.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add interaction identity and execution context
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/execution/execution-context.ts`
|
||||
- Test: `tests/platform/execution/execution-context.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `InteractionId`
|
||||
- `ExecutionContext`
|
||||
- `createExecutionContext(options)`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```ts
|
||||
it("creates one immutable root context with one abort signal and absolute deadline", () => {
|
||||
const now = 1_000;
|
||||
const context = createExecutionContext({
|
||||
interactionId: "interaction-1",
|
||||
startedAt: now,
|
||||
deadlineMs: 5_000,
|
||||
traffic: {
|
||||
maxPhysicalRequests: 4,
|
||||
maxConcurrentRequests: 2,
|
||||
maxRetries: 1,
|
||||
},
|
||||
});
|
||||
|
||||
expect(context.interaction.deadlineAt).toBe(6_000);
|
||||
expect(context.cancellation.signal.aborted).toBe(false);
|
||||
expect(Object.isFrozen(context.interaction)).toBe(true);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/execution/execution-context.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement immutable configuration and private mutable budget state**
|
||||
|
||||
```ts
|
||||
export interface ExecutionContext {
|
||||
readonly interaction: {
|
||||
readonly id: string;
|
||||
readonly startedAt: number;
|
||||
readonly deadlineAt: number;
|
||||
};
|
||||
readonly cancellation: {
|
||||
readonly signal: AbortSignal;
|
||||
};
|
||||
readonly traffic: TrafficRuntime;
|
||||
}
|
||||
```
|
||||
|
||||
`TrafficRuntime` is defined in later tasks and is injected by `createExecutionContext()`.
|
||||
|
||||
- [ ] **Step 4: Run focused test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/execution/execution-context.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Implement physical request budget
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/traffic/request-budget.ts`
|
||||
- Test: `tests/platform/traffic/request-budget.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `RequestBudgetExceededError`
|
||||
- `RequestBudget`
|
||||
- `createRequestBudget(maxPhysicalRequests)`
|
||||
|
||||
- [ ] **Step 1: Write failing tests**
|
||||
|
||||
```ts
|
||||
it("allows exactly the configured number of physical requests", () => {
|
||||
const budget = createRequestBudget(2);
|
||||
expect(budget.tryConsume()).toBe(true);
|
||||
expect(budget.tryConsume()).toBe(true);
|
||||
expect(budget.tryConsume()).toBe(false);
|
||||
expect(budget.consumed).toBe(2);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/traffic/request-budget.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement monotonic bounded consumption**
|
||||
|
||||
```ts
|
||||
export interface RequestBudget {
|
||||
readonly maximum: number;
|
||||
readonly consumed: number;
|
||||
tryConsume(): boolean;
|
||||
}
|
||||
```
|
||||
|
||||
Reject non-positive/non-safe-integer maxima at construction.
|
||||
|
||||
- [ ] **Step 4: Run test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/traffic/request-budget.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Implement interaction-scoped retry budget
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/resilience/retry-budget.ts`
|
||||
- Test: `tests/platform/resilience/retry-budget.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces `RetryBudget`.
|
||||
|
||||
- [ ] **Step 1: Write the shared-budget test**
|
||||
|
||||
```ts
|
||||
it("shares retry capacity across independent requests in the same interaction", () => {
|
||||
const budget = createRetryBudget(1);
|
||||
|
||||
expect(budget.tryConsume("request-a")).toBe(true);
|
||||
expect(budget.tryConsume("request-b")).toBe(false);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/resilience/retry-budget.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement**
|
||||
|
||||
```ts
|
||||
export interface RetryBudget {
|
||||
readonly maximum: number;
|
||||
readonly consumed: number;
|
||||
tryConsume(requestId: string): boolean;
|
||||
}
|
||||
```
|
||||
|
||||
Do not reset this budget per request.
|
||||
|
||||
- [ ] **Step 4: Run focused tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/resilience/retry-budget.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Implement cancellable concurrency leases with bounded waiting
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/traffic/concurrency-budget.ts`
|
||||
- Test: `tests/platform/traffic/concurrency-budget.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `ConcurrencyLease`
|
||||
- `ConcurrencyBudget`
|
||||
- `createConcurrencyBudget({ maximum, maxQueued })`
|
||||
|
||||
- [ ] **Step 1: Write the concurrency and abort tests**
|
||||
|
||||
```ts
|
||||
it("never grants more than maximum simultaneous leases", async () => {
|
||||
const budget = createConcurrencyBudget({ maximum: 2, maxQueued: 1 });
|
||||
const first = await budget.acquire(new AbortController().signal);
|
||||
const second = await budget.acquire(new AbortController().signal);
|
||||
|
||||
expect(budget.active).toBe(2);
|
||||
await expect(budget.acquire(new AbortController().signal)).rejects.toThrow(/queue/i);
|
||||
|
||||
first.release();
|
||||
second.release();
|
||||
});
|
||||
|
||||
it("removes an aborted waiter", async () => {
|
||||
const budget = createConcurrencyBudget({ maximum: 1, maxQueued: 1 });
|
||||
const lease = await budget.acquire(new AbortController().signal);
|
||||
const controller = new AbortController();
|
||||
const waiting = budget.acquire(controller.signal);
|
||||
controller.abort();
|
||||
|
||||
await expect(waiting).rejects.toMatchObject({ name: "AbortError" });
|
||||
lease.release();
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/traffic/concurrency-budget.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement FIFO bounded waiters**
|
||||
|
||||
Each lease is idempotently releasable. An abort listener removes its waiter immediately. `maxQueued` is mandatory and finite.
|
||||
|
||||
- [ ] **Step 4: Run focused tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/traffic/concurrency-budget.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Implement absolute deadline propagation
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/resilience/deadline.ts`
|
||||
- Test: `tests/platform/resilience/deadline.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `remainingDeadlineMs(deadlineAt, now)`
|
||||
- `DeadlineExceededError`
|
||||
|
||||
- [ ] **Step 1: Write the no-timeout-reset test**
|
||||
|
||||
```ts
|
||||
it("returns only time remaining from the original absolute deadline", () => {
|
||||
expect(remainingDeadlineMs(6_000, 1_000)).toBe(5_000);
|
||||
expect(remainingDeadlineMs(6_000, 5_500)).toBe(500);
|
||||
expect(() => remainingDeadlineMs(6_000, 6_001)).toThrow(DeadlineExceededError);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/resilience/deadline.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement with monotonic caller-provided time**
|
||||
|
||||
The helper does not call `Date.now()` internally; callers provide `now` so fake clocks and monotonic clocks can be used.
|
||||
|
||||
- [ ] **Step 4: Run test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/resilience/deadline.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Create one traffic runtime from immutable policy
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/traffic/traffic-budget.ts`
|
||||
- Modify: `src/platform/execution/execution-context.ts`
|
||||
- Test: `tests/platform/traffic/traffic-budget.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `TrafficBudget`
|
||||
- `TrafficRuntime`
|
||||
- `createTrafficRuntime(policy)`
|
||||
|
||||
- [ ] **Step 1: Write composition test**
|
||||
|
||||
```ts
|
||||
it("creates one request, retry, and concurrency budget per interaction", () => {
|
||||
const runtime = createTrafficRuntime({
|
||||
maxPhysicalRequests: 4,
|
||||
maxRetries: 1,
|
||||
maxConcurrentRequests: 2,
|
||||
maxQueuedRequests: 2,
|
||||
});
|
||||
|
||||
expect(runtime.requests.maximum).toBe(4);
|
||||
expect(runtime.retries.maximum).toBe(1);
|
||||
expect(runtime.concurrency.maximum).toBe(2);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/traffic/traffic-budget.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement immutable policy + mutable runtime separation**
|
||||
|
||||
```ts
|
||||
export interface TrafficBudget {
|
||||
readonly maxPhysicalRequests: number;
|
||||
readonly maxRetries: number;
|
||||
readonly maxConcurrentRequests: number;
|
||||
readonly maxQueuedRequests: number;
|
||||
}
|
||||
```
|
||||
|
||||
`ExecutionContext` creates the runtime once and shares it with all child operations.
|
||||
|
||||
- [ ] **Step 4: Run execution/traffic tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/execution tests/platform/traffic tests/platform/resilience
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Attach traffic policy to operation contracts
|
||||
|
||||
**Files:**
|
||||
- Modify: current HTTP operation-contract type file identified by the Phase 1 baseline map
|
||||
- Modify: representative reference-feature operation contract
|
||||
- Test: existing operation-contract tests plus `tests/platform/traffic/operation-traffic-policy.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `TrafficBudget`.
|
||||
- Produces operation metadata with explicit bounded request policy.
|
||||
|
||||
- [ ] **Step 1: Write a failing operation policy test**
|
||||
|
||||
```ts
|
||||
it("requires finite positive traffic limits for an operation", () => {
|
||||
expect(() =>
|
||||
defineQueryOperation({
|
||||
id: "reference.list",
|
||||
traffic: {
|
||||
maxPhysicalRequests: Number.POSITIVE_INFINITY,
|
||||
maxRetries: 1,
|
||||
maxConcurrentRequests: 2,
|
||||
maxQueuedRequests: 2,
|
||||
},
|
||||
}),
|
||||
).toThrow(/traffic/i);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/traffic/operation-traffic-policy.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Extend operation contracts**
|
||||
|
||||
Query/command operation definitions carry immutable traffic policy. Preserve current semantics/idempotency/replay metadata.
|
||||
|
||||
- [ ] **Step 4: Run operation contract tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests --testNamePattern="operation"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Integrate budgets into the physical HTTP dispatch path
|
||||
|
||||
**Files:**
|
||||
- Modify: the current HTTP executor file identified in the Phase 1 baseline map by searching `maxResponseBytes`, retry lifecycle, and `Retry-After`
|
||||
- Test: current HTTP executor tests plus `tests/platform/traffic/http-budget-integration.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `ExecutionContext`, operation traffic policy, current safe-retry logic.
|
||||
- Produces: one bounded physical-dispatch path.
|
||||
|
||||
- [ ] **Step 1: Add a failing request-budget integration test**
|
||||
|
||||
```ts
|
||||
it("does not dispatch after the interaction physical-request budget is exhausted", async () => {
|
||||
const transport = vi.fn().mockRejectedValue(new TypeError("network"));
|
||||
const context = testExecutionContext({
|
||||
maxPhysicalRequests: 1,
|
||||
maxRetries: 3,
|
||||
});
|
||||
|
||||
await expect(executeHttpOperation(TEST_QUERY, context, transport)).rejects.toBeDefined();
|
||||
expect(transport).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add a failing deadline integration test**
|
||||
|
||||
```ts
|
||||
it("does not reset the interaction deadline before retry", async () => {
|
||||
const clock = fakeClock([0, 4_900, 5_001]);
|
||||
const transport = vi.fn().mockRejectedValue(new TypeError("network"));
|
||||
|
||||
await expect(
|
||||
executeHttpOperation(TEST_QUERY, testExecutionContext({ deadlineMs: 5_000, clock }), transport),
|
||||
).rejects.toThrow(/deadline/i);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run focused test and verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/traffic/http-budget-integration.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Integrate enforcement in this order**
|
||||
|
||||
```text
|
||||
check cancellation
|
||||
check remaining deadline
|
||||
consume physical request budget
|
||||
acquire concurrency lease
|
||||
dispatch
|
||||
release lease
|
||||
classify failure
|
||||
verify existing retry safety/idempotency
|
||||
consume shared retry budget
|
||||
wait jittered backoff bounded by remaining deadline
|
||||
repeat
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Run complete HTTP tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests --testNamePattern="http|retry|idempot"
|
||||
```
|
||||
|
||||
Expected: current retry/idempotency behavior remains green, new budgets pass.
|
||||
|
||||
---
|
||||
|
||||
### Task 9: Add request fan-out budget to representative collection flows
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/traffic/request-fanout.ts`
|
||||
- Test: `tests/platform/traffic/request-fanout.test.ts`
|
||||
- Modify: representative reference-feature collection use case/test fixture
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `assertRequestFanoutWithinBudget()` for integration tests/diagnostics.
|
||||
|
||||
- [ ] **Step 1: Write cardinality-independent request-count test**
|
||||
|
||||
```ts
|
||||
it.each([10, 100, 1_000])(
|
||||
"does not create one physical request per row for %i rows",
|
||||
async (rows) => {
|
||||
const transport = vi.fn().mockResolvedValue(fakeCollectionResponse(rows));
|
||||
|
||||
await loadReferenceCollection({ rows, transport });
|
||||
|
||||
expect(transport.mock.calls.length).toBeLessThanOrEqual(3);
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify current behavior**
|
||||
|
||||
Run the test. If it already passes, preserve it as a regression gate. If it fails, replace per-row transport with a bounded bulk/read-model operation before continuing.
|
||||
|
||||
- [ ] **Step 3: Implement the assertion utility**
|
||||
|
||||
```ts
|
||||
export function assertRequestFanoutWithinBudget(
|
||||
physicalRequests: number,
|
||||
maximum: number,
|
||||
): void {
|
||||
if (physicalRequests > maximum) {
|
||||
throw new Error(`Request fan-out ${physicalRequests} exceeds ${maximum}`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run focused tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/traffic/request-fanout.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 10: Add dedup/coalescing regression coverage
|
||||
|
||||
**Files:**
|
||||
- Test: `tests/platform/traffic/request-deduplication.test.ts`
|
||||
- Modify: current TanStack Query/client request integration only if the test exposes a duplicate-dispatch gap
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: current query cache/in-flight behavior.
|
||||
- Produces proof that multiple consumers do not imply multiple physical requests for one query identity.
|
||||
|
||||
- [ ] **Step 1: Write the concurrent-consumer test**
|
||||
|
||||
```ts
|
||||
it("coalesces concurrent consumers of the same query identity", async () => {
|
||||
const transport = vi.fn().mockResolvedValue({ items: [] });
|
||||
|
||||
await Promise.all([
|
||||
loadSameQuery(transport),
|
||||
loadSameQuery(transport),
|
||||
loadSameQuery(transport),
|
||||
]);
|
||||
|
||||
expect(transport).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run and verify**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/traffic/request-deduplication.test.ts
|
||||
```
|
||||
|
||||
If current TanStack Query integration already satisfies it, no production modification is made.
|
||||
|
||||
---
|
||||
|
||||
### Task 11: Close Phase 2 with amplification invariants
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/platform/traffic/traffic-amplification.test.ts`
|
||||
- Modify: `package.json`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces `check:traffic`.
|
||||
|
||||
- [ ] **Step 1: Write an outage amplification bound**
|
||||
|
||||
```ts
|
||||
it("keeps physical requests bounded when every dispatch fails", async () => {
|
||||
const transport = vi.fn().mockRejectedValue(new TypeError("network"));
|
||||
const interactions = Array.from({ length: 1_000 }, () =>
|
||||
runInteraction({ transport, maxPhysicalRequests: 2, maxRetries: 1 }),
|
||||
);
|
||||
|
||||
await Promise.allSettled(interactions);
|
||||
|
||||
expect(transport.mock.calls.length).toBeLessThanOrEqual(2_000);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add the check script**
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"check:traffic": "vitest run tests/platform/execution tests/platform/traffic tests/platform/resilience"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run Phase 2 verification**
|
||||
|
||||
```bash
|
||||
pnpm run check:traffic
|
||||
pnpm exec tsc --project tsconfig.app.json --noEmit
|
||||
pnpm exec tsc --project tsconfig.test.json --noEmit
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Phase decision**
|
||||
|
||||
**완료** only if physical requests, retries, concurrency queues, and deadlines are all explicitly bounded and existing retry/idempotency semantics remain green. Otherwise **아직 더 봐야댐**.
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
# Extreme-Scale Frontend Architecture Implementation Master Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` (recommended where a subagent runner exists) or `superpowers:executing-plans` to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Evolve `clean-architecture-frontend-template` so global product growth toward 1,000,000 logical features is partitioned into bounded local build/runtime graphs, while spike traffic, sustained traffic, failures, validation, telemetry, and multi-replica releases remain explicitly bounded and testable.
|
||||
|
||||
**Architecture:** The implementation is deliberately split into five independently reviewable plans. Product growth is modeled as `Product -> Deployable App -> Bounded Context -> Feature -> Operation`, and no parent flattens all descendants into a global registry. Runtime work is rooted in an interaction-scoped execution context that carries request, retry, concurrency, cancellation, and deadline budgets. Error, validation, telemetry, scale testing, and release coherence all use the same bounded-cardinality principle.
|
||||
|
||||
**Tech Stack:** TypeScript, React, Vite, TanStack Query, existing HTTP operation-contract layer, Vitest/current unit-test runner, dependency-cruiser/current architecture checks, Node-based scale harnesses, current release-manifest/runtime-config implementation.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-09-23-extreme-scale-frontend-architecture-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Global logical feature count may reach 100, 1,000, 10,000, 100,000, or 1,000,000; one SPA must never compile or boot that entire global graph.
|
||||
- No cardinality may become implicitly unbounded.
|
||||
- Normal feature addition should change only the feature-owned directory plus generated indexes; central handwritten installation registries are not the extension mechanism.
|
||||
- No runtime discovery of arbitrary remote code or untrusted dynamic import paths.
|
||||
- Preserve existing Clean Architecture layer rules, capability-driven adapter composition, HTTP operation contracts, response-size bounds, retry/idempotency semantics, TanStack Query ownership, scope fencing, and release/build/config coherence.
|
||||
- Frontend validation improves UX and protects local runtime cost; backend validation remains authoritative.
|
||||
- Telemetry must be best-effort and must not fail business behavior.
|
||||
- No global mega-error union, telemetry union, route registry, feature registry, or compile graph.
|
||||
- No source UI/design changes are required for this architecture work.
|
||||
- Project repository instruction overrides generic workflow defaults: do not run destructive git commands, commit, merge, or discard existing changes.
|
||||
- Existing-file paths in the phase plans are based on the last verified `origin/main` snapshot from 2026-09-23. At execution start, verify those paths against the live worktree; if a listed existing path moved, update the plan mapping before code edits instead of guessing.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. **Global topology grows while one app is unchanged** — the unchanged app's generated index, initial route graph, bundle inputs, and compile graph must not grow materially.
|
||||
2. **Backend failure coincides with user spike** — retry, concurrency, and telemetry must remain bounded instead of multiplying the incident.
|
||||
3. **Malformed or oversized external payload** — size/structure limits must stop expensive parsing or mapping before unbounded CPU/memory work.
|
||||
4. **One feature/context fails** — unrelated contexts/features must continue to render and execute.
|
||||
5. **Rolling release mixes replicas** — coherent release tuples boot; mismatched HTML/config/manifest/assets fail closed without reload loops.
|
||||
|
||||
---
|
||||
|
||||
## Phase Order
|
||||
|
||||
1. `2026-09-23-topology-composition-plan.md`
|
||||
2. `2026-09-23-execution-traffic-plan.md`
|
||||
3. `2026-09-23-error-validation-telemetry-plan.md`
|
||||
4. `2026-09-23-scale-chaos-soak-plan.md`
|
||||
5. `2026-09-23-release-coherence-plan.md`
|
||||
|
||||
Each phase must be **완료** before moving to the next. If any acceptance condition is not met, its status is **아직 더 봐야댐**.
|
||||
|
||||
### Phase 1 exit contract
|
||||
|
||||
Produces:
|
||||
- `FeatureModule`
|
||||
- `BoundedContextModule`
|
||||
- `DeployableAppModule`
|
||||
- deterministic generated static indexes
|
||||
- O(N) duplicate-safe composition
|
||||
- indexed membership
|
||||
- cross-feature/context import gates
|
||||
- hierarchical route ownership
|
||||
- explicit cardinality budgets
|
||||
|
||||
### Phase 2 exit contract
|
||||
|
||||
Produces:
|
||||
- `ExecutionContext`
|
||||
- interaction-scoped `TrafficBudget`
|
||||
- request/retry/concurrency/deadline/cancellation enforcement
|
||||
- request fan-out budget
|
||||
- request dedup/coalescing integration points
|
||||
|
||||
### Phase 3 exit contract
|
||||
|
||||
Produces:
|
||||
- typed local error model without global union
|
||||
- bounded trust-boundary validation
|
||||
- provider-neutral `TelemetryPort`
|
||||
- redaction, fingerprinting, deduplication, deterministic sampling, bounded buffering, rate limiting
|
||||
- failure boundaries aligned to app/context/feature ownership
|
||||
|
||||
### Phase 4 exit contract
|
||||
|
||||
Produces:
|
||||
- S0/S1/S2 runtime/compiler fixtures
|
||||
- S3/S4 topology simulation up to 1,000,000 logical features
|
||||
- complexity-growth regression gates
|
||||
- request/retry/telemetry amplification tests
|
||||
- slow API, partial/total failure, network flap, telemetry-outage scenarios
|
||||
- soak/long-session memory-slope checks
|
||||
- PR/main/nightly/release test-tier commands
|
||||
|
||||
### Phase 5 exit contract
|
||||
|
||||
Produces:
|
||||
- multi-replica release-coherence matrix
|
||||
- old hashed-asset reachability checks
|
||||
- mixed release fail-closed tests
|
||||
- no reload-loop proof
|
||||
- deployment contract documentation/gates
|
||||
|
||||
## Final Verification
|
||||
|
||||
- [x] Run app TypeScript check.
|
||||
- [x] Run test TypeScript check.
|
||||
- [x] Run architecture check.
|
||||
- [x] Run complete unit/integration test suite.
|
||||
- [x] Run S0/S1 PR scale profile.
|
||||
- [x] Run S2 main scale profile.
|
||||
- [x] Run S3/S4 topology simulation.
|
||||
- [x] Run traffic amplification suite.
|
||||
- [x] Run telemetry-storm suite.
|
||||
- [x] Run release-coherence matrix.
|
||||
- [x] Compare current architecture budgets and benchmark artifacts against baselines. (`pnpm check:scale:baseline` against the approved `config/scale/benchmark-baseline.json`; also the `baseline-regression` step of `check:scale:{main,nightly,release}`.)
|
||||
- [x] Confirm no normal feature addition requires multiple central handwritten registry edits.
|
||||
- [x] Confirm no unrelated feature-to-feature concrete import can pass architecture checks.
|
||||
- [x] Confirm the final implementation meets every acceptance criterion in spec section 54.
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
# Multi-Replica Release Coherence Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` or `superpowers:executing-plans` to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Prove frontend horizontal scaling remains safe during rolling releases by enforcing coherent HTML/runtime-config/manifest/assets, immutable old assets, fail-closed mismatch behavior, and no reload loops.
|
||||
|
||||
**Architecture:** Stateless frontend replicas may scale horizontally without sticky sessions only when every boot observes a coherent release tuple. HTML is revalidated/no-cache, runtime config and release manifest are no-store, hashed assets are immutable and never overwritten, and old hashed assets remain reachable for clients that loaded an older HTML document.
|
||||
|
||||
**Tech Stack:** Current release manifest/runtime config validation, static asset deployment model, current HTTP/static test harness, Node/browser integration tests.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-09-23-extreme-scale-frontend-architecture-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- No hosting-instance user session is introduced.
|
||||
- Hashed assets are immutable and release-addressable.
|
||||
- Runtime config and release manifest are never cached as immutable assets.
|
||||
- Release mismatch fails closed; it must not limp forward with mixed contract/build identity.
|
||||
- Fail-closed handling must not create infinite reload loops.
|
||||
- Old release assets stay reachable through the rolling window.
|
||||
- Do not commit/merge/reset/discard repository changes.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. R10 HTML + R11 config must fail before application bootstrap.
|
||||
2. A browser holding R10 HTML during R11 rollout must still fetch R10 hashed assets successfully.
|
||||
3. Two replicas serving R10/R11 during rollout must not produce a silently mixed boot.
|
||||
4. A mismatch must not cause an automatic reload loop.
|
||||
5. CDN/LB caching headers must preserve HTML/config/manifest coherence assumptions.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Capture the existing release identity contract
|
||||
|
||||
**Files:**
|
||||
- Read: current runtime-config loader
|
||||
- Read: current release-manifest validator
|
||||
- Read: current static-delivery/cache policy docs/config
|
||||
- Create: `docs/reviews/2026-09-23-release-coherence-baseline.md`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces exact current fields for build id, release id, config identity, asset identity, and contract identity.
|
||||
|
||||
- [ ] **Step 1: Locate existing release identity code**
|
||||
|
||||
```bash
|
||||
rg -n 'releaseId|buildId|manifest|runtime.?config|no-store|immutable|max-age=31536000' src public docs nginx* . 2>/dev/null
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Record only verified fields/paths**
|
||||
|
||||
Baseline document lists the exact current identity tuple and cache directives. No new format is invented if current code already covers it.
|
||||
|
||||
- [ ] **Step 3: Run existing release/config tests**
|
||||
|
||||
Use the test files named by the search results. They must be green before changes.
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Extract one pure release-coherence validator
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/release/release-coherence.ts`
|
||||
- Modify: current boot/release validation path to delegate to it
|
||||
- Test: `tests/platform/release/release-coherence.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `ReleaseIdentity`
|
||||
- `assertReleaseCoherent(htmlIdentity, configIdentity, manifestIdentity)`
|
||||
|
||||
- [ ] **Step 1: Write the coherence matrix**
|
||||
|
||||
```ts
|
||||
it.each([
|
||||
["R10", "R10", "R10", true],
|
||||
["R10", "R11", "R10", false],
|
||||
["R10", "R10", "R11", false],
|
||||
["R11", "R11", "R11", true],
|
||||
])(
|
||||
"HTML %s config %s manifest %s => coherent=%s",
|
||||
(html, config, manifest, coherent) => {
|
||||
const run = () =>
|
||||
assertReleaseCoherent(
|
||||
identity(html),
|
||||
identity(config),
|
||||
identity(manifest),
|
||||
);
|
||||
|
||||
if (coherent) expect(run).not.toThrow();
|
||||
else expect(run).toThrow(/release.*mismatch/i);
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED/coverage against current code**
|
||||
|
||||
- [ ] **Step 3: Implement one pure fail-closed validator**
|
||||
|
||||
Compare every identity field that the current release contract treats as boot-critical. Return no partial-success state.
|
||||
|
||||
- [ ] **Step 4: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/release/release-coherence.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Add cache-policy contract tests
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/platform/release/cache-policy.test.ts`
|
||||
- Modify: current static-server/deployment config only if tests reveal a mismatch
|
||||
|
||||
**Interfaces:**
|
||||
- Produces cache policy assertions.
|
||||
|
||||
- [ ] **Step 1: Assert immutable hashed assets**
|
||||
|
||||
Expected directive includes:
|
||||
|
||||
```text
|
||||
public, max-age=31536000, immutable
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Assert HTML is revalidated/not immutable**
|
||||
|
||||
Expected: HTML does not carry immutable long-lived caching.
|
||||
|
||||
- [ ] **Step 3: Assert runtime config and release manifest are `no-store`**
|
||||
|
||||
Both resources must not be reused across release identity changes.
|
||||
|
||||
- [ ] **Step 4: Run test**
|
||||
|
||||
Use the repository's static-config test mechanism. If cache headers are generated outside TypeScript, parse that configuration as text in the test rather than duplicating values in production code.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Model two releases and old-asset reachability
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/release/fixtures/R10/`
|
||||
- Create: `tests/release/fixtures/R11/`
|
||||
- Create: `tests/release/old-asset-reachability.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces immutable fixture artifacts for two release tuples.
|
||||
|
||||
- [ ] **Step 1: Create distinct hashed assets**
|
||||
|
||||
Fixture example:
|
||||
|
||||
```text
|
||||
R10/assets/app.aaaa.js
|
||||
R11/assets/app.bbbb.js
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Write reachability test**
|
||||
|
||||
```ts
|
||||
it("keeps R10 hashed assets reachable after R11 becomes active", async () => {
|
||||
const deployment = createReleaseFixture(["R10", "R11"]);
|
||||
deployment.activate("R11");
|
||||
|
||||
expect(await deployment.fetch("/releases/R10/assets/app.aaaa.js"))
|
||||
.toMatchObject({ status: 200 });
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/release/old-asset-reachability.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Add mixed-replica routing simulation
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/release/mixed-replica.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces deterministic LB simulation alternating R10/R11 replica responses.
|
||||
|
||||
- [ ] **Step 1: Write coherent-old and coherent-new tests**
|
||||
|
||||
A request sequence that remains entirely R10 boots; entirely R11 boots.
|
||||
|
||||
- [ ] **Step 2: Write mixed tuple tests**
|
||||
|
||||
```ts
|
||||
it("fails closed when HTML and runtime config come from different releases", async () => {
|
||||
const result = await bootAgainstReplicaSequence([
|
||||
response("html", "R10"),
|
||||
response("config", "R11"),
|
||||
response("manifest", "R10"),
|
||||
]);
|
||||
|
||||
expect(result.state).toBe("release-mismatch");
|
||||
expect(result.applicationMounted).toBe(false);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/release/mixed-replica.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Prove mismatch handling cannot reload-loop
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/release/release-mismatch-recovery.ts`
|
||||
- Test: `tests/platform/release/release-mismatch-recovery.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces bounded mismatch recovery decision.
|
||||
|
||||
- [ ] **Step 1: Write one-recovery-attempt test**
|
||||
|
||||
```ts
|
||||
it("allows at most one automatic recovery attempt per release mismatch key", () => {
|
||||
const recovery = createReleaseMismatchRecovery(sessionStorageLike());
|
||||
|
||||
expect(recovery.decide("R10->R11")).toBe("reload-once");
|
||||
expect(recovery.decide("R10->R11")).toBe("show-failure");
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/release/release-mismatch-recovery.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement bounded recovery**
|
||||
|
||||
Recovery marker is scoped to a stable mismatch key and expires/clears after a coherent boot. It must not loop on every page load.
|
||||
|
||||
- [ ] **Step 4: Run test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/release/release-mismatch-recovery.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Add release-coherence command and close the architecture program
|
||||
|
||||
**Files:**
|
||||
- Modify: `package.json`
|
||||
- Create: `tests/release/release-matrix.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces `check:release-coherence`.
|
||||
|
||||
- [ ] **Step 1: Encode the complete matrix**
|
||||
|
||||
At minimum:
|
||||
- R10/R10/R10/old R10 asset => PASS
|
||||
- R10/R11/R10 => FAIL CLOSED
|
||||
- R10/R10/R11 => FAIL CLOSED
|
||||
- R10/R10/R10 with only R11 asset path => FAIL
|
||||
- R11/R11/R11/R11 asset => PASS
|
||||
- R10 client after R11 activation with R10 hashed asset retained => PASS
|
||||
|
||||
- [ ] **Step 2: Add script**
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"check:release-coherence": "vitest run tests/platform/release tests/release"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run final deterministic suite**
|
||||
|
||||
```bash
|
||||
pnpm run check:feature-index
|
||||
pnpm run check:architecture
|
||||
pnpm run check:topology
|
||||
pnpm run check:traffic
|
||||
pnpm run check:observability
|
||||
pnpm run check:scale:pr
|
||||
pnpm run check:scale:main
|
||||
pnpm run check:release-coherence
|
||||
pnpm exec tsc --project tsconfig.app.json --noEmit
|
||||
pnpm exec tsc --project tsconfig.test.json --noEmit
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Re-read spec section 54 and create an acceptance matrix**
|
||||
|
||||
Create `docs/reviews/2026-09-23-extreme-scale-acceptance.md` with exactly one row per acceptance criterion and status only:
|
||||
- `완료`
|
||||
- `아직 더 봐야댐`
|
||||
|
||||
Every `완료` row includes the exact test/script evidence path.
|
||||
|
||||
- [ ] **Step 5: Final decision**
|
||||
|
||||
The overall architecture work is **완료** only when every spec section 54 criterion is `완료`. Any remaining row makes the overall result **아직 더 봐야댐**.
|
||||
+550
@@ -0,0 +1,550 @@
|
||||
# Scale, Chaos, Spike, and Soak Verification Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` or `superpowers:executing-plans` to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Convert the extreme-scale architecture into executable evidence at 100 / 1K / 10K / 100K / 1M logical scale and under spike, sustained, partial-failure, total-failure, slow-upstream, telemetry-storm, and long-session conditions.
|
||||
|
||||
**Architecture:** Small/medium profiles instantiate real TypeScript/runtime fixtures; 100K/1M profiles simulate topology rather than compiling one impossible SPA. Gates combine absolute ceilings, relative baseline regression, and growth-shape checks. Traffic tests measure amplification factors rather than only latency.
|
||||
|
||||
**Tech Stack:** Node `perf_hooks`, current test runner, `tsc --extendedDiagnostics`, current browser/e2e runner when available, JSON benchmark artifacts.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-09-23-extreme-scale-frontend-architecture-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- S4 does not create one SPA with 1,000,000 TypeScript feature modules.
|
||||
- Global topology growth must not materially grow an unchanged app's local artifact/route/build inputs.
|
||||
- Structural failures are deterministic and fail immediately.
|
||||
- Performance gates use repeated samples/median where scheduler/environment noise matters.
|
||||
- No new load-test dependency is required for the first implementation; Node/browser fixtures are sufficient to prove client amplification and growth properties.
|
||||
- Do not commit/merge/reset/discard repository changes.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. A linear implementation must not fail because one noisy timing sample is slow.
|
||||
2. A quadratic implementation must fail even when absolute times are still small at S0.
|
||||
3. S3/S4 must test global/local independence rather than attempting a 1M-module compile.
|
||||
4. Total backend failure must keep request/retry/telemetry amplification within explicit ceilings.
|
||||
5. Long-running sessions must stabilize rather than exhibit positive unbounded heap/listener/timer slopes.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Define scale profiles and synthetic topology model
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/scale/scale-profile.ts`
|
||||
- Create: `tests/scale/synthetic-topology.ts`
|
||||
- Test: `tests/scale/synthetic-topology.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces S0-S4 profiles and topology generator.
|
||||
|
||||
- [ ] **Step 1: Write exact profile test**
|
||||
|
||||
```ts
|
||||
expect(SCALE_PROFILES).toEqual({
|
||||
S0: 100,
|
||||
S1: 1_000,
|
||||
S2: 10_000,
|
||||
S3: 100_000,
|
||||
S4: 1_000_000,
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Write local-bound preservation test**
|
||||
|
||||
```ts
|
||||
it("grows global topology without growing a selected local app beyond its budgets", () => {
|
||||
const small = createSyntheticTopology({ globalFeatures: 100 });
|
||||
const huge = createSyntheticTopology({ globalFeatures: 1_000_000 });
|
||||
|
||||
expect(huge.apps[0].contexts.length).toBeLessThanOrEqual(APP_CONTEXT_BUDGET);
|
||||
expect(huge.apps[0].localFeatureCount).toBeLessThanOrEqual(APP_LOCAL_FEATURE_BUDGET);
|
||||
expect(huge.apps[0].localFeatureCount).toBe(small.apps[0].localFeatureCount);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement topology generation with bounded app/context shards**
|
||||
|
||||
S3/S4 models store counts/identifiers compactly; they do not materialize a million source files.
|
||||
|
||||
- [ ] **Step 4: Run test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/scale/synthetic-topology.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Add reusable benchmark runner and JSON artifact schema
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/scale/benchmark.ts`
|
||||
- Create: `scripts/scale/benchmark-result.ts`
|
||||
- Test: `tests/scale/benchmark.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces median samples and machine-readable results.
|
||||
|
||||
- [ ] **Step 1: Write median/result test**
|
||||
|
||||
```ts
|
||||
it("records median rather than a single timing sample", async () => {
|
||||
const result = await benchmark("compose", {
|
||||
samples: 5,
|
||||
run: fakeDurations([10, 11, 100, 12, 9]),
|
||||
});
|
||||
|
||||
expect(result.medianMs).toBe(11);
|
||||
expect(result.samples).toHaveLength(5);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Implement result schema**
|
||||
|
||||
```ts
|
||||
export interface BenchmarkResult {
|
||||
readonly name: string;
|
||||
readonly profile: "S0" | "S1" | "S2" | "S3" | "S4";
|
||||
readonly cardinality: number;
|
||||
readonly samples: readonly number[];
|
||||
readonly medianMs: number;
|
||||
readonly heapBytes?: number;
|
||||
readonly metadata: Readonly<Record<string, string | number | boolean>>;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/scale/benchmark.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Add growth-shape regression detector
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/cardinality/growth-regression.ts`
|
||||
- Test: `tests/scale/growth-regression.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces `assertLinearOrBetter(samples, tolerance)`.
|
||||
|
||||
- [ ] **Step 1: Write linear and quadratic examples**
|
||||
|
||||
```ts
|
||||
it("accepts roughly linear growth", () => {
|
||||
expect(() =>
|
||||
assertLinearOrBetter([
|
||||
{ n: 100, cost: 1 },
|
||||
{ n: 1_000, cost: 10 },
|
||||
{ n: 10_000, cost: 100 },
|
||||
]),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects quadratic-shaped growth", () => {
|
||||
expect(() =>
|
||||
assertLinearOrBetter([
|
||||
{ n: 100, cost: 1 },
|
||||
{ n: 1_000, cost: 100 },
|
||||
{ n: 10_000, cost: 10_000 },
|
||||
]),
|
||||
).toThrow(/growth/i);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Implement ratio/slope based detector with tolerance**
|
||||
|
||||
It is a regression detector, not a mathematical Big-O proof. Document this in code comments.
|
||||
|
||||
- [ ] **Step 3: Run test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/scale/growth-regression.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Benchmark registry/composition S0-S2
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/scale/run-composition-scale.ts`
|
||||
- Test: `tests/scale/composition-scale.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes Phase 1 composition functions.
|
||||
- Produces S0/S1/S2 timing + heap artifact.
|
||||
|
||||
- [ ] **Step 1: Write structural test first**
|
||||
|
||||
```ts
|
||||
it.each([100, 1_000, 10_000])(
|
||||
"composes %i unique entries without duplicates",
|
||||
(count) => {
|
||||
const parts = createUniqueRegistryParts(count);
|
||||
const result = composeUniqueRecord(parts, () => "route");
|
||||
|
||||
expect(Object.keys(result)).toHaveLength(count);
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Implement runner**
|
||||
|
||||
Runner executes multiple samples and writes:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "registry-composition",
|
||||
"profile": "S2",
|
||||
"cardinality": 10000,
|
||||
"medianMs": 0,
|
||||
"heapBytes": 0,
|
||||
"metadata": {
|
||||
"implementation": "composeUniqueRecord"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Runtime values replace zero.
|
||||
|
||||
- [ ] **Step 3: Add growth assertion**
|
||||
|
||||
S0/S1/S2 result series must pass `assertLinearOrBetter()`.
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Capture TypeScript extended diagnostics for bounded local apps
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/scale/collect-tsc-diagnostics.ts`
|
||||
- Create: `tests/scale/fixtures/typescript/`
|
||||
- Test: `tests/scale/tsc-diagnostics-parser.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces parsed `Files`, `Types`, `Symbols`, `Instantiations`, `Memory used`, `Total time`.
|
||||
|
||||
- [ ] **Step 1: Write parser test against fixed diagnostic text**
|
||||
|
||||
```ts
|
||||
const text = `
|
||||
Files: 321
|
||||
Types: 12000
|
||||
Symbols: 18000
|
||||
Instantiations: 5000
|
||||
Memory used: 128000K
|
||||
Total time: 4.20s
|
||||
`;
|
||||
|
||||
expect(parseTscExtendedDiagnostics(text)).toMatchObject({
|
||||
files: 321,
|
||||
types: 12_000,
|
||||
symbols: 18_000,
|
||||
instantiations: 5_000,
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Implement parser and runner**
|
||||
|
||||
Runner invokes repository-supported TypeScript with:
|
||||
|
||||
```bash
|
||||
pnpm exec tsc --project tsconfig.app.json --noEmit --extendedDiagnostics
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Compare bounded local fixtures, not 1M modules**
|
||||
|
||||
S0/S1/S2 can use generated local fixtures up to the measured safe ceiling. S3/S4 only verify topology partitioning.
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Prove global-to-local independence at S3/S4
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/scale/global-local-independence.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes topology generator and generated-index projection logic.
|
||||
- Produces the central 1M architectural proof.
|
||||
|
||||
- [ ] **Step 1: Write the S4 invariance test**
|
||||
|
||||
```ts
|
||||
it("keeps one unchanged app's local inputs constant from S0 to S4", () => {
|
||||
const s0 = selectAppInputs(createSyntheticTopology({ globalFeatures: 100 }), "app-0");
|
||||
const s4 = selectAppInputs(createSyntheticTopology({ globalFeatures: 1_000_000 }), "app-0");
|
||||
|
||||
expect(s4.contextIds).toEqual(s0.contextIds);
|
||||
expect(s4.featureIds).toEqual(s0.featureIds);
|
||||
expect(s4.routeRootIds).toEqual(s0.routeRootIds);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/scale/global-local-independence.test.ts
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Add request/retry amplification metrics
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/scale/traffic/amplification-metrics.ts`
|
||||
- Test: `tests/scale/traffic/amplification-metrics.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces request, retry, telemetry amplification calculations.
|
||||
|
||||
- [ ] **Step 1: Write exact metric tests**
|
||||
|
||||
```ts
|
||||
expect(requestAmplification({
|
||||
interactions: 1_000,
|
||||
physicalRequests: 1_150,
|
||||
})).toBe(1.15);
|
||||
|
||||
expect(retryAmplification({
|
||||
initialRequests: 1_000,
|
||||
totalRequests: 1_200,
|
||||
})).toBe(1.2);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Reject zero/negative denominators**
|
||||
|
||||
Add explicit tests that invalid denominators throw.
|
||||
|
||||
- [ ] **Step 3: Implement and run**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/scale/traffic/amplification-metrics.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Add total/partial/slow failure traffic scenarios
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/scale/traffic/failure-scenarios.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes Phase 2 budgets.
|
||||
- Produces bounded failure-amplification evidence.
|
||||
|
||||
- [ ] **Step 1: Total outage test**
|
||||
|
||||
```ts
|
||||
it("bounds physical requests when all upstream calls fail", async () => {
|
||||
const result = await runSyntheticTraffic({
|
||||
interactions: 10_000,
|
||||
upstream: "always-fail",
|
||||
maxPhysicalRequestsPerInteraction: 2,
|
||||
maxRetriesPerInteraction: 1,
|
||||
});
|
||||
|
||||
expect(result.physicalRequests).toBeLessThanOrEqual(20_000);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Partial outage test**
|
||||
|
||||
Payment failures do not prevent order/catalog synthetic flows from completing; assert success counters by context.
|
||||
|
||||
- [ ] **Step 3: Slow upstream test**
|
||||
|
||||
Use a fake clock/controlled promises to assert:
|
||||
- active requests never exceed concurrency budget,
|
||||
- queued requests never exceed queue budget,
|
||||
- deadline expiration drains waiters,
|
||||
- no retry begins after deadline.
|
||||
|
||||
- [ ] **Step 4: Run**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/scale/traffic/failure-scenarios.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 9: Add Retry-After jitter distribution regression
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/scale/traffic/retry-after-jitter.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes current retry scheduling implementation.
|
||||
- Produces proof that a Retry-After cohort is not synchronized to one exact retry instant.
|
||||
|
||||
- [ ] **Step 1: Write distribution test**
|
||||
|
||||
```ts
|
||||
it("spreads retries around Retry-After instead of synchronizing all clients", () => {
|
||||
const delays = Array.from({ length: 10_000 }, (_, seed) =>
|
||||
calculateRetryDelay({
|
||||
retryAfterMs: 10_000,
|
||||
jitterSeed: seed,
|
||||
attempt: 1,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(new Set(delays).size).toBeGreaterThan(100);
|
||||
expect(Math.max(...delays) - Math.min(...delays)).toBeGreaterThan(500);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/scale/traffic/retry-after-jitter.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 10: Add telemetry-storm and collector-outage scenarios
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/scale/telemetry/telemetry-storm.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes Phase 3 telemetry pipeline.
|
||||
- Produces bounded-memory/network evidence.
|
||||
|
||||
- [ ] **Step 1: Repeated-error storm test**
|
||||
|
||||
```ts
|
||||
it("does not turn 100000 identical failures into 100000 sends", async () => {
|
||||
const result = await runTelemetryStorm({
|
||||
identicalEvents: 100_000,
|
||||
maxSendsPerMinute: 20,
|
||||
maxBufferedEvents: 200,
|
||||
});
|
||||
|
||||
expect(result.networkSends).toBeLessThanOrEqual(20);
|
||||
expect(result.peakBufferedEvents).toBeLessThanOrEqual(200);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Collector outage test**
|
||||
|
||||
The transport rejects every send; assert business promises remain fulfilled and buffer limits remain respected.
|
||||
|
||||
- [ ] **Step 3: Run**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/scale/telemetry/telemetry-storm.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 11: Add network flap and long-session state-cycle tests
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/scale/session/network-flap.test.ts`
|
||||
- Create: `tests/scale/session/long-session.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces regression evidence for offline/online, login/navigation/query/mutation/logout cycles.
|
||||
|
||||
- [ ] **Step 1: Network flap test**
|
||||
|
||||
Repeat online/offline transitions and assert:
|
||||
- no duplicate unsafe mutation replay,
|
||||
- retry queue stays bounded,
|
||||
- stale interaction cancellation completes.
|
||||
|
||||
- [ ] **Step 2: Long-session logical leak test**
|
||||
|
||||
Run thousands of synthetic cycles and record:
|
||||
- active timers,
|
||||
- listeners,
|
||||
- telemetry buffer size,
|
||||
- active AbortControllers,
|
||||
- query scope generations.
|
||||
|
||||
Assert each returns to or stabilizes near its post-warmup bound.
|
||||
|
||||
- [ ] **Step 3: Run**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/scale/session
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 12: Add optional browser heap-slope harness
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/scale/browser-soak.ts`
|
||||
- Create: `tests/scale/browser-soak.contract.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces JSON series `{ elapsedMs, heapBytes, domNodes, activeTimers }` when the repository's browser runner exposes these metrics.
|
||||
|
||||
- [ ] **Step 1: Test the slope classifier independently of browser availability**
|
||||
|
||||
```ts
|
||||
it("flags a persistent positive heap slope after warmup", () => {
|
||||
expect(
|
||||
classifyMemorySlope([
|
||||
{ minute: 10, heapMb: 100 },
|
||||
{ minute: 20, heapMb: 200 },
|
||||
{ minute: 30, heapMb: 300 },
|
||||
]),
|
||||
).toBe("unbounded-growth");
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Implement browser harness using the existing e2e runner**
|
||||
|
||||
Do not add a second browser automation framework. If the repository uses Playwright, use Playwright; if it uses another existing runner, use that runner.
|
||||
|
||||
- [ ] **Step 3: Write artifacts under `artifacts/scale/` and keep generated artifacts out of source imports**
|
||||
|
||||
---
|
||||
|
||||
### Task 13: Define PR/main/nightly/release commands
|
||||
|
||||
**Files:**
|
||||
- Modify: `package.json`
|
||||
- Create: `scripts/scale/run-scale-profile.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `check:scale:pr`
|
||||
- `check:scale:main`
|
||||
- `check:scale:nightly`
|
||||
- `check:scale:release`
|
||||
|
||||
- [ ] **Step 1: Wire PR**
|
||||
|
||||
PR includes S0/S1 architecture/composition/traffic tests.
|
||||
|
||||
- [ ] **Step 2: Wire main**
|
||||
|
||||
Main adds S2 registry/composition/TypeScript diagnostics.
|
||||
|
||||
- [ ] **Step 3: Wire nightly**
|
||||
|
||||
Nightly adds S3/S4 topology, telemetry storm, session cycles, browser soak if available.
|
||||
|
||||
- [ ] **Step 4: Wire release**
|
||||
|
||||
Release invokes release-coherence tests from Phase 5 plus the stable main/nightly subset appropriate to the environment.
|
||||
|
||||
- [ ] **Step 5: Run Phase 4 deterministic subset**
|
||||
|
||||
```bash
|
||||
pnpm run check:scale:pr
|
||||
pnpm run check:scale:main
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 6: Phase decision**
|
||||
|
||||
**완료** only if scale growth, amplification, topology independence, storm boundedness, and session-growth properties are executable and produce machine-readable results. Otherwise **아직 더 봐야댐**.
|
||||
+862
@@ -0,0 +1,862 @@
|
||||
# Topology, Composition, and Cardinality Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` or `superpowers:executing-plans` to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Replace flat central installation and scale-sensitive composition with feature-owned descriptors, bounded-context/app ownership, deterministic generated static indexes, O(N) composition, indexed membership, dependency gates, and hierarchical routing.
|
||||
|
||||
**Architecture:** Every feature owns one descriptor; contexts compose only direct features; deployable apps compose only direct contexts. Static generated indexes replace multi-file handwritten installation lists. Duplicate identifiers and budget violations fail deterministically. Cross-feature/context concrete imports fail architecture checks.
|
||||
|
||||
**Tech Stack:** TypeScript, current test runner, dependency-cruiser, Vite, current routing stack.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-09-23-extreme-scale-frontend-architecture-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- No global registry containing all product descendants.
|
||||
- No repeated object-spread accumulator on scale-sensitive paths.
|
||||
- Membership checks on scale-sensitive paths use `Set`/`Map`.
|
||||
- Generated indexes use static imports only.
|
||||
- Adding a normal feature changes feature-owned files plus generated files; central handwritten production registries are not manually extended.
|
||||
- Cross-feature concrete imports and cross-context concrete imports are forbidden.
|
||||
- Existing UI behavior and route URLs remain unchanged during this phase.
|
||||
- Do not commit/merge/reset/discard existing repository changes.
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. Duplicate feature/route/operation IDs must fail with deterministic diagnostics.
|
||||
2. Generated index order must be deterministic across repeated runs.
|
||||
3. A feature may import its own layers but may not concrete-import another feature.
|
||||
4. A context budget overflow must fail before runtime boot.
|
||||
5. Product selection must remain equivalent after replacing `includes()` scans with indexed membership.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Lock the live baseline before architectural edits
|
||||
|
||||
**Files:**
|
||||
- Read: `src/features/feature-adapter-contribution.ts`
|
||||
- Read: `src/features/installed-product-manifest.ts`
|
||||
- Read: `src/features/installed-feature-contracts.ts`
|
||||
- Read: `src/features/installed-feature-adapters.ts`
|
||||
- Read: `src/features/installed-feature-runtimes.tsx`
|
||||
- Read: `src/features/installed-feature-messages.ts`
|
||||
- Read: `src/features/installed-contract-contributions.ts`
|
||||
- Read: `src/features/product-features.ts`
|
||||
- Read: `.dependency-cruiser.json`
|
||||
- Read: `package.json`
|
||||
- Create: `docs/reviews/2026-09-23-extreme-scale-baseline-map.md`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: current `origin/main` implementation.
|
||||
- Produces: verified path/symbol map used by every later task.
|
||||
|
||||
- [ ] **Step 1: Verify expected files without modifying them**
|
||||
|
||||
```bash
|
||||
for f in \
|
||||
src/features/feature-adapter-contribution.ts \
|
||||
src/features/installed-product-manifest.ts \
|
||||
src/features/installed-feature-contracts.ts \
|
||||
src/features/installed-feature-adapters.ts \
|
||||
src/features/installed-feature-runtimes.tsx \
|
||||
src/features/installed-feature-messages.ts \
|
||||
src/features/installed-contract-contributions.ts \
|
||||
src/features/product-features.ts \
|
||||
.dependency-cruiser.json \
|
||||
package.json
|
||||
do
|
||||
test -f "$f" || { echo "MISSING:$f"; exit 1; }
|
||||
done
|
||||
```
|
||||
|
||||
Expected: exit `0`.
|
||||
|
||||
- [ ] **Step 2: Record the scale-sensitive symbols**
|
||||
|
||||
```bash
|
||||
rg -n \
|
||||
'INSTALLED_PRODUCT_FEATURE_IDS|INSTALLED_FEATURE_CONTRACTS|reduce\(|\.includes\(|ROUTE_REGISTRY|REFERENCE_FEATURE_ADAPTER_CONTRIBUTION|REFERENCE_MESSAGE_CATALOGS' \
|
||||
src .dependency-cruiser.json package.json \
|
||||
> /tmp/extreme-scale-baseline-symbols.txt
|
||||
```
|
||||
|
||||
Expected: matches identify the current composition and membership paths.
|
||||
|
||||
- [ ] **Step 3: Write the baseline map**
|
||||
|
||||
Create `docs/reviews/2026-09-23-extreme-scale-baseline-map.md` with the exact paths and symbol names returned above and the verified `origin/main` SHA. Do not describe unverified paths.
|
||||
|
||||
- [ ] **Step 4: Re-run current non-mutating baseline checks**
|
||||
|
||||
```bash
|
||||
pnpm exec tsc --project tsconfig.app.json --noEmit
|
||||
pnpm exec tsc --project tsconfig.test.json --noEmit
|
||||
```
|
||||
|
||||
Expected: PASS under the repository-supported Node version.
|
||||
|
||||
- [ ] **Step 5: Checkpoint**
|
||||
|
||||
Status is **완료** only when all expected files and baseline checks are verified. Otherwise status is **아직 더 봐야댐** and later tasks do not start.
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Introduce the feature-owned descriptor contract
|
||||
|
||||
**Files:**
|
||||
- Create: `src/features/feature-module.ts`
|
||||
- Test: `tests/features/feature-module.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: existing route/contracts/adapter/runtime/message contribution types.
|
||||
- Produces:
|
||||
- `FeatureModuleId`
|
||||
- `FeatureModule`
|
||||
- `defineFeatureModule()`
|
||||
|
||||
- [ ] **Step 1: Write the failing descriptor identity/immutability test**
|
||||
|
||||
```ts
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { defineFeatureModule } from "../../src/features/feature-module";
|
||||
|
||||
describe("defineFeatureModule", () => {
|
||||
it("keeps one stable feature id and freezes the descriptor", () => {
|
||||
const module = defineFeatureModule({
|
||||
id: "reference",
|
||||
routes: {},
|
||||
contracts: {},
|
||||
adapters: [],
|
||||
runtimes: [],
|
||||
messages: {},
|
||||
contractContributions: [],
|
||||
});
|
||||
|
||||
expect(module.id).toBe("reference");
|
||||
expect(Object.isFrozen(module)).toBe(true);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test and verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/features/feature-module.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL because `feature-module` does not exist.
|
||||
|
||||
- [ ] **Step 3: Implement the minimal descriptor**
|
||||
|
||||
```ts
|
||||
export type FeatureModuleId = string & { readonly __brand: "FeatureModuleId" };
|
||||
|
||||
export interface FeatureModule {
|
||||
readonly id: string;
|
||||
readonly routes: Readonly<Record<string, unknown>>;
|
||||
readonly contracts: Readonly<Record<string, unknown>>;
|
||||
readonly adapters: readonly unknown[];
|
||||
readonly runtimes: readonly unknown[];
|
||||
readonly messages: Readonly<Record<string, unknown>>;
|
||||
readonly contractContributions: readonly unknown[];
|
||||
}
|
||||
|
||||
export function defineFeatureModule<T extends FeatureModule>(module: T): Readonly<T> {
|
||||
return Object.freeze(module);
|
||||
}
|
||||
```
|
||||
|
||||
During implementation, replace `unknown` with the exact existing contribution types identified in Task 1; preserve the function and property names above.
|
||||
|
||||
- [ ] **Step 4: Run the focused test**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/features/feature-module.test.ts
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Run both TypeScript checks**
|
||||
|
||||
```bash
|
||||
pnpm exec tsc --project tsconfig.app.json --noEmit
|
||||
pnpm exec tsc --project tsconfig.test.json --noEmit
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Migrate the reference feature to one owned descriptor
|
||||
|
||||
**Files:**
|
||||
- Create: `src/features/reference-feature/feature-module.ts`
|
||||
- Modify: existing reference feature export barrel if one exists in the baseline map
|
||||
- Test: `tests/features/reference-feature/feature-module.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `defineFeatureModule()`.
|
||||
- Produces: `REFERENCE_FEATURE_MODULE`.
|
||||
|
||||
- [ ] **Step 1: Write the failing ownership test**
|
||||
|
||||
```ts
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { REFERENCE_FEATURE_MODULE } from "../../../src/features/reference-feature/feature-module";
|
||||
|
||||
describe("REFERENCE_FEATURE_MODULE", () => {
|
||||
it("owns every install-time contribution under one feature id", () => {
|
||||
expect(REFERENCE_FEATURE_MODULE.id).toBe("reference");
|
||||
expect(REFERENCE_FEATURE_MODULE.routes).toBeDefined();
|
||||
expect(REFERENCE_FEATURE_MODULE.adapters).toBeDefined();
|
||||
expect(REFERENCE_FEATURE_MODULE.runtimes).toBeDefined();
|
||||
expect(REFERENCE_FEATURE_MODULE.messages).toBeDefined();
|
||||
expect(REFERENCE_FEATURE_MODULE.contractContributions).toBeDefined();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/features/reference-feature/feature-module.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Create `REFERENCE_FEATURE_MODULE`**
|
||||
|
||||
```ts
|
||||
export const REFERENCE_FEATURE_MODULE = defineFeatureModule({
|
||||
id: "reference",
|
||||
routes: REFERENCE_ROUTES,
|
||||
contracts: REFERENCE_CONTRACTS,
|
||||
adapters: [REFERENCE_FEATURE_ADAPTER_CONTRIBUTION],
|
||||
runtimes: [REFERENCE_FEATURE_RUNTIME_CONTRIBUTION],
|
||||
messages: REFERENCE_MESSAGE_CATALOGS,
|
||||
contractContributions: [REFERENCE_CONTRACT_CONTRIBUTION],
|
||||
});
|
||||
```
|
||||
|
||||
Use the exact existing reference-feature symbols from Task 1.
|
||||
|
||||
- [ ] **Step 4: Run focused and reference-feature tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/features/reference-feature
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Add bounded-context and deployable-app descriptors
|
||||
|
||||
**Files:**
|
||||
- Create: `src/contexts/bounded-context-module.ts`
|
||||
- Create: `src/apps/deployable-app-module.ts`
|
||||
- Test: `tests/architecture/module-hierarchy.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `FeatureModule`.
|
||||
- Produces:
|
||||
- `BoundedContextModule`
|
||||
- `defineBoundedContextModule()`
|
||||
- `DeployableAppModule`
|
||||
- `defineDeployableAppModule()`
|
||||
|
||||
- [ ] **Step 1: Write the failing hierarchy test**
|
||||
|
||||
```ts
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module";
|
||||
import { defineDeployableAppModule } from "../../src/apps/deployable-app-module";
|
||||
|
||||
describe("module hierarchy", () => {
|
||||
it("exposes only direct children at each boundary", () => {
|
||||
const context = defineBoundedContextModule({
|
||||
id: "commerce",
|
||||
features: [],
|
||||
budget: { maxFeatures: 200 },
|
||||
});
|
||||
|
||||
const app = defineDeployableAppModule({
|
||||
id: "customer",
|
||||
contexts: [context],
|
||||
budget: { maxContexts: 20 },
|
||||
});
|
||||
|
||||
expect(app.contexts).toEqual([context]);
|
||||
expect("features" in app).toBe(false);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/architecture/module-hierarchy.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement direct-child descriptors**
|
||||
|
||||
```ts
|
||||
export interface BoundedContextModule {
|
||||
readonly id: string;
|
||||
readonly features: readonly FeatureModule[];
|
||||
readonly budget: Readonly<{ maxFeatures: number }>;
|
||||
}
|
||||
|
||||
export interface DeployableAppModule {
|
||||
readonly id: string;
|
||||
readonly contexts: readonly BoundedContextModule[];
|
||||
readonly budget: Readonly<{ maxContexts: number }>;
|
||||
}
|
||||
```
|
||||
|
||||
Both factory functions freeze descriptors and copy child arrays before freezing them.
|
||||
|
||||
- [ ] **Step 4: Run focused tests and TypeScript checks**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/architecture/module-hierarchy.test.ts
|
||||
pnpm exec tsc --project tsconfig.app.json --noEmit
|
||||
pnpm exec tsc --project tsconfig.test.json --noEmit
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Add explicit cardinality budgets and fail-fast validation
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/cardinality/cardinality-budget.ts`
|
||||
- Test: `tests/platform/cardinality/cardinality-budget.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `CardinalityBudgetExceededError`
|
||||
- `assertWithinCardinalityBudget(name, current, maximum)`
|
||||
|
||||
- [ ] **Step 1: Write failing tests**
|
||||
|
||||
```ts
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
CardinalityBudgetExceededError,
|
||||
assertWithinCardinalityBudget,
|
||||
} from "../../../src/platform/cardinality/cardinality-budget";
|
||||
|
||||
describe("assertWithinCardinalityBudget", () => {
|
||||
it("accepts the exact ceiling", () => {
|
||||
expect(() => assertWithinCardinalityBudget("commerce.features", 200, 200)).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects values above the ceiling with the boundary name", () => {
|
||||
expect(() => assertWithinCardinalityBudget("commerce.features", 201, 200))
|
||||
.toThrow(CardinalityBudgetExceededError);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/cardinality/cardinality-budget.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement fail-fast budget validation**
|
||||
|
||||
```ts
|
||||
export class CardinalityBudgetExceededError extends Error {
|
||||
constructor(
|
||||
readonly boundary: string,
|
||||
readonly current: number,
|
||||
readonly maximum: number,
|
||||
) {
|
||||
super(`${boundary} cardinality ${current} exceeds ${maximum}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertWithinCardinalityBudget(
|
||||
boundary: string,
|
||||
current: number,
|
||||
maximum: number,
|
||||
): void {
|
||||
if (!Number.isSafeInteger(maximum) || maximum < 1) {
|
||||
throw new TypeError(`Invalid cardinality ceiling for ${boundary}: ${maximum}`);
|
||||
}
|
||||
if (current > maximum) {
|
||||
throw new CardinalityBudgetExceededError(boundary, current, maximum);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/cardinality/cardinality-budget.test.ts
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Replace quadratic registry accumulation with duplicate-safe O(N) composition
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/cardinality/compose-unique-record.ts`
|
||||
- Modify: `src/features/installed-feature-contracts.ts`
|
||||
- Test: `tests/platform/cardinality/compose-unique-record.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `composeUniqueRecord(parts, describePart)`.
|
||||
|
||||
- [ ] **Step 1: Write failing duplicate and merge tests**
|
||||
|
||||
```ts
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { composeUniqueRecord } from "../../../src/platform/cardinality/compose-unique-record";
|
||||
|
||||
describe("composeUniqueRecord", () => {
|
||||
it("composes entries without repeated accumulator copies", () => {
|
||||
expect(composeUniqueRecord([{ a: 1 }, { b: 2 }], () => "test"))
|
||||
.toEqual({ a: 1, b: 2 });
|
||||
});
|
||||
|
||||
it("rejects duplicate keys", () => {
|
||||
expect(() => composeUniqueRecord([{ a: 1 }, { a: 2 }], () => "routes"))
|
||||
.toThrow(/Duplicate routes key: a/);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/cardinality/compose-unique-record.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement one mutable local accumulator and one final freeze**
|
||||
|
||||
```ts
|
||||
export function composeUniqueRecord<T>(
|
||||
parts: readonly Readonly<Record<string, T>>[],
|
||||
describePart: () => string,
|
||||
): Readonly<Record<string, T>> {
|
||||
const result: Record<string, T> = Object.create(null);
|
||||
|
||||
for (const part of parts) {
|
||||
for (const [key, value] of Object.entries(part)) {
|
||||
if (Object.hasOwn(result, key)) {
|
||||
throw new TypeError(`Duplicate ${describePart()} key: ${key}`);
|
||||
}
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return Object.freeze(result);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Replace the spread-reduce in `installed-feature-contracts.ts`**
|
||||
|
||||
Route/API/schema/mapper/invalidation composition uses `composeUniqueRecord()` rather than `{ ...registry, ...next }`.
|
||||
|
||||
- [ ] **Step 5: Run focused tests and scan for the old pattern**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/cardinality/compose-unique-record.test.ts
|
||||
rg -n '\{\s*\.\.\.[A-Za-z_][A-Za-z0-9_]*,\s*\.\.\.' src/features src/platform
|
||||
```
|
||||
|
||||
Expected: no scale-sensitive accumulation pattern remains.
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Replace scale-sensitive membership scans with indexed membership
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/features/product-features.ts`
|
||||
- Modify: `src/features/installed-feature-runtimes.tsx`
|
||||
- Modify: `src/features/installed-contract-contributions.ts`
|
||||
- Test: `tests/features/product-features.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: one immutable/set-backed installed-feature membership predicate.
|
||||
|
||||
- [ ] **Step 1: Add behavior-equivalence tests for product selection**
|
||||
|
||||
```ts
|
||||
it("selects requested compiled features and reports unknown ids", () => {
|
||||
const result = resolveProductFeatures(
|
||||
["reference", "unknown"],
|
||||
["reference", "local-draft"],
|
||||
);
|
||||
|
||||
expect(result.installed).toEqual(["reference"]);
|
||||
expect(result.unknownRequested).toEqual(["unknown"]);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the existing/product feature test and establish GREEN before refactor**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/features/product-features.test.ts
|
||||
```
|
||||
|
||||
Expected: PASS before refactor.
|
||||
|
||||
- [ ] **Step 3: Build `Set` instances once per resolution/composition call**
|
||||
|
||||
```ts
|
||||
const compiledSet = new Set(compiledIds);
|
||||
const requestedSet = new Set(requested);
|
||||
const installedSet = new Set(installedIds);
|
||||
```
|
||||
|
||||
All scale-sensitive membership checks use `.has()`.
|
||||
|
||||
- [ ] **Step 4: Replace runtime and contract filters**
|
||||
|
||||
`installed-feature-runtimes.tsx` and `installed-contract-contributions.ts` consume the same installed membership abstraction instead of repeating `INSTALLED_PRODUCT_FEATURE_IDS.includes(...)`.
|
||||
|
||||
- [ ] **Step 5: Verify equivalence and scan**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/features/product-features.test.ts
|
||||
rg -n 'INSTALLED_PRODUCT_FEATURE_IDS\.includes|compiledIds\.includes|requested\.includes' src/features
|
||||
```
|
||||
|
||||
Expected: tests PASS and scan returns no scale-sensitive matches.
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Generate a deterministic static feature index
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/generate-product-feature-index.ts`
|
||||
- Create: `src/.generated/product-feature-index.ts`
|
||||
- Test: `tests/scripts/generate-product-feature-index.test.ts`
|
||||
- Modify: `package.json`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: feature modules with stable `feature-module.ts` entrypoints.
|
||||
- Produces: deterministic static TypeScript import/index file.
|
||||
|
||||
- [ ] **Step 1: Write a failing deterministic-generation test**
|
||||
|
||||
```ts
|
||||
it("sorts feature module imports by normalized feature id and produces identical output", async () => {
|
||||
const first = renderFeatureIndex([
|
||||
{ id: "zeta", importPath: "../features/zeta/feature-module" },
|
||||
{ id: "alpha", importPath: "../features/alpha/feature-module" },
|
||||
]);
|
||||
const second = renderFeatureIndex([
|
||||
{ id: "alpha", importPath: "../features/alpha/feature-module" },
|
||||
{ id: "zeta", importPath: "../features/zeta/feature-module" },
|
||||
]);
|
||||
|
||||
expect(first).toBe(second);
|
||||
expect(first.indexOf("alpha")).toBeLessThan(first.indexOf("zeta"));
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/scripts/generate-product-feature-index.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement generator rules**
|
||||
|
||||
The generator:
|
||||
- enumerates approved local feature entrypoints,
|
||||
- reads stable ids from a deterministic metadata source,
|
||||
- sorts by id,
|
||||
- rejects duplicate ids,
|
||||
- emits literal static imports,
|
||||
- writes only `src/.generated/product-feature-index.ts`,
|
||||
- never emits runtime-computed import paths.
|
||||
|
||||
- [ ] **Step 4: Add scripts**
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"generate:feature-index": "tsx scripts/generate-product-feature-index.ts",
|
||||
"check:feature-index": "pnpm generate:feature-index && git diff --exit-code -- src/.generated/product-feature-index.ts"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Use the repository's existing TypeScript script runner if it differs from `tsx`; do not add a new runtime dependency solely for this task.
|
||||
|
||||
- [ ] **Step 5: Run generator twice and compare hashes**
|
||||
|
||||
```bash
|
||||
pnpm generate:feature-index
|
||||
sha256sum src/.generated/product-feature-index.ts > /tmp/index.first
|
||||
pnpm generate:feature-index
|
||||
sha256sum src/.generated/product-feature-index.ts > /tmp/index.second
|
||||
diff -u /tmp/index.first /tmp/index.second
|
||||
```
|
||||
|
||||
Expected: no diff.
|
||||
|
||||
---
|
||||
|
||||
### Task 9: Retire handwritten multi-registry feature installation
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/features/installed-product-manifest.ts`
|
||||
- Modify: `src/features/installed-feature-adapters.ts`
|
||||
- Modify: `src/features/installed-feature-runtimes.tsx`
|
||||
- Modify: `src/features/installed-feature-messages.ts`
|
||||
- Modify: `src/features/installed-contract-contributions.ts`
|
||||
- Modify: `src/features/installed-feature-contracts.ts`
|
||||
- Test: existing sample-removal test and new `tests/features/feature-installation-surface.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: generated feature index.
|
||||
- Produces: generic composition from `FeatureModule[]`.
|
||||
|
||||
- [ ] **Step 1: Write the installation-surface test**
|
||||
|
||||
```ts
|
||||
it("derives install-time collections from feature modules instead of reference-specific imports", async () => {
|
||||
const sourceFiles = await readInstalledFeatureSourceFiles();
|
||||
|
||||
for (const source of sourceFiles) {
|
||||
expect(source).not.toMatch(/REFERENCE_FEATURE_(ADAPTER|RUNTIME|CONTRACT)/);
|
||||
expect(source).not.toMatch(/REFERENCE_MESSAGE_CATALOGS/);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/features/feature-installation-surface.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL against current handwritten reference imports.
|
||||
|
||||
- [ ] **Step 3: Rewrite installed collections as generic projections**
|
||||
|
||||
Conceptual shape:
|
||||
|
||||
```ts
|
||||
export const INSTALLED_FEATURE_ADAPTERS =
|
||||
INSTALLED_PRODUCT_FEATURE_MODULES.flatMap((feature) => feature.adapters);
|
||||
```
|
||||
|
||||
Equivalent projections are used for runtimes/messages/contracts, with duplicate detection where identifier collisions are possible.
|
||||
|
||||
- [ ] **Step 4: Run feature installation and sample-removal tests**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/features
|
||||
pnpm run test:sample-removal
|
||||
```
|
||||
|
||||
Use the exact existing sample-removal script name from `package.json` if its spelling differs.
|
||||
|
||||
- [ ] **Step 5: Scan for reference-specific imports in installed central files**
|
||||
|
||||
```bash
|
||||
rg -n 'REFERENCE_' \
|
||||
src/features/installed-product-manifest.ts \
|
||||
src/features/installed-feature-adapters.ts \
|
||||
src/features/installed-feature-runtimes.tsx \
|
||||
src/features/installed-feature-messages.ts \
|
||||
src/features/installed-contract-contributions.ts \
|
||||
src/features/installed-feature-contracts.ts
|
||||
```
|
||||
|
||||
Expected: no install-time reference-specific import.
|
||||
|
||||
---
|
||||
|
||||
### Task 10: Enforce cross-feature and cross-context concrete import prohibition
|
||||
|
||||
**Files:**
|
||||
- Modify: `.dependency-cruiser.json`
|
||||
- Test fixture: `tests/architecture/fixtures/cross-feature-import/`
|
||||
- Test fixture: `tests/architecture/fixtures/same-feature-import/`
|
||||
- Test: `tests/architecture/dependency-boundaries.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces deterministic architecture failures for illegal feature/context edges.
|
||||
|
||||
- [ ] **Step 1: Create an illegal fixture**
|
||||
|
||||
```ts
|
||||
// tests/architecture/fixtures/cross-feature-import/order.ts
|
||||
import { concretePaymentThing } from "../../../../src/features/payment/application/concrete-payment-thing";
|
||||
|
||||
export const illegal = concretePaymentThing;
|
||||
```
|
||||
|
||||
The fixture must target two real/synthetic feature roots that exist in the test harness.
|
||||
|
||||
- [ ] **Step 2: Create a legal same-feature fixture**
|
||||
|
||||
```ts
|
||||
// tests/architecture/fixtures/same-feature-import/order.ts
|
||||
import { orderPort } from "../../../../src/features/order/application/order-port";
|
||||
|
||||
export const legal = orderPort;
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Extend dependency-cruiser rules**
|
||||
|
||||
The rule must reject `src/features/<A>/** -> src/features/<B>/**` when `A !== B`, except imports through explicitly approved shared `src/contracts/**`, `src/application/ports/**`, or orchestration/public-facade boundaries.
|
||||
|
||||
Add the analogous stricter context rule for `src/contexts/<A>/** -> src/contexts/<B>/**`.
|
||||
|
||||
- [ ] **Step 4: Run architecture checks against both fixtures**
|
||||
|
||||
```bash
|
||||
pnpm run check:architecture
|
||||
```
|
||||
|
||||
Expected: legal fixture accepted; illegal cross-feature fixture rejected by the named rule.
|
||||
|
||||
- [ ] **Step 5: Run full architecture checks**
|
||||
|
||||
```bash
|
||||
pnpm run check:architecture
|
||||
```
|
||||
|
||||
Expected: PASS for production sources.
|
||||
|
||||
---
|
||||
|
||||
### Task 11: Introduce hierarchical/lazy route ownership
|
||||
|
||||
**Files:**
|
||||
- Create: `src/platform/routing/context-route-module.ts`
|
||||
- Modify: current `AppRouter` file identified in Task 1 baseline map
|
||||
- Modify: `src/features/installed-feature-contracts.ts` only if route projection remains there
|
||||
- Test: `tests/platform/routing/context-route-module.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: app/context/feature descriptors.
|
||||
- Produces:
|
||||
- top-level context routes at app boot,
|
||||
- lazy feature route resolution inside the selected context.
|
||||
|
||||
- [ ] **Step 1: Write a failing test proving boot does not flatten all feature routes**
|
||||
|
||||
```ts
|
||||
it("creates only direct context route entries at app boot", () => {
|
||||
const routes = createAppRoutes(customerApp);
|
||||
|
||||
expect(routes.map((route) => route.id)).toEqual(["commerce", "account"]);
|
||||
expect(routes.some((route) => route.id === "order-create")).toBe(false);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify RED**
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests/platform/routing/context-route-module.test.ts
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Implement lazy context route modules**
|
||||
|
||||
```ts
|
||||
export interface ContextRouteModule {
|
||||
readonly id: string;
|
||||
readonly path: string;
|
||||
readonly loadRoutes: () => Promise<readonly RouteObject[]>;
|
||||
}
|
||||
```
|
||||
|
||||
The app router creates only `ContextRouteModule` entries. `loadRoutes()` imports the context-owned static route module; it does not accept arbitrary runtime paths.
|
||||
|
||||
- [ ] **Step 4: Preserve existing public route URLs**
|
||||
|
||||
Run route contract tests and compare route URL snapshots before/after.
|
||||
|
||||
```bash
|
||||
pnpm exec vitest run tests --testNamePattern="route"
|
||||
```
|
||||
|
||||
Expected: route URLs unchanged.
|
||||
|
||||
---
|
||||
|
||||
### Task 12: Add topology/cardinality composition tests and close Phase 1
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/architecture/topology-cardinality.test.ts`
|
||||
- Modify: `package.json`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: module hierarchy, generated index, cardinality assertions.
|
||||
- Produces: `check:topology`.
|
||||
|
||||
- [ ] **Step 1: Write boundary-ceiling tests**
|
||||
|
||||
```ts
|
||||
it("rejects a context above its feature budget", () => {
|
||||
const features = Array.from({ length: 201 }, (_, index) => fakeFeature(`f${index}`));
|
||||
|
||||
expect(() =>
|
||||
defineBoundedContextModule({
|
||||
id: "commerce",
|
||||
features,
|
||||
budget: { maxFeatures: 200 },
|
||||
}),
|
||||
).toThrow(/commerce.*201.*200/);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add duplicate-id tests**
|
||||
|
||||
```ts
|
||||
it("rejects duplicate direct child ids", () => {
|
||||
expect(() =>
|
||||
defineDeployableAppModule({
|
||||
id: "customer",
|
||||
contexts: [fakeContext("commerce"), fakeContext("commerce")],
|
||||
budget: { maxContexts: 20 },
|
||||
}),
|
||||
).toThrow(/Duplicate.*commerce/);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add `check:topology`**
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"check:topology": "vitest run tests/architecture/topology-cardinality.test.ts tests/platform/cardinality tests/platform/routing"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run Phase 1 verification**
|
||||
|
||||
```bash
|
||||
pnpm run check:feature-index
|
||||
pnpm run check:architecture
|
||||
pnpm run check:topology
|
||||
pnpm exec tsc --project tsconfig.app.json --noEmit
|
||||
pnpm exec tsc --project tsconfig.test.json --noEmit
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Phase decision**
|
||||
|
||||
**완료** only if:
|
||||
- feature installation no longer depends on multiple reference-specific central registry edits,
|
||||
- scale-sensitive composition has no repeated accumulator spread,
|
||||
- membership scans are indexed,
|
||||
- cross-feature/context illegal imports fail,
|
||||
- app boot routing is hierarchical,
|
||||
- cardinality budgets are executable.
|
||||
|
||||
Otherwise: **아직 더 봐야댐**.
|
||||
+1294
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,38 @@
|
||||
# Release coherence baseline (2026-09-23)
|
||||
|
||||
Verified before Phase 5 edits. Only fields and paths that exist in the live tree are listed.
|
||||
|
||||
## Identity tuple
|
||||
|
||||
| Source | Where it is read | Boot-critical identity fields |
|
||||
| --- | --- | --- |
|
||||
| HTML + hashed JS (build) | `src/contracts/env.ts` `getBuildConfig()` (`VITE_BUILD_ID`) | `buildId`; optional expected `assetManifestHash` (`LoadReleaseManifestOptions.expectedAssetManifestHash`) |
|
||||
| Runtime config (`/config.json`) | `src/bootstrap/load-runtime-config.ts`, `src/bootstrap/runtime-config-schema.ts` | `BUILD_ID` (optional in schema, always written by `scripts/generate-runtime-config.ts`), `RELEASE_ID` (same), `CONFIG_SCHEMA_VERSION` |
|
||||
| Release manifest (`/release-manifest.json`) | `src/bootstrap/load-release-manifest.ts` | `buildId`, `releaseId`, `configSchemaVersion`, `assetManifestHash`, `contractSet` (V2) / `legacyApiContractVersion` (V1) |
|
||||
|
||||
Existing checks before Phase 5:
|
||||
|
||||
- `loadRuntimeConfig`: config `BUILD_ID` vs build `buildId` → `CONFIG_BUILD_MISMATCH`.
|
||||
- `loadReleaseManifest` (order: build, config schema, V1 API contract, release, assets, then contract set): `MANIFEST_BUILD_MISMATCH`, `MANIFEST_CONFIG_SCHEMA_MISMATCH`, `MANIFEST_API_CONTRACT_MISMATCH`, `MANIFEST_RELEASE_MISMATCH`, `MANIFEST_ASSET_MISMATCH`, `CONTRACT_SET_*`.
|
||||
- `src/contracts/compatibility.ts` `verifyCompatibilityTuple()` treats `releaseId` as a warning only; it is used by release tooling, not by boot.
|
||||
- Boot failure renders `BootErrorShell` from `src/bootstrap/main.tsx`; there was no automatic boot reload, so no loop, but also no bounded recovery for a stale HTML document during a rolling release.
|
||||
- Runtime chunk recovery already has a reload-once guard (`src/application/use-cases/decide-chunk-recovery.ts`, storage key `CHUNK_RELOAD_GUARD`).
|
||||
|
||||
## Cache directives
|
||||
|
||||
| Surface | `config/hosting/cache-policy.json` | `config/hosting/response-headers.fixture.json` |
|
||||
| --- | --- | --- |
|
||||
| `/` (HTML) | `no-cache` | `no-cache` |
|
||||
| `/config.json` | `no-store` | `no-store` |
|
||||
| `/release-manifest.json` | `no-store` | `no-store` |
|
||||
| `/assets/*` (hashed) | `public, max-age=31536000, immutable` | same |
|
||||
|
||||
Client side, `src/bootstrap/read-bounded-boot-json.ts` fetches config and manifest with `cache: "no-store"`.
|
||||
|
||||
## Existing tests exercised before changes
|
||||
|
||||
- `tests/runtime-schema/release-manifest.test.ts`, `tests/runtime-schema/runtime-config.test.ts` (boot loaders), `tests/unit/release-coherence.test.ts` and `tests/unit/compatibility.test.ts` (release tooling tuple), `tests/unit/read-bounded-boot-json.test.ts` (no-store boot reads), `scripts/verify-hosting-headers.ts` (fixture headers).
|
||||
|
||||
## Phase 5 ruling
|
||||
|
||||
No new identity format is introduced. Phase 5 extracts the existing comparisons into one pure validator (`src/platform/release/release-coherence.ts`) that both boot loaders delegate to, keeps the existing error codes and precedence, and adds a bounded reload-once recovery keyed by the mismatch.
|
||||
+21
-3
@@ -78,9 +78,9 @@
|
||||
"test:realtime-removal": "node scripts/test-realtime-runtime-removal.ts",
|
||||
"test:reference-feature": "node scripts/run-vitest.ts run tests/features/reference-feature --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/reference-feature.xml --passWithNoTests",
|
||||
"check:v8-coverage-counter-semantics": "node scripts/check-v8-coverage-counter-semantics.ts",
|
||||
"test:coverage": "corepack pnpm check:v8-coverage-counter-semantics && node scripts/run-vitest.ts run tests/runtime-schema tests/unit tests/contract tests/component tests/integration tests/features/reference-feature --coverage --maxWorkers=4 --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml && node scripts/check-risk-coverage.ts",
|
||||
"test:coverage": "corepack pnpm check:v8-coverage-counter-semantics && node scripts/run-vitest.ts run tests/runtime-schema tests/unit tests/contract tests/component tests/integration tests/features/reference-feature tests/platform --coverage --maxWorkers=4 --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml && node scripts/check-risk-coverage.ts",
|
||||
"check:coverage:fixture": "node scripts/check-risk-coverage.ts --summary tests/fixtures/coverage/below-threshold.json --artifact artifacts/quality/risk-coverage-fixture.json",
|
||||
"test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:contract && corepack pnpm test:component && corepack pnpm test:integration && corepack pnpm test:reference-feature && corepack pnpm test:recipes",
|
||||
"test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:contract && corepack pnpm test:component && corepack pnpm test:integration && corepack pnpm test:reference-feature && corepack pnpm test:platform && corepack pnpm check:release-coherence && corepack pnpm test:recipes",
|
||||
"verify:lockfile": "corepack pnpm install --frozen-lockfile --ignore-scripts",
|
||||
"check:frozen-lockfile:fixture": "node scripts/check-frozen-lockfile-fixture.ts",
|
||||
"generate:artifact-schemas": "node scripts/generate-artifact-schemas.ts",
|
||||
@@ -131,7 +131,25 @@
|
||||
"check:types:fixture:http-route-id": "tsc -p tests/fixtures/typecheck/tsconfig.http-route-id.json",
|
||||
"check:types:fixture:feature-contribution-input": "tsc -p tests/fixtures/typecheck/tsconfig.feature-contribution-input.json",
|
||||
"check:types:fixture:feature-capability-selection": "tsc -p tests/fixtures/typecheck/tsconfig.feature-capability-selection.json",
|
||||
"check:types:fixture:direct-feature-composition": "tsc -p tests/fixtures/typecheck/tsconfig.direct-feature-composition.json"
|
||||
"check:types:fixture:direct-feature-composition": "tsc -p tests/fixtures/typecheck/tsconfig.direct-feature-composition.json",
|
||||
"generate:feature-index": "node scripts/generate-product-feature-index.ts",
|
||||
"check:feature-index": "node scripts/generate-product-feature-index.ts --check",
|
||||
"check:topology": "node scripts/run-vitest.ts run tests/architecture/topology-cardinality.test.ts tests/architecture/context-lazy-loading.test.ts tests/platform/cardinality tests/platform/routing --reporter=default",
|
||||
"check:traffic": "node scripts/run-vitest.ts run tests/platform/execution tests/platform/traffic tests/platform/resilience --reporter=default",
|
||||
"check:observability": "node scripts/run-vitest.ts run tests/platform/errors tests/platform/validation tests/platform/telemetry tests/architecture/observability-boundaries.test.ts --reporter=default",
|
||||
"test:platform": "node scripts/run-vitest.ts run tests/platform tests/architecture --no-file-parallelism --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/platform.xml",
|
||||
"check:scale:pr": "node scripts/scale/run-scale-profile.ts pr",
|
||||
"check:scale:main": "node scripts/scale/run-scale-profile.ts main",
|
||||
"check:scale:nightly": "node scripts/scale/run-scale-profile.ts nightly",
|
||||
"check:scale:release": "node scripts/scale/run-scale-profile.ts release",
|
||||
"check:scale:baseline": "node scripts/scale/check-scale-baseline.ts",
|
||||
"update:scale-baseline": "node scripts/scale/check-scale-baseline.ts --update",
|
||||
"verify:extreme-scale": "node scripts/verify-extreme-scale.ts",
|
||||
"check:request-fanout": "node scripts/check-request-fanout.ts && node scripts/check-request-fanout.ts --fixture",
|
||||
"check:app-build-input": "node scripts/check-app-build-input.ts",
|
||||
"check:app-build-input:bundle": "node scripts/check-app-build-input.ts --require-bundle",
|
||||
"test:extreme-scale:focused": "node scripts/run-vitest.ts run tests/scale/global-local-independence.test.ts tests/architecture/app-build-input.test.ts tests/architecture/request-fanout.test.ts tests/platform/traffic/request-fanout.test.ts tests/platform/traffic/request-deduplication.test.ts tests/features/reference-feature/reference-request-fanout.test.ts tests/features/reference-feature/reference-request-deduplication.test.ts tests/scripts/generate-product-feature-index.test.ts --reporter=default",
|
||||
"check:release-coherence": "node scripts/run-vitest.ts run tests/platform/release tests/release --reporter=default"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "5.101.4",
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
createFileSystemDeclarationSource,
|
||||
type TopologyDeclarationSource,
|
||||
} from "./generate-product-feature-index.ts";
|
||||
|
||||
/**
|
||||
* Spec §3 / §37. Build-input regression gate for deployable-app isolation.
|
||||
*
|
||||
* The app being built is the one recorded in `src/.generated/product-app.ts`.
|
||||
* Its allowed features are exactly those owned (via their context) by that
|
||||
* app's declarations. The gate fails when
|
||||
* - a generated index imports a feature or declares a context outside that
|
||||
* ownership set (e.g. a regression back to "import every src/features"),
|
||||
* - the production bundle's module inventory contains a module of a feature
|
||||
* the app does not own.
|
||||
*/
|
||||
export type AppBuildInputReport = Readonly<{
|
||||
appId: string;
|
||||
ownedContexts: readonly string[];
|
||||
ownedFeatureDirectories: readonly string[];
|
||||
generatedFeatureImports: readonly string[];
|
||||
generatedContexts: readonly string[];
|
||||
bundle: Readonly<{ checked: boolean; featureDirectories: readonly string[] }>;
|
||||
violations: readonly string[];
|
||||
}>;
|
||||
|
||||
const GENERATED = [
|
||||
"src/.generated/product-feature-index.ts",
|
||||
"src/.generated/product-context-index.ts",
|
||||
"src/.generated/product-app.ts",
|
||||
] as const;
|
||||
|
||||
function unique(values: Iterable<string>): string[] {
|
||||
return [...new Set(values)].sort();
|
||||
}
|
||||
|
||||
export async function inspectAppBuildInput(
|
||||
root: string,
|
||||
options: Readonly<{
|
||||
source?: TopologyDeclarationSource;
|
||||
bundleInventory?: string | null;
|
||||
}> = {},
|
||||
): Promise<AppBuildInputReport> {
|
||||
const source = options.source ?? (await createFileSystemDeclarationSource(root));
|
||||
const [featureIndex, contextIndex, appIndex] = await Promise.all(
|
||||
GENERATED.map((file) => readFile(path.join(root, file), "utf8")),
|
||||
);
|
||||
const appId = /id:\s*"([^"]+)"/u.exec(appIndex ?? "")?.[1];
|
||||
const violations: string[] = [];
|
||||
if (!appId || !source.app(appId)) {
|
||||
violations.push(`generated app ${appId ?? "<missing>"} is not a declared deployable app`);
|
||||
}
|
||||
const ownedContexts = appId ? source.contextsOf(appId).map((context) => context.id) : [];
|
||||
const ownedFeatureDirectories = unique(
|
||||
ownedContexts.flatMap((contextId) => source.featuresOf(contextId).map((feature) => feature.directory)),
|
||||
);
|
||||
const owned = new Set(ownedFeatureDirectories);
|
||||
|
||||
const featureDirectoriesIn = (text: string) =>
|
||||
unique([...text.matchAll(/\.\.\/features\/([^/"']+)\//gu)].map((match) => match[1] as string));
|
||||
const generatedFeatureImports = unique([
|
||||
...featureDirectoriesIn(featureIndex ?? ""),
|
||||
...featureDirectoriesIn(contextIndex ?? ""),
|
||||
]);
|
||||
for (const directory of generatedFeatureImports) {
|
||||
if (!owned.has(directory)) {
|
||||
violations.push(`generated index imports feature "${directory}" not owned by app ${appId}`);
|
||||
}
|
||||
}
|
||||
const generatedContexts = unique(
|
||||
[...(contextIndex ?? "").matchAll(/defineBoundedContextModule\(\{\s*id:\s*"([^"]+)"/gu)].map(
|
||||
(match) => match[1] as string,
|
||||
),
|
||||
);
|
||||
const ownedContextSet = new Set(ownedContexts);
|
||||
for (const contextId of generatedContexts) {
|
||||
if (!ownedContextSet.has(contextId)) {
|
||||
violations.push(`generated index declares context "${contextId}" not owned by app ${appId}`);
|
||||
}
|
||||
}
|
||||
|
||||
let bundle: AppBuildInputReport["bundle"] = { checked: false, featureDirectories: [] };
|
||||
const inventoryPath =
|
||||
options.bundleInventory === undefined
|
||||
? path.join(root, "artifacts/quality/vite-module-inventory.json")
|
||||
: options.bundleInventory;
|
||||
if (inventoryPath) {
|
||||
const raw = await readFile(inventoryPath, "utf8").catch(() => null);
|
||||
if (raw !== null) {
|
||||
const inventory = JSON.parse(raw) as { chunks?: { modules?: string[] }[] };
|
||||
const modules = (inventory.chunks ?? []).flatMap((chunk) => chunk.modules ?? []);
|
||||
const featureDirectories = unique(
|
||||
modules.flatMap((module) => {
|
||||
const match = /^src\/features\/([^/]+)\//u.exec(module);
|
||||
return match ? [match[1] as string] : [];
|
||||
}),
|
||||
);
|
||||
bundle = { checked: true, featureDirectories };
|
||||
for (const directory of featureDirectories) {
|
||||
if (!owned.has(directory)) {
|
||||
violations.push(`production bundle contains feature "${directory}" not owned by app ${appId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
appId: appId ?? "",
|
||||
ownedContexts: unique(ownedContexts),
|
||||
ownedFeatureDirectories,
|
||||
generatedFeatureImports,
|
||||
generatedContexts,
|
||||
bundle,
|
||||
violations,
|
||||
});
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
// The bundle inventory is only meaningful right after a build of this tree;
|
||||
// without `--require-bundle` the gate checks the generated indexes only, so a
|
||||
// stale inventory from another build can never pass or fail it.
|
||||
const requireBundle = process.argv.includes("--require-bundle");
|
||||
const report = await inspectAppBuildInput(process.cwd(), requireBundle ? {} : { bundleInventory: null });
|
||||
if (requireBundle && !report.bundle.checked) {
|
||||
process.stderr.write("app build input: no production module inventory; run the build first\n");
|
||||
process.exit(1);
|
||||
}
|
||||
for (const violation of report.violations) process.stderr.write(`FAIL ${violation}\n`);
|
||||
process.stdout.write(
|
||||
`app build input: app=${report.appId} contexts=${report.ownedContexts.length} ` +
|
||||
`features=${report.ownedFeatureDirectories.length} generatedImports=${report.generatedFeatureImports.length} ` +
|
||||
`bundle=${report.bundle.checked ? `${report.bundle.featureDirectories.length} feature dirs` : "not checked"} ` +
|
||||
`${report.violations.length === 0 ? "PASS" : "FAIL"}\n`,
|
||||
);
|
||||
if (report.violations.length > 0) process.exitCode = 1;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
await main();
|
||||
}
|
||||
@@ -824,14 +824,21 @@ async function runGraphFixtureChecks(): Promise<GraphFixtureResult> {
|
||||
"tests/fixtures/architecture/dependency-graph",
|
||||
);
|
||||
const allowedRoot = resolve(fixtureRoot, "allowed");
|
||||
const [allowedGraph, unresolvedGraph, layerGraph, cycleGraph, barrelGraph] =
|
||||
await Promise.all([
|
||||
analyzeSourceGraph(allowedRoot, "src"),
|
||||
analyzeSourceGraph(resolve(fixtureRoot, "unresolved"), "src"),
|
||||
analyzeSourceGraph(resolve(fixtureRoot, "layer"), "src"),
|
||||
analyzeSourceGraph(resolve(fixtureRoot, "cycle"), "src"),
|
||||
analyzeSourceGraph(resolve(fixtureRoot, "barrel"), "src"),
|
||||
]);
|
||||
const [
|
||||
allowedGraph,
|
||||
unresolvedGraph,
|
||||
layerGraph,
|
||||
cycleGraph,
|
||||
barrelGraph,
|
||||
crossBoundaryGraph,
|
||||
] = await Promise.all([
|
||||
analyzeSourceGraph(allowedRoot, "src"),
|
||||
analyzeSourceGraph(resolve(fixtureRoot, "unresolved"), "src"),
|
||||
analyzeSourceGraph(resolve(fixtureRoot, "layer"), "src"),
|
||||
analyzeSourceGraph(resolve(fixtureRoot, "cycle"), "src"),
|
||||
analyzeSourceGraph(resolve(fixtureRoot, "barrel"), "src"),
|
||||
analyzeSourceGraph(resolve(fixtureRoot, "cross-boundary"), "src"),
|
||||
]);
|
||||
const allowedFiles = new Set(await listFiles(allowedRoot));
|
||||
const allowedSourceFile = resolve(
|
||||
allowedRoot,
|
||||
@@ -851,6 +858,24 @@ async function runGraphFixtureChecks(): Promise<GraphFixtureResult> {
|
||||
),
|
||||
);
|
||||
const assertions = [
|
||||
{
|
||||
name: "cross-feature concrete imports are rejected",
|
||||
passed: blockingViolations(crossBoundaryGraph).some(
|
||||
({ rule, source, target }) =>
|
||||
rule === "features-do-not-import-other-features" &&
|
||||
source === "src/features/alpha/read-beta.ts" &&
|
||||
target === "src/features/beta/value.ts",
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "cross-context concrete imports are rejected",
|
||||
passed: blockingViolations(crossBoundaryGraph).some(
|
||||
({ rule, source, target }) =>
|
||||
rule === "contexts-do-not-import-other-contexts" &&
|
||||
source === "src/contexts/customer/read-admin.ts" &&
|
||||
target === "src/contexts/admin/value.ts",
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "deep adapter import from outside the group is rejected",
|
||||
passed: blockingViolations(barrelGraph).some(
|
||||
|
||||
@@ -4,8 +4,15 @@ import { diagnosticsReportArtifactSchema } from "./contracts/release-artifacts.t
|
||||
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
|
||||
import path from "node:path";
|
||||
|
||||
import { DIAGNOSTIC_EVENT_REGISTRY } from "../src/contracts/diagnostics.ts";
|
||||
import { TELEMETRY_REGISTRY } from "../src/contracts/telemetry.ts";
|
||||
import {
|
||||
DIAGNOSTIC_CONTEXT_ALLOWLIST,
|
||||
DIAGNOSTIC_CONTEXT_CARDINALITY,
|
||||
DIAGNOSTIC_EVENT_REGISTRY,
|
||||
} from "../src/contracts/diagnostics.ts";
|
||||
import {
|
||||
TELEMETRY_ATTRIBUTE_ALLOWLIST,
|
||||
TELEMETRY_REGISTRY,
|
||||
} from "../src/contracts/telemetry.ts";
|
||||
|
||||
const fixtureMode = process.argv.includes("--fixture");
|
||||
const failures: string[] = [];
|
||||
@@ -40,7 +47,20 @@ const diagnosticProducerFiles: Readonly<Record<string, string>> = {
|
||||
"ui.render.failed": "src/application/create-application.ts",
|
||||
"release.mismatch.detected": "src/application/create-application.ts",
|
||||
"telemetry.delivery.dropped": "src/bootstrap/runtime-adapters.ts",
|
||||
};
|
||||
};
|
||||
|
||||
for (const key of DIAGNOSTIC_CONTEXT_ALLOWLIST) {
|
||||
if (!DIAGNOSTIC_CONTEXT_CARDINALITY[key]) {
|
||||
failures.push(`diagnostic context key has no cardinality class: ${key}`);
|
||||
}
|
||||
}
|
||||
for (const key of TELEMETRY_ATTRIBUTE_ALLOWLIST) {
|
||||
// Defensive at runtime: the types already exclude it, the gate still checks.
|
||||
const cardinality: string | undefined = DIAGNOSTIC_CONTEXT_CARDINALITY[key];
|
||||
if (cardinality === "request") {
|
||||
failures.push(`request-cardinality telemetry attribute is forbidden: ${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!fixtureMode) {
|
||||
for (const eventName of Object.keys(TELEMETRY_REGISTRY)) {
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { parseAsync } from "@babel/core";
|
||||
|
||||
/**
|
||||
* Spec §12 / §41. Source gate against frontend N+1 request fan-out.
|
||||
*
|
||||
* In feature code and application use cases, a physical-request dispatch must
|
||||
* not run once per element of a collection. The gate rejects a dispatch call
|
||||
* - inside a loop statement (for / for-of / for-in / while / do-while), or
|
||||
* - inside a callback passed to an array iteration method
|
||||
* (map, flatMap, forEach, filter, reduce, some, every, find, findIndex),
|
||||
* where a dispatch is `fetch(...)`, or any method call on a receiver named like
|
||||
* a transport (`http`, `executor`, `client`, `gateway`, `api`, `transport`).
|
||||
*
|
||||
* The HTTP runtime itself (src/adapters/http) owns its bounded retry loop and is
|
||||
* out of scope. A reviewed exception is written on the call's line as
|
||||
* `// fanout-reviewed: <reason>`.
|
||||
*/
|
||||
export const REQUEST_FANOUT_ROOTS = Object.freeze(["src/features", "src/application"]);
|
||||
|
||||
const TRANSPORT_RECEIVER = /^(?:http|executor|client|gateway|api|transport)$|(?:Http|Executor|Client|Gateway|Api|Transport)$/u;
|
||||
const ITERATION_METHODS = new Set([
|
||||
"map",
|
||||
"flatMap",
|
||||
"forEach",
|
||||
"filter",
|
||||
"reduce",
|
||||
"some",
|
||||
"every",
|
||||
"find",
|
||||
"findIndex",
|
||||
]);
|
||||
const LOOP_TYPES = new Set([
|
||||
"ForStatement",
|
||||
"ForOfStatement",
|
||||
"ForInStatement",
|
||||
"WhileStatement",
|
||||
"DoWhileStatement",
|
||||
]);
|
||||
const FUNCTION_TYPES = new Set(["ArrowFunctionExpression", "FunctionExpression"]);
|
||||
|
||||
type Node = { type: string; loc?: { start: { line: number } } } & Record<string, unknown>;
|
||||
|
||||
export type FanoutViolation = Readonly<{ file: string; line: number; call: string; context: string }>;
|
||||
|
||||
function receiverName(node: Node | undefined): string | null {
|
||||
if (!node) return null;
|
||||
if (node.type === "Identifier") return node["name"] as string;
|
||||
if (node.type === "MemberExpression" && (node["property"] as Node).type === "Identifier") {
|
||||
return ((node["property"] as Node)["name"] as string) ?? null;
|
||||
}
|
||||
if (node.type === "ThisExpression") return "this";
|
||||
return null;
|
||||
}
|
||||
|
||||
function dispatchDescription(call: Node): string | null {
|
||||
const callee = call["callee"] as Node;
|
||||
if (callee.type === "Identifier" && callee["name"] === "fetch") return "fetch()";
|
||||
if (callee.type === "MemberExpression") {
|
||||
const receiver = receiverName(callee["object"] as Node);
|
||||
const property = callee["property"] as Node;
|
||||
const method = property.type === "Identifier" ? (property["name"] as string) : "?";
|
||||
if (receiver && TRANSPORT_RECEIVER.test(receiver)) return `${receiver}.${method}()`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function iterationCallback(parent: Node | undefined, child: Node): string | null {
|
||||
if (!parent || parent.type !== "CallExpression" || !FUNCTION_TYPES.has(child.type)) return null;
|
||||
if (!(parent["arguments"] as Node[]).includes(child)) return null;
|
||||
const callee = parent["callee"] as Node;
|
||||
if (callee.type !== "MemberExpression") return null;
|
||||
const property = callee["property"] as Node;
|
||||
const method = property.type === "Identifier" ? (property["name"] as string) : "";
|
||||
return ITERATION_METHODS.has(method) ? `.${method}() callback` : null;
|
||||
}
|
||||
|
||||
export async function findRequestFanout(
|
||||
file: string,
|
||||
sourceText: string,
|
||||
): Promise<readonly FanoutViolation[]> {
|
||||
const plugins: ("jsx" | ["typescript", { dts: boolean }])[] = [["typescript", { dts: false }]];
|
||||
if (file.endsWith(".tsx")) plugins.push("jsx");
|
||||
const tree = (await parseAsync(sourceText, {
|
||||
filename: file,
|
||||
babelrc: false,
|
||||
configFile: false,
|
||||
sourceType: "module",
|
||||
parserOpts: { plugins },
|
||||
})) as unknown as Node | null;
|
||||
if (!tree) throw new Error(`cannot parse ${file}`);
|
||||
const lines = sourceText.split("\n");
|
||||
const violations: FanoutViolation[] = [];
|
||||
|
||||
const visit = (node: Node, parent: Node | undefined, repeating: string | null): void => {
|
||||
let context = repeating;
|
||||
if (LOOP_TYPES.has(node.type)) context = node.type.replace("Statement", " loop");
|
||||
const callback = iterationCallback(parent, node);
|
||||
if (callback) context = callback;
|
||||
// A nested function declared (not iterated) resets the repetition context.
|
||||
if (!callback && FUNCTION_TYPES.has(node.type)) context = null;
|
||||
if (node.type === "FunctionDeclaration") context = null;
|
||||
|
||||
if (node.type === "CallExpression" && context) {
|
||||
const call = dispatchDescription(node);
|
||||
const line = node.loc?.start.line ?? 0;
|
||||
if (call && !/fanout-reviewed:\s*\S/u.test(lines[line - 1] ?? "")) {
|
||||
violations.push({ file, line, call, context });
|
||||
}
|
||||
}
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
if (key === "loc" || key === "start" || key === "end" || key === "extra") continue;
|
||||
const children = Array.isArray(value) ? value : [value];
|
||||
for (const child of children) {
|
||||
if (child && typeof child === "object" && typeof (child as Node).type === "string") {
|
||||
visit(child as Node, node, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
visit(tree, undefined, null);
|
||||
return violations;
|
||||
}
|
||||
|
||||
async function sourceFiles(directory: string): Promise<string[]> {
|
||||
const found: string[] = [];
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(directory, { withFileTypes: true });
|
||||
} catch {
|
||||
return found;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const target = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) found.push(...(await sourceFiles(target)));
|
||||
else if (/\.tsx?$/u.test(entry.name) && !/\.d\.ts$/u.test(entry.name)) found.push(target);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
export async function scanRequestFanout(
|
||||
root: string,
|
||||
roots: readonly string[] = REQUEST_FANOUT_ROOTS,
|
||||
): Promise<Readonly<{ files: number; violations: readonly FanoutViolation[] }>> {
|
||||
const files = (await Promise.all(roots.map((entry) => sourceFiles(path.join(root, entry))))).flat();
|
||||
const violations: FanoutViolation[] = [];
|
||||
for (const file of files) {
|
||||
violations.push(
|
||||
...(await findRequestFanout(path.relative(root, file), await readFile(file, "utf8"))),
|
||||
);
|
||||
}
|
||||
return { files: files.length, violations };
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const fixture = process.argv.includes("--fixture");
|
||||
const root = process.cwd();
|
||||
if (fixture) {
|
||||
// The forbidden fixture must be rejected; the allowed fixture must pass.
|
||||
const forbidden = await scanRequestFanout(root, ["tests/fixtures/architecture/request-fanout/forbidden"]);
|
||||
const allowed = await scanRequestFanout(root, ["tests/fixtures/architecture/request-fanout/allowed"]);
|
||||
const ok = forbidden.violations.length >= forbidden.files && forbidden.files > 0 && allowed.violations.length === 0;
|
||||
process.stdout.write(
|
||||
`request fan-out fixtures: forbidden ${forbidden.violations.length} rejected in ${forbidden.files} files, allowed ${allowed.violations.length} violations ${ok ? "PASS" : "FAIL"}\n`,
|
||||
);
|
||||
if (!ok) process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
const result = await scanRequestFanout(root);
|
||||
for (const violation of result.violations) {
|
||||
process.stderr.write(
|
||||
`FAIL ${violation.file}:${violation.line} ${violation.call} inside ${violation.context}\n`,
|
||||
);
|
||||
}
|
||||
process.stdout.write(
|
||||
`request fan-out: ${result.files} files scanned, ${result.violations.length} per-row dispatches ${result.violations.length === 0 ? "PASS" : "FAIL"}\n`,
|
||||
);
|
||||
if (result.violations.length > 0) process.exitCode = 1;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
await main();
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { dirname, relative, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export type FeatureImportEntry = Readonly<{
|
||||
id: string;
|
||||
importPath: string;
|
||||
}>;
|
||||
|
||||
export type FeatureIndexEntry = FeatureImportEntry & Readonly<{
|
||||
directory: string;
|
||||
contextId: string;
|
||||
contextRoutePath: string;
|
||||
contextMaxFeatures: number;
|
||||
}>;
|
||||
|
||||
export function renderFeatureIndex(entries: readonly FeatureImportEntry[]): string {
|
||||
const sorted = [...entries].sort((left, right) => left.id.localeCompare(right.id));
|
||||
const imports = sorted
|
||||
.map(
|
||||
(entry, index) =>
|
||||
`import { FEATURE_MODULE as featureModule${index} } from ${JSON.stringify(entry.importPath)};`,
|
||||
)
|
||||
.join("\n");
|
||||
const modules = sorted.map((_, index) => ` featureModule${index},`).join("\n");
|
||||
const featureImports = imports.length > 0 ? `${imports}\n` : "";
|
||||
return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\nimport type { FeatureModule } from "../features/feature-module.ts";\n${featureImports}\nexport const PRODUCT_FEATURE_MODULES = Object.freeze([\n${modules}\n] as const);\n\ntype GeneratedProductFeatureModule = (typeof PRODUCT_FEATURE_MODULES)[number];\nexport type ProductFeatureModule =\n [GeneratedProductFeatureModule] extends [never]\n ? FeatureModule\n : GeneratedProductFeatureModule;\n`;
|
||||
}
|
||||
|
||||
export function renderContextIndex(entries: readonly FeatureIndexEntry[]): string {
|
||||
if (entries.length === 0) {
|
||||
return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\nexport const PRODUCT_CONTEXT_MODULES = Object.freeze([] as const);\n`;
|
||||
}
|
||||
const sorted = [...entries].sort((left, right) => left.id.localeCompare(right.id));
|
||||
const imports = sorted
|
||||
.map(
|
||||
(entry, index) =>
|
||||
`import { FEATURE_MODULE as featureModule${index} } from ${JSON.stringify(entry.importPath)};`,
|
||||
)
|
||||
.join("\n");
|
||||
const indexById = new Map(sorted.map((entry, index) => [entry.id, index] as const));
|
||||
const grouped = new Map<string, FeatureIndexEntry[]>();
|
||||
for (const entry of sorted) {
|
||||
const group = grouped.get(entry.contextId) ?? [];
|
||||
group.push(entry);
|
||||
grouped.set(entry.contextId, group);
|
||||
}
|
||||
|
||||
const contexts = [...grouped.entries()]
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([contextId, features]) => {
|
||||
const first = features[0];
|
||||
if (!first) throw new Error(`Context ${contextId} has no features`);
|
||||
for (const feature of features) {
|
||||
if (feature.contextRoutePath !== first.contextRoutePath) {
|
||||
throw new Error(
|
||||
`Context ${contextId} has conflicting route paths: ${first.contextRoutePath}, ${feature.contextRoutePath}`,
|
||||
);
|
||||
}
|
||||
if (feature.contextMaxFeatures !== first.contextMaxFeatures) {
|
||||
throw new Error(
|
||||
`Context ${contextId} has conflicting maxFeatures budgets: ${first.contextMaxFeatures}, ${feature.contextMaxFeatures}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (features.length > first.contextMaxFeatures) {
|
||||
throw new Error(
|
||||
`Context ${contextId} feature cardinality ${features.length} exceeds budget ${first.contextMaxFeatures}`,
|
||||
);
|
||||
}
|
||||
const featureRefs = features
|
||||
.map((feature) => `featureModule${indexById.get(feature.id)}`)
|
||||
.join(", ");
|
||||
const routeImports = features
|
||||
.map(
|
||||
(feature, index) =>
|
||||
` import(${JSON.stringify(`../features/${feature.directory}/context-routes.ts`)})${index < features.length - 1 ? "," : ""}`,
|
||||
)
|
||||
.join("\n");
|
||||
const routeSpreads = features
|
||||
.map((_, index) => ` ...routeModule${index}.FEATURE_CONTEXT_ROUTES,`)
|
||||
.join("\n");
|
||||
const routeBindings = features
|
||||
.map((_, index) => `routeModule${index}`)
|
||||
.join(", ");
|
||||
return ` defineBoundedContextModule({\n id: ${JSON.stringify(contextId)},\n features: Object.freeze([${featureRefs}]),\n budget: Object.freeze({ maxFeatures: ${first.contextMaxFeatures} }),\n route: Object.freeze({\n path: ${JSON.stringify(first.contextRoutePath)},\n async loadRoutes() {\n const [${routeBindings}] = await Promise.all([\n${routeImports}\n ]);\n return Object.freeze([\n${routeSpreads}\n ]);\n },\n }),\n }),`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
const featureImports = imports.length > 0 ? `${imports}\n` : "";
|
||||
return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\nimport { defineBoundedContextModule } from "../contexts/bounded-context-module.ts";\n${featureImports}\nexport const PRODUCT_CONTEXT_MODULES = Object.freeze([\n${contexts}\n] as const);\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spec §3.2 / §5. Ownership declarations the generator reads. Each boundary
|
||||
* declares only its parent:
|
||||
*
|
||||
* src/apps/<app>/app-module.ts APP_MODULE_ID, APP_MAX_CONTEXTS
|
||||
* src/contexts/<context>/context-module.ts CONTEXT_MODULE_ID, CONTEXT_APP_ID,
|
||||
* CONTEXT_ROUTE_PATH, CONTEXT_MAX_FEATURES
|
||||
* src/features/<feature>/feature-module.ts FEATURE_MODULE_ID, FEATURE_CONTEXT_ID
|
||||
*
|
||||
* The generated indexes describe exactly one deployable app: the contexts it
|
||||
* owns and the features those contexts own. Features of other apps are never
|
||||
* imported, so global growth elsewhere cannot enter this app's compile or
|
||||
* boot graph.
|
||||
*/
|
||||
export type AppDeclaration = Readonly<{ id: string; maxContexts: number }>;
|
||||
export type ContextDeclaration = Readonly<{
|
||||
id: string;
|
||||
appId: string;
|
||||
routePath: string;
|
||||
maxFeatures: number;
|
||||
}>;
|
||||
export type FeatureDeclaration = Readonly<{
|
||||
id: string;
|
||||
contextId: string;
|
||||
directory: string;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* Ownership-indexed view of the declarations. The generator only asks for one
|
||||
* app, that app's contexts and those contexts' features, so its work and its
|
||||
* output are local to the selected app.
|
||||
*/
|
||||
export interface TopologyDeclarationSource {
|
||||
appIds(): readonly string[];
|
||||
app(appId: string): AppDeclaration | undefined;
|
||||
contextsOf(appId: string): readonly ContextDeclaration[];
|
||||
featuresOf(contextId: string): readonly FeatureDeclaration[];
|
||||
}
|
||||
|
||||
export type SelectedAppIndexes = Readonly<{
|
||||
app: AppDeclaration;
|
||||
entries: readonly FeatureIndexEntry[];
|
||||
featureIndex: string;
|
||||
contextIndex: string;
|
||||
appIndex: string;
|
||||
}>;
|
||||
|
||||
export function renderAppIndex(app: AppDeclaration): string {
|
||||
return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.
|
||||
export const PRODUCT_APP = Object.freeze({
|
||||
id: ${JSON.stringify(app.id)},
|
||||
maxContexts: ${app.maxContexts},
|
||||
} as const);
|
||||
`;
|
||||
}
|
||||
|
||||
export function resolveSelectedApp(
|
||||
source: TopologyDeclarationSource,
|
||||
requested: string | undefined,
|
||||
): string {
|
||||
if (requested) {
|
||||
if (!source.app(requested)) throw new Error(`Unknown deployable app: ${requested}`);
|
||||
return requested;
|
||||
}
|
||||
const ids = source.appIds();
|
||||
if (ids.length !== 1) {
|
||||
throw new Error(
|
||||
`Select a deployable app with --app=<id> or PRODUCT_APP_ID (declared: ${ids.join(", ") || "none"})`,
|
||||
);
|
||||
}
|
||||
return ids[0] as string;
|
||||
}
|
||||
|
||||
/** The production selection: one app -> its direct contexts -> their features. */
|
||||
export function selectAppIndexes(
|
||||
source: TopologyDeclarationSource,
|
||||
appId: string,
|
||||
): SelectedAppIndexes {
|
||||
const app = source.app(appId);
|
||||
if (!app) throw new Error(`Unknown deployable app: ${appId}`);
|
||||
const contexts = [...source.contextsOf(appId)].sort((left, right) =>
|
||||
left.id.localeCompare(right.id),
|
||||
);
|
||||
const entries: FeatureIndexEntry[] = [];
|
||||
let populatedContexts = 0;
|
||||
for (const context of contexts) {
|
||||
const features = source.featuresOf(context.id);
|
||||
if (features.length === 0) continue;
|
||||
populatedContexts += 1;
|
||||
if (features.length > context.maxFeatures) {
|
||||
throw new Error(
|
||||
`Context ${context.id} feature cardinality ${features.length} exceeds budget ${context.maxFeatures}`,
|
||||
);
|
||||
}
|
||||
for (const feature of features) {
|
||||
entries.push({
|
||||
id: feature.id,
|
||||
importPath: `../features/${feature.directory}/feature-module.ts`,
|
||||
directory: feature.directory,
|
||||
contextId: context.id,
|
||||
contextRoutePath: context.routePath,
|
||||
contextMaxFeatures: context.maxFeatures,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (populatedContexts > app.maxContexts) {
|
||||
throw new Error(
|
||||
`App ${app.id} context cardinality ${populatedContexts} exceeds budget ${app.maxContexts}`,
|
||||
);
|
||||
}
|
||||
const ids = entries.map((entry) => entry.id);
|
||||
if (new Set(ids).size !== ids.length) {
|
||||
throw new Error(`Duplicate generated feature ids: ${ids.join(", ")}`);
|
||||
}
|
||||
return Object.freeze({
|
||||
app,
|
||||
entries: Object.freeze(entries),
|
||||
featureIndex: renderFeatureIndex(entries),
|
||||
contextIndex: renderContextIndex(entries),
|
||||
appIndex: renderAppIndex(app),
|
||||
});
|
||||
}
|
||||
|
||||
function requiredLiteral(source: string, name: string, file: string): string {
|
||||
const match = source.match(
|
||||
new RegExp(`export\\s+const\\s+${name}\\s*=\\s*["']([^"']+)["']`),
|
||||
);
|
||||
if (!match?.[1]) {
|
||||
throw new Error(`${file} must export a literal ${name}`);
|
||||
}
|
||||
return match[1];
|
||||
}
|
||||
|
||||
function requiredInteger(source: string, name: string, file: string): number {
|
||||
const match = source.match(
|
||||
new RegExp(`export\\s+const\\s+${name}\\s*=\\s*(\\d+)`),
|
||||
);
|
||||
const parsed = match?.[1] ? Number.parseInt(match[1], 10) : Number.NaN;
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 1) {
|
||||
throw new Error(`${file} must export a positive integer ${name}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
async function readDeclarations(
|
||||
directory: string,
|
||||
fileName: string,
|
||||
): Promise<readonly Readonly<{ directory: string; file: string; source: string }>[]> {
|
||||
const found: { directory: string; file: string; source: string }[] = [];
|
||||
let items;
|
||||
try {
|
||||
items = await readdir(directory, { withFileTypes: true });
|
||||
} catch {
|
||||
return found;
|
||||
}
|
||||
for (const item of items) {
|
||||
if (!item.isDirectory()) continue;
|
||||
const file = resolve(directory, item.name, fileName);
|
||||
try {
|
||||
found.push({ directory: item.name, file, source: await readFile(file, "utf8") });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filesystem declaration source. Declarations are small literal headers, so
|
||||
* reading them is a metadata scan; only the selected app's features are ever
|
||||
* imported by the generated output.
|
||||
*/
|
||||
export async function createFileSystemDeclarationSource(
|
||||
root: string,
|
||||
): Promise<TopologyDeclarationSource> {
|
||||
const apps = new Map<string, AppDeclaration>();
|
||||
for (const declaration of await readDeclarations(resolve(root, "src/apps"), "app-module.ts")) {
|
||||
const id = requiredLiteral(declaration.source, "APP_MODULE_ID", declaration.file);
|
||||
if (apps.has(id)) throw new Error(`Duplicate app id: ${id}`);
|
||||
apps.set(id, {
|
||||
id,
|
||||
maxContexts: requiredInteger(declaration.source, "APP_MAX_CONTEXTS", declaration.file),
|
||||
});
|
||||
}
|
||||
const contextsByApp = new Map<string, ContextDeclaration[]>();
|
||||
const contextIds = new Set<string>();
|
||||
for (const declaration of await readDeclarations(resolve(root, "src/contexts"), "context-module.ts")) {
|
||||
const context: ContextDeclaration = {
|
||||
id: requiredLiteral(declaration.source, "CONTEXT_MODULE_ID", declaration.file),
|
||||
appId: requiredLiteral(declaration.source, "CONTEXT_APP_ID", declaration.file),
|
||||
routePath: requiredLiteral(declaration.source, "CONTEXT_ROUTE_PATH", declaration.file),
|
||||
maxFeatures: requiredInteger(declaration.source, "CONTEXT_MAX_FEATURES", declaration.file),
|
||||
};
|
||||
if (contextIds.has(context.id)) throw new Error(`Duplicate context id: ${context.id}`);
|
||||
if (!apps.has(context.appId)) {
|
||||
throw new Error(`Context ${context.id} belongs to undeclared app ${context.appId}`);
|
||||
}
|
||||
contextIds.add(context.id);
|
||||
const owned = contextsByApp.get(context.appId) ?? [];
|
||||
owned.push(context);
|
||||
contextsByApp.set(context.appId, owned);
|
||||
}
|
||||
const featuresByContext = new Map<string, FeatureDeclaration[]>();
|
||||
const featureIds = new Set<string>();
|
||||
for (const declaration of await readDeclarations(resolve(root, "src/features"), "feature-module.ts")) {
|
||||
const feature: FeatureDeclaration = {
|
||||
id: requiredLiteral(declaration.source, "FEATURE_MODULE_ID", declaration.file),
|
||||
contextId: requiredLiteral(declaration.source, "FEATURE_CONTEXT_ID", declaration.file),
|
||||
directory: declaration.directory,
|
||||
};
|
||||
if (featureIds.has(feature.id)) throw new Error(`Duplicate generated feature ids: ${feature.id}`);
|
||||
if (!contextIds.has(feature.contextId)) {
|
||||
throw new Error(`Feature ${feature.id} belongs to undeclared context ${feature.contextId}`);
|
||||
}
|
||||
featureIds.add(feature.id);
|
||||
const owned = featuresByContext.get(feature.contextId) ?? [];
|
||||
owned.push(feature);
|
||||
featuresByContext.set(feature.contextId, owned);
|
||||
}
|
||||
return Object.freeze({
|
||||
appIds: () => [...apps.keys()].sort(),
|
||||
app: (appId: string) => apps.get(appId),
|
||||
contextsOf: (appId: string) => contextsByApp.get(appId) ?? [],
|
||||
featuresOf: (contextId: string) => featuresByContext.get(contextId) ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
export async function generateAppIndexes(
|
||||
root: string,
|
||||
requestedApp: string | undefined,
|
||||
): Promise<SelectedAppIndexes> {
|
||||
const source = await createFileSystemDeclarationSource(root);
|
||||
return selectAppIndexes(source, resolveSelectedApp(source, requestedApp));
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||
// `--root=` points the same production command at another checkout (used by
|
||||
// the multi-app topology evidence); the default is this repository.
|
||||
const rootArgument = process.argv
|
||||
.find((argument) => argument.startsWith("--root="))
|
||||
?.slice("--root=".length);
|
||||
const root = rootArgument ? resolve(rootArgument) : resolve(scriptDir, "..");
|
||||
const outputRoot = resolve(root, "src/.generated");
|
||||
const outputs = {
|
||||
feature: resolve(outputRoot, "product-feature-index.ts"),
|
||||
context: resolve(outputRoot, "product-context-index.ts"),
|
||||
app: resolve(outputRoot, "product-app.ts"),
|
||||
};
|
||||
const requestedApp =
|
||||
process.argv.find((argument) => argument.startsWith("--app="))?.slice("--app=".length) ||
|
||||
process.env["PRODUCT_APP_ID"] ||
|
||||
undefined;
|
||||
const selected = await generateAppIndexes(root, requestedApp);
|
||||
const rendered = {
|
||||
feature: selected.featureIndex,
|
||||
context: selected.contextIndex,
|
||||
app: selected.appIndex,
|
||||
};
|
||||
await mkdir(outputRoot, { recursive: true });
|
||||
|
||||
if (process.argv.includes("--check")) {
|
||||
const stale: string[] = [];
|
||||
for (const key of ["feature", "context", "app"] as const) {
|
||||
const current = await readFile(outputs[key], "utf8").catch(() => "");
|
||||
if (current !== rendered[key]) stale.push(relative(root, outputs[key]));
|
||||
}
|
||||
if (stale.length > 0) {
|
||||
throw new Error(`Generated topology index is stale: ${stale.join(", ")}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
(["feature", "context", "app"] as const).map((key) =>
|
||||
writeFile(outputs[key], rendered[key], "utf8"),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
await main();
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
/**
|
||||
* Spec §48. Machine-readable benchmark result.
|
||||
*/
|
||||
export type BenchmarkProfile = "S0" | "S1" | "S2" | "S3" | "S4";
|
||||
|
||||
export interface BenchmarkResult {
|
||||
readonly name: string;
|
||||
readonly profile: BenchmarkProfile;
|
||||
readonly cardinality: number;
|
||||
readonly samples: readonly number[];
|
||||
readonly medianMs: number;
|
||||
readonly heapBytes?: number;
|
||||
readonly metadata: Readonly<Record<string, string | number | boolean>>;
|
||||
}
|
||||
|
||||
export type BenchmarkArtifact = Readonly<{
|
||||
schemaVersion: 1;
|
||||
suite: string;
|
||||
generatedAt: string;
|
||||
node: string;
|
||||
passed: boolean;
|
||||
results: readonly BenchmarkResult[];
|
||||
checks: readonly Readonly<{ name: string; passed: boolean; detail: string }>[];
|
||||
}>;
|
||||
|
||||
const PROFILES: ReadonlySet<string> = new Set(["S0", "S1", "S2", "S3", "S4"]);
|
||||
|
||||
export function median(values: readonly number[]): number {
|
||||
if (values.length === 0) throw new TypeError("median of an empty series");
|
||||
const sorted = [...values].sort((left, right) => left - right);
|
||||
const middle = Math.floor(sorted.length / 2);
|
||||
return sorted.length % 2 === 1
|
||||
? (sorted[middle] as number)
|
||||
: ((sorted[middle - 1] as number) + (sorted[middle] as number)) / 2;
|
||||
}
|
||||
|
||||
export function assertBenchmarkResult(value: BenchmarkResult): BenchmarkResult {
|
||||
if (typeof value.name !== "string" || value.name.length === 0) {
|
||||
throw new TypeError("benchmark name required");
|
||||
}
|
||||
if (!PROFILES.has(value.profile)) {
|
||||
throw new TypeError(`unknown benchmark profile ${String(value.profile)}`);
|
||||
}
|
||||
if (!Number.isSafeInteger(value.cardinality) || value.cardinality < 0) {
|
||||
throw new TypeError("benchmark cardinality must be a non-negative integer");
|
||||
}
|
||||
if (
|
||||
value.samples.length === 0 ||
|
||||
value.samples.some((sample) => !Number.isFinite(sample) || sample < 0)
|
||||
) {
|
||||
throw new TypeError("benchmark samples must be finite non-negative numbers");
|
||||
}
|
||||
if (value.medianMs !== median(value.samples)) {
|
||||
throw new TypeError("benchmark medianMs must be the median of its samples");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export async function writeBenchmarkArtifact(
|
||||
path: string,
|
||||
artifact: BenchmarkArtifact,
|
||||
): Promise<void> {
|
||||
for (const result of artifact.results) assertBenchmarkResult(result);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, `${JSON.stringify(artifact, null, 2)}\n`);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
import {
|
||||
assertBenchmarkResult,
|
||||
median,
|
||||
type BenchmarkProfile,
|
||||
type BenchmarkResult,
|
||||
} from "./benchmark-result.ts";
|
||||
|
||||
/**
|
||||
* Spec §49. Repeated samples with a median, so one noisy scheduler slice can
|
||||
* neither fail a linear implementation nor hide a slow one.
|
||||
*
|
||||
* `run` either does the work (and is timed here) or returns a duration it
|
||||
* measured itself, which lets tests inject exact durations.
|
||||
*/
|
||||
export type BenchmarkOptions = Readonly<{
|
||||
samples: number;
|
||||
warmup?: number;
|
||||
profile?: BenchmarkProfile;
|
||||
cardinality?: number;
|
||||
metadata?: Readonly<Record<string, string | number | boolean>>;
|
||||
measureHeap?: boolean;
|
||||
run: () => unknown;
|
||||
}>;
|
||||
|
||||
function heapUsed(): number {
|
||||
return process.memoryUsage().heapUsed;
|
||||
}
|
||||
|
||||
export async function benchmark(
|
||||
name: string,
|
||||
options: BenchmarkOptions,
|
||||
): Promise<BenchmarkResult> {
|
||||
if (!Number.isSafeInteger(options.samples) || options.samples < 1) {
|
||||
throw new TypeError("benchmark samples must be a positive integer");
|
||||
}
|
||||
for (let index = 0; index < (options.warmup ?? 0); index += 1) {
|
||||
await options.run();
|
||||
}
|
||||
const samples: number[] = [];
|
||||
let peakHeapDelta = 0;
|
||||
for (let index = 0; index < options.samples; index += 1) {
|
||||
const heapBefore = options.measureHeap ? heapUsed() : 0;
|
||||
const startedAt = performance.now();
|
||||
const reported = await options.run();
|
||||
const elapsed = performance.now() - startedAt;
|
||||
if (options.measureHeap) {
|
||||
peakHeapDelta = Math.max(peakHeapDelta, heapUsed() - heapBefore);
|
||||
}
|
||||
samples.push(typeof reported === "number" && Number.isFinite(reported) ? reported : elapsed);
|
||||
}
|
||||
return assertBenchmarkResult(
|
||||
Object.freeze({
|
||||
name,
|
||||
profile: options.profile ?? "S0",
|
||||
cardinality: options.cardinality ?? 0,
|
||||
samples: Object.freeze(samples),
|
||||
medianMs: median(samples),
|
||||
...(options.measureHeap ? { heapBytes: Math.max(0, peakHeapDelta) } : {}),
|
||||
metadata: Object.freeze({ ...(options.metadata ?? {}) }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
import { createReadStream } from "node:fs";
|
||||
import { access, mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
classifyCounterSeries,
|
||||
classifyMemorySlope,
|
||||
type MemorySlopeClass,
|
||||
} from "./memory-slope.ts";
|
||||
|
||||
/**
|
||||
* Spec §33 / §44. Browser soak on the existing Playwright runner.
|
||||
*
|
||||
* Serves the built `dist/` on an OS-assigned 127.0.0.1 port and keeps one
|
||||
* long-lived page cycling through the app's routes by client-side navigation.
|
||||
* The served runtime config turns telemetry on (pointed at a local collector)
|
||||
* and points the API at a stub that always answers 503, so every cycle also
|
||||
* exercises bounded retries and telemetry under a sustained backend failure.
|
||||
*
|
||||
* Collected per sample: JS heap, DOM nodes, event listeners, live timers,
|
||||
* in-flight fetches, Web Storage size. Collected overall: cycles, navigation
|
||||
* failures, API requests, telemetry POSTs/events. Without a build or browser
|
||||
* the result is `skipped` (never a pass); too little evidence fails.
|
||||
*/
|
||||
export type SoakSample = Readonly<{
|
||||
elapsedMs: number;
|
||||
cycles: number;
|
||||
heapBytes: number;
|
||||
domNodes: number;
|
||||
listeners: number;
|
||||
activeTimers: number;
|
||||
inFlightRequests: number;
|
||||
storageKeys: number;
|
||||
storageBytes: number;
|
||||
}>;
|
||||
|
||||
export type SoakSummary = Readonly<{
|
||||
cycles: number;
|
||||
navigationFailures: number;
|
||||
maxHeapBytes: number;
|
||||
heapClassification: MemorySlopeClass;
|
||||
listenerDelta: number;
|
||||
listenerClassification: MemorySlopeClass;
|
||||
timerDelta: number;
|
||||
maxActiveTimers: number;
|
||||
domNodeDelta: number;
|
||||
maxInFlightRequests: number;
|
||||
finalInFlightRequests: number;
|
||||
storageKeyDelta: number;
|
||||
storageByteDelta: number;
|
||||
apiRequests: number;
|
||||
referenceVisits: number;
|
||||
settledReferenceVisits: number;
|
||||
apiRequestsPerReferenceVisit: number;
|
||||
telemetryPosts: number;
|
||||
telemetryEvents: number;
|
||||
maxTelemetryPostsPerMinute: number;
|
||||
}>;
|
||||
|
||||
export type SoakCheck = Readonly<{ name: string; passed: boolean; detail: string }>;
|
||||
|
||||
export type SoakArtifact = Readonly<{
|
||||
schemaVersion: 2;
|
||||
status: "passed" | "failed" | "skipped";
|
||||
reason?: string;
|
||||
durationMs: number;
|
||||
classification?: MemorySlopeClass;
|
||||
summary?: SoakSummary;
|
||||
checks?: readonly SoakCheck[];
|
||||
/** Identity of the soaked build (from dist/release-manifest.json). */
|
||||
build?: Readonly<{ buildId?: string; releaseId?: string; builtAt?: string }>;
|
||||
browser?: string;
|
||||
samples: readonly SoakSample[];
|
||||
}>;
|
||||
|
||||
/** Thresholds a soak must meet; each is checked and recorded by name. */
|
||||
export const SOAK_LIMITS = Object.freeze({
|
||||
minCycles: 200,
|
||||
minPostWarmupSamples: 3,
|
||||
maxListenerDelta: 50,
|
||||
maxTimerDelta: 10,
|
||||
maxStorageKeyDelta: 2,
|
||||
/** One logical execution: 1 attempt + at most 2 retries. */
|
||||
maxApiRequestsPerReferenceVisit: 3,
|
||||
/** Two bounded pipelines (platform events + feature events) x 20/min. */
|
||||
maxTelemetryPostsPerMinute: 40,
|
||||
});
|
||||
|
||||
export function summarizeSoak(
|
||||
samples: readonly Pick<SoakSample, "elapsedMs" | "heapBytes">[],
|
||||
warmupMs: number,
|
||||
): MemorySlopeClass {
|
||||
return classifyMemorySlope(
|
||||
samples.map((sample) => ({
|
||||
minute: sample.elapsedMs / 60_000,
|
||||
heapMb: sample.heapBytes / (1024 * 1024),
|
||||
})),
|
||||
{ warmupMinutes: warmupMs / 60_000, maxSlopeMbPerMinute: 1, maxRelativeGrowth: 0.2 },
|
||||
);
|
||||
}
|
||||
|
||||
export type SoakTotals = Readonly<{
|
||||
cycles: number;
|
||||
navigationFailures: number;
|
||||
referenceVisits: number;
|
||||
settledReferenceVisits: number;
|
||||
finalInFlightRequests: number;
|
||||
apiRequests: number;
|
||||
telemetryPosts: number;
|
||||
telemetryEvents: number;
|
||||
telemetryPostTimes: readonly number[];
|
||||
}>;
|
||||
|
||||
export function evaluateSoak(
|
||||
samples: readonly SoakSample[],
|
||||
totals: SoakTotals,
|
||||
warmupMs: number,
|
||||
): Readonly<{ summary: SoakSummary; checks: readonly SoakCheck[] }> {
|
||||
const measured = samples.filter((sample) => sample.elapsedMs >= warmupMs);
|
||||
const first = measured[0];
|
||||
const last = measured[measured.length - 1];
|
||||
const delta = (pick: (sample: SoakSample) => number) =>
|
||||
first && last ? pick(last) - pick(first) : 0;
|
||||
let maxTelemetryPostsPerMinute = 0;
|
||||
for (const time of totals.telemetryPostTimes) {
|
||||
const inWindow = totals.telemetryPostTimes.filter(
|
||||
(other) => other >= time && other < time + 60_000,
|
||||
).length;
|
||||
maxTelemetryPostsPerMinute = Math.max(maxTelemetryPostsPerMinute, inWindow);
|
||||
}
|
||||
const summary: SoakSummary = {
|
||||
cycles: totals.cycles,
|
||||
navigationFailures: totals.navigationFailures,
|
||||
maxHeapBytes: Math.max(0, ...samples.map((sample) => sample.heapBytes)),
|
||||
heapClassification: summarizeSoak(samples, warmupMs),
|
||||
listenerDelta: delta((sample) => sample.listeners),
|
||||
listenerClassification: classifyCounterSeries(
|
||||
measured.map((sample) => sample.listeners),
|
||||
{ maxSlopePerSample: 1 },
|
||||
),
|
||||
timerDelta: delta((sample) => sample.activeTimers),
|
||||
maxActiveTimers: Math.max(0, ...samples.map((sample) => sample.activeTimers)),
|
||||
domNodeDelta: delta((sample) => sample.domNodes),
|
||||
maxInFlightRequests: Math.max(0, ...samples.map((sample) => sample.inFlightRequests)),
|
||||
finalInFlightRequests: totals.finalInFlightRequests,
|
||||
storageKeyDelta: delta((sample) => sample.storageKeys),
|
||||
storageByteDelta: delta((sample) => sample.storageBytes),
|
||||
apiRequests: totals.apiRequests,
|
||||
referenceVisits: totals.referenceVisits,
|
||||
settledReferenceVisits: totals.settledReferenceVisits,
|
||||
apiRequestsPerReferenceVisit:
|
||||
totals.referenceVisits === 0
|
||||
? 0
|
||||
: Math.round((totals.apiRequests / totals.referenceVisits) * 1_000) / 1_000,
|
||||
telemetryPosts: totals.telemetryPosts,
|
||||
telemetryEvents: totals.telemetryEvents,
|
||||
maxTelemetryPostsPerMinute,
|
||||
};
|
||||
const checks: SoakCheck[] = [
|
||||
{ name: "cycles", passed: summary.cycles >= SOAK_LIMITS.minCycles, detail: `${summary.cycles} >= ${SOAK_LIMITS.minCycles}` },
|
||||
{
|
||||
name: "post-warmup samples",
|
||||
passed: measured.length >= SOAK_LIMITS.minPostWarmupSamples,
|
||||
detail: `${measured.length} >= ${SOAK_LIMITS.minPostWarmupSamples}`,
|
||||
},
|
||||
{ name: "navigation", passed: summary.navigationFailures === 0, detail: `${summary.navigationFailures} failures` },
|
||||
{ name: "heap slope", passed: summary.heapClassification === "stable", detail: summary.heapClassification },
|
||||
{
|
||||
name: "listeners",
|
||||
passed:
|
||||
summary.listenerClassification === "stable" &&
|
||||
summary.listenerDelta <= SOAK_LIMITS.maxListenerDelta,
|
||||
detail: `${summary.listenerClassification}, delta ${summary.listenerDelta}`,
|
||||
},
|
||||
{
|
||||
name: "timers",
|
||||
passed: summary.timerDelta <= SOAK_LIMITS.maxTimerDelta,
|
||||
detail: `delta ${summary.timerDelta}, max ${summary.maxActiveTimers}`,
|
||||
},
|
||||
{
|
||||
name: "in-flight settles",
|
||||
passed: summary.finalInFlightRequests === 0,
|
||||
detail: `final ${summary.finalInFlightRequests}, max ${summary.maxInFlightRequests}`,
|
||||
},
|
||||
{
|
||||
name: "storage growth",
|
||||
passed: summary.storageKeyDelta <= SOAK_LIMITS.maxStorageKeyDelta,
|
||||
detail: `keys ${summary.storageKeyDelta}, bytes ${summary.storageByteDelta}`,
|
||||
},
|
||||
{
|
||||
name: "backend failure exercised",
|
||||
passed:
|
||||
summary.settledReferenceVisits > 0 && summary.apiRequests > 0 && summary.telemetryEvents > 0,
|
||||
detail: `${summary.settledReferenceVisits} settled visits, ${summary.apiRequests} API requests, ${summary.telemetryEvents} telemetry events`,
|
||||
},
|
||||
{
|
||||
name: "request amplification",
|
||||
passed:
|
||||
summary.referenceVisits > 0 &&
|
||||
summary.apiRequestsPerReferenceVisit <= SOAK_LIMITS.maxApiRequestsPerReferenceVisit,
|
||||
detail: `${summary.apiRequests} requests / ${summary.referenceVisits} visits`,
|
||||
},
|
||||
{
|
||||
name: "telemetry rate",
|
||||
passed: summary.maxTelemetryPostsPerMinute <= SOAK_LIMITS.maxTelemetryPostsPerMinute,
|
||||
detail: `max ${summary.maxTelemetryPostsPerMinute}/min, ${summary.telemetryPosts} posts, ${summary.telemetryEvents} events`,
|
||||
},
|
||||
];
|
||||
return { summary, checks };
|
||||
}
|
||||
|
||||
const CONTENT_TYPES: Readonly<Record<string, string>> = {
|
||||
".css": "text/css; charset=utf-8",
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".json": "application/json; charset=utf-8",
|
||||
".svg": "image/svg+xml",
|
||||
".png": "image/png",
|
||||
".webmanifest": "application/manifest+json",
|
||||
};
|
||||
|
||||
type Counters = {
|
||||
apiRequests: number;
|
||||
telemetryPosts: number;
|
||||
telemetryEvents: number;
|
||||
telemetryPostTimes: number[];
|
||||
};
|
||||
|
||||
async function serveSoakTarget(
|
||||
root: string,
|
||||
counters: Counters,
|
||||
startedAt: () => number,
|
||||
): Promise<Readonly<{ server: Server; baseUrl: string }>> {
|
||||
let baseUrl = "";
|
||||
const baseConfig = JSON.parse(
|
||||
await readFile(path.join(root, "config.json"), "utf8"),
|
||||
) as Record<string, unknown>;
|
||||
const server = createServer(async (request, response) => {
|
||||
try {
|
||||
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
||||
if (url.pathname === "/__telemetry") {
|
||||
let body = "";
|
||||
request.on("data", (chunk: Buffer) => {
|
||||
body += chunk.toString("utf8");
|
||||
});
|
||||
request.on("end", () => {
|
||||
counters.telemetryPosts += 1;
|
||||
counters.telemetryPostTimes.push(Date.now() - startedAt());
|
||||
try {
|
||||
const parsed = JSON.parse(body) as { events?: unknown[] };
|
||||
counters.telemetryEvents += Array.isArray(parsed.events) ? parsed.events.length : 0;
|
||||
} catch {
|
||||
// Counted as a post regardless of its body.
|
||||
}
|
||||
response.writeHead(204).end();
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) {
|
||||
counters.apiRequests += 1;
|
||||
response.writeHead(503, { "Content-Type": "application/json" }).end("{}");
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/config.json") {
|
||||
response
|
||||
.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" })
|
||||
.end(
|
||||
JSON.stringify({
|
||||
...baseConfig,
|
||||
API_BASE_URL: `${baseUrl}/api/`,
|
||||
TELEMETRY_ENABLED: true,
|
||||
TELEMETRY_ENDPOINT: `${baseUrl}/__telemetry`,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const requested = path.resolve(root, `.${decodeURIComponent(url.pathname)}`);
|
||||
if (requested !== root && !requested.startsWith(`${root}${path.sep}`)) {
|
||||
response.writeHead(403).end();
|
||||
return;
|
||||
}
|
||||
const details = await stat(requested).catch(() => null);
|
||||
const file = details?.isFile() ? requested : path.join(root, "index.html");
|
||||
response.writeHead(200, {
|
||||
"Content-Type": CONTENT_TYPES[path.extname(file)] ?? "application/octet-stream",
|
||||
"Cache-Control": "no-store",
|
||||
});
|
||||
createReadStream(file).pipe(response);
|
||||
} catch {
|
||||
response.writeHead(404).end();
|
||||
}
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
baseUrl = `http://127.0.0.1:${port}`;
|
||||
return { server, baseUrl };
|
||||
}
|
||||
|
||||
const PAGE_PROBES = `
|
||||
(() => {
|
||||
const live = new Set();
|
||||
const setT = window.setTimeout, clearT = window.clearTimeout;
|
||||
const setI = window.setInterval, clearI = window.clearInterval;
|
||||
window.setTimeout = (fn, ms, ...rest) => {
|
||||
const id = setT(() => { live.delete(id); typeof fn === "function" && fn(...rest); }, ms);
|
||||
live.add(id); return id;
|
||||
};
|
||||
window.clearTimeout = (id) => { live.delete(id); clearT(id); };
|
||||
window.setInterval = (fn, ms, ...rest) => { const id = setI(fn, ms, ...rest); live.add(id); return id; };
|
||||
window.clearInterval = (id) => { live.delete(id); clearI(id); };
|
||||
let inFlight = 0;
|
||||
const nativeFetch = window.fetch.bind(window);
|
||||
window.fetch = (...args) => {
|
||||
inFlight += 1;
|
||||
return nativeFetch(...args).finally(() => { inFlight -= 1; });
|
||||
};
|
||||
const storageSize = (storage) => {
|
||||
let bytes = 0;
|
||||
for (let i = 0; i < storage.length; i += 1) {
|
||||
const key = storage.key(i) ?? "";
|
||||
bytes += key.length + (storage.getItem(key) ?? "").length;
|
||||
}
|
||||
return { keys: storage.length, bytes };
|
||||
};
|
||||
Object.defineProperty(window, "__soakProbe", {
|
||||
value: () => {
|
||||
const local = storageSize(window.localStorage);
|
||||
const session = storageSize(window.sessionStorage);
|
||||
return {
|
||||
activeTimers: live.size,
|
||||
inFlight,
|
||||
storageKeys: local.keys + session.keys,
|
||||
storageBytes: local.bytes + session.bytes,
|
||||
};
|
||||
},
|
||||
});
|
||||
})();
|
||||
`;
|
||||
|
||||
type Probe = { activeTimers: number; inFlight: number; storageKeys: number; storageBytes: number };
|
||||
|
||||
export async function runBrowserSoak(
|
||||
options: Readonly<{
|
||||
distRoot: string;
|
||||
durationMs: number;
|
||||
intervalMs: number;
|
||||
warmupMs: number;
|
||||
routes: readonly string[];
|
||||
}>,
|
||||
): Promise<SoakArtifact> {
|
||||
try {
|
||||
await access(path.join(options.distRoot, "index.html"));
|
||||
await access(path.join(options.distRoot, "config.json"));
|
||||
} catch {
|
||||
return {
|
||||
schemaVersion: 2,
|
||||
status: "skipped",
|
||||
reason: "no built dist/index.html + config.json",
|
||||
durationMs: 0,
|
||||
samples: [],
|
||||
};
|
||||
}
|
||||
let chromium: (typeof import("@playwright/test"))["chromium"];
|
||||
try {
|
||||
({ chromium } = await import("@playwright/test"));
|
||||
} catch {
|
||||
return { schemaVersion: 2, status: "skipped", reason: "playwright unavailable", durationMs: 0, samples: [] };
|
||||
}
|
||||
const counters: Counters = {
|
||||
apiRequests: 0,
|
||||
telemetryPosts: 0,
|
||||
telemetryEvents: 0,
|
||||
telemetryPostTimes: [],
|
||||
};
|
||||
let started = Date.now();
|
||||
const { server, baseUrl } = await serveSoakTarget(
|
||||
path.resolve(options.distRoot),
|
||||
counters,
|
||||
() => started,
|
||||
);
|
||||
let browser: Awaited<ReturnType<typeof chromium.launch>> | undefined;
|
||||
try {
|
||||
try {
|
||||
browser = await chromium.launch();
|
||||
} catch (error) {
|
||||
return {
|
||||
schemaVersion: 2,
|
||||
status: "skipped",
|
||||
reason: `browser unavailable: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`,
|
||||
durationMs: 0,
|
||||
samples: [],
|
||||
};
|
||||
}
|
||||
const page = await browser.newPage();
|
||||
await page.addInitScript(PAGE_PROBES);
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
await cdp.send("Performance.enable");
|
||||
await page.goto(`${baseUrl}/examples/reference-resources`, { waitUntil: "load" });
|
||||
await page.waitForSelector("#root > *", { timeout: 15_000 });
|
||||
// Protected routes need a session: start the local demo session once, so
|
||||
// the reference feature really dispatches its (failing) API requests.
|
||||
const login = page.getByRole("button", { name: /로그인 시작|Sign in|Start sign-in/u });
|
||||
if (await login.count()) {
|
||||
await login.first().click();
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
|
||||
const samples: SoakSample[] = [];
|
||||
started = Date.now();
|
||||
let nextSample = 0;
|
||||
let cycles = 0;
|
||||
let navigationFailures = 0;
|
||||
let referenceVisits = 0;
|
||||
let settledReferenceVisits = 0;
|
||||
const probe = async () =>
|
||||
(await page.evaluate(() =>
|
||||
(window as unknown as { __soakProbe: () => Probe }).__soakProbe(),
|
||||
)) as Probe;
|
||||
while (Date.now() - started < options.durationMs) {
|
||||
const route = options.routes[cycles % options.routes.length] ?? "/";
|
||||
cycles += 1;
|
||||
if (route === "/examples/reference-resources") referenceVisits += 1;
|
||||
// Client-side navigation keeps one long-lived document, like a real session.
|
||||
await page.evaluate((target) => {
|
||||
window.history.pushState({}, "", target);
|
||||
window.dispatchEvent(new PopStateEvent("popstate"));
|
||||
}, route);
|
||||
await page.waitForTimeout(50);
|
||||
const rendered = await page.evaluate(
|
||||
(target) =>
|
||||
window.location.pathname === target &&
|
||||
(document.getElementById("root")?.childElementCount ?? 0) > 0,
|
||||
route,
|
||||
);
|
||||
if (!rendered) navigationFailures += 1;
|
||||
// Most visits leave after 50ms, which cancels the query (a cancelled
|
||||
// request is intentionally not reported). Every 5th reference visit
|
||||
// dwells until its interaction settles, so the failing backend is really
|
||||
// observed end to end: bounded retries, then feature/platform telemetry.
|
||||
if (route === "/examples/reference-resources" && referenceVisits % 5 === 1) {
|
||||
await page.waitForTimeout(200);
|
||||
await page
|
||||
.waitForFunction(
|
||||
() => (window as unknown as { __soakProbe: () => Probe }).__soakProbe().inFlight === 0,
|
||||
undefined,
|
||||
{ timeout: 5_000 },
|
||||
)
|
||||
.catch(() => undefined);
|
||||
settledReferenceVisits += 1;
|
||||
}
|
||||
const elapsedMs = Date.now() - started;
|
||||
if (elapsedMs >= nextSample) {
|
||||
nextSample = elapsedMs + options.intervalMs;
|
||||
await cdp.send("HeapProfiler.collectGarbage").catch(() => undefined);
|
||||
const { metrics } = (await cdp.send("Performance.getMetrics")) as {
|
||||
metrics: { name: string; value: number }[];
|
||||
};
|
||||
const metric = (name: string) => metrics.find((entry) => entry.name === name)?.value ?? 0;
|
||||
const probed = await probe();
|
||||
samples.push({
|
||||
elapsedMs,
|
||||
cycles,
|
||||
heapBytes: metric("JSHeapUsedSize"),
|
||||
domNodes: metric("Nodes"),
|
||||
listeners: metric("JSEventListeners"),
|
||||
activeTimers: probed.activeTimers,
|
||||
inFlightRequests: probed.inFlight,
|
||||
storageKeys: probed.storageKeys,
|
||||
storageBytes: probed.storageBytes,
|
||||
});
|
||||
}
|
||||
}
|
||||
// Let the last interaction's bounded retries and deadlines settle.
|
||||
let finalInFlightRequests = (await probe()).inFlight;
|
||||
for (let wait = 0; wait < 30 && finalInFlightRequests > 0; wait += 1) {
|
||||
await page.waitForTimeout(500);
|
||||
finalInFlightRequests = (await probe()).inFlight;
|
||||
}
|
||||
const evaluation = evaluateSoak(
|
||||
samples,
|
||||
{
|
||||
cycles,
|
||||
navigationFailures,
|
||||
referenceVisits,
|
||||
settledReferenceVisits,
|
||||
finalInFlightRequests,
|
||||
apiRequests: counters.apiRequests,
|
||||
telemetryPosts: counters.telemetryPosts,
|
||||
telemetryEvents: counters.telemetryEvents,
|
||||
telemetryPostTimes: counters.telemetryPostTimes,
|
||||
},
|
||||
options.warmupMs,
|
||||
);
|
||||
const build = await readFile(path.join(options.distRoot, "release-manifest.json"), "utf8")
|
||||
.then((raw) => {
|
||||
const manifest = JSON.parse(raw) as Record<string, unknown>;
|
||||
const pick = (key: string) =>
|
||||
typeof manifest[key] === "string" ? (manifest[key] as string) : undefined;
|
||||
return {
|
||||
...(pick("buildId") ? { buildId: pick("buildId") } : {}),
|
||||
...(pick("releaseId") ? { releaseId: pick("releaseId") } : {}),
|
||||
...(pick("builtAt") ? { builtAt: pick("builtAt") } : {}),
|
||||
};
|
||||
})
|
||||
.catch(() => ({}));
|
||||
return {
|
||||
schemaVersion: 2,
|
||||
status: evaluation.checks.every((check) => check.passed) ? "passed" : "failed",
|
||||
durationMs: options.durationMs,
|
||||
classification: evaluation.summary.heapClassification,
|
||||
summary: evaluation.summary,
|
||||
checks: evaluation.checks,
|
||||
build,
|
||||
browser: `chromium ${browser.version()}`,
|
||||
samples,
|
||||
};
|
||||
} finally {
|
||||
await browser?.close().catch(() => undefined);
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const argument = (name: string, fallback: string) =>
|
||||
process.argv.find((entry) => entry.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback;
|
||||
const artifact = path.resolve(argument("artifact", "artifacts/scale/browser-soak.json"));
|
||||
const result = await runBrowserSoak({
|
||||
distRoot: argument("dist", "dist"),
|
||||
durationMs: Number(argument("duration-ms", "60000")),
|
||||
intervalMs: Number(argument("interval-ms", "5000")),
|
||||
warmupMs: Number(argument("warmup-ms", "15000")),
|
||||
routes: argument(
|
||||
"routes",
|
||||
"/,/examples/reference-resources,/examples/platform,/examples/ui,/examples/states,/examples/reference-resources/status",
|
||||
).split(","),
|
||||
});
|
||||
await mkdir(path.dirname(artifact), { recursive: true });
|
||||
await writeFile(artifact, `${JSON.stringify(result, null, 2)}\n`);
|
||||
process.stdout.write(
|
||||
`browser soak: ${result.status}${result.reason ? ` (${result.reason})` : ""}` +
|
||||
`${result.classification ? ` classification=${result.classification}` : ""} samples=${result.samples.length}` +
|
||||
`${result.summary ? ` cycles=${result.summary.cycles}` : ""}\n`,
|
||||
);
|
||||
for (const check of result.checks ?? []) {
|
||||
process.stdout.write(`${check.passed ? "PASS" : "FAIL"} ${check.name} (${check.detail})\n`);
|
||||
}
|
||||
if (result.status === "failed") process.exitCode = 1;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
await main();
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { collectTscScale } from "./collect-tsc-diagnostics.ts";
|
||||
import { runCompositionScale } from "./run-composition-scale.ts";
|
||||
import {
|
||||
approveBaseline,
|
||||
compareToBaseline,
|
||||
currentEnvironment,
|
||||
snapshotMetrics,
|
||||
type ScaleBaseline,
|
||||
} from "./scale-baseline.ts";
|
||||
|
||||
/**
|
||||
* Spec §48–§49. Relative regression gate against the stored, approved scale
|
||||
* baseline (`config/scale/benchmark-baseline.json`).
|
||||
*
|
||||
* node scripts/scale/check-scale-baseline.ts compare, fail on regression
|
||||
* SCALE_BASELINE_OWNER=... SCALE_BASELINE_REASON=... \
|
||||
* node scripts/scale/check-scale-baseline.ts --update re-measure and re-approve
|
||||
*
|
||||
* The comparison is written to artifacts/scale/baseline-comparison.json (or
|
||||
* `--artifact=`). Updating is an explicit, attributed act; the check never
|
||||
* rewrites the baseline.
|
||||
*/
|
||||
export const BASELINE_PATH = "config/scale/benchmark-baseline.json";
|
||||
export const LOCAL_TSC_SIZES = Object.freeze([25, 100, 400]);
|
||||
|
||||
function typescriptVersion(): string {
|
||||
const result = spawnSync(path.resolve("node_modules/.bin/tsc"), ["-v"], { encoding: "utf8" });
|
||||
const match = /Version\s+(\S+)/u.exec(result.stdout ?? "");
|
||||
if (!match?.[1]) throw new Error("cannot determine TypeScript version");
|
||||
return match[1];
|
||||
}
|
||||
|
||||
async function measure() {
|
||||
const composition = await runCompositionScale(["S0", "S1", "S2"], { samples: 9, warmup: 2 });
|
||||
const compiler = await collectTscScale(LOCAL_TSC_SIZES);
|
||||
return snapshotMetrics(composition.results, compiler);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const update = process.argv.includes("--update");
|
||||
const artifact = path.resolve(
|
||||
process.argv.find((entry) => entry.startsWith("--artifact="))?.slice("--artifact=".length) ??
|
||||
"artifacts/scale/baseline-comparison.json",
|
||||
);
|
||||
const environment = currentEnvironment(typescriptVersion());
|
||||
const metrics = await measure();
|
||||
|
||||
if (update) {
|
||||
const owner = process.env["SCALE_BASELINE_OWNER"];
|
||||
const reason = process.env["SCALE_BASELINE_REASON"];
|
||||
if (!owner || !reason) {
|
||||
process.stderr.write("SCALE_BASELINE_OWNER and SCALE_BASELINE_REASON are required.\n");
|
||||
process.exit(1);
|
||||
}
|
||||
const baseline = approveBaseline(environment, metrics, {
|
||||
owner,
|
||||
reason,
|
||||
approvedAt: new Date().toISOString(),
|
||||
});
|
||||
await mkdir(path.dirname(BASELINE_PATH), { recursive: true });
|
||||
await writeFile(BASELINE_PATH, `${JSON.stringify(baseline, null, 2)}\n`);
|
||||
process.stdout.write(`scale baseline approved: ${baseline.approval.metricsDigest}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
let baseline: ScaleBaseline;
|
||||
try {
|
||||
baseline = JSON.parse(await readFile(BASELINE_PATH, "utf8")) as ScaleBaseline;
|
||||
} catch {
|
||||
process.stderr.write(`missing or unreadable ${BASELINE_PATH}; run update:scale-baseline\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
const comparison = compareToBaseline(baseline, environment, metrics);
|
||||
await mkdir(path.dirname(artifact), { recursive: true });
|
||||
await writeFile(
|
||||
artifact,
|
||||
`${JSON.stringify(
|
||||
{ schemaVersion: 1, generatedAt: new Date().toISOString(), environment, baselineApproval: baseline.approval, ...comparison },
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
const { compatibility } = comparison;
|
||||
process.stdout.write(
|
||||
`compatibility: structural=${compatibility.structural.ok} compiler=${compatibility.compiler.ok} timing=${compatibility.timing.ok}\n`,
|
||||
);
|
||||
if (!compatibility.timing.ok) {
|
||||
process.stdout.write(
|
||||
`timing regression NOT compared (incomplete): ${compatibility.timing.reasons.join("; ")}\n`,
|
||||
);
|
||||
}
|
||||
process.stdout.write(
|
||||
`axes: absolute ${comparison.absolute.findings.length} (${comparison.absolute.passed ? "ok" : "FAIL"}), ` +
|
||||
`growth ${comparison.growth.findings.length} (${comparison.growth.passed ? "ok" : "FAIL"}), ` +
|
||||
`relative ${comparison.compiler.length} compiler + ${comparison.timing.length} timing\n`,
|
||||
);
|
||||
for (const failure of comparison.failures) process.stdout.write(`FAIL ${failure}\n`);
|
||||
process.stdout.write(
|
||||
`scale baseline gate: ${comparison.status.toUpperCase()} (${path.relative(process.cwd(), artifact)})\n`,
|
||||
);
|
||||
if (comparison.status === "failed") process.exitCode = 1;
|
||||
else if (comparison.status === "incomplete" && process.env["SCALE_ALLOW_INCOMPLETE"] !== "1") {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
await main();
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import {
|
||||
assertLinearOrBetter,
|
||||
growthExponents,
|
||||
} from "../../src/platform/cardinality/growth-regression.ts";
|
||||
|
||||
/**
|
||||
* Spec §38. TypeScript scale gate.
|
||||
*
|
||||
* Parses `tsc --extendedDiagnostics` and measures bounded local fixtures:
|
||||
* generated feature modules composed by one context, at increasing local
|
||||
* cardinality. S3/S4 are never compiled; they are verified as topology.
|
||||
*/
|
||||
export type TscDiagnostics = Readonly<{
|
||||
files: number;
|
||||
lines?: number;
|
||||
types: number;
|
||||
symbols: number;
|
||||
instantiations: number;
|
||||
memoryKb?: number;
|
||||
totalTimeSeconds?: number;
|
||||
}>;
|
||||
|
||||
const FIELD_NAMES: Readonly<Record<string, keyof TscDiagnostics>> = Object.freeze({
|
||||
Files: "files",
|
||||
Lines: "lines",
|
||||
Types: "types",
|
||||
Symbols: "symbols",
|
||||
Instantiations: "instantiations",
|
||||
"Memory used": "memoryKb",
|
||||
"Total time": "totalTimeSeconds",
|
||||
});
|
||||
|
||||
export function parseTscExtendedDiagnostics(text: string): TscDiagnostics {
|
||||
const parsed: Partial<Record<keyof TscDiagnostics, number>> = {};
|
||||
for (const line of text.split(/\r?\n/u)) {
|
||||
const match = /^\s*([A-Za-z][A-Za-z ]*?):\s+([\d.]+)\s*([KMs]?)\s*$/u.exec(line);
|
||||
if (!match) continue;
|
||||
const field = FIELD_NAMES[match[1] as string];
|
||||
if (!field) continue;
|
||||
const value = Number(match[2]);
|
||||
if (!Number.isFinite(value)) continue;
|
||||
parsed[field] = match[3] === "M" ? value * 1024 : value;
|
||||
}
|
||||
for (const required of ["files", "types", "symbols", "instantiations"] as const) {
|
||||
if (parsed[required] === undefined) {
|
||||
throw new TypeError(`tsc diagnostics missing ${required}`);
|
||||
}
|
||||
}
|
||||
return Object.freeze(parsed) as TscDiagnostics;
|
||||
}
|
||||
|
||||
export function runTscDiagnostics(project: string, cwd = process.cwd()): TscDiagnostics {
|
||||
const tsc = resolve(cwd, "node_modules/.bin/tsc");
|
||||
const result = spawnSync(tsc, ["--project", project, "--noEmit", "--extendedDiagnostics"], {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
});
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`tsc failed for ${project}: ${(result.stdout + result.stderr).slice(-2_000)}`);
|
||||
}
|
||||
return parseTscExtendedDiagnostics(result.stdout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates one bounded local app: `features` feature modules, each with its
|
||||
* own typed contract, composed by one generated index. The shape mirrors the
|
||||
* repository's feature-module/generated-index pattern.
|
||||
*/
|
||||
export async function writeLocalTscFixture(
|
||||
root: string,
|
||||
features: number,
|
||||
): Promise<string> {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
await mkdir(join(root, "features"), { recursive: true });
|
||||
const imports: string[] = [];
|
||||
const members: string[] = [];
|
||||
for (let index = 0; index < features; index += 1) {
|
||||
const id = `feature${index}`;
|
||||
await writeFile(
|
||||
join(root, "features", `${id}.ts`),
|
||||
`export type ${id}Input = Readonly<{ id: string; limit: number; tags?: readonly string[] }>;\n` +
|
||||
`export type ${id}Output = Readonly<{ items: readonly Readonly<{ id: string; name: string }>[] }>;\n` +
|
||||
`export const ${id} = Object.freeze({\n` +
|
||||
` id: "${id}" as const,\n` +
|
||||
` routes: Object.freeze({ ${id.toUpperCase()}_LIST: "/${id}" }),\n` +
|
||||
` execute(input: ${id}Input): ${id}Output {\n` +
|
||||
` return { items: [{ id: input.id, name: String(input.limit) }] };\n` +
|
||||
` },\n` +
|
||||
`});\n`,
|
||||
);
|
||||
imports.push(`import { ${id} } from "./features/${id}.ts";`);
|
||||
members.push(` ${id},`);
|
||||
}
|
||||
await writeFile(
|
||||
join(root, "index.ts"),
|
||||
`${imports.join("\n")}\nexport const LOCAL_FEATURES = Object.freeze([\n${members.join("\n")}\n] as const);\n` +
|
||||
`export type LocalFeatureId = (typeof LOCAL_FEATURES)[number]["id"];\n`,
|
||||
);
|
||||
const tsconfig = join(root, "tsconfig.json");
|
||||
await writeFile(
|
||||
tsconfig,
|
||||
JSON.stringify(
|
||||
{
|
||||
compilerOptions: {
|
||||
target: "ES2022",
|
||||
module: "ESNext",
|
||||
moduleResolution: "Bundler",
|
||||
allowImportingTsExtensions: true,
|
||||
strict: true,
|
||||
noEmit: true,
|
||||
skipLibCheck: true,
|
||||
types: [],
|
||||
lib: ["ES2022"],
|
||||
},
|
||||
include: ["index.ts", "features/*.ts"],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
return tsconfig;
|
||||
}
|
||||
|
||||
export type TscScaleReport = Readonly<{
|
||||
passed: boolean;
|
||||
app: TscDiagnostics;
|
||||
local: readonly Readonly<{ features: number; diagnostics: TscDiagnostics }>[];
|
||||
checks: readonly Readonly<{ name: string; passed: boolean; detail: string }>[];
|
||||
}>;
|
||||
|
||||
export async function collectTscScale(
|
||||
localSizes: readonly number[],
|
||||
cwd = process.cwd(),
|
||||
): Promise<TscScaleReport> {
|
||||
const app = runTscDiagnostics("tsconfig.app.json", cwd);
|
||||
const local: { features: number; diagnostics: TscDiagnostics }[] = [];
|
||||
for (const features of localSizes) {
|
||||
const tsconfig = await writeLocalTscFixture(
|
||||
resolve(cwd, ".tmp/scale-tsc", `local-${features}`),
|
||||
features,
|
||||
);
|
||||
local.push({ features, diagnostics: runTscDiagnostics(tsconfig, cwd) });
|
||||
}
|
||||
const checks: { name: string; passed: boolean; detail: string }[] = [];
|
||||
for (const metric of ["types", "symbols", "instantiations"] as const) {
|
||||
const series = local.map(({ features, diagnostics }) => ({
|
||||
n: features,
|
||||
// Library/baseline cost is constant; growth is judged on what the local
|
||||
// features add on top of the smallest fixture.
|
||||
cost: Math.max(1, diagnostics[metric]),
|
||||
}));
|
||||
try {
|
||||
assertLinearOrBetter(series, { maxExponent: 1.3 });
|
||||
checks.push({
|
||||
name: `tsc:${metric}`,
|
||||
passed: true,
|
||||
detail: `exponents ${growthExponents(series).map((value) => value.toFixed(2)).join(", ")}`,
|
||||
});
|
||||
} catch (error) {
|
||||
checks.push({
|
||||
name: `tsc:${metric}`,
|
||||
passed: false,
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
return Object.freeze({
|
||||
passed: checks.every((check) => check.passed),
|
||||
app,
|
||||
local: Object.freeze(local),
|
||||
checks: Object.freeze(checks),
|
||||
});
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const artifactArg = process.argv.find((argument) => argument.startsWith("--artifact="));
|
||||
const sizesArg = process.argv.find((argument) => argument.startsWith("--local-sizes="));
|
||||
const sizes = (sizesArg?.slice("--local-sizes=".length) ?? "25,100,400")
|
||||
.split(",")
|
||||
.map(Number)
|
||||
.filter((value) => Number.isSafeInteger(value) && value > 0);
|
||||
const artifact = resolve(
|
||||
artifactArg?.slice("--artifact=".length) ?? "artifacts/scale/tsc-diagnostics.json",
|
||||
);
|
||||
const report = await collectTscScale(sizes);
|
||||
await mkdir(resolve(artifact, ".."), { recursive: true });
|
||||
await writeFile(
|
||||
artifact,
|
||||
`${JSON.stringify({ schemaVersion: 1, generatedAt: new Date().toISOString(), ...report }, null, 2)}\n`,
|
||||
);
|
||||
process.stdout.write(
|
||||
`tsc app: files=${report.app.files} types=${report.app.types} instantiations=${report.app.instantiations}\n`,
|
||||
);
|
||||
for (const check of report.checks) {
|
||||
process.stdout.write(`${check.passed ? "PASS" : "FAIL"} ${check.name} (${check.detail})\n`);
|
||||
}
|
||||
process.stdout.write(`tsc diagnostics artifact: ${artifact}\n`);
|
||||
if (!report.passed) process.exitCode = 1;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
await main();
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { composeUniqueRecord } from "../../src/platform/cardinality/compose-unique-record.ts";
|
||||
import {
|
||||
resolveProductFeatures,
|
||||
selectCompiledProductFeatures,
|
||||
} from "../../src/contracts/product-features.ts";
|
||||
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts";
|
||||
import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts";
|
||||
|
||||
/**
|
||||
* Spec §39. Scale-sensitive production composition paths, each parameterized
|
||||
* by one cardinality `n`. Inputs are built outside the timed region.
|
||||
*/
|
||||
export type CompositionWorkload = Readonly<{
|
||||
name: string;
|
||||
implementation: string;
|
||||
prepare(n: number): () => unknown;
|
||||
}>;
|
||||
|
||||
export function createUniqueRegistryParts(
|
||||
count: number,
|
||||
): readonly Readonly<Record<string, number>>[] {
|
||||
return Array.from({ length: count }, (_, index) =>
|
||||
Object.freeze({ [`route-${index}`]: index }),
|
||||
);
|
||||
}
|
||||
|
||||
function featureIds(count: number): string[] {
|
||||
return Array.from(
|
||||
{ length: count },
|
||||
(_, index) => `feature-${index.toString().padStart(7, "0")}`,
|
||||
);
|
||||
}
|
||||
|
||||
const CONTEXT_FEATURES = 200;
|
||||
|
||||
export const COMPOSITION_WORKLOADS: readonly CompositionWorkload[] = Object.freeze([
|
||||
{
|
||||
name: "registry-composition",
|
||||
implementation: "composeUniqueRecord",
|
||||
prepare(n: number) {
|
||||
const parts = createUniqueRegistryParts(n);
|
||||
return () => composeUniqueRecord(parts, () => "route");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "product-feature-selection",
|
||||
implementation: "selectCompiledProductFeatures",
|
||||
prepare(n: number) {
|
||||
const compiled = featureIds(n).map((featureId) => Object.freeze({ featureId }));
|
||||
const declared = compiled
|
||||
.filter((_, index) => index % 2 === 0)
|
||||
.map((feature) => feature.featureId)
|
||||
.join(",");
|
||||
return () => selectCompiledProductFeatures(compiled, declared);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "product-feature-resolution",
|
||||
implementation: "resolveProductFeatures",
|
||||
prepare(n: number) {
|
||||
const compiled = featureIds(n);
|
||||
const installed = compiled.filter((_, index) => index % 3 !== 0);
|
||||
return () => resolveProductFeatures(compiled, installed);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "context-hierarchy-composition",
|
||||
implementation: "defineBoundedContextModule+defineDeployableAppModule",
|
||||
prepare(n: number) {
|
||||
const features = featureIds(n).map((id) =>
|
||||
Object.freeze({
|
||||
id,
|
||||
contracts: Object.freeze({ featureId: id }),
|
||||
routes: Object.freeze({}),
|
||||
adapters: Object.freeze([]),
|
||||
runtimes: Object.freeze([]),
|
||||
messages: Object.freeze({}),
|
||||
contractContributions: Object.freeze([]),
|
||||
}),
|
||||
);
|
||||
const contextCount = Math.ceil(n / CONTEXT_FEATURES);
|
||||
return () => {
|
||||
const contexts = Array.from({ length: contextCount }, (_, contextIndex) =>
|
||||
defineBoundedContextModule({
|
||||
id: `context-${contextIndex}`,
|
||||
features: features.slice(
|
||||
contextIndex * CONTEXT_FEATURES,
|
||||
(contextIndex + 1) * CONTEXT_FEATURES,
|
||||
),
|
||||
budget: Object.freeze({ maxFeatures: CONTEXT_FEATURES }),
|
||||
}),
|
||||
);
|
||||
// Apps are sharded by the same direct-child budget.
|
||||
const apps: unknown[] = [];
|
||||
for (let index = 0; index < contexts.length; index += 20) {
|
||||
apps.push(
|
||||
defineDeployableAppModule({
|
||||
id: `app-${index / 20}`,
|
||||
contexts: contexts.slice(index, index + 20),
|
||||
budget: Object.freeze({ maxContexts: 20 }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return apps;
|
||||
};
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Spec §44. Soak classification.
|
||||
*
|
||||
* The leak signal is sustained positive growth after warm-up, not an
|
||||
* arbitrary absolute maximum. The classifier fits a least-squares line over
|
||||
* the post-warm-up samples and reports `unbounded-growth` only when both the
|
||||
* slope and the total relative growth are material.
|
||||
*/
|
||||
export type SlopeSample = Readonly<{ minute: number; heapMb: number }>;
|
||||
|
||||
export type MemorySlopeClass = "stable" | "unbounded-growth" | "insufficient-data";
|
||||
|
||||
export type MemorySlopeOptions = Readonly<{
|
||||
/** Samples before this minute are warm-up. Default 0. */
|
||||
warmupMinutes?: number;
|
||||
/** Largest tolerated post-warm-up slope in MB per minute. Default 0.5. */
|
||||
maxSlopeMbPerMinute?: number;
|
||||
/** Largest tolerated relative growth first->last fitted value. Default 0.1. */
|
||||
maxRelativeGrowth?: number;
|
||||
}>;
|
||||
|
||||
export function linearSlope(points: readonly Readonly<{ x: number; y: number }>[]): number {
|
||||
const count = points.length;
|
||||
if (count < 2) return 0;
|
||||
const meanX = points.reduce((sum, point) => sum + point.x, 0) / count;
|
||||
const meanY = points.reduce((sum, point) => sum + point.y, 0) / count;
|
||||
let numerator = 0;
|
||||
let denominator = 0;
|
||||
for (const point of points) {
|
||||
numerator += (point.x - meanX) * (point.y - meanY);
|
||||
denominator += (point.x - meanX) ** 2;
|
||||
}
|
||||
return denominator === 0 ? 0 : numerator / denominator;
|
||||
}
|
||||
|
||||
export function classifyMemorySlope(
|
||||
samples: readonly SlopeSample[],
|
||||
options: MemorySlopeOptions = {},
|
||||
): MemorySlopeClass {
|
||||
const warmup = options.warmupMinutes ?? 0;
|
||||
const maxSlope = options.maxSlopeMbPerMinute ?? 0.5;
|
||||
const maxGrowth = options.maxRelativeGrowth ?? 0.1;
|
||||
const measured = samples
|
||||
.filter((sample) => sample.minute >= warmup)
|
||||
.filter((sample) => Number.isFinite(sample.minute) && Number.isFinite(sample.heapMb))
|
||||
.sort((left, right) => left.minute - right.minute);
|
||||
if (measured.length < 3) return "insufficient-data";
|
||||
const slope = linearSlope(measured.map((sample) => ({ x: sample.minute, y: sample.heapMb })));
|
||||
const first = measured[0] as SlopeSample;
|
||||
const last = measured[measured.length - 1] as SlopeSample;
|
||||
const fittedStart = Math.max(first.heapMb, Number.MIN_VALUE);
|
||||
const growth = (slope * (last.minute - first.minute)) / fittedStart;
|
||||
return slope > maxSlope && growth > maxGrowth ? "unbounded-growth" : "stable";
|
||||
}
|
||||
|
||||
/** Generic variant for logical counters (timers, listeners, buffered events). */
|
||||
export function classifyCounterSeries(
|
||||
values: readonly number[],
|
||||
options: Readonly<{ warmupSamples?: number; maxSlopePerSample?: number }> = {},
|
||||
): MemorySlopeClass {
|
||||
const warmup = options.warmupSamples ?? 0;
|
||||
const measured = values.slice(warmup);
|
||||
if (measured.length < 3) return "insufficient-data";
|
||||
const slope = linearSlope(measured.map((y, x) => ({ x, y })));
|
||||
return slope > (options.maxSlopePerSample ?? 0.01) ? "unbounded-growth" : "stable";
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import {
|
||||
assertLinearOrBetter,
|
||||
growthExponents,
|
||||
} from "../../src/platform/cardinality/growth-regression.ts";
|
||||
import { benchmark } from "./benchmark.ts";
|
||||
import {
|
||||
writeBenchmarkArtifact,
|
||||
type BenchmarkProfile,
|
||||
type BenchmarkResult,
|
||||
} from "./benchmark-result.ts";
|
||||
import { COMPOSITION_WORKLOADS } from "./composition-workloads.ts";
|
||||
|
||||
/**
|
||||
* Spec §36 / §39. Runtime composition scale gate for S0-S2.
|
||||
*
|
||||
* Every production composition workload runs at each requested profile with
|
||||
* warm-up and repeated samples; the median series must be linear-or-better.
|
||||
* Results are written as a machine-readable artifact under artifacts/scale/.
|
||||
*/
|
||||
export const COMPOSITION_PROFILES: Readonly<Record<string, number>> = Object.freeze({
|
||||
S0: 100,
|
||||
S1: 1_000,
|
||||
S2: 10_000,
|
||||
});
|
||||
|
||||
/** Scheduler noise below this median is not evidence of growth. */
|
||||
export const COMPOSITION_NOISE_FLOOR_MS = 0.5;
|
||||
/**
|
||||
* n log n paths (sorting, allocation-heavy string work) measure ~1.1-1.4
|
||||
* between S1 and S2; a quadratic path measures ~2. 1.6 separates the two.
|
||||
*/
|
||||
export const COMPOSITION_MAX_EXPONENT = 1.6;
|
||||
|
||||
export type CompositionScaleReport = Readonly<{
|
||||
passed: boolean;
|
||||
results: readonly BenchmarkResult[];
|
||||
checks: readonly Readonly<{ name: string; passed: boolean; detail: string }>[];
|
||||
}>;
|
||||
|
||||
export async function runCompositionScale(
|
||||
profiles: readonly string[],
|
||||
options: Readonly<{
|
||||
samples?: number;
|
||||
warmup?: number;
|
||||
/**
|
||||
* `median` (default) for standalone gate runs. `min` (best observed) when
|
||||
* the gate shares the machine with other suites: stolen CPU and foreign
|
||||
* GC only ever add time, so the minimum keeps the algorithmic shape.
|
||||
*/
|
||||
statistic?: "median" | "min";
|
||||
}> = {},
|
||||
): Promise<CompositionScaleReport> {
|
||||
const results: BenchmarkResult[] = [];
|
||||
const checks: { name: string; passed: boolean; detail: string }[] = [];
|
||||
for (const workload of COMPOSITION_WORKLOADS) {
|
||||
const series: { n: number; cost: number }[] = [];
|
||||
for (const profile of profiles) {
|
||||
const cardinality = COMPOSITION_PROFILES[profile];
|
||||
if (cardinality === undefined) throw new TypeError(`unknown profile ${profile}`);
|
||||
const run = workload.prepare(cardinality);
|
||||
const result = await benchmark(workload.name, {
|
||||
samples: options.samples ?? 7,
|
||||
warmup: options.warmup ?? 2,
|
||||
profile: profile as BenchmarkProfile,
|
||||
cardinality,
|
||||
measureHeap: true,
|
||||
metadata: { implementation: workload.implementation },
|
||||
run,
|
||||
});
|
||||
results.push(result);
|
||||
series.push({
|
||||
n: cardinality,
|
||||
cost:
|
||||
options.statistic === "min" ? Math.min(...result.samples) : result.medianMs,
|
||||
});
|
||||
}
|
||||
if (series.length < 2) continue;
|
||||
try {
|
||||
assertLinearOrBetter(series, {
|
||||
maxExponent: COMPOSITION_MAX_EXPONENT,
|
||||
noiseFloor: COMPOSITION_NOISE_FLOOR_MS,
|
||||
});
|
||||
checks.push({
|
||||
name: `${workload.name}:growth`,
|
||||
passed: true,
|
||||
detail: `exponents ${growthExponents(series, COMPOSITION_NOISE_FLOOR_MS)
|
||||
.map((exponent) => exponent.toFixed(2))
|
||||
.join(", ")}`,
|
||||
});
|
||||
} catch (error) {
|
||||
checks.push({
|
||||
name: `${workload.name}:growth`,
|
||||
passed: false,
|
||||
detail: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
return Object.freeze({
|
||||
passed: checks.every((check) => check.passed),
|
||||
results: Object.freeze(results),
|
||||
checks: Object.freeze(checks),
|
||||
});
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const profileArg = process.argv.find((argument) => argument.startsWith("--profiles="));
|
||||
const artifactArg = process.argv.find((argument) => argument.startsWith("--artifact="));
|
||||
const profiles = (profileArg?.slice("--profiles=".length) ?? "S0,S1,S2")
|
||||
.split(",")
|
||||
.map((entry) => entry.trim())
|
||||
.filter(Boolean);
|
||||
const artifact = resolve(
|
||||
artifactArg?.slice("--artifact=".length) ?? "artifacts/scale/composition-scale.json",
|
||||
);
|
||||
const report = await runCompositionScale(profiles);
|
||||
await writeBenchmarkArtifact(artifact, {
|
||||
schemaVersion: 1,
|
||||
suite: "composition-scale",
|
||||
generatedAt: new Date().toISOString(),
|
||||
node: process.version,
|
||||
passed: report.passed,
|
||||
results: report.results,
|
||||
checks: report.checks,
|
||||
});
|
||||
for (const check of report.checks) {
|
||||
process.stdout.write(`${check.passed ? "PASS" : "FAIL"} ${check.name} (${check.detail})\n`);
|
||||
}
|
||||
process.stdout.write(`composition scale artifact: ${artifact}\n`);
|
||||
if (!report.passed) process.exitCode = 1;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
await main();
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* Spec §47. CI execution tiers for the scale/chaos/soak program.
|
||||
*
|
||||
* pr S0/S1 architecture, composition and traffic invariants
|
||||
* main pr + S2 composition, TypeScript diagnostics and the stored
|
||||
* baseline regression gate (config/scale/benchmark-baseline.json)
|
||||
* nightly main + S3/S4 topology, telemetry storm, session cycles, browser soak
|
||||
* release release-coherence matrix + the stable main/nightly subset
|
||||
*
|
||||
* Every step's output goes to artifacts/scale/<tier>/<step>.log and the tier
|
||||
* writes one machine-readable summary.json. A step that could not run (e.g. a
|
||||
* browser soak without a build or browser) is `skipped`, and a tier with any
|
||||
* skipped step is `incomplete`: it is never reported as passed and exits
|
||||
* non-zero. `SCALE_ALLOW_INCOMPLETE=1` keeps the exit code zero for local runs,
|
||||
* but the summary still says `incomplete`.
|
||||
*/
|
||||
export type ScaleTier = "pr" | "main" | "nightly" | "release";
|
||||
|
||||
type Step = Readonly<{
|
||||
id: string;
|
||||
command: readonly string[];
|
||||
/** A step that may legitimately report `skipped` in its own artifact. */
|
||||
optional?: boolean;
|
||||
}>;
|
||||
|
||||
const VITEST = ["scripts/run-vitest.ts", "run", "--reporter=default"];
|
||||
|
||||
const PR_STEPS: readonly Step[] = [
|
||||
{
|
||||
id: "architecture-topology",
|
||||
command: [...VITEST, "tests/architecture", "tests/platform/cardinality", "tests/platform/routing"],
|
||||
},
|
||||
{
|
||||
id: "traffic-budgets",
|
||||
command: [...VITEST, "tests/platform/execution", "tests/platform/traffic", "tests/platform/resilience"],
|
||||
},
|
||||
{
|
||||
id: "scale-units",
|
||||
command: [
|
||||
...VITEST,
|
||||
"tests/scale/growth-regression.test.ts",
|
||||
"tests/scale/benchmark.test.ts",
|
||||
"tests/scale/synthetic-topology.test.ts",
|
||||
"tests/scale/scale-baseline.test.ts",
|
||||
"tests/scale/traffic",
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "composition-s0-s1",
|
||||
command: ["scripts/scale/run-composition-scale.ts", "--profiles=S0,S1"],
|
||||
},
|
||||
];
|
||||
|
||||
const MAIN_STEPS: readonly Step[] = [
|
||||
...PR_STEPS,
|
||||
{
|
||||
id: "composition-s0-s2",
|
||||
command: ["scripts/scale/run-composition-scale.ts", "--profiles=S0,S1,S2"],
|
||||
},
|
||||
{
|
||||
id: "composition-scale-suite",
|
||||
command: [...VITEST, "tests/scale/composition-scale.test.ts", "tests/scale/tsc-diagnostics-parser.test.ts"],
|
||||
},
|
||||
{
|
||||
id: "typescript-diagnostics",
|
||||
command: ["scripts/scale/collect-tsc-diagnostics.ts", "--local-sizes=25,100,400"],
|
||||
},
|
||||
{
|
||||
id: "baseline-regression",
|
||||
command: ["scripts/scale/check-scale-baseline.ts"],
|
||||
},
|
||||
];
|
||||
|
||||
const NIGHTLY_STEPS: readonly Step[] = [
|
||||
...MAIN_STEPS,
|
||||
{
|
||||
id: "topology-s3-s4",
|
||||
command: [...VITEST, "tests/scale/global-local-independence.test.ts", "tests/platform/cardinality/extreme-scale-registry.test.ts"],
|
||||
},
|
||||
{
|
||||
id: "telemetry-storm",
|
||||
command: [...VITEST, "tests/scale/telemetry", "tests/platform/telemetry"],
|
||||
},
|
||||
{ id: "session-cycles", command: [...VITEST, "tests/scale/session"] },
|
||||
{
|
||||
id: "browser-soak",
|
||||
command: ["scripts/scale/browser-soak.ts", "--duration-ms=120000", "--interval-ms=5000", "--warmup-ms=30000"],
|
||||
optional: true,
|
||||
},
|
||||
];
|
||||
|
||||
const RELEASE_STEPS: readonly Step[] = [
|
||||
{
|
||||
id: "release-coherence",
|
||||
command: [...VITEST, "tests/platform/release", "tests/release"],
|
||||
},
|
||||
...MAIN_STEPS,
|
||||
{
|
||||
id: "topology-s3-s4",
|
||||
command: [...VITEST, "tests/scale/global-local-independence.test.ts"],
|
||||
},
|
||||
{
|
||||
id: "telemetry-storm",
|
||||
command: [...VITEST, "tests/scale/telemetry"],
|
||||
},
|
||||
];
|
||||
|
||||
export const SCALE_TIERS: Readonly<Record<ScaleTier, readonly Step[]>> = Object.freeze({
|
||||
pr: PR_STEPS,
|
||||
main: MAIN_STEPS,
|
||||
nightly: NIGHTLY_STEPS,
|
||||
release: RELEASE_STEPS,
|
||||
});
|
||||
|
||||
function withArtifact(step: Step, directory: string): readonly string[] {
|
||||
const script = step.command[0] ?? "";
|
||||
if (
|
||||
script.endsWith("run-composition-scale.ts") ||
|
||||
script.endsWith("collect-tsc-diagnostics.ts") ||
|
||||
script.endsWith("browser-soak.ts") ||
|
||||
script.endsWith("check-scale-baseline.ts")
|
||||
) {
|
||||
return [...step.command, `--artifact=${path.join(directory, `${step.id}.json`)}`];
|
||||
}
|
||||
return step.command;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const tier = process.argv[2] as ScaleTier | undefined;
|
||||
if (!tier || !(tier in SCALE_TIERS)) {
|
||||
process.stderr.write(`usage: run-scale-profile.ts <${Object.keys(SCALE_TIERS).join("|")}>\n`);
|
||||
process.exit(2);
|
||||
}
|
||||
const directory = path.resolve("artifacts/scale", tier);
|
||||
await mkdir(directory, { recursive: true });
|
||||
const results: { id: string; status: "passed" | "failed" | "skipped"; durationMs: number; log: string }[] = [];
|
||||
for (const step of SCALE_TIERS[tier]) {
|
||||
const startedAt = Date.now();
|
||||
const run = spawnSync(process.execPath, [...withArtifact(step, directory)], {
|
||||
encoding: "utf8",
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
env: { ...process.env, SCALE_ARTIFACT_DIR: path.join(directory, "metrics") },
|
||||
});
|
||||
const log = path.join(directory, `${step.id}.log`);
|
||||
await writeFile(log, `${run.stdout ?? ""}${run.stderr ?? ""}`);
|
||||
const skipped = step.optional === true && /: skipped/u.test(run.stdout ?? "");
|
||||
const status = run.status === 0 ? (skipped ? "skipped" : "passed") : "failed";
|
||||
results.push({ id: step.id, status, durationMs: Date.now() - startedAt, log: path.relative(process.cwd(), log) });
|
||||
process.stdout.write(`${status.toUpperCase()} ${tier}:${step.id} (${Date.now() - startedAt}ms)\n`);
|
||||
}
|
||||
const failed = results.some((result) => result.status === "failed");
|
||||
const skipped = results.filter((result) => result.status === "skipped").map((result) => result.id);
|
||||
const status = failed ? "failed" : skipped.length > 0 ? "incomplete" : "passed";
|
||||
await writeFile(
|
||||
path.join(directory, "summary.json"),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
schemaVersion: 1,
|
||||
tier,
|
||||
generatedAt: new Date().toISOString(),
|
||||
node: process.version,
|
||||
environment: {
|
||||
node: process.version,
|
||||
nodeMajor: Number(process.versions.node.split(".")[0]),
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
},
|
||||
status,
|
||||
passed: status === "passed",
|
||||
skipped,
|
||||
steps: results,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
process.stdout.write(
|
||||
`scale tier ${tier}: ${status.toUpperCase()}${skipped.length > 0 ? ` (skipped: ${skipped.join(", ")})` : ""} (artifacts/scale/${tier}/summary.json)\n`,
|
||||
);
|
||||
if (status === "failed") process.exitCode = 1;
|
||||
else if (status === "incomplete" && process.env["SCALE_ALLOW_INCOMPLETE"] !== "1") process.exitCode = 1;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
await main();
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { cpus } from "node:os";
|
||||
|
||||
import { growthExponents } from "../../src/platform/cardinality/growth-regression.ts";
|
||||
import type { BenchmarkResult } from "./benchmark-result.ts";
|
||||
import type { TscDiagnostics } from "./collect-tsc-diagnostics.ts";
|
||||
|
||||
/**
|
||||
* Spec §48–§49. Stored benchmark baseline, compatibility check and relative
|
||||
* regression gate.
|
||||
*
|
||||
* The growth gates judge the *shape* of one run. This module compares a run
|
||||
* against an approved stored baseline so a change that keeps the shape but
|
||||
* multiplies the cost (or silently adds compiler work) is still caught.
|
||||
*
|
||||
* Two kinds of metric are compared differently:
|
||||
* - deterministic metrics (TypeScript types/symbols/instantiations/files) are
|
||||
* exact for a given compiler, so they use a tight relative tolerance and
|
||||
* require a compatible toolchain;
|
||||
* - timing metrics depend on the machine, so they use a loose tolerance plus an
|
||||
* absolute noise floor, and are only enforced on a compatible environment.
|
||||
*/
|
||||
export const SCALE_BASELINE_SCHEMA_VERSION = 1;
|
||||
|
||||
export type ScaleEnvironment = Readonly<{
|
||||
nodeMajor: number;
|
||||
platform: string;
|
||||
arch: string;
|
||||
cpuModel: string;
|
||||
cpuCount: number;
|
||||
typescript: string;
|
||||
}>;
|
||||
|
||||
export type TimingEntry = Readonly<{
|
||||
workload: string;
|
||||
profile: string;
|
||||
cardinality: number;
|
||||
medianMs: number;
|
||||
minMs: number;
|
||||
}>;
|
||||
|
||||
export type CompilerEntry = Readonly<{
|
||||
fixture: string;
|
||||
files: number;
|
||||
types: number;
|
||||
symbols: number;
|
||||
instantiations: number;
|
||||
}>;
|
||||
|
||||
export type ScaleMetrics = Readonly<{
|
||||
timing: readonly TimingEntry[];
|
||||
compiler: readonly CompilerEntry[];
|
||||
}>;
|
||||
|
||||
export type ScaleBaseline = Readonly<{
|
||||
schemaVersion: typeof SCALE_BASELINE_SCHEMA_VERSION;
|
||||
environment: ScaleEnvironment;
|
||||
metrics: ScaleMetrics;
|
||||
approval: Readonly<{
|
||||
owner: string;
|
||||
reason: string;
|
||||
approvedAt: string;
|
||||
metricsDigest: string;
|
||||
}>;
|
||||
}>;
|
||||
|
||||
export const REGRESSION_TOLERANCE = Object.freeze({
|
||||
/** Deterministic compiler counts may grow at most 10% without re-approval. */
|
||||
compilerRelative: 0.1,
|
||||
/** Timings may grow at most 2.5x (scheduler/GC noise lives below that)... */
|
||||
timingRelative: 1.5,
|
||||
/** ...and never fail on differences below this absolute noise floor. */
|
||||
timingNoiseFloorMs: 1,
|
||||
});
|
||||
|
||||
/**
|
||||
* Axis 1 — absolute ceilings. Machine-agnostic hard limits (roughly 50x the
|
||||
* approved baseline for timings, ~2x for compiler work) that hold even with
|
||||
* no comparable baseline.
|
||||
*/
|
||||
export const ABSOLUTE_CEILINGS = Object.freeze({
|
||||
timingMinMsByProfile: Object.freeze({ S0: 5, S1: 25, S2: 150 } as Record<string, number>),
|
||||
app: Object.freeze({ files: 1_500, types: 600_000, symbols: 1_600_000, instantiations: 1_500_000 }),
|
||||
/**
|
||||
* Generated `local-<N>` compiler fixtures: a fixed base (lib/runtime
|
||||
* overhead present at any N) plus a per-local-feature allowance.
|
||||
*/
|
||||
localBase: Object.freeze({ files: 100, types: 5_000, symbols: 15_000, instantiations: 5_000 }),
|
||||
localPerFeature: Object.freeze({ files: 2, types: 100, symbols: 250, instantiations: 150 }),
|
||||
});
|
||||
|
||||
/** Axis 3 — growth shape (see src/platform/cardinality/growth-regression.ts). */
|
||||
export const GROWTH_LIMITS = Object.freeze({
|
||||
timingMaxExponent: 1.6,
|
||||
timingNoiseFloorMs: 0.5,
|
||||
compilerMaxExponent: 1.3,
|
||||
});
|
||||
|
||||
export function currentEnvironment(typescript: string): ScaleEnvironment {
|
||||
const cpu = cpus();
|
||||
return Object.freeze({
|
||||
nodeMajor: Number(process.versions.node.split(".")[0]),
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
cpuModel: cpu[0]?.model.trim() ?? "unknown",
|
||||
cpuCount: cpu.length,
|
||||
typescript,
|
||||
});
|
||||
}
|
||||
|
||||
function canonical(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
||||
if (value && typeof value === "object") {
|
||||
return `{${Object.keys(value)
|
||||
.sort()
|
||||
.map((key) => `${JSON.stringify(key)}:${canonical((value as Record<string, unknown>)[key])}`)
|
||||
.join(",")}}`;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
export function metricsDigest(metrics: ScaleMetrics): string {
|
||||
return createHash("sha256").update(canonical(metrics)).digest("hex");
|
||||
}
|
||||
|
||||
export function snapshotMetrics(
|
||||
composition: readonly BenchmarkResult[],
|
||||
compiler: Readonly<{
|
||||
app: TscDiagnostics;
|
||||
local: readonly Readonly<{ features: number; diagnostics: TscDiagnostics }>[];
|
||||
}>,
|
||||
): ScaleMetrics {
|
||||
const round = (value: number) => Math.round(value * 1_000) / 1_000;
|
||||
const toCompiler = (fixture: string, diagnostics: TscDiagnostics): CompilerEntry => ({
|
||||
fixture,
|
||||
files: diagnostics.files,
|
||||
types: diagnostics.types,
|
||||
symbols: diagnostics.symbols,
|
||||
instantiations: diagnostics.instantiations,
|
||||
});
|
||||
return Object.freeze({
|
||||
timing: composition
|
||||
.map((result) => ({
|
||||
workload: result.name,
|
||||
profile: result.profile,
|
||||
cardinality: result.cardinality,
|
||||
medianMs: round(result.medianMs),
|
||||
minMs: round(Math.min(...result.samples)),
|
||||
}))
|
||||
.sort((left, right) =>
|
||||
`${left.workload}/${left.profile}`.localeCompare(`${right.workload}/${right.profile}`),
|
||||
),
|
||||
compiler: [
|
||||
toCompiler("app", compiler.app),
|
||||
...compiler.local.map((entry) => toCompiler(`local-${entry.features}`, entry.diagnostics)),
|
||||
].sort((left, right) => left.fixture.localeCompare(right.fixture)),
|
||||
});
|
||||
}
|
||||
|
||||
export type Compatibility = Readonly<{
|
||||
/** Baseline format, digest and metric coverage are usable at all. */
|
||||
structural: Readonly<{ ok: boolean; reasons: readonly string[] }>;
|
||||
/** Same compiler: deterministic compiler counts are comparable. */
|
||||
compiler: Readonly<{ ok: boolean; reasons: readonly string[] }>;
|
||||
/** Same machine class and runtime: timings are comparable. */
|
||||
timing: Readonly<{ ok: boolean; reasons: readonly string[] }>;
|
||||
}>;
|
||||
|
||||
export function checkCompatibility(
|
||||
baseline: ScaleBaseline,
|
||||
environment: ScaleEnvironment,
|
||||
current: ScaleMetrics,
|
||||
): Compatibility {
|
||||
const structural: string[] = [];
|
||||
if (baseline.schemaVersion !== SCALE_BASELINE_SCHEMA_VERSION) {
|
||||
structural.push(`baseline schemaVersion ${String(baseline.schemaVersion)} is not ${SCALE_BASELINE_SCHEMA_VERSION}`);
|
||||
}
|
||||
if (metricsDigest(baseline.metrics) !== baseline.approval?.metricsDigest) {
|
||||
structural.push("baseline metrics do not match their approved digest (hand-edited?)");
|
||||
}
|
||||
const timingKey = (entry: TimingEntry) => `${entry.workload}/${entry.profile}/${entry.cardinality}`;
|
||||
const baselineTiming = new Set(baseline.metrics.timing.map(timingKey));
|
||||
const baselineCompiler = new Set(baseline.metrics.compiler.map((entry) => entry.fixture));
|
||||
for (const entry of current.timing) {
|
||||
if (!baselineTiming.has(timingKey(entry))) structural.push(`no baseline for timing ${timingKey(entry)}`);
|
||||
}
|
||||
for (const entry of current.compiler) {
|
||||
if (!baselineCompiler.has(entry.fixture)) structural.push(`no baseline for compiler fixture ${entry.fixture}`);
|
||||
}
|
||||
|
||||
const compiler: string[] = [];
|
||||
if (baseline.environment.typescript !== environment.typescript) {
|
||||
compiler.push(`TypeScript ${environment.typescript} differs from baseline ${baseline.environment.typescript}`);
|
||||
}
|
||||
|
||||
const timing: string[] = [];
|
||||
const base = baseline.environment;
|
||||
if (base.nodeMajor !== environment.nodeMajor) timing.push(`Node ${environment.nodeMajor} vs baseline ${base.nodeMajor}`);
|
||||
if (base.platform !== environment.platform || base.arch !== environment.arch) {
|
||||
timing.push(`${environment.platform}/${environment.arch} vs baseline ${base.platform}/${base.arch}`);
|
||||
}
|
||||
if (base.cpuModel !== environment.cpuModel) timing.push(`CPU "${environment.cpuModel}" vs baseline "${base.cpuModel}"`);
|
||||
return Object.freeze({
|
||||
structural: { ok: structural.length === 0, reasons: structural },
|
||||
compiler: { ok: compiler.length === 0, reasons: compiler },
|
||||
timing: { ok: timing.length === 0, reasons: timing },
|
||||
});
|
||||
}
|
||||
|
||||
export type RegressionFinding = Readonly<{
|
||||
metric: string;
|
||||
baseline: number;
|
||||
current: number;
|
||||
limit: number;
|
||||
passed: boolean;
|
||||
}>;
|
||||
|
||||
export type AxisResult = Readonly<{
|
||||
passed: boolean;
|
||||
findings: readonly RegressionFinding[];
|
||||
}>;
|
||||
|
||||
export type BaselineComparison = Readonly<{
|
||||
/**
|
||||
* `passed` only when every axis was evaluated and held. `incomplete` when the
|
||||
* environment is not timing-compatible: timing regression was not compared,
|
||||
* so it is not evidence of a pass.
|
||||
*/
|
||||
status: "passed" | "failed" | "incomplete";
|
||||
passed: boolean;
|
||||
compatibility: Compatibility;
|
||||
absolute: AxisResult;
|
||||
growth: AxisResult;
|
||||
compiler: readonly RegressionFinding[];
|
||||
/** Empty when the environment is not timing-compatible. */
|
||||
timing: readonly RegressionFinding[];
|
||||
failures: readonly string[];
|
||||
}>;
|
||||
|
||||
function finding(metric: string, baseline: number, current: number, limit: number): RegressionFinding {
|
||||
return { metric, baseline, current, limit: Math.round(limit * 1_000) / 1_000, passed: current <= limit };
|
||||
}
|
||||
|
||||
export function checkAbsoluteCeilings(current: ScaleMetrics): AxisResult {
|
||||
const findings: RegressionFinding[] = [];
|
||||
for (const entry of current.timing) {
|
||||
const limit = ABSOLUTE_CEILINGS.timingMinMsByProfile[entry.profile];
|
||||
if (limit !== undefined) {
|
||||
findings.push(finding(`ceiling:time:${entry.workload}/${entry.profile}`, 0, entry.minMs, limit));
|
||||
}
|
||||
}
|
||||
for (const entry of current.compiler) {
|
||||
const local = /^local-(\d+)$/u.exec(entry.fixture);
|
||||
for (const metric of ["files", "types", "symbols", "instantiations"] as const) {
|
||||
const limit = local
|
||||
? ABSOLUTE_CEILINGS.localBase[metric] +
|
||||
ABSOLUTE_CEILINGS.localPerFeature[metric] * Number(local[1])
|
||||
: entry.fixture === "app"
|
||||
? ABSOLUTE_CEILINGS.app[metric]
|
||||
: Number.POSITIVE_INFINITY;
|
||||
findings.push(finding(`ceiling:tsc:${entry.fixture}:${metric}`, 0, entry[metric], limit));
|
||||
}
|
||||
}
|
||||
return { passed: findings.every((item) => item.passed), findings };
|
||||
}
|
||||
|
||||
export function checkGrowthShape(current: ScaleMetrics): AxisResult {
|
||||
const findings: RegressionFinding[] = [];
|
||||
const byWorkload = new Map<string, { n: number; cost: number }[]>();
|
||||
for (const entry of current.timing) {
|
||||
const series = byWorkload.get(entry.workload) ?? [];
|
||||
series.push({ n: entry.cardinality, cost: entry.minMs });
|
||||
byWorkload.set(entry.workload, series);
|
||||
}
|
||||
for (const [workload, series] of byWorkload) {
|
||||
if (series.length < 2) continue;
|
||||
const worst = Math.max(...growthExponents(series, GROWTH_LIMITS.timingNoiseFloorMs));
|
||||
findings.push(finding(`growth:time:${workload}`, 1, Math.round(worst * 1_000) / 1_000, GROWTH_LIMITS.timingMaxExponent));
|
||||
}
|
||||
const local = current.compiler
|
||||
.map((entry) => ({ entry, n: Number(/^local-(\d+)$/u.exec(entry.fixture)?.[1]) }))
|
||||
.filter(({ n }) => Number.isFinite(n));
|
||||
if (local.length >= 2) {
|
||||
for (const metric of ["files", "types", "symbols", "instantiations"] as const) {
|
||||
const worst = Math.max(...growthExponents(local.map(({ entry, n }) => ({ n, cost: entry[metric] }))));
|
||||
findings.push(finding(`growth:tsc:local:${metric}`, 1, Math.round(worst * 1_000) / 1_000, GROWTH_LIMITS.compilerMaxExponent));
|
||||
}
|
||||
}
|
||||
return { passed: findings.every((item) => item.passed), findings };
|
||||
}
|
||||
|
||||
export function compareToBaseline(
|
||||
baseline: ScaleBaseline,
|
||||
environment: ScaleEnvironment,
|
||||
current: ScaleMetrics,
|
||||
tolerance = REGRESSION_TOLERANCE,
|
||||
): BaselineComparison {
|
||||
const compatibility = checkCompatibility(baseline, environment, current);
|
||||
const failures: string[] = [...compatibility.structural.reasons];
|
||||
// A different compiler changes every deterministic count: the baseline must
|
||||
// be re-approved, it is never silently compared or silently skipped.
|
||||
if (!compatibility.compiler.ok) {
|
||||
failures.push(
|
||||
...compatibility.compiler.reasons.map((reason) => `${reason}; re-approve with update:scale-baseline`),
|
||||
);
|
||||
}
|
||||
|
||||
const absolute = checkAbsoluteCeilings(current);
|
||||
const growth = checkGrowthShape(current);
|
||||
for (const item of [...absolute.findings, ...growth.findings]) {
|
||||
if (!item.passed) failures.push(`${item.metric} ${item.current} exceeds ${item.limit}`);
|
||||
}
|
||||
|
||||
const compiler: RegressionFinding[] = [];
|
||||
if (compatibility.structural.ok && compatibility.compiler.ok) {
|
||||
const byFixture = new Map(baseline.metrics.compiler.map((entry) => [entry.fixture, entry]));
|
||||
for (const entry of current.compiler) {
|
||||
const reference = byFixture.get(entry.fixture);
|
||||
if (!reference) continue;
|
||||
for (const metric of ["files", "types", "symbols", "instantiations"] as const) {
|
||||
const item = finding(
|
||||
`tsc:${entry.fixture}:${metric}`,
|
||||
reference[metric],
|
||||
entry[metric],
|
||||
Math.floor(reference[metric] * (1 + tolerance.compilerRelative)),
|
||||
);
|
||||
compiler.push(item);
|
||||
if (!item.passed) {
|
||||
failures.push(`${item.metric} ${item.current} exceeds ${item.limit} (baseline ${item.baseline})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const timing: RegressionFinding[] = [];
|
||||
if (compatibility.structural.ok && compatibility.timing.ok) {
|
||||
const key = (entry: TimingEntry) => `${entry.workload}/${entry.profile}`;
|
||||
const byKey = new Map(baseline.metrics.timing.map((entry) => [key(entry), entry]));
|
||||
for (const entry of current.timing) {
|
||||
const reference = byKey.get(key(entry));
|
||||
if (!reference) continue;
|
||||
// Best-observed samples: contention only ever adds time.
|
||||
const item = finding(
|
||||
`time:${key(entry)}`,
|
||||
reference.minMs,
|
||||
entry.minMs,
|
||||
Math.max(reference.minMs * (1 + tolerance.timingRelative), reference.minMs + tolerance.timingNoiseFloorMs),
|
||||
);
|
||||
timing.push(item);
|
||||
if (!item.passed) {
|
||||
failures.push(`${item.metric} ${item.current}ms exceeds ${item.limit}ms (baseline ${item.baseline}ms)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const status =
|
||||
failures.length > 0 ? "failed" : compatibility.timing.ok ? "passed" : "incomplete";
|
||||
return Object.freeze({
|
||||
status,
|
||||
passed: status === "passed",
|
||||
compatibility,
|
||||
absolute,
|
||||
growth,
|
||||
compiler,
|
||||
timing,
|
||||
failures,
|
||||
});
|
||||
}
|
||||
|
||||
export function approveBaseline(
|
||||
environment: ScaleEnvironment,
|
||||
metrics: ScaleMetrics,
|
||||
approval: Readonly<{ owner: string; reason: string; approvedAt: string }>,
|
||||
): ScaleBaseline {
|
||||
return Object.freeze({
|
||||
schemaVersion: SCALE_BASELINE_SCHEMA_VERSION,
|
||||
environment,
|
||||
metrics,
|
||||
approval: { ...approval, metricsDigest: metricsDigest(metrics) },
|
||||
});
|
||||
}
|
||||
@@ -41,6 +41,8 @@ const commonTestPaths = [
|
||||
const featureOwnedPaths = [
|
||||
featureSource,
|
||||
featureTests,
|
||||
// The sample's bounded-context declaration; the template app stays.
|
||||
"src/contexts/reference-context",
|
||||
"tests/integration/http-scenario-catalog.test.ts",
|
||||
"tests/component/product-feature-switch.test.tsx",
|
||||
"tests/e2e/reference-form.spec.ts",
|
||||
@@ -64,116 +66,6 @@ const featureOwnedPaths = [
|
||||
"tests/fixtures/typecheck/tsconfig.feature-capability-selection.json",
|
||||
];
|
||||
|
||||
const emptyProductManifest = `export const COMPILED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze([]);
|
||||
export const INSTALLED_PRODUCT_FEATURES: readonly never[] = Object.freeze([]);
|
||||
export const INSTALLED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze([]);
|
||||
`;
|
||||
|
||||
const emptyContracts = `import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../contracts/route-runtime-contract.ts";
|
||||
import { PLATFORM_ROUTE_REGISTRY, type RouteDefinition } from "../contracts/routes.ts";
|
||||
import { PLATFORM_SCHEMA_REGISTRY } from "../contracts/schema-registry.ts";
|
||||
import { INSTALLED_PRODUCT_FEATURES } from "./installed-product-manifest.ts";
|
||||
|
||||
export const INSTALLED_FEATURE_CONTRACTS = INSTALLED_PRODUCT_FEATURES;
|
||||
export const ROUTE_REGISTRY = PLATFORM_ROUTE_REGISTRY;
|
||||
export const ROUTE_RUNTIME_CONTRACT = PLATFORM_ROUTE_RUNTIME_CONTRACT;
|
||||
export const API_OPERATIONS = Object.freeze({});
|
||||
export const INVALIDATION_REGISTRY = Object.freeze({
|
||||
topics: Object.freeze([]),
|
||||
namespaces: Object.freeze([]),
|
||||
edges: Object.freeze([]),
|
||||
});
|
||||
export const INVALIDATION_TOPIC_VERSIONS = Object.freeze([]);
|
||||
export const SCHEMA_REGISTRY = PLATFORM_SCHEMA_REGISTRY;
|
||||
export const ROUTE_FEATURE_OWNER: Readonly<Record<string, string>> = Object.freeze({});
|
||||
export const NAVIGATION_ROUTES = Object.freeze(
|
||||
Object.values(ROUTE_REGISTRY)
|
||||
.filter((definition) => definition.navigationOrder !== null)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
left.navigationOrder! - right.navigationOrder!,
|
||||
),
|
||||
);
|
||||
export function getRoute(routeId: string): RouteDefinition {
|
||||
const registry = ROUTE_REGISTRY as Readonly<Record<string, RouteDefinition>>;
|
||||
const selected = registry[routeId];
|
||||
if (!selected) throw new Error(\`Unregistered route: \${routeId}\`);
|
||||
return selected;
|
||||
}
|
||||
export function routePath(routeId: string): string {
|
||||
return getRoute(routeId).path;
|
||||
}
|
||||
`;
|
||||
|
||||
const emptyRuntimes = `import { PLATFORM_ROUTE_CODECS } from "../presentation/routes/platform-route-codecs.ts";
|
||||
import { PLATFORM_ROUTE_RUNTIME } from "../presentation/routes/route-runtime.tsx";
|
||||
import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts";
|
||||
|
||||
const COMPILED_FEATURE_RUNTIME_CONTRIBUTIONS: readonly Readonly<{
|
||||
featureId: string;
|
||||
}>[] = Object.freeze([]);
|
||||
|
||||
const INSTALLED_FEATURE_RUNTIME_CONTRIBUTIONS =
|
||||
COMPILED_FEATURE_RUNTIME_CONTRIBUTIONS.filter((contribution) =>
|
||||
INSTALLED_PRODUCT_FEATURE_IDS.includes(contribution.featureId),
|
||||
);
|
||||
|
||||
void INSTALLED_FEATURE_RUNTIME_CONTRIBUTIONS;
|
||||
|
||||
export const ROUTE_CODECS = PLATFORM_ROUTE_CODECS;
|
||||
export const ROUTE_RUNTIME = PLATFORM_ROUTE_RUNTIME;
|
||||
`;
|
||||
|
||||
const emptyAdapters = `import {
|
||||
composeFeatureAdapterInputs,
|
||||
type InstalledFeatureInputs,
|
||||
} from "./feature-adapter-contribution.ts";
|
||||
import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts";
|
||||
|
||||
const COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS = Object.freeze([] as const);
|
||||
|
||||
export function createInstalledFeatureInputs(
|
||||
context: Readonly<Record<never, never>>,
|
||||
): InstalledFeatureInputs {
|
||||
return composeFeatureAdapterInputs(
|
||||
COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS,
|
||||
INSTALLED_PRODUCT_FEATURE_IDS,
|
||||
context,
|
||||
);
|
||||
}
|
||||
`;
|
||||
|
||||
const emptyContractContributions = `import {
|
||||
composeContractContributions,
|
||||
type InstalledContractContribution,
|
||||
type InstalledContractPackageIdentity,
|
||||
} from "../contracts/external-contract-runtime.ts";
|
||||
import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts";
|
||||
|
||||
const COMPILED_CONTRACT_CONTRIBUTIONS: readonly InstalledContractContribution[] =
|
||||
Object.freeze([]);
|
||||
|
||||
export const INSTALLED_CONTRACT_CONTRIBUTIONS: readonly InstalledContractContribution[] =
|
||||
Object.freeze(
|
||||
COMPILED_CONTRACT_CONTRIBUTIONS.filter((contribution) =>
|
||||
INSTALLED_PRODUCT_FEATURE_IDS.includes(contribution.featureId),
|
||||
),
|
||||
);
|
||||
|
||||
export const COMPOSED_CONTRACT_CONTRIBUTIONS = composeContractContributions(
|
||||
INSTALLED_CONTRACT_CONTRIBUTIONS,
|
||||
);
|
||||
|
||||
export const EXPECTED_CONTRACT_SET_PACKAGES: readonly InstalledContractPackageIdentity[] =
|
||||
COMPOSED_CONTRACT_CONTRIBUTIONS.externalPackages;
|
||||
`;
|
||||
|
||||
const emptyMessages = `export const INSTALLED_MESSAGE_CATALOGS = Object.freeze({
|
||||
"ko-KR": Object.freeze({}),
|
||||
"en-US": Object.freeze({}),
|
||||
});
|
||||
`;
|
||||
|
||||
type CoveragePolicy = {
|
||||
repositoryBaseline: number;
|
||||
generatedPaths: string[];
|
||||
@@ -236,30 +128,9 @@ try {
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
await writeFile(
|
||||
path.join(fixtureRoot, "src/features/installed-product-manifest.ts"),
|
||||
emptyProductManifest,
|
||||
);
|
||||
await writeFile(
|
||||
path.join(fixtureRoot, "src/features/installed-feature-contracts.ts"),
|
||||
emptyContracts,
|
||||
);
|
||||
await writeFile(
|
||||
path.join(fixtureRoot, "src/features/installed-feature-runtimes.tsx"),
|
||||
emptyRuntimes,
|
||||
);
|
||||
await writeFile(
|
||||
path.join(fixtureRoot, "src/features/installed-feature-adapters.ts"),
|
||||
emptyAdapters,
|
||||
);
|
||||
await writeFile(
|
||||
path.join(fixtureRoot, "src/features/installed-feature-messages.ts"),
|
||||
emptyMessages,
|
||||
);
|
||||
await writeFile(
|
||||
path.join(fixtureRoot, "src/features/installed-contract-contributions.ts"),
|
||||
emptyContractContributions,
|
||||
);
|
||||
if (!runPnpm("generate:feature-index")) {
|
||||
throw new Error("Feature topology indexes failed to regenerate after sample removal");
|
||||
}
|
||||
|
||||
// Runtime profiles are product configuration. Once the feature is physically
|
||||
// removed, its override key must disappear too or the built config still
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { arch, platform, userInfo } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* Executable evidence for the extreme-scale acceptance matrix.
|
||||
*
|
||||
* Runs every gate the acceptance rows cite, in order, under the *current*
|
||||
* Node, and writes one machine-readable record:
|
||||
* artifacts/quality/extreme-scale-gates.json
|
||||
* artifacts/quality/extreme-scale-gates/<gate>.log
|
||||
*
|
||||
* On an unsupported Node the gates are not run at all and the record says
|
||||
* `not-executed`; it is never reported as a failure of the code or as a pass.
|
||||
* In an environment whose default Node is too old, put a supported binary
|
||||
* first on PATH (for example a repository-local `.tmp/node24/bin`).
|
||||
*/
|
||||
export const EXTREME_SCALE_GATES = Object.freeze([
|
||||
"check:feature-index",
|
||||
"check:types:app",
|
||||
"check:types:test",
|
||||
"check:types",
|
||||
"lint",
|
||||
"check:architecture",
|
||||
"check:app-build-input",
|
||||
"check:request-fanout",
|
||||
"check:registries",
|
||||
"check:diagnostics",
|
||||
"test:extreme-scale:focused",
|
||||
"check:topology",
|
||||
"check:traffic",
|
||||
"check:observability",
|
||||
"check:release-coherence",
|
||||
"test:platform",
|
||||
"test:reference-feature",
|
||||
"check:scale:pr",
|
||||
"check:scale:main",
|
||||
"check:scale:baseline",
|
||||
// The soak needs a build of the current source, never a stale dist/.
|
||||
"build",
|
||||
// The production bundle closure of the built app contains only its features.
|
||||
"check:app-build-input:bundle",
|
||||
"check:scale:nightly",
|
||||
"check:scale:release",
|
||||
] as const);
|
||||
|
||||
/** Inputs whose content defines "the current code" for this evidence. */
|
||||
const SOURCE_ROOTS = Object.freeze(["src", "scripts", "tests", "config", ".storybook", "recipes"]);
|
||||
const SOURCE_FILES = Object.freeze([
|
||||
"package.json",
|
||||
"pnpm-lock.yaml",
|
||||
".dependency-cruiser.json",
|
||||
"eslint.config.ts",
|
||||
"vite.config.ts",
|
||||
"vitest.config.ts",
|
||||
"tsconfig.json",
|
||||
"tsconfig.app.json",
|
||||
"tsconfig.test.json",
|
||||
"tsconfig.node.json",
|
||||
]);
|
||||
|
||||
async function listFiles(directory: string): Promise<string[]> {
|
||||
const found: string[] = [];
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(directory, { withFileTypes: true });
|
||||
} catch {
|
||||
return found;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const target = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) found.push(...(await listFiles(target)));
|
||||
else if (entry.isFile()) found.push(target);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** sha256 over every source input (path + content), in a stable order. */
|
||||
export async function sourceDigest(root: string): Promise<Readonly<{ digest: string; files: number }>> {
|
||||
const files = [
|
||||
...(await Promise.all(SOURCE_ROOTS.map((entry) => listFiles(path.join(root, entry))))).flat(),
|
||||
...SOURCE_FILES.map((file) => path.join(root, file)).filter((file) => existsSync(file)),
|
||||
]
|
||||
.map((file) => path.relative(root, file))
|
||||
.sort();
|
||||
const hash = createHash("sha256");
|
||||
for (const file of files) {
|
||||
hash.update(file).update("\0").update(await readFile(path.join(root, file))).update("\0");
|
||||
}
|
||||
return { digest: hash.digest("hex"), files: files.length };
|
||||
}
|
||||
|
||||
/** Sums vitest `Tests N passed` / `N failed` lines from a gate log. */
|
||||
export function vitestCounts(log: string): Readonly<{ passed: number; failed: number; skipped: number; files: number }> {
|
||||
const escape = String.fromCharCode(27);
|
||||
const plain = log.split(escape).map((part, index) => (index === 0 ? part : part.replace(/^\[[0-9;]*m/u, ""))).join("");
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
let skipped = 0;
|
||||
let files = 0;
|
||||
for (const line of plain.split("\n")) {
|
||||
const tests = /^\s*Tests\s+(.*)$/u.exec(line);
|
||||
if (tests) {
|
||||
passed += Number(/(\d+) passed/u.exec(tests[1] as string)?.[1] ?? 0);
|
||||
failed += Number(/(\d+) failed/u.exec(tests[1] as string)?.[1] ?? 0);
|
||||
skipped += Number(/(\d+) skipped/u.exec(tests[1] as string)?.[1] ?? 0);
|
||||
}
|
||||
const fileLine = /^\s*Test Files\s+.*?(\d+) passed/u.exec(line);
|
||||
if (fileLine) files += Number(fileLine[1]);
|
||||
}
|
||||
return { passed, failed, skipped, files };
|
||||
}
|
||||
|
||||
type Version = readonly [number, number, number];
|
||||
|
||||
function parseVersion(value: string): Version {
|
||||
const [major = 0, minor = 0, patch = 0] = value.replace(/^v/u, "").split(".").map(Number);
|
||||
return [major, minor, patch];
|
||||
}
|
||||
|
||||
function compare(left: Version, right: Version): number {
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
const difference = (left[index] ?? 0) - (right[index] ?? 0);
|
||||
if (difference !== 0) return difference;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Supports the `>=a.b.c <x.y.z` form this repository declares. */
|
||||
export function satisfiesEngine(version: string, range: string): boolean {
|
||||
const current = parseVersion(version);
|
||||
for (const clause of range.trim().split(/\s+/u)) {
|
||||
const match = /^(>=|<=|>|<|=)?(\d+(?:\.\d+){0,2})$/u.exec(clause);
|
||||
if (!match) return false;
|
||||
const order = compare(current, parseVersion(match[2] as string));
|
||||
const operator = match[1] ?? "=";
|
||||
const ok =
|
||||
operator === ">=" ? order >= 0
|
||||
: operator === "<=" ? order <= 0
|
||||
: operator === ">" ? order > 0
|
||||
: operator === "<" ? order < 0
|
||||
: order === 0;
|
||||
if (!ok) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const root = process.cwd();
|
||||
const pkg = JSON.parse(await readFile(path.join(root, "package.json"), "utf8")) as {
|
||||
engines?: { node?: string };
|
||||
};
|
||||
const engine = pkg.engines?.node ?? "";
|
||||
const directory = path.join(root, "artifacts/quality/extreme-scale-gates");
|
||||
const artifact = path.join(root, "artifacts/quality/extreme-scale-gates.json");
|
||||
await mkdir(directory, { recursive: true });
|
||||
const startedAt = new Date();
|
||||
const pnpmVersion =
|
||||
spawnSync("corepack", ["pnpm", "--version"], { cwd: root, encoding: "utf8" }).stdout?.trim() ?? "";
|
||||
const identity = {
|
||||
node: process.version,
|
||||
nodeMajor: Number(process.versions.node.split(".")[0]),
|
||||
pnpm: pnpmVersion,
|
||||
engine,
|
||||
platform: platform(),
|
||||
arch: arch(),
|
||||
user: (() => {
|
||||
try {
|
||||
return userInfo().username;
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
})(),
|
||||
};
|
||||
|
||||
if (!satisfiesEngine(process.version, engine)) {
|
||||
await writeFile(
|
||||
artifact,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
schemaVersion: 1,
|
||||
generatedAt: new Date().toISOString(),
|
||||
...identity,
|
||||
status: "not-executed",
|
||||
reason: `Node ${process.version} does not satisfy engines.node "${engine}"`,
|
||||
gates: [],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
process.stderr.write(
|
||||
`not executed: Node ${process.version} does not satisfy "${engine}". Put a supported node first on PATH.\n`,
|
||||
);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const browsers = path.join(root, ".tmp/ms-playwright");
|
||||
const env = {
|
||||
...process.env,
|
||||
pnpm_config_verify_deps_before_run: "false",
|
||||
...(process.env["PLAYWRIGHT_BROWSERS_PATH"] === undefined && existsSync(browsers)
|
||||
? { PLAYWRIGHT_BROWSERS_PATH: browsers }
|
||||
: {}),
|
||||
};
|
||||
const only = process.argv.find((argument) => argument.startsWith("--only="))?.slice(7).split(",");
|
||||
const gates = only ? EXTREME_SCALE_GATES.filter((gate) => only.includes(gate)) : EXTREME_SCALE_GATES;
|
||||
const sourceBefore = await sourceDigest(root);
|
||||
const results: {
|
||||
gate: string;
|
||||
status: "passed" | "failed";
|
||||
exitCode: number | null;
|
||||
durationMs: number;
|
||||
tests: ReturnType<typeof vitestCounts>;
|
||||
log: string;
|
||||
}[] = [];
|
||||
for (const gate of gates) {
|
||||
const gateStartedAt = Date.now();
|
||||
const run = spawnSync("corepack", ["pnpm", "run", gate], {
|
||||
cwd: root,
|
||||
env,
|
||||
encoding: "utf8",
|
||||
maxBuffer: 256 * 1024 * 1024,
|
||||
});
|
||||
const log = path.join(directory, `${gate.replaceAll(":", "-")}.log`);
|
||||
await writeFile(log, `${run.stdout ?? ""}${run.stderr ?? ""}`);
|
||||
const status = run.status === 0 ? "passed" : "failed";
|
||||
const tests = vitestCounts(`${run.stdout ?? ""}${run.stderr ?? ""}`);
|
||||
results.push({
|
||||
gate,
|
||||
status,
|
||||
exitCode: run.status,
|
||||
durationMs: Date.now() - gateStartedAt,
|
||||
tests,
|
||||
log: path.relative(root, log),
|
||||
});
|
||||
process.stdout.write(
|
||||
`${status.toUpperCase()} ${gate} (${Date.now() - gateStartedAt}ms${tests.passed + tests.failed > 0 ? `, ${tests.passed} tests passed, ${tests.failed} failed` : ""})\n`,
|
||||
);
|
||||
}
|
||||
const sourceAfter = await sourceDigest(root);
|
||||
|
||||
const readJson = async (relative: string) => {
|
||||
const file = path.join(root, relative);
|
||||
if (!existsSync(file)) return null;
|
||||
const fresh = (await stat(file)).mtimeMs >= startedAt.getTime();
|
||||
return { fresh, value: JSON.parse(await readFile(file, "utf8")) as Record<string, unknown> };
|
||||
};
|
||||
// Machine-readable artifacts the acceptance depends on must be produced by
|
||||
// this run, on this Node, and say passed. An old PASS is not evidence.
|
||||
const evidenceChecks: { artifact: string; check: string; passed: boolean }[] = [];
|
||||
const expect = (artifact: string, check: string, passed: boolean) =>
|
||||
evidenceChecks.push({ artifact, check, passed });
|
||||
const ran = new Set(gates);
|
||||
for (const tier of ["nightly", "release"] as const) {
|
||||
if (!ran.has(`check:scale:${tier}`)) continue;
|
||||
const relative = `artifacts/scale/${tier}/summary.json`;
|
||||
const summary = await readJson(relative);
|
||||
expect(relative, "regenerated during this run", summary?.fresh === true);
|
||||
expect(relative, "status passed with no skipped step", summary?.value["status"] === "passed" && Array.isArray(summary.value["skipped"]) && summary.value["skipped"].length === 0);
|
||||
const environment = summary?.value["environment"] as { nodeMajor?: number } | undefined;
|
||||
expect(relative, `environment.nodeMajor == ${identity.nodeMajor}`, environment?.nodeMajor === identity.nodeMajor);
|
||||
}
|
||||
const soakRecord = ran.has("check:scale:nightly")
|
||||
? await readJson("artifacts/scale/nightly/browser-soak.json")
|
||||
: null;
|
||||
if (ran.has("check:scale:nightly")) {
|
||||
expect("artifacts/scale/nightly/browser-soak.json", "regenerated during this run", soakRecord?.fresh === true);
|
||||
expect("artifacts/scale/nightly/browser-soak.json", "status passed (not skipped)", soakRecord?.value["status"] === "passed");
|
||||
}
|
||||
if (ran.has("check:scale:baseline")) {
|
||||
const comparison = await readJson("artifacts/scale/baseline-comparison.json");
|
||||
expect("artifacts/scale/baseline-comparison.json", "regenerated during this run", comparison?.fresh === true);
|
||||
expect("artifacts/scale/baseline-comparison.json", "status passed on all axes (timing compatible)", comparison?.value["status"] === "passed");
|
||||
}
|
||||
if (ran.has("check:app-build-input:bundle")) {
|
||||
const inventory = await readJson("artifacts/quality/vite-module-inventory.json");
|
||||
expect(
|
||||
"artifacts/quality/vite-module-inventory.json",
|
||||
"produced by this run's build (bundle isolation checked on current code)",
|
||||
inventory?.fresh === true,
|
||||
);
|
||||
}
|
||||
expect("source tree", "unchanged while the gates ran", sourceBefore.digest === sourceAfter.digest);
|
||||
const soak = soakRecord?.value ?? null;
|
||||
const status =
|
||||
results.every((result) => result.status === "passed") && evidenceChecks.every((check) => check.passed)
|
||||
? "passed"
|
||||
: "failed";
|
||||
await writeFile(
|
||||
artifact,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
schemaVersion: 1,
|
||||
generatedAt: new Date().toISOString(),
|
||||
startedAt: startedAt.toISOString(),
|
||||
...identity,
|
||||
source: { digest: sourceAfter.digest, files: sourceAfter.files },
|
||||
status,
|
||||
gates: results,
|
||||
totals: {
|
||||
gates: results.length,
|
||||
passedGates: results.filter((result) => result.status === "passed").length,
|
||||
testsPassed: results.reduce((sum, result) => sum + result.tests.passed, 0),
|
||||
testsFailed: results.reduce((sum, result) => sum + result.tests.failed, 0),
|
||||
},
|
||||
evidenceChecks,
|
||||
browserSoak: soak
|
||||
? {
|
||||
status: soak["status"],
|
||||
classification: soak["classification"],
|
||||
samples: Array.isArray(soak["samples"]) ? soak["samples"].length : 0,
|
||||
summary: soak["summary"],
|
||||
browser: soak["browser"],
|
||||
build: soak["build"],
|
||||
}
|
||||
: null,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
process.stdout.write(`extreme-scale gates: ${status.toUpperCase()} on Node ${process.version} (${path.relative(root, artifact)})\n`);
|
||||
if (status !== "passed") process.exitCode = 1;
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
await main();
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type FailureKind,
|
||||
} from "../../contracts/errors.ts";
|
||||
import type { MutationIntent } from "../../contracts/mutation-intent.ts";
|
||||
import type { ExecutionContext } from "../../platform/execution/execution-context.ts";
|
||||
import type {
|
||||
HttpExecutionOutcome,
|
||||
SafeResponseMetadata,
|
||||
@@ -64,6 +65,7 @@ export type InstalledHttpOperationExecutor = Readonly<{
|
||||
routeId: string;
|
||||
signal?: AbortSignal;
|
||||
intent?: MutationIntent;
|
||||
execution?: ExecutionContext;
|
||||
}>,
|
||||
): Promise<HttpExecutionOutcome<WireOutput, Problem>>;
|
||||
}>;
|
||||
@@ -211,6 +213,7 @@ export type FeatureHttpBinding<
|
||||
context?: Readonly<{
|
||||
signal?: AbortSignal;
|
||||
intent?: MutationIntent;
|
||||
execution?: ExecutionContext;
|
||||
}>,
|
||||
): Promise<Result<OperationValue<Operations[OperationId]>, ApiFailure>>;
|
||||
}>;
|
||||
@@ -243,6 +246,7 @@ export function createFeatureHttpBinding<
|
||||
context: Readonly<{
|
||||
signal?: AbortSignal;
|
||||
intent?: MutationIntent;
|
||||
execution?: ExecutionContext;
|
||||
}> = {},
|
||||
): Promise<Result<OperationValue<Operations[OperationId]>, ApiFailure>> {
|
||||
const operation = operations[operationId];
|
||||
@@ -261,6 +265,9 @@ export function createFeatureHttpBinding<
|
||||
routeId: operation.routeId,
|
||||
...(context.signal === undefined ? {} : { signal: context.signal }),
|
||||
...(context.intent === undefined ? {} : { intent: context.intent }),
|
||||
...(context.execution === undefined
|
||||
? {}
|
||||
: { execution: context.execution }),
|
||||
});
|
||||
return projectExecutionOutcome(
|
||||
operation.operationId,
|
||||
|
||||
@@ -109,6 +109,10 @@ const TRANSPORT_OWNED_HEADERS: ReadonlySet<string> = new Set([
|
||||
"accept",
|
||||
"content-type",
|
||||
"idempotency-key",
|
||||
// Spec §29. Interaction trace propagation is runtime-owned; a credential
|
||||
// collaborator can never supply or shadow these.
|
||||
"traceparent",
|
||||
"x-correlation-id",
|
||||
]);
|
||||
|
||||
const FORBIDDEN_REQUEST_HEADERS: ReadonlySet<string> = new Set([
|
||||
|
||||
@@ -41,6 +41,19 @@ import {
|
||||
type PhysicalAttemptState,
|
||||
} from "./http-effect-certainty.ts";
|
||||
import { parseRetryAfter } from "./retry-policy.ts";
|
||||
import {
|
||||
createExecutionContext,
|
||||
MAX_INTERACTION_DEADLINE_MS,
|
||||
type ExecutionContext,
|
||||
} from "../../platform/execution/execution-context.ts";
|
||||
import {
|
||||
ConcurrencyQueueFullError,
|
||||
type ConcurrencyLease,
|
||||
} from "../../platform/traffic/concurrency-budget.ts";
|
||||
import type { TrafficBudget } from "../../platform/traffic/traffic-budget.ts";
|
||||
import { checkJsonStructure } from "../../platform/validation/bounded-json.ts";
|
||||
import { buildTraceHeaders } from "../../platform/telemetry/trace-context.ts";
|
||||
import { responseValidationBudget } from "../../platform/validation/validation-budget.ts";
|
||||
import {
|
||||
canRetryTransport,
|
||||
isRetryableHttpStatus,
|
||||
@@ -196,8 +209,28 @@ export interface HttpExecutionContext {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly scope: CacheScopeSnapshot;
|
||||
readonly intent?: MutationIntent;
|
||||
/**
|
||||
* Spec §10–§15. The interaction this execution belongs to. Every physical
|
||||
* attempt consumes the interaction's shared request budget, retry budget and
|
||||
* concurrency lease, and the interaction's absolute deadline caps the
|
||||
* operation deadline. Absent, the executor creates a single-operation
|
||||
* interaction from the operation's own traffic policy, so no execution is
|
||||
* ever unbudgeted.
|
||||
*/
|
||||
readonly execution?: ExecutionContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spec §11. The bounded traffic policy of an operation that declares none:
|
||||
* one initial attempt plus the hard retry ceiling, strictly sequential.
|
||||
*/
|
||||
export const DEFAULT_OPERATION_TRAFFIC_BUDGET: TrafficBudget = Object.freeze({
|
||||
maxPhysicalRequests: 1 + HTTP_EXECUTION_CEILINGS.hardRetryCount,
|
||||
maxRetries: HTTP_EXECUTION_CEILINGS.hardRetryCount,
|
||||
maxConcurrentRequests: 1,
|
||||
maxQueuedRequests: 0,
|
||||
});
|
||||
|
||||
export interface ContractHttpExecutor {
|
||||
execute<Input, WireOutput, Problem>(
|
||||
operation: InstalledHttpContract<Input, WireOutput, Problem>,
|
||||
@@ -417,9 +450,30 @@ export function createContractHttpExecutor(
|
||||
// §8.5. One monotonic deadline covers credential resolution, encoding,
|
||||
// backoff, every physical attempt, body read and validation.
|
||||
const startedAt = now();
|
||||
const totalDeadlineMs = effectiveDeadlineMs(policy.totalDeadlineMs);
|
||||
const execution =
|
||||
context.execution ??
|
||||
createExecutionContext({
|
||||
interactionId: "implicit-operation",
|
||||
deadlineMs: Math.max(
|
||||
1,
|
||||
Math.min(
|
||||
MAX_INTERACTION_DEADLINE_MS,
|
||||
Math.ceil(effectiveDeadlineMs(policy.totalDeadlineMs)),
|
||||
),
|
||||
),
|
||||
traffic: policy.traffic ?? DEFAULT_OPERATION_TRAFFIC_BUDGET,
|
||||
clock: now,
|
||||
startedAt,
|
||||
});
|
||||
// Spec §15. A late operation only receives what is left of the
|
||||
// interaction's absolute deadline; it never restarts its own full timeout.
|
||||
const totalDeadlineMs = Math.max(
|
||||
0,
|
||||
Math.min(effectiveDeadlineMs(policy.totalDeadlineMs), execution.remainingMs()),
|
||||
);
|
||||
const deadlineAt = startedAt + totalDeadlineMs;
|
||||
const remaining = () => deadlineAt - now();
|
||||
const remaining = () =>
|
||||
Math.min(deadlineAt - now(), execution.remainingMs());
|
||||
|
||||
let attemptState: PhysicalAttemptState = "PREPARING";
|
||||
let attempts = 0;
|
||||
@@ -460,6 +514,15 @@ export function createContractHttpExecutor(
|
||||
once: true,
|
||||
});
|
||||
}
|
||||
// Spec §10. Cancelling the interaction cancels every child execution the
|
||||
// same way the caller's own signal does.
|
||||
const interactionSignal = context.execution?.cancellation.signal;
|
||||
if (interactionSignal?.aborted) forwardCallerToLifetime();
|
||||
else {
|
||||
interactionSignal?.addEventListener("abort", forwardCallerToLifetime, {
|
||||
once: true,
|
||||
});
|
||||
}
|
||||
if (context.scope.signal.aborted) forwardScopeToLifetime();
|
||||
else {
|
||||
context.scope.signal.addEventListener("abort", forwardScopeToLifetime, {
|
||||
@@ -476,6 +539,7 @@ export function createContractHttpExecutor(
|
||||
lifetimeDisposed = true;
|
||||
clearTimeout(lifetimeDeadlineTimer);
|
||||
callerSignal?.removeEventListener("abort", forwardCallerToLifetime);
|
||||
interactionSignal?.removeEventListener("abort", forwardCallerToLifetime);
|
||||
context.scope.signal.removeEventListener("abort", forwardScopeToLifetime);
|
||||
lifetimeController.abort();
|
||||
};
|
||||
@@ -688,6 +752,11 @@ export function createContractHttpExecutor(
|
||||
if (intentValidation.intent?.idempotencyKey !== undefined) {
|
||||
headers["Idempotency-Key"] = intentValidation.intent.idempotencyKey;
|
||||
}
|
||||
// Spec §29. Only an interaction that opted into tracing propagates its
|
||||
// identity; every child request carries the same trace and correlation.
|
||||
if (context.execution?.trace !== undefined) {
|
||||
Object.assign(headers, buildTraceHeaders(context.execution));
|
||||
}
|
||||
|
||||
const retryCeiling = Math.min(
|
||||
policy.retryBudget,
|
||||
@@ -695,8 +764,15 @@ export function createContractHttpExecutor(
|
||||
HTTP_EXECUTION_CEILINGS.hardRetryCount,
|
||||
);
|
||||
|
||||
// Spec §13. A retry is admitted only when the interaction still has both a
|
||||
// shared retry and a physical request left; the retry budget is consumed
|
||||
// only for a retry that will actually be dispatched.
|
||||
const admitRetry = (): boolean =>
|
||||
execution.traffic.requests.remaining > 0 &&
|
||||
execution.traffic.retries.tryConsume(contract.operationId);
|
||||
|
||||
for (let retryIndex = 0; ; retryIndex += 1) {
|
||||
if (callerSignal?.aborted) {
|
||||
if (callerSignal?.aborted || interactionSignal?.aborted) {
|
||||
terminalCancellation ??= "CALLER";
|
||||
return finish(
|
||||
cancelled(abandonedCertainty()),
|
||||
@@ -711,6 +787,41 @@ export function createContractHttpExecutor(
|
||||
);
|
||||
}
|
||||
|
||||
if (remaining() <= 0) {
|
||||
return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT");
|
||||
}
|
||||
// Spec §11 / §14. Physical request budget first, then a cancellable
|
||||
// concurrency lease whose wait is bounded by the operation lifetime.
|
||||
if (!execution.traffic.requests.tryConsume()) {
|
||||
return finish(
|
||||
abandonedTransportFailure("OVERLOADED_BEFORE_SEND"),
|
||||
"TRAFFIC_BUDGET_EXCEEDED",
|
||||
);
|
||||
}
|
||||
let lease: ConcurrencyLease;
|
||||
try {
|
||||
lease = await execution.traffic.concurrency.acquire(
|
||||
lifetimeController.signal,
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof ConcurrencyQueueFullError) {
|
||||
return finish(
|
||||
abandonedTransportFailure("OVERLOADED_BEFORE_SEND"),
|
||||
"TRAFFIC_BUDGET_EXCEEDED",
|
||||
);
|
||||
}
|
||||
if (terminalCancellation === "CALLER") {
|
||||
return finish(cancelled(abandonedCertainty()), "CANCELLED");
|
||||
}
|
||||
if (terminalCancellation === "SCOPE_FENCE") {
|
||||
return finish(
|
||||
abandonedTransportFailure("ABORTED_BY_SCOPE"),
|
||||
"SCOPE_FENCED",
|
||||
);
|
||||
}
|
||||
return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT");
|
||||
}
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const budget = remaining();
|
||||
if (budget <= 0) {
|
||||
@@ -821,7 +932,8 @@ export function createContractHttpExecutor(
|
||||
remaining() > 0
|
||||
) {
|
||||
const delay = jitteredDelay(retryIndex, random);
|
||||
if (delay < remaining()) {
|
||||
if (delay < remaining() && admitRetry()) {
|
||||
lease.release();
|
||||
const slept = await awaitWithAbort(
|
||||
sleep(delay, lifetimeController.signal),
|
||||
lifetimeController.signal,
|
||||
@@ -905,7 +1017,8 @@ export function createContractHttpExecutor(
|
||||
isRetryableSemantics(contract.retrySemantics)
|
||||
) {
|
||||
const delay = retryDelayFor(outcome.retryAfterMs, retryIndex, random);
|
||||
if (delay !== null && delay < remaining()) {
|
||||
if (delay !== null && delay < remaining() && admitRetry()) {
|
||||
lease.release();
|
||||
clearTimeout(deadlineTimer);
|
||||
lifetimeController.signal.removeEventListener(
|
||||
"abort",
|
||||
@@ -934,6 +1047,9 @@ export function createContractHttpExecutor(
|
||||
clearTimeout(deadlineTimer);
|
||||
lifetimeController.signal.removeEventListener("abort", forwardLifetime);
|
||||
}
|
||||
} finally {
|
||||
lease.release();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return finish(
|
||||
@@ -1191,6 +1307,20 @@ async function admitResponse<Input, WireOutput, Problem>(
|
||||
"CONTRACT_VIOLATION",
|
||||
);
|
||||
}
|
||||
// Spec §21–§22. Structure before validation/mapping: the byte ceiling
|
||||
// already bounded the parse; the structural budget bounds what the schema
|
||||
// validator and mapper are asked to walk.
|
||||
if (
|
||||
!checkJsonStructure(
|
||||
decoded.value,
|
||||
responseValidationBudget(policy.responseByteLimit),
|
||||
).ok
|
||||
) {
|
||||
return settled(
|
||||
violation("RESPONSE_TOO_LARGE", "RESPONSE", postDispatchEffect(isCommand)),
|
||||
"RESPONSE_STRUCTURE_LIMIT",
|
||||
);
|
||||
}
|
||||
|
||||
const validated = invokeValidator(contract.outputValidator, decoded.value);
|
||||
if (validated.outcome === "THROWN") {
|
||||
@@ -1393,6 +1523,24 @@ async function admitProblem<Input, WireOutput, Problem>(
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
!checkJsonStructure(
|
||||
decoded.value,
|
||||
responseValidationBudget(HTTP_EXECUTION_CEILINGS.problemResponseBytes),
|
||||
).ok
|
||||
) {
|
||||
return Object.freeze({
|
||||
result: violation<WireOutput, Problem>(
|
||||
"PROBLEM_SCHEMA_INVALID",
|
||||
"VALIDATION",
|
||||
postDispatchEffect(isCommand),
|
||||
),
|
||||
certainty: isCommand ? "MAYBE_APPLIED" : "NOT_STARTED",
|
||||
retryHint: false,
|
||||
retryAfterMs: metadata.retryAfterMs ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
const validated = invokeValidator(contract.problemValidator, decoded.value);
|
||||
if (validated.outcome !== "VALID") {
|
||||
return Object.freeze({
|
||||
|
||||
@@ -33,25 +33,34 @@ export function isRetryableSemantics(semantics: RetrySemantics): boolean {
|
||||
return semantics === "SAFE" || semantics === "IDEMPOTENT";
|
||||
}
|
||||
|
||||
function localJitterCeiling(retryIndex: number): number {
|
||||
return Math.min(RETRY_MAX_LOCAL_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** retryIndex);
|
||||
}
|
||||
|
||||
/** Full jitter over min(2000, 250 * 2^retryIndex). */
|
||||
export function jitteredDelay(
|
||||
retryIndex: number,
|
||||
random: () => number,
|
||||
): number {
|
||||
const ceiling = Math.min(
|
||||
RETRY_MAX_LOCAL_DELAY_MS,
|
||||
RETRY_BASE_DELAY_MS * 2 ** retryIndex,
|
||||
);
|
||||
return Math.floor(random() * ceiling);
|
||||
return Math.floor(random() * localJitterCeiling(retryIndex));
|
||||
}
|
||||
|
||||
/**
|
||||
* Spec §13.3. `Retry-After` is a floor, never an exact instant: every client
|
||||
* that received the same hint would otherwise retry in one synchronized second
|
||||
* spike. The cohort is spread over a bounded window that grows with the hint
|
||||
* (a quarter of it) but never beyond the local 2s jitter ceiling.
|
||||
*/
|
||||
export function retryDelayFor(
|
||||
retryAfterMs: number | null,
|
||||
retryIndex: number,
|
||||
random: () => number,
|
||||
): number | null {
|
||||
const local = jitteredDelay(retryIndex, random);
|
||||
if (retryAfterMs === null) return local;
|
||||
if (retryAfterMs === null) return jitteredDelay(retryIndex, random);
|
||||
if (retryAfterMs > RETRY_AFTER_CEILING_MS) return null;
|
||||
return Math.max(local, retryAfterMs);
|
||||
const window = Math.min(
|
||||
RETRY_MAX_LOCAL_DELAY_MS,
|
||||
Math.max(localJitterCeiling(retryIndex), Math.ceil(retryAfterMs / 4)),
|
||||
);
|
||||
return retryAfterMs + Math.floor(random() * window);
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@ export {
|
||||
type HttpTransportFailure,
|
||||
type SafeResponseMetadata,
|
||||
} from "./http-execution-v3.ts";
|
||||
/** Spec §17. V3 결과를 플랫폼 오류 봉투(`AppError`)로 정규화한다. */
|
||||
export { platformErrorForOutcome } from "./platform-error-mapping.ts";
|
||||
export {
|
||||
createFeatureHttpBinding,
|
||||
defineFeatureHttpOperation,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user