diff --git a/docs/README.md b/docs/README.md index d0086516..2d152a47 100644 --- a/docs/README.md +++ b/docs/README.md @@ -29,6 +29,7 @@ README와 입구 문서는 영어, recipe·ledger·스타일 문서는 한국어 입구 문서가 가리키는 세부 규칙: +- 규모 설계(구조·소유·실행·트래픽·오류·검증·텔레메트리·릴리스 일관성)와 코드 주석 `scale-architecture.md §N`의 근거: [`architecture/scale-architecture.md`](architecture/scale-architecture.md). 절마다 현재 계약인지 기록만인지 머리말 표에 적었다 - 계약 소유와 호환성: [`architecture/contract-ownership.md`](architecture/contract-ownership.md), [`contracts/compatibility.md`](contracts/compatibility.md) - 정적 배포와 런타임 설정: [`architecture/static-delivery.md`](architecture/static-delivery.md) - 기능 개발자가 알아야 하는 양: [`architecture/capability-consumer-experience.md`](architecture/capability-consumer-experience.md) diff --git a/docs/architecture/scale-architecture.md b/docs/architecture/scale-architecture.md new file mode 100644 index 00000000..bba6bf92 --- /dev/null +++ b/docs/architecture/scale-architecture.md @@ -0,0 +1,1406 @@ +# Scale Architecture + +> **상태 머리말 (2026-11-03)** +> +> - **현재 계약인 범위.** 아래 표에서 상태가 "현재 계약"인 절만 지금 코드가 지키는 규칙이다. "기록만"인 절은 2026-09-23 설계 당시의 계획·목록이고, 구현되지 않았거나 바뀌었다. 문서와 코드가 다르면 코드가 맞다. +> - **출처.** 2026-09-23 설계서 "Extreme-Scale Frontend Architecture Design"을 커밋 `6f6c48e`(2026-09-24)에서 옮겼다. 원래 파일은 작업 이력 묶음 안에 있어 복사한 프로젝트가 지울 수 있다. 원문은 `git show 6f6c48e:docs/reviews/2026-09-23-extreme-scale-frontend-plan-bundle/docs/superpowers/specs/2026-09-23-extreme-scale-frontend-architecture-design.md`로 볼 수 있다. +> - **본문.** §1~§55는 영어 원문 그대로다. 절 번호는 바꾸지 않았다. 원문 머리의 날짜·대상·상태·예정 경로 줄만 이 머리말로 바꿨다. +> - **코드가 이 문서를 가리키는 방법.** 코드 주석은 `scale-architecture.md §N` 형식으로 쓴다. 문서 이름이 없는 "Spec" + 절 번호 참조는 `tests/unit/deletable-history-documents.test.ts`가 거부한다. 절 번호를 바꾸면 `git grep "scale-architecture.md §"`로 찾은 주석을 모두 함께 고친다. +> - **코드와 달라진 곳을 적는 규칙.** 원문 문장은 고치지 않는다. 확인한 차이는 그 절 끝에 `> YYYY-MM-DD 현재:` 한두 줄로 적는다. 절의 상태가 바뀌면 아래 표도 고친다. + +## 절 상태 + +- **현재 계약 (코드 참조)**: 코드 주석이 `scale-architecture.md §N`으로 가리키는 절이다. 2026-11-03에 절의 주장을 그 절을 가리키는 모듈의 타입·머리 주석·테스트 이름과 대조했다. 동작을 실행해 확인한 것은 아니다. +- **현재 계약**: 코드가 가리키지 않지만 지금 코드가 지키는 절이다. 같은 날 같은 방법으로 대조했다. +- **기록만**: 구현되지 않았거나 바뀐 절이다. 설계 당시의 기록으로 남긴다. +- "차이 메모"가 "있음"이면 그 절 끝에 `2026-11-03 현재` 메모가 있다. + +집계: 현재 계약 (코드 참조) 41 · 현재 계약 10 · 기록만 4 · 미확인 0. + +| § | 제목 | 상태 | 차이 메모 | +|---|---|---|---| +| 1 | Purpose | 현재 계약 | | +| 2 | Core Principle | 현재 계약 | | +| 3 | Scale Model | 현재 계약 (코드 참조) | | +| 4 | Target Source Structure | 현재 계약 (코드 참조) | 있음 | +| 5 | Module Ownership | 현재 계약 | 있음 | +| 6 | Dependency Rules | 현재 계약 | | +| 7 | Cardinality Budgets | 현재 계약 | 있음 | +| 8 | Registry Composition | 현재 계약 | | +| 9 | Router Architecture | 현재 계약 | | +| 10 | Execution Model | 현재 계약 (코드 참조) | 있음 | +| 11 | Traffic Budget | 현재 계약 (코드 참조) | 있음 | +| 12 | Request Fan-Out | 현재 계약 (코드 참조) | | +| 13 | Retry Model | 현재 계약 (코드 참조) | | +| 14 | Concurrency Budget | 현재 계약 (코드 참조) | | +| 15 | Deadline Propagation | 현재 계약 (코드 참조) | | +| 16 | Request Deduplication and Coalescing | 현재 계약 (코드 참조) | | +| 17 | Error Model | 현재 계약 (코드 참조) | | +| 18 | Error Envelope | 현재 계약 (코드 참조) | | +| 19 | Presentation Error Mapping | 현재 계약 (코드 참조) | | +| 20 | Validation Boundaries | 현재 계약 (코드 참조) | | +| 21 | Validate Once at Trust Boundaries | 현재 계약 (코드 참조) | | +| 22 | Validation Budget | 현재 계약 (코드 참조) | | +| 23 | Telemetry Model | 현재 계약 (코드 참조) | | +| 24 | Telemetry Ownership | 현재 계약 (코드 참조) | 있음 | +| 25 | Telemetry Pipeline | 현재 계약 (코드 참조) | 있음 | +| 26 | Telemetry Must Fail Open for Business Behavior | 현재 계약 (코드 참조) | | +| 27 | Telemetry Storm Protection | 현재 계약 (코드 참조) | | +| 28 | Telemetry Privacy and Redaction | 현재 계약 (코드 참조) | | +| 29 | Trace and Correlation | 현재 계약 (코드 참조) | 있음 | +| 30 | Failure Boundaries | 현재 계약 (코드 참조) | | +| 31 | Async Failure Model | 현재 계약 | 있음 | +| 32 | Spike Traffic Design | 현재 계약 (코드 참조) | 있음 | +| 33 | Sustained Traffic Design | 현재 계약 (코드 참조) | | +| 34 | Amplification Metrics | 현재 계약 (코드 참조) | | +| 35 | Scale Profiles | 현재 계약 (코드 참조) | | +| 36 | Local Scale Verification | 현재 계약 (코드 참조) | 있음 | +| 37 | Global Topology Verification | 현재 계약 (코드 참조) | 있음 | +| 38 | TypeScript Scale Gate | 현재 계약 (코드 참조) | | +| 39 | Runtime Composition Scale Gate | 현재 계약 (코드 참조) | | +| 40 | Browser Boot Gate | 기록만 | 있음 | +| 41 | Request Fan-Out Gate | 현재 계약 (코드 참조) | | +| 42 | Failure and Chaos Scenarios | 현재 계약 (코드 참조) | | +| 43 | Telemetry Storm Test | 현재 계약 (코드 참조) | | +| 44 | Soak Testing | 현재 계약 (코드 참조) | 있음 | +| 45 | Horizontal Scaling and Release Coherence | 현재 계약 (코드 참조) | 있음 | +| 46 | Multi-Replica Release Matrix | 현재 계약 (코드 참조) | | +| 47 | CI Execution Tiers | 현재 계약 (코드 참조) | 있음 | +| 48 | Benchmark Result Format | 현재 계약 (코드 참조) | 있음 | +| 49 | Regression Policy | 현재 계약 (코드 참조) | | +| 50 | Required Architecture Gates | 현재 계약 (코드 참조) | 있음 | +| 51 | Compatibility With Current Template Strengths | 기록만 | | +| 52 | Explicit Non-Goals | 현재 계약 | | +| 53 | Implementation Sequence Constraints | 기록만 | | +| 54 | Acceptance Criteria | 기록만 | | +| 55 | Design Summary | 현재 계약 | | + +## 1. Purpose + +This design evolves the frontend template from a single-application Clean Architecture skeleton into a frontend application platform that remains maintainable when logical domain count, traffic, failure rate, and operating duration become extreme. + +The design must remain valid under worst-case growth assumptions: + +- 100, 1,000, 10,000, 100,000, or 1,000,000 logical features/domains across the product ecosystem. +- Short, severe spike traffic. +- Sustained high traffic over long periods. +- Partial and total backend failures. +- Retry storms, telemetry storms, cache-miss storms, and slow upstreams. +- Long-lived browser sessions. +- Multi-replica frontend deployments during rolling releases. + +The goal is **not** to make one SPA compile and boot one million features. The goal is to make global growth independent from local runtime and build cost by enforcing bounded architecture boundaries. + +## 2. Core Principle + +> No cardinality may become implicitly unbounded. + +The same rule applies to: + +- compile graphs, +- route graphs, +- feature registries, +- cross-feature dependencies, +- HTTP request fan-out, +- retries, +- concurrency, +- payload size, +- validation cost, +- telemetry buffering, +- timers/listeners, +- browser storage, +- failure propagation. + +The platform must expose these costs explicitly in code and CI instead of allowing them to hide behind arrays, `map`, `Promise.all`, global registries, retries, timers, or framework abstractions. + +## 3. Scale Model + +### 3.1 Separate global and local cardinality + +Two different concepts must never be conflated: + +```text +GlobalFeatureCount += logical feature count across the whole product ecosystem + +LocalFeatureCount += feature count compiled and booted by one deployable frontend application +``` + +A system may contain 1,000,000 logical features while an individual deployable app sees only 100-300 features. + +### 3.2 Architectural hierarchy + +```text +Product + -> Deployable App + -> Bounded Context + -> Feature + -> Use Case / Operation + -> Route / Adapter +``` + +A parent boundary knows only its direct children. It does not flatten every descendant into a global registry. + +Example: + +```text +Product + -> Commerce App + -> Order Context + -> Order Creation Feature + -> Payment Context + -> Account App + -> Identity Context +``` + +`Product` must not import `OrderCreatePage`, `PaymentRefundUseCase`, or other deep descendants. + +### 3.3 Scale escape rule + +When a boundary reaches its measured cardinality ceiling, the response is architectural split, not increasing the ceiling indefinitely. + +```text +Feature too large + -> split feature + +Context too large + -> split bounded context + +App too large + -> split deployable app +``` + +This is equivalent to refusing an implicit unbounded one-to-many relation in server-side architecture. + +## 4. Target Source Structure + +```text +src/ +├─ domain/ +├─ application/ +│ └─ ports/ +├─ contracts/ +├─ platform/ +│ ├─ cardinality/ +│ ├─ traffic/ +│ ├─ resilience/ +│ ├─ errors/ +│ ├─ validation/ +│ └─ telemetry/ +├─ features/ +│ └─ / +│ ├─ domain/ +│ ├─ application/ +│ ├─ contracts/ +│ ├─ adapters/ +│ ├─ presentation/ +│ └─ feature-module.ts +├─ contexts/ +│ └─ / +│ └─ context-module.ts +├─ apps/ +│ └─ / +│ └─ app-module.ts +├─ .generated/ +│ └─ +└─ bootstrap/ + └─ compose-product.ts +``` + +The exact path layout may adapt to current repository conventions, but ownership boundaries are mandatory. + +> 2026-11-03 현재: 위 그림의 최상위 `domain/` 폴더는 없다. domain 계층은 기능 안(`src/features/reference-feature/domain`)에만 있다. `src/platform`에는 `execution`·`release`·`routing`도 있다. +> 색인은 생성기가 git이 무시하는 `src/.generated/`에 쓴다. 조립 코드는 `src/bootstrap/`에 있고 `compose-product.ts`라는 파일은 없다. 실제 폴더 목록의 정본은 [`layers.md`](layers.md)다. + +## 5. Module Ownership + +### 5.1 Feature module + +Each feature owns one descriptor containing its own contributions. + +Conceptual API: + +```ts +export const ORDER_FEATURE = defineFeatureModule({ + id: "order", + contracts, + adapters, + runtime, + routes, + messages, + invalidation, + telemetry, +}); +``` + +A new feature must not require hand editing multiple central installation files. + +Target change surface: + +```text +src/features/new-feature/** +.generated/** +``` + +Central handwritten production files changed for a normal feature addition: + +```text +0 preferred +1 maximum when a deliberate bounded-context registration is required +``` + +### 5.2 Bounded context module + +A context composes only its direct feature modules. + +```ts +export const COMMERCE_CONTEXT = defineBoundedContextModule({ + id: "commerce", + features: COMMERCE_FEATURE_INDEX, + budget: COMMERCE_CARDINALITY_BUDGET, +}); +``` + +It does not expose concrete internal feature implementations to unrelated contexts. + +### 5.3 Deployable app module + +A deployable app owns only direct bounded contexts. + +```ts +export const CUSTOMER_APP = defineDeployableApp({ + id: "customer", + contexts: CUSTOMER_CONTEXT_INDEX, +}); +``` + +Each app becomes an independent compilation and deployment unit once scale requires it. + +### 5.4 Generated indexes + +Indexes are generated at build time from approved static source declarations. + +Required properties: + +- static TypeScript imports, +- deterministic output, +- no arbitrary runtime import path, +- no runtime plugin discovery from untrusted configuration, +- generated files are not handwritten registries. + +This preserves tree-shaking, supply-chain reviewability, and compile-time visibility while eliminating central merge hotspots. + +> 2026-11-03 현재: 실제 API는 `defineFeatureModule`(`src/features/feature-module.ts`), `defineBoundedContextModule`(`src/contexts/bounded-context-module.ts`), `defineDeployableAppModule`(`src/apps/deployable-app-module.ts`)이다. 기능 모듈의 필드는 `id`·`contracts`·`routes`·`messages`·`loadRuntime`이다. +> context와 app은 `context-module.ts`·`app-module.ts`의 상수로 소유와 한도를 선언한다. 생성기 `scripts/generate-product-feature-index.ts`가 이 선언을 읽어 색인을 만든다. + +## 6. Dependency Rules + +### 6.1 Cross-feature concrete imports are forbidden + +For different features A and B: + +```text +src/features/A/** -> src/features/B/** +``` + +is an architecture violation unless the dependency is through an explicitly approved public contract boundary. + +Preferred interaction boundaries: + +```text +feature + -> src/contracts + -> src/application/ports + -> explicit orchestration/workflow feature +``` + +### 6.2 Cross-context imports are stricter + +A context must not import another context's concrete feature internals. + +Allowed communication is through: + +- public contracts, +- application ports, +- explicitly named integration contracts, +- server-backed integration where appropriate. + +### 6.3 Cycles are always forbidden + +No cycle is permitted across feature, context, or app boundaries. + +## 7. Cardinality Budgets + +The platform defines explicit architectural budgets. + +Conceptual shape: + +```ts +interface ArchitectureCardinalityBudget { + readonly maxContextsPerApp: number; + readonly maxFeaturesPerContext: number; + readonly maxRoutesPerFeature: number; + readonly maxOperationsPerFeature: number; + readonly maxMessagesPerFeature: number; +} +``` + +Initial numeric values are not hardcoded by this design. They must be established through repository benchmarks. + +Budget files must be visible in review and version controlled. + +Budget increases must produce a detectable architecture-review signal. + +Example failure: + +```text +ARCHITECTURE_CARDINALITY_EXCEEDED +Context: commerce +Current: 201 +Allowed: 200 +Action: split the context or create another deployable boundary. +``` + +> 2026-11-03 현재: 한도를 하나로 묶은 `ArchitectureCardinalityBudget` 타입은 없다. 선언마다 자기 한도를 가진다(`APP_MAX_CONTEXTS = 20`, `CONTEXT_MAX_FEATURES = 200`). +> 한도를 넘으면 `src/platform/cardinality/cardinality-budget.ts`의 `assertWithinCardinalityBudget`이 `CardinalityBudgetExceededError`를 던진다. + +## 8. Registry Composition + +### 8.1 No repeated object spread in accumulation loops + +This pattern is forbidden in scale-sensitive composition paths: + +```ts +features.reduce( + (registry, feature) => ({ ...registry, ...feature.routes }), + {}, +); +``` + +It repeatedly copies accumulated state and becomes quadratic-like as the registry grows. + +### 8.2 Required composition strategy + +Use one mutable local accumulator, explicit duplicate detection, then freeze once. + +```ts +const result = Object.create(null); + +for (const feature of features) { + for (const [id, route] of Object.entries(feature.routes)) { + if (Object.hasOwn(result, id)) { + throw new DuplicateRouteError(id); + } + result[id] = route; + } +} + +return Object.freeze(result); +``` + +The same strategy applies to operation, schema, mapper, invalidation, adapter, runtime, and message contribution composition when a registry is necessary. + +### 8.3 Membership checks + +Repeated linear membership tests such as: + +```ts +installedIds.includes(featureId) +``` + +must not be used in scale-sensitive loops. + +Build a `Set` once and use `has`. + +## 9. Router Architecture + +A flat product-wide route table is not an acceptable extreme-scale model. + +Target hierarchy: + +```text +Product Router + -> Deployable App Router + -> Context Router + -> Feature Router + -> Page Route +``` + +Only the next boundary is loaded eagerly. + +Example at global scale: + +```text +Global logical features: 1,000,000 +Browser boot routes: product/app boundary only +Commerce app selected: commerce context routes loaded +Order context selected: order feature routes loaded +``` + +Global feature count must not linearly increase initial route object count, initial bundle size, or boot heap. + +## 10. Execution Model + +### 10.1 Interaction is the root execution scope + +HTTP requests are not the highest-level unit. A user or application interaction is. + +Examples: + +- open an order page, +- submit a payment, +- change workspace, +- load search results. + +Conceptual context: + +```ts +interface ExecutionContext { + readonly interaction: InteractionContext; + readonly traffic: TrafficContext; + readonly telemetry: TelemetryContext; + readonly cancellation: CancellationContext; +} +``` + +Operations run under the same interaction scope. + +### 10.2 Interaction context + +```ts +interface InteractionContext { + readonly interactionId: InteractionId; + readonly startedAt: number; + readonly deadlineAt: number; +} +``` + +All child operations inherit correlation and deadline information. + +> 2026-11-03 현재: `src/platform/execution/execution-context.ts`의 `ExecutionContext` 필드는 `interaction`(`id`·`startedAt`·`deadlineAt`), `cancellation`, `traffic`, 선택 필드 `trace`, `clock`이다. `telemetry` 필드는 없다. + +## 11. Traffic Budget + +Traffic cost must be explicit and bounded. + +Conceptual model: + +```ts +interface TrafficBudget { + readonly maxPhysicalRequests: number; + readonly maxConcurrentRequests: number; + readonly maxRetries: number; + readonly deadlineMs: number; +} +``` + +A feature owns the policy declaration; the platform owns enforcement. + +```ts +defineQueryOperation({ + id: "order.list", + traffic: { + maxPhysicalRequests: 2, + maxConcurrentRequests: 2, + maxRetries: 1, + deadlineMs: 4_000, + }, +}); +``` + +The platform must not maintain one global per-feature traffic registry. + +> 2026-11-03 현재: `TrafficBudget`의 필드는 `maxPhysicalRequests`·`maxRetries`·`maxConcurrentRequests`·`maxQueuedRequests`다. 마감 시간은 따로 받는다(`createExecutionContext`의 `deadlineMs`, HTTP 계약의 `totalDeadlineMs`). +> 연산의 정책은 HTTP 계약의 선택 필드 `traffic`(`src/contracts/external-contract-runtime.ts`)이다. 없으면 `src/adapters/http/http-execution-v3.ts`의 `DEFAULT_OPERATION_TRAFFIC_BUDGET`을 쓴다. `defineQueryOperation`은 없다. + +## 12. Request Fan-Out + +Frontend N+1 is treated as an architecture defect. + +Forbidden behavior: + +```text +load 1 collection + -> N rows + -> N detail requests +``` + +Preferred behavior: + +- pagination/cursor APIs, +- bounded page sizes, +- backend bulk endpoints, +- backend read models, +- request coalescing, +- shared query/cache ownership. + +A representative user interaction must have a physical-request budget. + +Synthetic integration tests increase data cardinality while asserting that network request count remains bounded rather than O(N). + +## 13. Retry Model + +### 13.1 Retry budget is interaction-scoped + +Retry count is not independently reset for every request. + +```text +Interaction retry budget = 2 +A consumes retry +B consumes retry +C cannot retry after budget exhaustion +``` + +This prevents multiple child requests from multiplying recovery traffic. + +### 13.2 Retry prerequisites + +Retries are allowed only when operation semantics permit them. + +The existing idempotency/replay semantics remain authoritative. + +### 13.3 Retry-After and jitter + +A `Retry-After` response must not synchronize all clients into a second spike. + +Effective scheduling combines server guidance with bounded jitter. + +## 14. Concurrency Budget + +Each interaction has bounded concurrent physical requests. + +Waiting work must be cancelable. + +Cancellation of an interaction must cancel or release: + +- queued requests, +- in-flight requests where possible, +- retry timers, +- concurrency leases, +- delayed telemetry associated only with that discarded interaction when safe. + +## 15. Deadline Propagation + +Timeouts do not reset after each retry or downstream call. + +A root deadline is established at interaction start. + +Each child computes remaining time: + +```ts +remainingMs = deadlineAt - now(); +``` + +A chain of retries therefore cannot turn a 5-second user operation into an unbounded 20- or 30-second operation. + +## 16. Request Deduplication and Coalescing + +Multiple consumers requesting the same logical resource concurrently should share compatible in-flight work. + +```text +10 consumers + -> 1 physical request + -> 10 subscribers +``` + +The existing TanStack Query infrastructure is a natural implementation foundation where its semantics match the operation. + +Deduplication must never merge requests across incompatible authentication, tenant, scope, locale, or cache identity boundaries. + +## 17. Error Model + +Errors are owned at the correct boundary. + +```text +Platform Error +Contract Error +Application / Domain Error +Presentation Mapping +``` + +### 17.1 Platform errors + +Examples: + +- network unavailable, +- request timeout, +- cancellation, +- response too large, +- unsupported content type, +- malformed transport response, +- traffic budget exceeded. + +### 17.2 Contract errors + +Contract failures identify violations at an external boundary: + +- schema mismatch, +- protocol mismatch, +- unsupported media type, +- missing required field, +- malformed payload. + +### 17.3 Domain/application errors + +Concrete business errors remain feature-owned. + +Example: + +```ts +type PaymentError = + | PaymentDeclined + | PaymentAlreadyProcessed + | PaymentLimitExceeded; +``` + +### 17.4 No global error union + +This is forbidden: + +```ts +type GlobalApplicationError = + | OrderError + | PaymentError + | ...; +``` + +Use local generic boundaries instead: + +```ts +Result +``` + +The platform understands only the common envelope. + +## 18. Error Envelope + +Unstructured `throw new Error("...")` is not the primary cross-layer error contract. + +Conceptual common metadata: + +```ts +interface AppError { + readonly kind: string; + readonly category: ErrorCategory; + readonly retryability: Retryability; + readonly severity: ErrorSeverity; +} +``` + +Concrete domain error semantics remain local. + +## 19. Presentation Error Mapping + +HTTP status codes and transport details must not leak into presentation logic. + +Bad: + +```ts +if (status === 409) { ... } +``` + +Preferred flow: + +```text +HTTP 409 + -> Transport/Contract interpretation + -> PaymentAlreadyProcessed + -> localized presentation message +``` + +## 20. Validation Boundaries + +Validation has distinct purposes: + +1. user-input validation, +2. transport validation, +3. domain invariant validation, +4. runtime configuration validation. + +Frontend validation improves UX but is never an authoritative security boundary. Backend validation remains authoritative. + +## 21. Validate Once at Trust Boundaries + +External data enters as unknown/untrusted data. + +```text +unknown HTTP body + -> size/content checks + -> parse + -> schema validation + -> Validated DTO + -> mapper + -> domain/application types +``` + +The same payload should not be repeatedly schema-validated at every internal layer without a specific trust-boundary reason. + +## 22. Validation Budget + +Validation itself has bounded cost. + +Before expensive parsing and validation, enforce structural constraints where possible: + +- maximum response bytes, +- maximum collection items, +- maximum string lengths, +- maximum allowed nesting/depth where relevant, +- bounded mapper output size. + +Oversized responses must be rejected before allocating or validating an arbitrarily large object graph. + +## 23. Telemetry Model + +Production frontend observability is required, but raw logging is not the architecture. + +The platform supports: + +- error reporting, +- real user monitoring, +- trace/correlation propagation, +- structured operational events, +- performance metrics. + +Feature code must not depend directly on a vendor SDK such as Sentry or Datadog. + +Conceptual port: + +```ts +interface TelemetryPort { + emit(event: TelemetryEvent): void; +} +``` + +Provider adapters live behind the platform boundary. + +## 24. Telemetry Ownership + +The platform owns a common envelope, not every feature event definition. + +Common metadata may include: + +- event name, +- severity, +- release, +- app/context/feature identifiers, +- interaction ID, +- trace/correlation identifiers, +- timestamp, +- safe attributes. + +Concrete event payload schemas remain feature-owned. + +No global telemetry event union containing every feature is allowed. + +> 2026-11-03 현재: 봉투(`src/platform/telemetry/telemetry-event.ts`)의 필드는 `kind`·`severity`·`contextId`·`featureId`·`interactionId`·`traceId`·`payload`다. +> 릴리스 식별자(`build_id`·`release_id`)는 수집기 adapter(`src/adapters/telemetry/telemetry-collector.ts`)가 붙인다. 시각과 app 식별자는 봉투에 없다. + +## 25. Telemetry Pipeline + +Required conceptual pipeline: + +```text +Feature event + -> normalize + -> redact + -> fingerprint + -> deduplicate + -> sample + -> bounded buffer + -> batch + -> rate limit + -> transport +``` + +All in-browser queues and maps are bounded. + +> 2026-11-03 현재: 코드의 순서는 봉투 검사 → redact → fingerprint → deduplicate → sample → buffer → rate limit → batch → transport다(`src/platform/telemetry/telemetry-pipeline.ts`). normalize 자리에 봉투 검사가 있고, rate limit이 batch보다 앞이다. + +## 26. Telemetry Must Fail Open for Business Behavior + +Telemetry failure must not fail application behavior. + +```text +business path +telemetry path +``` + +are separated. + +When telemetry capacity is exhausted, low-priority observability data is dropped rather than growing browser memory or blocking user operations. + +## 27. Telemetry Storm Protection + +A production incident may cause millions of browsers to report the same error simultaneously. + +The telemetry subsystem therefore requires: + +- deterministic or policy-driven sampling, +- repeated-error fingerprinting, +- bounded deduplication state, +- bounded batch size, +- bounded queue bytes/events, +- rate limiting, +- priority-based dropping. + +Observability must never amplify an incident into another outage. + +## 28. Telemetry Privacy and Redaction + +Feature authors must not be able to casually emit secrets. + +Runtime sanitization must reject/redact sensitive classes such as: + +- Authorization values, +- cookies, +- access tokens, +- refresh tokens, +- passwords, +- known secret fields. + +Typed safe payloads may be added where they improve correctness, but runtime defense remains required because compile-time types are not a security boundary. + +## 29. Trace and Correlation + +User interactions should connect browser events with backend traces where supported. + +```text +user interaction + -> interaction id + -> request trace/correlation metadata + -> backend trace + -> downstream dependency +``` + +Trace propagation must follow the chosen backend/OTel contract and must not invent incompatible identifiers independently per feature. + +> 2026-11-03 현재: 전파는 interaction이 켰을 때만 한다(`ExecutionContext`의 `trace`는 선택 필드). 헤더는 `traceparent`와 `x-correlation-id`다(`src/platform/telemetry/trace-context.ts`). + +## 30. Failure Boundaries + +Failure containment mirrors architecture ownership. + +```text +App Boundary + -> Context Boundary + -> Feature Boundary + -> Page Boundary where useful +``` + +Not every component gets an ErrorBoundary. Boundaries correspond to meaningful recovery/fallback domains. + +A payment UI failure should not necessarily destroy order, catalog, or account UI. + +## 31. Async Failure Model + +React render failures are only one class of failure. + +The architecture also models: + +- query failure, +- mutation failure, +- validation failure, +- timeout, +- cancellation, +- traffic-budget exhaustion. + +Presentation state should distinguish recoverable, terminal, and cancelled outcomes where useful. + +> 2026-11-03 현재: 화면 상태는 `src/application/view-models/async-state.ts`가 정한다. 기본 상태 `terminal-error`와 덧씌움 `stale-degraded`·`mutation-effect-unknown`·`mutation-conflict`가 있다. 취소만 따로 보여 주는 상태는 이 목록에 없다. + +## 32. Spike Traffic Design + +Spike scenarios include rapid jumps such as: + +```text +100 clients + -> 10,000 + -> 100,000+ +``` + +The frontend platform cannot control the number of users, but it must control client-side amplification. + +Critical risks: + +- retry storm, +- authentication refresh storm, +- cache-miss storm, +- telemetry storm, +- synchronized `Retry-After`, +- uncontrolled concurrency, +- duplicate requests. + +> 2026-11-03 현재: 이 절을 가리키는 테스트(`tests/platform/traffic/traffic-amplification.test.ts`)는 실패와 병렬 연산에서 요청·재시도 증폭만 본다. 인증 갱신 폭주와 cache-miss 폭주를 따로 재는 규모 테스트는 찾지 못했다. + +## 33. Sustained Traffic Design + +Long-running high traffic and long-lived SPA sessions expose different risks: + +- heap growth, +- timer/listener leaks, +- query cache churn, +- browser storage growth, +- stale auth/session state, +- repeated background polling, +- telemetry backlog, +- orphaned AbortControllers or tasks. + +Scale verification therefore includes soak-style tests and memory slope, not only peak request count. + +## 34. Amplification Metrics + +The platform test harness defines operational amplification metrics. + +### 34.1 Request amplification + +```text +physical HTTP requests / logical interactions +``` + +### 34.2 Retry amplification + +```text +total physical attempts / initial physical requests +``` + +### 34.3 Telemetry amplification + +```text +telemetry sends / logical failures or events +``` + +These are measured under healthy, slow, partial-failure, and total-failure conditions. + +## 35. Scale Profiles + +Synthetic scale profiles: + +```text +S0 100 +S1 1,000 +S2 10,000 +S3 100,000 +S4 1,000,000 +``` + +These do not all mean “generate that many TypeScript source files”. + +### S0-S1 + +Can exercise concrete module composition and type-check fixtures. + +### S2 + +Exercises larger generated indexes and composition structures when affordable. + +### S3-S4 + +Primarily verify global topology and local-boundary independence. They model one hundred thousand or one million logical features while asserting that any one app/context remains within local budgets. + +## 36. Local Scale Verification + +Within one allowed boundary, measure: + +- registry composition, +- route composition, +- generated index cost, +- TypeScript diagnostics, +- bundle/build cost, +- browser boot cost. + +Scale-sensitive composition should exhibit linear-or-better growth where linear work is unavoidable. + +Quadratic-like growth is a failure. + +> 2026-11-03 현재: 규모 측정(`scripts/scale/run-composition-scale.ts`, `scripts/scale/collect-tsc-diagnostics.ts`)은 registry·route 조립, 생성 색인, TypeScript 진단을 잰다. 번들·빌드 비용과 브라우저 부팅 비용은 이 측정에 없다(§40). + +## 37. Global Topology Verification + +Increase global logical cardinality while holding one app unchanged. + +Assertions: + +```text +Global feature count increases +but unchanged App A should not materially increase: +- TypeScript source graph +- initial bundle bytes +- initial routes +- initial runtime registries +- boot heap +- boot CPU +``` + +This is the critical proof that the architecture can extend toward 100K/1M logical domains. + +> 2026-11-03 현재: `tests/scale/global-local-independence.test.ts`는 생성 색인, 소스 그래프, 부팅 때 읽는 context 루트를 본다. 번들은 `check:app-build-input:bundle`이 "소유하지 않은 기능의 모듈이 없다"만 본다. 부팅 heap·CPU는 재지 않는다. + +## 38. TypeScript Scale Gate + +Use compiler diagnostics where supported, including `--extendedDiagnostics`. + +Track at least: + +- source file count, +- type count, +- symbol count, +- instantiations, +- memory, +- total type-check time. + +A global module augmentation or giant union that causes unrelated app compile cost to rise with global domain count is a design regression. + +## 39. Runtime Composition Scale Gate + +Benchmark relevant registries: + +- route, +- API operation, +- schema, +- mapper, +- invalidation, +- adapter contribution, +- runtime contribution, +- locale/message contribution. + +Test multiple N values to detect nonlinear regression. + +Absolute timing alone is insufficient; growth behavior matters. + +## 40. Browser Boot Gate + +Measure: + +- initial JS transferred, +- parsed/executed JS, +- initial route count, +- initial heap, +- bootstrap CPU, +- runtime config fetch, +- release manifest verification, +- first meaningful application render. + +Global topology growth must not cause proportional growth in these metrics for an unchanged app. + +> 2026-11-03 현재: 이 목록을 재는 부팅 게이트는 없다. 초기 JS gzip 크기만 `check:bundle`이 `config/performance/budgets.json`의 `initialJsGzipBytes`로 막는다. 초기 heap, 부팅 CPU, 첫 렌더, 초기 route 수는 재지 않는다. + +## 41. Request Fan-Out Gate + +Use representative collection pages with increasing server-returned cardinality: + +```text +N = 10 +N = 100 +N = 1,000 +``` + +A page that requires two bounded bulk requests should remain around that request count instead of issuing O(N) row-detail calls. + +> **Implementation note (2026-09-23).** The template's representative collection contract is a paginated bulk read with a hard page ceiling of 100 rows (`limit` ≤ 100, response schema `max(100)`). `N` above is the server-side collection cardinality, not the size of one response. Acceptance is therefore two-layered: +> +> - supported cardinality — collections of N = 10 / 50 / 100 / 1,000 rows load a page with **1** physical request, and a full 1,000-row walk costs ≤ ceil(N / 100) + 1 page requests, never one request per row; +> - oversized response — a single response carrying more than the page ceiling (e.g. 1,000 rows at once) is rejected within **1** request as a contract violation, with no per-row downstream fan-out. +> +> The ceiling is not raised to make an oversized fixture pass. A source gate (`pnpm check:request-fanout`) rejects any request dispatch inside a loop or array-iteration callback in feature/application code. + +## 42. Failure and Chaos Scenarios + +Required scenarios include: + +### Total API failure + +Verify: + +- retry bound, +- concurrency bound, +- telemetry bound, +- bounded memory, +- no infinite loop, +- no reload loop. + +### Partial failure + +Example: + +```text +Payment 100% failure +Order healthy +Catalog healthy +``` + +Payment should degrade without collapsing unrelated contexts. + +### Slow API + +Test long-tail latency. Verify deadlines, cancellation, concurrency queues, and queue limits. + +### Network flap + +Repeated online/offline transitions must not produce duplicate unsafe mutations or retry bursts. + +### Telemetry endpoint failure + +Business behavior remains functional and telemetry storage remains bounded. + +## 43. Telemetry Storm Test + +Generate a large number of identical errors/events. + +Expected behavior: + +```text +many logical errors + -> fingerprint/dedup/sample + -> bounded number of buffered/sent telemetry events +``` + +The test records emitted, deduplicated, sampled, dropped, and transmitted counts. + +## 44. Soak Testing + +Long-session profiles may include 30 minutes, 2 hours, 8 hours, or 24 hours depending on environment cost. + +Observe: + +- heap size and slope, +- active timers, +- event listeners, +- DOM nodes, +- query cache size, +- telemetry buffer, +- IndexedDB/browser storage, +- stale auth/session leakage. + +The primary leak signal is sustained positive growth after expected warm-up stabilization, not only an arbitrary maximum heap value. + +> 2026-11-03 현재: 브라우저 soak(`scripts/scale/browser-soak.ts`)은 nightly 단계에서 2분 돈다. heap, DOM 노드, listener, timer, 진행 중 fetch, Web Storage를 잰다. +> query cache와 telemetry buffer는 논리 테스트(`tests/scale/session/long-session.test.ts`)가 본다. IndexedDB는 재지 않고, 30분 이상 돌리는 실행은 없다. + +## 45. Horizontal Scaling and Release Coherence + +Frontend application instances are intended to remain stateless with respect to server-hosted browser user state. + +Horizontal scaling is safe only when release coherence is maintained. + +Deployment contract: + +- content-hashed assets are immutable, +- HTML is revalidated/no-cache according to current release strategy, +- runtime config and release manifest are no-store, +- old hashed assets remain available during rolling release windows, +- a deployment switches an active release tuple atomically, +- mixed incompatible HTML/config/manifest combinations fail closed rather than executing ambiguously. + +> 2026-11-03 현재: 불일치를 만나면 세션마다 한 번만 자동으로 다시 불러오고, 그 뒤의 불일치는 실패 화면으로 끝낸다(`src/platform/release/release-mismatch-recovery.ts`). 이 재시도는 원문에 없다. + +## 46. Multi-Replica Release Matrix + +At minimum verify: + +| HTML | Config | Manifest | Asset | Expected | +| --- | --- | --- | --- | --- | +| R10 | R10 | R10 | R10 | PASS | +| R10 | R11 | R10 | R10 | FAIL CLOSED | +| R10 | R10 | R11 | R10 | FAIL CLOSED | +| R10 | R10 | R10 | missing/incompatible | FAIL | +| R11 | R11 | R11 | R11 | PASS | + +Rolling deployments must also preserve reachability of previous immutable hashed assets for clients that loaded earlier HTML. + +## 47. CI Execution Tiers + +Heavy scale tests must not make every pull request unusably expensive. + +### Pull request + +Fast deterministic gates: + +- dependency architecture, +- cardinality budgets, +- unit tests, +- app/test type-check, +- small composition fixtures, +- duplicate collision tests, +- cross-feature dependency fixture, +- small request fan-out fixture. + +### Main branch + +Medium scale regression: + +- 1K/10K synthetic composition where appropriate, +- TypeScript diagnostic comparison, +- route/bootstrap growth checks, +- generated index validation. + +### Nightly + +Heavy synthetic and browser verification: + +- 10K/100K/1M topology model, +- browser memory and route loading, +- telemetry storm, +- failure scenarios, +- longer navigation/session cycles. + +### Release / dedicated environment + +Environment-dependent checks: + +- spike load, +- soak load, +- cache behavior, +- multi-replica mixed-release validation, +- CDN/LB/origin release contract. + +> 2026-11-03 현재: CI는 `pr` 단계만 돌린다(FE-GATE-005). `main`·`nightly`·`release`는 로컬 명령이다. 기준선 시간 비교가 그 기준선을 기록한 CPU에서만 성립하기 때문이다(`scripts/scale/run-scale-profile.ts`). + +## 48. Benchmark Result Format + +Scale results are machine-readable artifacts, not only console output. + +Example: + +```json +{ + "profile": "S2", + "globalLogicalFeatures": 10000, + "localFeatures": 150, + "routeCompositionMs": 3.21, + "typescriptMs": 4312, + "heapBytes": 1234567 +} +``` + +Store enough metadata to compare against a compatible baseline. + +> 2026-11-03 현재: 실제 형식은 `scripts/scale/benchmark-result.ts`의 `BenchmarkResult`(`name`·`profile`·`cardinality`·`samples`·`medianMs`·`heapBytes`·`metadata`)와 이를 담는 `BenchmarkArtifact`다. 위 JSON은 예시다. + +## 49. Regression Policy + +Use three kinds of thresholds: + +1. absolute ceiling, +2. relative regression percentage, +3. growth-complexity trend. + +Performance measurements should use multiple runs and robust summaries such as median where environment noise is relevant. + +Structural failures such as cycles, duplicate IDs, cross-feature concrete imports, or cardinality-budget violations are deterministic and should fail immediately. + +## 50. Required Architecture Gates + +The architecture must eventually provide automated gates for: + +1. cross-feature concrete import prohibition, +2. cross-context concrete import prohibition, +3. cycle prohibition, +4. cardinality budgets, +5. duplicate feature/route/operation/schema IDs, +6. O(N²)-style registry regression, +7. request fan-out regression, +8. retry-budget enforcement, +9. telemetry-buffer boundedness, +10. global-to-local scale independence, +11. TypeScript/build scale regression, +12. multi-replica release coherence. + +> 2026-11-03 현재: 1~3번은 `.dependency-cruiser.json`의 `features-do-not-import-other-features`, `contexts-do-not-import-other-contexts`, `no-circular-dependencies`다. 11번(TypeScript 규모)은 `main` 단계에만 있어 CI에서 돌지 않는다(§47). + +## 51. Compatibility With Current Template Strengths + +This design preserves and extends current strengths rather than replacing them: + +- Clean Architecture layer rules, +- capability-driven adapter composition, +- HTTP operation contracts, +- bounded response handling, +- retry/idempotency semantics, +- TanStack Query cache ownership, +- scope fencing/generation behavior, +- release/build/config coherence, +- immutable static asset release model. + +The implementation should refactor composition and introduce platform policies without unnecessary UI/design changes. + +## 52. Explicit Non-Goals + +This design does not require: + +- one SPA containing 1M TypeScript features, +- runtime discovery of arbitrary remote code, +- Module Federation or micro-frontends as the default starting point, +- a global mega-registry, +- a global mega-error union, +- a global telemetry schema union, +- vendor-specific observability APIs in feature code, +- frontend validation as a replacement for backend validation. + +Remote/micro-frontend deployment can remain an optional future escalation when organizational or deployment boundaries require independent teams/releases. It is not required to solve the current scaling architecture. + +## 53. Implementation Sequence Constraints + +Implementation should be incremental and preserve behavior. + +A safe high-level sequence is: + +1. establish deterministic architecture/scale tests around current behavior, +2. remove known O(N²) and repeated-membership composition paths, +3. introduce feature-owned descriptor boundaries, +4. generate static product/context indexes, +5. enforce cross-feature/context dependency rules, +6. introduce hierarchical route composition, +7. introduce cardinality budgets, +8. introduce execution context and traffic budgets, +9. normalize error and validation boundaries, +10. introduce telemetry port/pipeline/budgets, +11. add scale/chaos/soak/release gates by CI tier. + +The detailed implementation plan must decompose these into test-first tasks and identify exact existing files after re-reading the live repository state. + +## 54. Acceptance Criteria + +The design is considered implemented only when all of the following are true: + +- Adding a normal feature does not require editing a collection of central handwritten installation registries. +- Composition does not contain known quadratic accumulation patterns. +- Membership checks on scale-sensitive paths use appropriate indexed structures. +- Concrete imports across unrelated features fail architecture checks. +- Context/app cardinality ceilings are explicit and testable. +- An unchanged local app does not grow materially when global logical topology grows toward S3/S4 fixtures. +- Initial routing is hierarchical/lazy rather than a product-wide flat feature table. +- User interactions carry bounded request, retry, concurrency, cancellation, and deadline semantics. +- Representative collections do not create frontend N+1 request fan-out. +- Errors remain local and typed without constructing a global union of all feature errors. +- External data is validated at trust boundaries with bounded payload/structure cost. +- Feature code emits observability through a platform port rather than vendor SDKs. +- Telemetry is redacted, deduplicated, sampled, buffered, and rate-limited with bounded memory. +- Telemetry failure does not fail business behavior. +- Failure boundaries prevent one feature/context from unnecessarily collapsing unrelated UI. +- Spike and sustained-load tests detect request, retry, telemetry, and memory amplification. +- Multi-replica release tests verify fail-closed coherence and old-asset reachability. + +## 55. Design Summary + +The architecture is based on one rule: + +> Global scale must be partitioned into bounded local scale, and every remaining local cardinality must have an explicit budget. + +Therefore the platform avoids: + +```text +unbounded registry +unbounded compile graph +unbounded route graph +unbounded request fan-out +unbounded retries +unbounded concurrency +unbounded payloads +unbounded validation +unbounded telemetry +unbounded memory growth +unbounded failure propagation +``` + +This allows the product ecosystem to grow from hundreds toward hundreds of thousands or millions of logical domains without requiring a single browser, TypeScript compiler invocation, router, or runtime registry to directly carry that global cardinality.