[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,137 +2,32 @@
id: wiki-2026-0508-20260429-스포티앤리치-개발일정-회의록
title: 20260429 스포티앤리치 개발일정 회의록
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
status: duplicate
canonical_id: meeting-notes
duplicate_of: "[[Meeting Notes]]"
aliases: []
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: ["Sporty&Rich", Development, Schedule, Client, QA, Security, Biz]
raw_sources: []
last_reinforced: 2026-05-08
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
confidence_score: 0.9
verification_status: redirected
tags: [duplicate, meeting, project]
last_reinforced: 2026-05-10
github_commit: applied
---
# 📑 [회의록] 스포티앤리치 전체 개발 일정 및 팀별 주요 업무 점검
# 20260429 스포티앤리치 개발일정 회의록
> **일시:** 2026.04.29
> **주요 안건:** 전체 마일스톤 점검, 팀별 R&R 확정, 지연 리스크(URL 리다이렉션) 대응
> **핵심 결정:** 5/17 빌드 프리징 및 5/06 보안 심사 대응을 위한 전사적 협력 체계 가동
> **이 문서는 [[Meeting Notes]] 의 중복본입니다.** 프로젝트별 회의록은 canonical 문서로 redirect.
---
## 핵심 요약
- 일자별 프로젝트 회의록 entry — generic meeting note pattern.
- BLUF + Action Items 구조.
## 🏛️ I. 전체 개발 마일스톤 및 일정 합의
## 🔗 Graph
- 부모: [[Meeting Notes]] (canonical)
- Adjacent: [[BLUF (Bottom Line Up Front)]]
프로젝트 완수를 위해 각 단계별 마감 기한과 담당자를 명확히 확정함.
| 단계 | 기간 / 마감 | 담당 주체 | 비고 / 핵심 목표 |
| :--- | :--- | :--- | :--- |
| **클라이언트 개발** | 04/27 ~ 05/13 | 송병준, 박진규, 박태수 | 인벤토리 확장 및 상단 메뉴 개편 |
| **상품 제작 (20 SKU)** | 04/23 ~ 05/13 | 안현제 | AI 이미지 기반 SKU 생성 및 데이터 정리 |
| **보안 심사** | 05/06 (예정) | 김상엽, 김성환, 정승민 | 사전 점검 및 취약점 대응 준비 |
| **채널 연동 (롯데온)** | 05/14 | 정현욱 | 채널 토큰 공유 (ASAP 요청 건) |
| **개선 및 QA** | 05/14 ~ 05/17 | 송병준, 김상엽, 최성연 | 빌드 프리징 전 최종 품질 확보 |
---
## 🛡️ II. 팀별 세부 업무 및 리스크 관리
각 팀은 확정된 R&R에 따라 진행 상황을 관리하며, 지연 항목에 대해서는 즉각적인 대응을 실시함.
| 팀 | 주요 진행 업무 (Items) | 상태 (Status) | 이슈 및 대응 방향 |
| :--- | :--- | :--- | :--- |
| **클라이언트** | 데이터 지표 개발, 피팅룸 기능 개선, 메뉴 구조 개편 | **진행중** | 05/13 완료 목표로 개발 가속화 |
| **UI / 기획** | 피팅룸 UI 기획 및 시안 제작, UI 제작(~05/08) | **진행중** | 개발 가이드 전달 및 UI 제작 진행 |
| **사업실** | 로그 수집 구조 정의, 채널 토큰 수령/적용 | **주의** | **URL 리다이렉션 처리 지연 (04/27 목표 도과) ➔ 즉시 조치 필요** |
| **상품 제작** | AI 이미지 SKU 20종 생성, 모델 데이터 정리 | **진행중** | 05/13 최종 마감 준수 |
| **QA / 보안** | 빌드 QA 완료, 보안 심사 대응 준비 | **대기** | 05/06 보안 심사 리스크 사전 차단 |
---
## 📅 III. 향후 액션 플랜 (Next Steps & Owner)
| ID | 작업 항목 | 상세 목표 및 실행 방향 | 담당자 | 기한 |
| :--- | :--- | :--- | :--- | :--- |
| **A1** | **URL 리다이렉션 지연 해결** | 지연된 리다이렉션 처리 완료 및 결과 공유 | 정현욱 (사업실) | **즉시** |
| **A2** | **보안 심사 사전 리허설** | 보안 심사 대응을 위한 자체 점검 및 버퍼 확보 | 김상엽, 김성환 | 05/05 |
| **A3** | **채널 토큰 조기 수령** | 롯데온 연동 토큰 05/14 전 조기 확보 및 전달 | 정현욱 | 05/13 |
| **A4** | **빌드 프리징 준비** | 모든 개선 사항 반영 및 최종 QA 돌입 준비 | 송병준, 최성연 | 05/14 |
---
"조직이 시스템이다. 실질적인 결과물과 일정으로 증명한다." - P-Reinforce Logic 🫡🚩🐟
## 🔗 지식 연결 (Graph)
### Related Concepts (Auto-Linked)
* [[Logic]]
* [[P-Reinforce]]
## 📌 한 줄 통찰 (The Karpathy Summary)
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
## 📖 구조화된 지식 (Synthesized Content)
**추출된 패턴:**
> *(TODO)*
**세부 내용:**
- *(TODO)*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
```
## 🤔 의사결정 기준 (Decision Criteria)
**선택 A를 써야 할 때:**
- *(TODO)*
**선택 B를 써야 할 때:**
- *(TODO)*
**기본값:**
> *(TODO)*
## ❌ 안티패턴 (Anti-Patterns)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -2,62 +2,149 @@
id: wiki-2026-0508-acl-prevention
title: ACL Prevention
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-HEALTH-001]
aliases: [P-Reinforce-HEALTH-001, ACL Injury Prevention]
duplicate_of: none
source_trust_level: A
confidence_score: 0.89
tags: [health, sports, injury, prevention]
confidence_score: 0.9
verification_status: applied
tags: [security, devops, health, biomechanics]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: batch-reinforce-01
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: python
framework: pandas
---
# ACL Injury Prevention [[Protocols|Protocols]]
# ACL Prevention
## 📌 한 줄 통찰 (The Karpathy Summary)
> 전방십자인대 부상 위험을 최소화하기 위해 바이오메카닉 분석과 신경근 훈련을 결합한 과학적 예방 체계.
## 한 줄
> **"매 ACL 부상 prevention 의 핵심 = neuromuscular training + landing mechanics + proprioception."**. ACL (Anterior Cruciate Ligament) tear 의 70% 는 non-contact pivoting/landing 상황에서 발생하며, FIFA 11+, PEP, KIPP 같은 evidence-based program 이 incidence 를 50-70% 감소시킨다.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 점프 착지 및 방향 전환 시 무릎 정렬을 최적화하는 신경근 제어(Neuromuscular Control) 강화 패턴.
- **세부 내용:**
- 고유수용성 감각([[Proprioception|Proprioception]]) 훈련을 통한 관절 안정화.
- 햄스트링 강화 및 콰드-햄스트링 균형 최적화.
- 연령 및 성별에 따른 맞춤형 부상 방지 프로그램 설계.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순 근력 강화에서 움직임의 질(Quality of Movement) 중심 예방으로 진화.
- **정책 변화:** 지식 연결성(w2) 관점에서 바이오메카닉과 스포츠 심리학의 연계성 강화.
### 매 Risk Factor
- **Modifiable**: knee valgus on landing, weak hip abductors, quad-dominant deceleration, fatigue.
- **Non-modifiable**: female sex (2-8x risk), narrow intercondylar notch, generalized joint laxity.
- **Environmental**: cleat-surface interaction, fatigue late in match, prior injury history.
## 🔗 지식 연결 (Graph)
- **Parent:** 10_Wiki/💡 Topics/Health
- **Related:** [[Neuromuscular-Control|Neuromuscular-Control]], Sports-Science, [[Proprioception|Proprioception]]
- **Raw Source:** 00_Raw/2026-04-20/ACL-Injury-Prevention-Protocols.md
### 매 Prevention Pillar
- **Neuromuscular training** — plyometric + balance + strength, 2-3x/week.
- **Landing mechanics** — soft landing, knee over toe, hip-dominant.
- **Core/hip strength** — gluteus medius, hip external rotators.
- **Proprioception** — single-leg balance, perturbation training.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Youth soccer FIFA 11+ warmup (15 min pre-training).
2. Female collegiate athletes PEP program.
3. Post-ACLR return-to-sport batteries.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Risk Score Aggregator
```python
import pandas as pd
## 🧪 검증 상태 (Validation)
def acl_risk_score(athlete: dict) -> float:
"""0-1 risk; >0.6 → enroll in prevention program."""
score = 0.0
if athlete["sex"] == "F": score += 0.25
if athlete["prior_acl"]: score += 0.30
if athlete["knee_valgus_deg"] > 8: score += 0.20
if athlete["hop_lsi"] < 0.85: score += 0.15 # limb symmetry
if athlete["age"] < 18: score += 0.10
return min(score, 1.0)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Drop Vertical Jump (DVJ) Analyzer
```python
import numpy as np
## 🧬 중복 검사 (Duplicate Check)
def knee_abduction_moment(forces, lever_arms):
"""Hewett 2005 — KAM > 25.3 Nm predicts ACL injury."""
return np.dot(forces, lever_arms)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
def classify_landing(kam_nm: float) -> str:
if kam_nm > 25.3: return "high-risk"
if kam_nm > 15.0: return "moderate"
return "low-risk"
```
## 🕓 변경 이력 (Changelog)
### FIFA 11+ Session Builder
```python
FIFA_11_PLUS = {
"part1_running": ["straight ahead", "hip out", "hip in", "circling partner"],
"part2_strength": ["bench", "sideways bench", "hamstrings", "single-leg stance"],
"part3_running": ["across pitch", "bounding", "plant-and-cut"],
}
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
def build_session(level: int = 1) -> list[str]:
drills = []
for part, items in FIFA_11_PLUS.items():
drills.extend(items if level >= 2 else items[:2])
return drills
```
### Hop Test Battery
```python
def hop_lsi(injured: float, uninjured: float) -> float:
"""Limb Symmetry Index — RTS threshold ≥ 0.90."""
return injured / uninjured
def cleared_for_rts(single_hop, triple_hop, crossover) -> bool:
return all(lsi >= 0.90 for lsi in (single_hop, triple_hop, crossover))
```
### Cohort Tracking with Pandas
```python
import pandas as pd
def season_incidence(df: pd.DataFrame) -> pd.Series:
"""ACL injuries per 1000 athlete-exposures."""
return df.groupby("team")["acl_injury"].sum() / df.groupby("team")["ae"].sum() * 1000
```
### Fatigue Monitor
```python
def fatigue_flag(rpe: int, srpe_load: int, acwr: float) -> bool:
"""Acute:chronic workload ratio > 1.5 → injury risk spike."""
return rpe >= 8 or acwr > 1.5
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Youth team, no history | FIFA 11+ |
| Female collegiate | PEP / KIPP |
| Post-ACLR | Criterion-based RTS battery |
| Pro athlete in-season | Modified neuromuscular maintenance |
**기본값**: FIFA 11+ 2-3x/week.
## 🔗 Graph
- 부모: [[Sports Medicine]] · [[Injury Prevention]]
- 변형: [[FIFA 11+]] · [[PEP Program]] · [[KIPP]]
- 응용: [[Return to Sport Testing]] · [[Neuromuscular Training]]
- Adjacent: [[Biomechanics]] · [[Knee Valgus]]
## 🤖 LLM 활용
**언제**: structured risk-stratification, program selection, periodization advice.
**언제 X**: clinical diagnosis, surgical decision, individualized rehab prescription.
## ❌ 안티패턴
- **Static stretching only**: 매 효과 없음. Dynamic warmup 필요.
- **Knee-only focus**: hip/core ignore 시 valgus 재발.
- **Volume without quality**: poor landing form 의 reps 는 risk 증가.
- **Generic program**: sex/age/sport-specific tailoring 없으면 effect size 감소.
## 🧪 검증 / 중복
- Verified (Hewett 2005, Sadoghi 2012 meta-analysis, FIFA 11+ RCT).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with risk scoring + FIFA 11+ patterns |
@@ -2,93 +2,150 @@
id: wiki-2026-0508-adversarial-code-stylometry
title: Adversarial Code Stylometry
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-36585B]
aliases: [P-Reinforce-AUTO-36585B, Code Authorship Obfuscation]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [security, ml, privacy, deanonymization]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Adversarial Code Stylometry"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: python
framework: scikit-learn
---
# [[Adversarial Code Stylometry|Adversarial Code Stylometry]]
# Adversarial Code Stylometry
## 📌 한 줄 통찰 (The Karpathy Summary)
> Adversarial Code Stylometry(적대적 코드 문체론)는 프로그래머가 코드 문체 분석(Code Stylometry) 시스템의 추적을 우회하여 자신의 익명성을 보호하기 위해 의도적으로 코드를 변형하는 기법입니다 [1-3]. 주로 자신의 고유한 코딩 스타일을 숨기는 난독화(obfuscation)와 다른 프로그래머의 스타일을 흉내 내는 모방(mimicry) 기술을 사용합니다 [2-4]. 이는 감시와 검열에 맞서 프라이버시 향상 도구를 개발하는 오픈소스 기여자들이 신원 노출로 인한 탄압을 피하기 위한 핵심적인 방어 수단으로 연구되고 있습니다 [5-7].
## 한 줄
> **"매 source code 의 author 를 statistical fingerprint 로 식별 — 그리고 attacker 는 이를 회피한다."**. Code stylometry 는 AST features + n-grams + lexical patterns 로 author 를 95% accuracy 로 deanonymize 가능; adversarial stylometry 는 transformation/obfuscation 으로 이를 무력화한다.
## 📖 구조화된 지식 (Synthesized Content)
* **배경 및 필요성:** 인터넷 검열과 감시가 강화됨에 따라 프라이버시 향상 기술이나 검열 우회 도구를 개발하는 오픈소스 개발자들이 국가나 기관의 표적이 되는 사례가 늘고 있습니다 [5, 6, 8]. 코드 작성자의 코딩 스타일을 분석해 신원을 파악하는 소스 코드 문체론(Source Code Stylometry)은 이러한 개발자들에게 심각한 위협이 되며, 이에 대항하여 익명성을 유지할 수 있는 적대적 방어 기법이 필요해졌습니다 [7].
* **공격 기법 (난독화 및 모방):** 적대적 코드 문체론은 크게 두 가지 접근법을 취합니다. 첫째는 자신의 식별 가능한 코딩 스타일을 모호하게 만드는 '난독화(obfuscation / masking)'이고, 둘째는 다른 특정 작가로 기계 학습 모델을 속이기 위해 의도적으로 대상의 스타일을 흉내 내는 '모방(mimicry / forgery)' 공격입니다 [2-4, 9].
* **기존 문체 분석 시스템의 취약성:** 최첨단 소스 코드 문체 분석 시스템조차도 적대적 수정에 취약한 것으로 나타났습니다 [3, 9]. 변수 이름, 매크로, 리터럴, API 호출 등 국소적인 정보(local changes)나 표면적인 형식 변경만으로도 분류기(classifier)를 속여 다른 사람으로 오분류하게 만드는 것이 가능합니다 [10, 11].
* **방어 지원 도구 ([[StyleCounsel|StyleCounsel]]):** 개발자가 다른 이의 스타일을 모방하고 자신의 스타일을 난독화할 수 있도록 돕는 `StyleCounsel`과 같은 시스템이 개발되었습니다 [2, 12]. 이 도구는 랜덤 포레스트(Random Forest)와 같은 기계 학습 모델의 의사 결정 트리를 분석하여, 오분류를 유도할 수 있는 구체적이고 최소한의 코드 변경 사항(예: 특정 구문의 사용 빈도 조절 등)을 사용자에게 추천합니다 [2, 13, 14].
* **코드 포매팅을 통한 프라이버시 보호막:** [[Prettier|Prettier]]나 Black 등과 같은 결정론적 코드 포매터(Formatter) 및 최소화(Minification) 도구를 적용하는 것만으로도 작성자 인식 정확도를 크게 떨어뜨릴 수 있습니다 [15, 16]. 연구에 따르면 코드 포매팅 적용 시 식별 정확도가 68%에서 53%로 하락하며, 최소화를 거치면 50%까지 떨어져 코드 문체론 분석에 대한 실질적인 프라이버시 보호막(Privacy shield) 역할을 수행합니다 [17-19].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** AI 분야의 자동 자산화 수행.
### 매 Feature Family
- **Lexical**: identifier length, naming convention, comment density.
- **Syntactic (AST)**: subtree frequency, depth distribution, control-flow patterns.
- **Layout**: indentation, brace style, line length.
- **Semantic**: API choice, idiom preference (list comp vs loop).
## 🔗 지식 연결 (Graph)
- **Related Topics:** Code Stylometry, Obfuscation, Mimicry Attack, [[StyleCounsel|StyleCounsel]]
- **Projects/Contexts:** 오픈소스 기여자 익명성 보장, 검열 우회 및 프라이버시 보호 도구 개발
- **Contradictions/Notes:** Caliskan-Islam 등의 기존 연구에서는 'Stunnix'와 같은 상용 난독화 도구를 사용해도 분류기의 식별 정확도가 거의 떨어지지 않는다고 보고했습니다. 그러나 Simko 등의 적대적 연구에서는 실험 참가자들이 표면적인 수준의 변수명 교체나 국소적인 구조 변경 등 간단한 조작을 가하는 것만으로도 기계 학습 모델을 성공적으로 속일 수 있음을 입증하며 기존 분류 시스템의 취약성과 한계를 지적했습니다 [11, 20].
### 매 Attack Surface
- **Open-source contributors** — GitHub commits 의 deanonymization.
- **Malware authorship** — APT attribution.
- **Plagiarism detection** — academic/hiring context.
- **Bug bounty / leak** — anonymous reporter identification.
---
*Last updated: 2026-04-19*
### 매 Defense
1. Code transformation (Caliskan 2018 — paraphrase preserving semantics).
2. LLM-mediated rewrite (rewrite via Claude/GPT to neutralize style).
3. Style transfer to another author (mimicry).
4. Mechanical normalization (autoformatter + identifier randomization).
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### AST Feature Extractor
```python
import ast
from collections import Counter
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def ast_node_freq(source: str) -> Counter:
tree = ast.parse(source)
return Counter(type(n).__name__ for n in ast.walk(tree))
```
## 🤔 의사결정 기준 (Decision Criteria)
### Author Classifier (sklearn)
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
**선택 A를 써야 할 때:**
- *(TODO)*
pipe = Pipeline([
("tfidf", TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 5))),
("rf", RandomForestClassifier(n_estimators=300, n_jobs=-1)),
])
pipe.fit(train_sources, train_authors)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Style Obfuscation via Rewrite
```python
import anthropic
**기본값:**
> *(TODO)*
client = anthropic.Anthropic()
## ❌ 안티패턴 (Anti-Patterns)
def neutralize_style(code: str) -> str:
msg = client.messages.create(
model="claude-opus-4-7",
max_tokens=4096,
messages=[{"role": "user", "content": f"""Rewrite this code to neutralize authorial style.
Preserve semantics exactly. Use generic identifiers, standard idioms, mechanical formatting.
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
```python
{code}
```"""}],
)
return msg.content[0].text
```
### Mimicry Attack (target style)
```python
def mimic(code: str, target_samples: list[str]) -> str:
"""Rewrite `code` to look like `target_samples` author."""
target_blob = "\n---\n".join(target_samples[:3])
prompt = f"Target author samples:\n{target_blob}\n\nRewrite preserving semantics:\n{code}"
return llm_call(prompt)
```
### Detection of Obfuscated Code
```python
def obfuscation_signal(code: str) -> float:
"""High score → likely autoformatted/normalized."""
feats = ast_node_freq(code)
entropy = -sum((c/sum(feats.values())) * np.log2(c/sum(feats.values())) for c in feats.values())
return 1.0 - entropy / np.log2(len(feats)) # uniform → 0, peaked → 1
```
### Defensive Pre-commit Hook
```bash
#!/usr/bin/env bash
# .git/hooks/pre-commit
ruff format --quiet .
python -m style_neutralizer **/*.py
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Anonymous OSS contribution | LLM rewrite + autoformat |
| Whistleblower | Full mimicry to public author |
| Defensive (detection) | Char n-gram + AST RF |
| Research baseline | Caliskan 2015 features |
**기본값**: autoformat + LLM neutralization for adversarial; char n-gram TF-IDF + RF for detection.
## 🔗 Graph
- 부모: [[Stylometry]] · [[Code Authorship Attribution]]
- 변형: [[Mimicry Attack]] · [[Code Obfuscation]]
- 응용: [[Malware Attribution]] · [[Anonymous OSS]]
- Adjacent: [[Adversarial ML]] · [[Differential Privacy]]
## 🤖 LLM 활용
**언제**: style neutralization, mimicry attack, defensive paraphrase.
**언제 X**: ground-truth authorship verification 에 LLM judgment 단독 사용.
## ❌ 안티패턴
- **Autoformatter 만 의존**: AST/lexical features 는 그대로 leak.
- **Identifier rename only**: control-flow signature 가 식별 가능.
- **Single-pass LLM rewrite**: subtle idioms 잔존 — multi-pass 필요.
- **Train/test 동일 repo**: leakage — author-disjoint split 필수.
## 🧪 검증 / 중복
- Verified (Caliskan 2015 USENIX Sec, Abuhamad 2018 CCS).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — AST features, attack/defense patterns |
@@ -2,68 +2,136 @@
id: wiki-2026-0508-alternative-realities
title: Alternative Realities
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ALRE-001]
aliases: [XR, Mixed Reality, MR/AR/VR Spectrum]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced, alternative-realities, virtual-reality, multiverse, simulation-theory, digital-perception]
verification_status: applied
tags: [xr, vr, ar, mr, immersive]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: TypeScript
framework: WebXR/Three.js/Unity
---
# [[Alternative Realities|Alternative Realities]]
# Alternative Realities
## 📌 한 줄 통찰 (The Karpathy Summary)
> "인식하는 대로 창조되는 세계: 기술을 통해 물리적 현실을 확장하거나(AR), 완전히 새로운 가상 세계에 몰입(VR)함으로써 인간이 경험할 수 있는 '현실'의 경계를 무너뜨리는 복합적 지각 혁명."
## 한 줄
> **"매 reality 는 spectrum 위 한 점이다."**. Milgram 1994 RV continuum 부터 modern XR (Apple Vision Pro M5, Quest 4, Snap Spectacles 6) 까지, alternative realities 는 physical reality 를 augment / replace / blend 하는 매 mediated environment 의 총칭. 2026 의 mainstream 은 passthrough MR + hand tracking + neural input.
## 📖 구조화된 지식 (Synthesized Content)
대안 현실(Alternative Realities)은 우리가 통상적으로 인지하는 물리적 환경을 대신하거나 보완하는 모든 형태의 기술적 경험 공간을 의미합니다.
## 매 핵심
1. **범주형 모델 (Mixed Reality Spectrum)**:
* **Augmented Reality (AR)**: 현실 위에 디지털 정보를 덧씌움. (예: 스마트 글래스 내 정보 표시)
* **Virtual Reality (VR)**: 물리적 감각을 차단하고 완전히 만들어진 세계에 참여함.
* **Mixed Reality (MR)**: 현실과 가상의 사물이 실시간으로 상호작용함.
2. **영향력**:
* **Perception [[Shift|Shift]]**: '진짜'의 정의에 대한 질문. 디지털 자산(NFT)이나 가상 인간과의 교류가 실질적인 경제적/감정적 영향을 미침.
* **[[Spatial Computing|Spatial Computing]]**: 마우스나 터치가 아닌 '공간' 자체가 인터페이스가 되는 혁신.
3. **심리적/철학적 관점**:
* **Simulation Theory**: 우리 우주 자체가 누군가에 의해 설계된 대안 현실일 수 있다는 가설.
### 매 Reality-Virtuality Continuum
- **VR (Virtual Reality)**: 매 100% synthetic — Quest 4, Vision Pro fully-immersive mode.
- **AR (Augmented Reality)**: 매 real + overlay — phone AR, Snap Spectacles, HoloLens.
- **MR (Mixed Reality)**: 매 real + virtual interact — Vision Pro passthrough, Quest 4 color passthrough.
- **XR (Extended Reality)**: 매 umbrella term — VR/AR/MR all-inclusive.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 시각적 자극에 치중한 '엔터테인먼트 전용' 정책이었으나, 현대의 공간 지능 정책은 의료, 제조, 교육 현장에서의 실질적 협업을 위한 '산업용 대안 현실 정책'으로 시장의 중심을 옮김(RL Update).
- **정책 변화(RL Update)**: 가상 공간에서의 범죄나 괴롭힘 리스크 정책이 부각됨에 따라, 현실 세계의 법률을 대안 현실 공간까지 확장 적용하는 '메타버스 거버넌스 정책'이 글로벌 논의 단계에 진입함.
### 매 Tech Stack 2026
- **Display**: micro-OLED 4K/eye, varifocal, foveated rendering.
- **Tracking**: inside-out 6DoF, eye tracking, hand tracking 26-joint, body pose.
- **Input**: pinch + gaze (Vision Pro), neural EMG (Meta wristband 2026), voice (Whisper-on-device).
- **Compute**: Apple M5/Snapdragon XR3 — 매 on-device transformer inference.
## 🔗 지식 연결 (Graph)
- [[Visual-Effects-VFX|Visual-Effects-VFX]], Human-Computer Interaction (HCI), [[Aesthetic-Value|Aesthetic-Value]], Simulation Theory, [[Sociology of Knowledge|Sociology of Knowledge]]
- **Modern Tech/Tools**: Apple Vision Pro, Meta Quest, [[Unity|Unity]]/Unreal Engine, Omniverse.
---
### 매 응용
1. **Productivity**: Vision Pro virtual displays, Immersed VR coding.
2. **Training**: surgical sim, military, industrial maintenance.
3. **Therapy**: VR exposure (PTSD, phobia), pain distraction.
4. **Social**: Horizon Worlds, VRChat, Rec Room.
5. **Industrial Twin**: AR overlay on factory equipment.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### WebXR session bootstrap
```typescript
// Modern WebXR (2026) — immersive-ar with hand tracking
const xr = navigator.xr;
if (await xr.isSessionSupported('immersive-ar')) {
const session = await xr.requestSession('immersive-ar', {
requiredFeatures: ['hand-tracking', 'hit-test'],
optionalFeatures: ['anchors', 'plane-detection', 'mesh-detection'],
});
session.addEventListener('end', cleanup);
await renderer.xr.setSession(session);
}
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### Hand-tracking pinch gesture
```typescript
function onXRFrame(time: number, frame: XRFrame) {
const refSpace = renderer.xr.getReferenceSpace();
for (const inputSource of frame.session.inputSources) {
if (!inputSource.hand) continue;
const thumb = frame.getJointPose(inputSource.hand.get('thumb-tip'), refSpace);
const index = frame.getJointPose(inputSource.hand.get('index-finger-tip'), refSpace);
const dist = vec3.distance(thumb.transform.position, index.transform.position);
if (dist < 0.02) emit('pinch', inputSource.handedness);
}
}
```
## 🧪 검증 상태 (Validation)
### Passthrough + virtual content (Three.js)
```typescript
renderer.xr.enabled = true;
renderer.setClearAlpha(0); // 매 transparent — passthrough shows through
scene.background = null;
// 매 virtual cube anchored to detected plane
const anchor = await frame.createAnchor(planePose.transform, refSpace);
scene.add(makeCubeAtAnchor(anchor));
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Foveated rendering hint
```typescript
const layer = xr.glLayer;
layer.fixedFoveation = 0.7; // 매 0=off, 1=max — 매 30% GPU savings
```
## 🧬 중복 검사 (Duplicate Check)
### Eye-tracked gaze input
```typescript
session.requestReferenceSpace('viewer').then(viewerSpace => {
// 매 Vision Pro / Quest Pro — gaze ray from eye
const gazePose = frame.getPose(viewerSpace, refSpace);
raycaster.set(gazePose.transform.position, gazeDirection);
});
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Web 배포 | WebXR + Three.js |
| Native iOS | RealityKit + ARKit |
| Native Android | ARCore + Sceneform/Filament |
| Cross-platform native | Unity XR / Unreal |
| Enterprise 산업 | Vision Pro / HoloLens 2 |
## 🕓 변경 이력 (Changelog)
**기본값**: 매 WebXR 시도 → 부족시 native.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🔗 Graph
- 부모: [[VR 엑서게임 (VR Exergaming)]] · [[HMD(Head-Mounted Display) 기반 엑서게임 환경]]
- 변형: [[Digital Twins]] · [[Digital-Twin-Technology]]
- 응용: [[Beat Saber 엑서게임 연구(Beat Saber Exergaming Study)]] · [[Remote-Rehabilitation]]
- Adjacent: [[Visual-Effects-VFX]]
## 🤖 LLM 활용
**언제**: XR scene authoring, gesture pattern matching, accessibility caption generation.
**언제 X**: 매 real-time inner loop (latency budget 11ms) 에서 cloud LLM 호출.
## ❌ 안티패턴
- **VR 멀미 무시**: 매 locomotion = teleport/snap-turn 권장. Smooth locomotion 은 매 opt-in.
- **60fps 미만**: 매 90fps 미만 = motion sickness. 매 budget 11ms.
- **Untracked controllers**: 매 always handle controller-lost 이벤트.
- **Single-eye render**: 매 stereo render 필수 — single-eye 는 depth 깨짐.
## 🧪 검증 / 중복
- Verified: Milgram & Kishino 1994; W3C WebXR Device API 2024; Apple visionOS 3 docs.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — XR continuum + 2026 stack + WebXR patterns |
@@ -2,21 +2,148 @@
id: wiki-2026-0508-analyze-runtime-performance
title: Analyze runtime performance
category: 10_Wiki/Topics
status: merged
redirect_to: 성능_프로파일링_및_메모리_관리_표준
canonical_id: wiki-2026-0508-040
aliases: []
status: verified
canonical_id: self
aliases: [Performance Analysis, Profiling, Runtime Profiling]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [profiling, performance, devtools]
raw_sources: []
last_reinforced: 2026-05-08
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: JavaScript/Python
framework: Chrome DevTools/perf/py-spy
---
# Redirect
# Analyze runtime performance
이 문서는 Canonical 문서인 [[성능_프로파일링_및_메모리_관리_표준]]으로 통합되었습니다.
모든 최신 지식과 세부 내용은 위 링크를 참조하십시오.
## 매 한 줄
> **"매 측정 없이 최적화 없다."**. Runtime performance 분석은 sampling profiler + tracing + flame graph + RAIL/Web Vitals metrics 의 stack 으로 매 hot path 와 long task 를 식별. 2026 stack: Chrome Performance panel (Insights AI), perf+FlameGraph, py-spy, eBPF/bpftrace, Datadog APM.
## 매 핵심
### 매 Profiler Type
- **Sampling**: 매 N ms 마다 stack 캡처 — 매 low overhead, statistical (perf, py-spy, async-profiler).
- **Instrumentation**: 매 fn enter/exit 기록 — 매 accurate, high overhead.
- **Tracing**: 매 event timeline (Chrome trace, perfetto).
- **Hardware counters**: PMU — IPC, cache miss, branch miss.
### 매 RAIL Model (web)
- **Response**: < 100ms input → feedback.
- **Animation**: < 16ms / frame (60fps).
- **Idle**: 50ms work blocks max.
- **Load**: < 5s on 4G.
### 매 Core Web Vitals 2026
- **LCP** (Largest Contentful Paint) < 2.5s.
- **INP** (Interaction to Next Paint) < 200ms — 매 FID 대체 (2024+).
- **CLS** (Cumulative Layout Shift) < 0.1.
### 매 응용
1. Web app TTI/INP 개선.
2. Backend p99 latency 추적.
3. Game/XR frame budget.
4. ML inference latency.
5. CI pipeline 시간 단축.
## 💻 패턴
### Chrome Performance panel + AI insights
```javascript
// 매 manual marker — show up in Performance timeline
performance.mark('ai-search:start');
const r = await search(q);
performance.mark('ai-search:end');
performance.measure('ai-search', 'ai-search:start', 'ai-search:end');
// 매 record trace in DevTools → AI Insights highlights bottleneck (2025+)
```
### User Timing API + reporter
```javascript
const obs = new PerformanceObserver(list => {
list.getEntries().forEach(e => analytics('perf', { name: e.name, dur: e.duration }));
});
obs.observe({ entryTypes: ['measure', 'navigation', 'resource', 'longtask'] });
```
### py-spy live flame graph
```bash
# 매 attach to running PID, no code change
py-spy record -o flame.svg --pid 12345 --duration 30
# 매 live top-like
py-spy top --pid 12345
```
### Linux perf flame graph
```bash
sudo perf record -F 99 -g -p $PID -- sleep 30
sudo perf script | \
./stackcollapse-perf.pl | ./flamegraph.pl > flame.svg
```
### Web Vitals INP measurement
```javascript
import { onINP, onLCP, onCLS } from 'web-vitals';
onINP(m => beacon('inp', m.value, m.id));
onLCP(m => beacon('lcp', m.value, m.id));
onCLS(m => beacon('cls', m.value, m.id));
```
### Node --prof + --prof-process
```bash
node --prof server.js
# 매 after run
node --prof-process isolate-*.log > profile.txt
```
### eBPF (bpftrace) syscall latency
```bash
sudo bpftrace -e '
tracepoint:syscalls:sys_enter_read { @s[tid] = nsecs; }
tracepoint:syscalls:sys_exit_read /@s[tid]/ {
@us = hist((nsecs - @s[tid]) / 1000);
delete(@s[tid]);
}'
```
## 매 결정 기준
| 상황 | Tool |
|---|---|
| Web (Chromium) | DevTools Performance + Web Vitals |
| Node.js | clinic.js / 0x / --prof |
| Python | py-spy / scalene / cProfile |
| JVM | async-profiler / JFR |
| Go | pprof |
| Linux native | perf + FlameGraph / eBPF |
| Production APM | Datadog / NewRelic / OTel |
**기본값**: 매 sampling profiler 우선, instrumentation 은 spot-check.
## 🔗 Graph
- 부모: [[Flame_Graphs]]
- 변형: [[CPU Bottleneck]]
- 응용: [[High Resolution Time]] · [[Memory Management]]
- Adjacent: [[Page Experience Algorithm]] · [[Debugger_Techniques]]
## 🤖 LLM 활용
**언제**: flame graph 해석, perf insight 요약, regression hypothesis.
**언제 X**: 매 nanosecond-level profiling — specialized tool 만이 정확.
## ❌ 안티패턴
- **Production 에 instrumenting profiler**: 매 overhead 폭발.
- **Single-run 결론**: 매 statistical noise — multi-run 필요.
- **Average only**: 매 p50 보다 p99 가 user 체감.
- **Profile dev build**: 매 prod build 와 다름 — release/optimized 측정.
## 🧪 검증 / 중복
- Verified: web.dev Performance docs; Brendan Gregg "Systems Performance"; Chrome DevTools docs.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — RAIL/INP + multi-language profilers |
@@ -2,94 +2,147 @@
id: wiki-2026-0508-anomaly-detection
title: Anomaly Detection
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-ANDE-001]
aliases: [Outlier Detection, Novelty Detection, 이상 탐지]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
tags: [auto-reinforced, anomaly-detection, data-science, security, Quality-Control, machine-learning]
confidence_score: 0.9
verification_status: applied
tags: [security, ml, monitoring, observability]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: unspecified
framework: unspecified
language: Python
framework: scikit-learn/PyOD/Prometheus
---
# [[Anomaly-Detection|Anomaly-Detection]]
# Anomaly Detection
## 📌 한 줄 통찰 (The Karpathy Summary)
> "정상 속에 숨은 이질감 찾기: 평소와 다른 데이터 패턴을 즉각 감지하여, 잠재적인 사고, 부정 결제, 해킹, 혹은 신기술 탄생의 징후를 골라내는 지능형 레이더."
## 한 줄
> **"매 normal 의 boundary 를 학습하고 그 밖을 flag 한다."**. Anomaly detection 은 fraud, intrusion, equipment failure, log spike 등을 unsupervised 로 발견하는 매 core observability/security primitive. 2026 의 standard 는 Isolation Forest + LSTM-AE + transformer-based time-series (PatchTST, TimesNet).
## 📖 구조화된 지식 (Synthesized Content)
이상 탐지(Anomaly-Detection)는 대다수의 데이터와는 현저하게 다른 특성을 가진 '이상치(Outliers)'를 찾아내는 머신러닝 기법입니다.
## 매 핵심
1. **핵심 유형**:
* **Point Anomaly**: 특정 데이터 포인트가 전체 분포에서 크게 벗어남. (예: 카드 도용 고액 결제)
* **Contextual Anomaly**: 값 자체는 정상이나 맥락상 이상함. (예: 한여름에 난방비 급증)
* **Collective Anomaly**: 여러 데이터가 모였을 때 비정상적 패턴 형성. (예: 디도스 공격)
2. **학습 방식**:
* **Unsupervised**: 이상 데이터가 사전에 없어도 '정상'의 기준을 학습하여 나머지를 이상으로 간주. (가장 흔함)
* **Supervised**: 알려진 이상 사례(레이블)를 학습하여 탐지.
3. **적용 분야**:
* 공장 설비 고전 진단, 금융 사기 탐지(FDS), 네트워크 침입 감지, 암세포 진단.
### 매 Anomaly Type 3가지
- **Point anomaly**: 매 single observation 이 outlier — credit card 단일 거래.
- **Contextual anomaly**: 매 context 에서만 anomaly — 여름의 영하 온도.
- **Collective anomaly**: 매 group 으로만 anomaly — DDoS 의 packet sequence.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 특정 임계값(Threshold)을 넘으면 알람을 울리는 단순 정책이었으나, 현대 AI 정책은 데이터의 동적 변화를 반영하여 임계값을 스스로 조정하는 'Adaptive Threshold 정책'으로 진화함(RL Update).
- **정책 변화(RL Update)**: 보안 및 개인정보 정책에서, 단순 탐지를 넘어 보이지 않는 위협을 선제적으로 차단하는 'Zero Trust 보안 정책'의 핵심 기술로 이상 탐지 알고리즘이 채택됨.
### 매 Algorithm Family
- **Statistical**: z-score, MAD, Grubbs, EWMA — 매 univariate baseline.
- **Distance-based**: kNN, LOF — 매 density 차이로 detect.
- **Tree-based**: Isolation Forest, Extended IF — 매 high-dim 잘 작동.
- **Reconstruction**: Autoencoder, VAE — 매 reconstruction error = anomaly score.
- **Time-series DL**: LSTM-AE, Transformer (PatchTST 2024, TimesNet) — 매 SOTA 2026.
- **One-class**: One-Class SVM, Deep SVDD — 매 normal-only training.
## 🔗 지식 연결 (Graph)
- [[Time-Series-Analysis|Time-Series-Analysis]], Pattern Recognition, [[Safety & Reliability|Safety & Reliability]], [[Variational Autoencoders (VAE)|Variational Autoencoders (VAE)]], [[Decision Theory|Decision Theory]]
- **Modern Tech/Tools**: Isolation Forest, One-Class SVM, Amazon Lookout for Metrics.
---
### 매 응용
1. **Fraud detection**: payment, account takeover.
2. **Intrusion detection (IDS)**: network traffic anomaly.
3. **Predictive maintenance**: vibration sensor, temp.
4. **APM**: latency/error rate spike — Datadog Watchdog, New Relic.
5. **Log anomaly**: unseen log template — DeepLog, LogBERT.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Isolation Forest baseline
```python
from sklearn.ensemble import IsolationForest
import numpy as np
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# 매 contamination = expected anomaly fraction
clf = IsolationForest(contamination=0.01, n_estimators=200, random_state=42)
clf.fit(X_train)
scores = -clf.score_samples(X_test) # 매 high score = more anomalous
preds = clf.predict(X_test) # -1=anomaly, 1=normal
```
## 🤔 의사결정 기준 (Decision Criteria)
### LOF for density anomaly
```python
from sklearn.neighbors import LocalOutlierFactor
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.01, novelty=True)
lof.fit(X_train)
anomaly_score = -lof.score_samples(X_test)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Autoencoder reconstruction error (PyTorch)
```python
import torch.nn as nn
class AE(nn.Module):
def __init__(self, d=64):
super().__init__()
self.enc = nn.Sequential(nn.Linear(d,32), nn.ReLU(), nn.Linear(32,8))
self.dec = nn.Sequential(nn.Linear(8,32), nn.ReLU(), nn.Linear(32,d))
def forward(self, x): return self.dec(self.enc(x))
**선택 B를 써야 할 때:**
- *(TODO)*
# 매 train on normal only — anomaly = high reconstruction error
recon = model(x)
score = ((x - recon) ** 2).mean(dim=1)
```
**기본값:**
> *(TODO)*
### EWMA streaming detector
```python
class EWMA:
def __init__(self, alpha=0.1, k=3.0):
self.alpha, self.k = alpha, k
self.mu = self.var = None
def step(self, x):
if self.mu is None: self.mu, self.var = x, 1.0; return False
z = abs(x - self.mu) / (self.var ** 0.5 + 1e-9)
self.mu = self.alpha * x + (1 - self.alpha) * self.mu
self.var = self.alpha * (x - self.mu)**2 + (1 - self.alpha) * self.var
return z > self.k
```
## ❌ 안티패턴 (Anti-Patterns)
### PyOD ensemble
```python
from pyod.models.iforest import IForest
from pyod.models.lof import LOF
from pyod.models.combination import average
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
scores = np.column_stack([
IForest().fit(X).decision_function(X),
LOF().fit(X).decision_function(X),
])
ensemble_score = average(scores)
```
## 매 결정 기준
| 상황 | Algorithm |
|---|---|
| Tabular, low-dim | Isolation Forest |
| Tabular, density 중요 | LOF |
| Time-series univariate | EWMA / Prophet |
| Time-series multivariate | LSTM-AE / PatchTST |
| Image | PaDiM / PatchCore |
| Log sequence | LogBERT / DeepLog |
**기본값**: 매 Isolation Forest baseline → 부족시 deep model.
## 🔗 Graph
- 부모: [[Statistics & Data Analysis]]
- 변형: [[Inferential-Statistics]]
- 응용: [[Malware-Analysis]] · [[Deepfake-Detection]] · [[Logging_and_Error_Handling]]
- Adjacent: [[경고 피로 (Alert Fatigue)]]
## 🤖 LLM 활용
**언제**: log template 추출, anomaly explanation generation, false-positive triage.
**언제 X**: 매 high-frequency stream 의 inner-loop scoring (use specialized model).
## ❌ 안티패턴
- **Threshold hard-coding**: 매 environment drift 시 무용지물 — adaptive threshold 사용.
- **Class imbalance 무시**: 매 anomaly 0.1% 일 때 accuracy 99.9% 무의미 — PR-AUC.
- **Train on contaminated data**: 매 anomaly 가 train set 에 섞이면 mask 됨.
- **Alert fatigue**: 매 raw score 그대로 alert 면 dev 가 무시.
## 🧪 검증 / 중복
- Verified: Liu et al. 2008 (Isolation Forest); PyOD docs; Nie et al. 2023 (PatchTST).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — algorithm taxonomy + PyOD/AE patterns |
@@ -2,21 +2,32 @@
id: wiki-2026-0508-appsec-애플리케이션-보안
title: AppSec (애플리케이션 보안)
category: 10_Wiki/Topics
status: merged
redirect_to: 보안_및_시스템_신뢰성_표준
canonical_id: wiki-2026-0507-039
aliases: []
duplicate_of: none
status: duplicate
canonical_id: appsec
duplicate_of: "[[OWASP Top 10]]"
aliases: [Application Security, 앱보안]
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
raw_sources: []
last_reinforced: 2026-05-08
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
confidence_score: 0.9
verification_status: redirected
tags: [duplicate, appsec, security]
last_reinforced: 2026-05-10
github_commit: applied
---
# Redirect
# AppSec (애플리케이션 보안)
이 문서는 Canonical 문서인 [[보안_및_시스템_신뢰성_표준]]으로 통합되었습니다.
모든 최신 지식과 세부 내용은 위 링크를 참조하십시오.
> **이 문서는 [[OWASP Top 10]] 의 중복본입니다.** AppSec 의 정수는 OWASP Top 10 + DevSecOps loop 으로 흡수되어 canonical 로 redirect.
## 핵심 요약
- AppSec = SAST + DAST + SCA + Secret scanning + Threat modeling + Runtime protection.
- Korean alias 로 maintain — 매 OWASP Top 10 / DevSecOps_Framework 가 substantive content.
## 🔗 Graph
- 부모: [[OWASP Top 10]] (canonical) · [[DevSecOps_Framework]]
- Adjacent: [[SAST]] · [[DAST]] · [[SCA]] · [[Secret_Management]] · [[안전한 소프트웨어 개발 수명주기(SSDLC)]]
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — OWASP Top 10 / DevSecOps_Framework 로 redirect |
@@ -2,96 +2,147 @@
id: wiki-2026-0508-automated-quality-review
title: "Automated Quality & Review"
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-REINFORCE-AUTO-WIKI-AUTO-001]
aliases: [Automated Code Review, AI Code Review, CR Automation]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [automation, code-review, static-analysis, linting, quality-gate, dev-tools, p-reinforce]
confidence_score: 0.9
verification_status: applied
tags: [code-review, ci, devops, llm]
raw_sources: []
last_reinforced: 2026-05-01
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript/Python
framework: GitHub Actions/Claude Code/Copilot
---
# [[Automated Quality & Review|Automated Quality & Review]]
# Automated Quality & Review
## 📌 한 줄 통찰 (The Karpathy Summary)
> "인간 리뷰어보다 먼저 코드의 구문, 스타일, 알려진 취약점을 필터링하여 품질의 최소 기준을 강제하고, 리뷰 시간을 고부가가치 설계 토론에 집중시키는 지능형 자동화 방어선."
## 한 줄
> **"매 PR 의 first reviewer 는 machine 이다."**. Automated Quality & Review 는 lint, type-check, test, SAST, AI review 를 PR pipeline 에 stack 하여 human reviewer 가 매 substance 만 보게 하는 매 modern engineering practice. 2026 의 stack: Biome + tsc + Vitest + Semgrep + Claude/Copilot review bot.
## 📖 구조화된 지식 (Synthesized Content)
자동화된 품질 관리는 현대 엔지니어링의 생산성을 결정짓는 필수 인프라입니다.
## 매 핵심
1. **정적 분석 및 린팅 (Static Analysis & Linting)**:
* **구문 및 스타일 강제**: 린터(Linter)와 포매터(Formatter)를 통해 팀의 컨벤션을 자동으로 유지하며 소모적인 스타일 논쟁을 제거합니다.
* **[[SAST (Static Application Security Testing)|SAST (Static Application Security Testing]]**: 소스 코드 레벨에서 OWASP Top 10 등의 보안 결함을 조기에 탐지합니다.
2. **리뷰 자동화 (Review Automation)**:
* **품질 게이트 (Quality Gate)**: CI/CD 파이프라인과 연동하여 테스트 커버리지, 코드 복잡도, 보안 기준을 충족하지 못한 PR의 병합을 시스템적으로 차단합니다.
* **사전 커밋 훅 (Pre-commit Hooks)**: 코드가 원격 저장소에 푸시되기 전 로컬에서 즉각적인 피드백을 제공하여 수정 주기를 단축합니다.
3. **도구 통합 (Tools Integration)**:
* GitHub Actions, SonarQube, CodeClimate 등 다양한 분석 도구를 PR 워크플로우에 통합하여 코드 건강 상태를 가시화하고 추적합니다.
### 매 Quality Gate Layer
1. **Format**: Biome / Prettier — 매 zero-arg.
2. **Lint**: Biome / ESLint / Ruff — 매 style + likely-bug rules.
3. **Type**: tsc / mypy / pyright — 매 static contract.
4. **Test**: Vitest / Jest / pytest — 매 unit + integration.
5. **Coverage**: c8 / coverage.py — 매 80%+ delta enforced.
6. **SAST**: Semgrep / CodeQL — 매 security pattern.
7. **AI review**: Claude Code, Copilot Workspace, Cursor — 매 semantic.
8. **Mutation**: Stryker — 매 test quality 검증 (optional).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **오탐(False Positive)의 노이즈**: 자동화 도구가 실제 위협이 아닌 코드를 결함으로 지적할 경우 개발자의 피로도가 증가합니다. 프로젝트 맥락에 맞는 규칙 커스터마이징과 예외 처리 정책이 중요합니다.
- **인간의 대체 불가능성**: 자동화는 정해진 패턴은 잘 찾지만 비즈니스 맥락, 아키텍처 의도, 복잡한 접근 제어 로직은 이해하지 못합니다. 기계는 '규칙 준수'를, 인간은 '의도와 설계'를 검증하는 분업 구조를 유지해야 합니다.
### 매 AI Review 2026 Capability
- **Logic bug detection**: Claude Opus 4.7 finds nil-deref, race, off-by-one.
- **Convention enforcement**: 매 codebase context 학습 후 style 위반 flag.
- **Security**: SQLi, XSS, IDOR, deserialization 의 dataflow 추적.
- **Performance**: N+1 query, O(n²) loop, unbounded recursion.
- **Test gap**: 매 코드 변경 vs test coverage delta 분석.
## 🔗 지식 연결 (Graph)
- [[SAST (Static Application Security Testing)|SAST (Static Application Security Testing]]: 정적 보안 분석의 심화.
- [[CI-CD Pipeline|CI-CD Pipeline]]: 자동화 검증이 실행되는 핵심 환경.
- [[Code Review Checklist|Code Review Checklist]]: 자동화가 처리하지 못하는 인간의 영역.
- Shift-Left Security: 보안 점검을 자동화로 조기 도입하는 전략.
- [[Technical-Debt|Technical Debt]]: 자동화된 대시보드를 통해 관리되는 부채.
---
### 매 응용
1. PR comment bot — 매 inline suggestions.
2. Pre-merge gate — 매 critical issue block.
3. Refactor suggester — 매 nightly batch.
4. Onboarding — 매 junior dev 의 mentor.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### GitHub Actions quality pipeline
```yaml
name: pr-quality
on: pull_request
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2
- run: bun install --frozen-lockfile
- run: bun run biome check .
- run: bun run tsc --noEmit
- run: bun run vitest run --coverage
- uses: returntocorp/semgrep-action@v1
with: { config: 'p/owasp-top-ten' }
- uses: anthropics/claude-code-action@v1
with:
mode: review
model: claude-opus-4-7
```
## 🤔 의사결정 기준 (Decision Criteria)
### Claude Code review prompt
```markdown
You are reviewing PR #{number}. Focus on:
1. Logic bugs (off-by-one, null deref, race conditions)
2. Security (OWASP Top 10)
3. Performance (N+1, unbounded loops)
4. Test coverage for changed lines
**선택 A를 써야 할 때:**
- *(TODO)*
Output format: file:line — severity — description.
Skip: style nits (handled by Biome).
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Reviewdog inline comment
```yaml
- run: bun run biome check --reporter=github . | reviewdog -f=github-check -reporter=github-pr-review
```
**기본값:**
> *(TODO)*
### Coverage delta gate
```yaml
- uses: ArtiomTr/jest-coverage-report-action@v2
with:
threshold: '{"lines":80,"branches":75}'
annotations: failed-tests
```
## ❌ 안티패턴 (Anti-Patterns)
### Semgrep custom rule
```yaml
rules:
- id: hardcoded-secret
pattern-either:
- pattern: const $K = "$VAL"
metavariable-regex:
$K: '(?i)(api[_-]?key|secret|token|password)'
message: Hardcoded secret detected
severity: ERROR
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Tool |
|---|---|
| TS/JS format+lint | Biome (single tool) |
| Python format+lint | Ruff |
| Type check | tsc strict / pyright strict |
| Security SAST | Semgrep + CodeQL |
| AI review | Claude Code Action |
| PR comment UX | reviewdog |
**기본값**: 매 Biome + tsc + Vitest + Semgrep + Claude review.
## 🔗 Graph
- 부모: [[CI_CD_Pipeline]]
- 변형: [[수동 코드 리뷰]] · [[자동화된 코드 리뷰]]
- 응용: [[SAST]] · [[Husky]] · [[lint-staged]]
- Adjacent: [[Engineering Metrics (DORA)]] · [[Test_Automation]]
## 🤖 LLM 활용
**언제**: PR review, refactor suggestion, test gap detection, commit message generation.
**언제 X**: 매 deterministic check (lint, type) — specialized tool 이 빠르고 정확.
## ❌ 안티패턴
- **AI-only review**: 매 human approval 없이 merge 허용 — accountability 사라짐.
- **Slow pipeline**: 매 30분 PR check 면 dev 가 우회. 5분 budget.
- **Style nit storm**: 매 AI 가 nit 만 쏟으면 중요한 logic bug 가 묻힘.
- **No fail-fast**: 매 lint fail 후에도 test 실행 — 매 sequential gate.
## 🧪 검증 / 중복
- Verified: GitHub Actions docs; Anthropic Claude Code docs; Semgrep playbook 2024.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — quality gate layers + Claude Code action |
@@ -2,94 +2,142 @@
id: wiki-2026-0508-bluf-bottom-line-up-front
title: BLUF (Bottom Line Up Front)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [a1b2c3d4-e5f6-4901-2e3f-4a5b6c7d8e9f]
aliases: [a1b2c3d4-e5f6-4901-2e3f-4a5b6c7d8e9f, Bottom Line Up Front]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [bluf, bottom-line-up-front, pyramid-principle, executive-communication, Efficiency]
verification_status: applied
tags: [communication, writing, devops, incident-response]
raw_sources: []
last_reinforced: 2026-04-27
github_commit: "[[P-Reinforce|P-Reinforce]]-comm"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: markdown
framework: none
---
# [[BLUF (Bottom Line Up Front)|BLUF (Bottom Line Up Front]]
# BLUF (Bottom Line Up Front)
## 📌 한 줄 통찰 (The Karpathy Summary)
> BLUF는 핵심 결론을 최상단에 배치하여 의사결정자의 시간을 존중하고 소통의 명확성을 즉각적으로 확보하는 고효율 커뮤니케이션 프로토콜이다.
## 한 줄
> **"매 conclusion 을 첫 줄에 — recipient 가 더 못 읽어도 OK 하도록."**. US military origin 의 writing convention; 매 incident report, exec memo, PR description, on-call alert 의 표준 — 매 reader 의 cognitive load 를 minimize 하고 fastest decision-making 을 enable.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 결론 우선 제시(Answer First)를 통한 인지 효율성 극대화 및 비판적 분석 유도.
- **핵심 원리:**
- **Bottom Line Up Front:** 도입부 직후에 권고사항, 결론, 요청 사항을 직접적으로 전달.
- **Time Efficiency:** 바쁜 임원진의 시간을 절약하고 세부 정보 탐독 여부를 신속히 결정하게 함.
- **Critical [[Analysis|Analysis]] [[Support|Support]]:** 결론을 먼저 인지한 청중이 이어지는 근거들을 더 목적 지향적이고 비판적으로 분석 가능하게 함.
- **Professional Presence:** 주장의 확신과 전문성을 드러내어 설득력을 강화.
- **예외 케이스:** 결론에 대한 강한 반감이 예상되거나 극도의 논리적 축적이 필요한 경우 연역적(Deductive) 접근법 고려.
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Parent:** Communication & Tech
- **Related:** The [[Pyramid Principle|Pyramid Principle]], Executive Communication, [[SCQA Framework|SCQA Framework]]
- **Raw Source:** 00_Raw/BLUF (Bottom Line Up Front, 00_Raw/BLUF(Bottom Line Up Front), 00_Raw/Bottom Line Up Front (BLUF)
### 매 Structure
- **Line 1**: the conclusion / decision needed / status verdict.
- **Line 2-N**: supporting evidence in priority order.
- **Tail**: details, appendices, traces.
---
*Last updated: 2026-04-27*
### 매 vs Narrative
- Narrative: "We started X, encountered Y, debugged Z, found root cause W, fixed it." — reader waits for punchline.
- BLUF: "Outage resolved. Root cause: misconfigured DNS. Restored 14:23 UTC." — punchline first.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Incident postmortem TL;DR.
2. PR description first sentence.
3. Slack on-call escalation.
4. Email subject + first line.
5. Architecture decision record (ADR) summary.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Incident Slack Alert
```markdown
**[P1] Checkout API 5xx — DEGRADED**
Impact: 12% of orders failing since 14:05 UTC.
Action: rollback v2.4.1 in progress, ETA 5 min.
Owner: @oncall-payments
Thread: ↓
```
## 🤔 의사결정 기준 (Decision Criteria)
### Postmortem Top
```markdown
# Postmortem: 2026-05-08 Checkout Outage
**선택 A를 써야 할 때:**
- *(TODO)*
**TL;DR**: 47-min P1 outage due to DNS TTL misconfig in v2.4.1 deploy.
- Customer impact: ~3,200 failed orders (~$84k revenue)
- Resolution: rollback at 14:23 UTC
- Action items: 4 (see §6)
**선택 B를 써야 할 때:**
- *(TODO)*
## Timeline
...
```
**기본값:**
> *(TODO)*
### PR Description
```markdown
**Adds rate limiting to /api/checkout to prevent abuse.**
## ❌ 안티패턴 (Anti-Patterns)
- New: `RateLimiter` middleware with Redis token bucket
- Default: 60 req/min per IP, configurable via env
- Tests: integration coverage for 429 path
- Risk: low — feature-flagged behind `RATE_LIMIT_ENABLED`
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## Why
Spike on 05-06 saturated DB connections...
```
### Email Template
```markdown
Subject: [DECISION NEEDED by Fri] Migrate auth to OIDC — recommend Keycloak
Recommendation: adopt Keycloak for SSO; deprecate legacy LDAP by Q3.
Cost: $0 (OSS) + 2 SRE-weeks integration.
Risk: medium (auth migration); mitigated by phased rollout.
Background: ...
```
### ADR Header
```markdown
# ADR-0042: Use SQLite for local dev DB
**Decision**: SQLite for local; Postgres for staging/prod.
**Status**: accepted (2026-05-10)
**Context**: ... (3 paragraphs below)
```
### On-Call Status Page
```markdown
🟢 **All systems operational** — last incident 9 days ago.
Recent: deploys 4 (all green) · alerts 0 · SLO budget 99.4%
```
## 매 결정 기준
| 상황 | BLUF 적용 |
|---|---|
| Incident alert | YES — line 1 = severity + impact |
| Postmortem | YES — TL;DR block before timeline |
| Tutorial / explainer | NO — narrative 적합 |
| Marketing copy | NO — hook 후 reveal |
| ADR | YES — decision first |
| Bug report | YES — observed vs expected first |
**기본값**: ops/exec communication 은 BLUF; pedagogical/narrative 은 example-first.
## 🔗 Graph
- 부모: [[Technical Writing]] · [[Incident Response]]
- 변형: [[TL;DR]] · [[Inverted Pyramid]]
- 응용: [[Postmortem]] · [[ADR]] · [[On-Call Runbook]]
- Adjacent: [[Pyramid Principle]] · [[Minto]]
## 🤖 LLM 활용
**언제**: ask LLM to "rewrite as BLUF" — high-quality reflow.
**언제 X**: storytelling / customer-facing narrative.
## ❌ 안티패턴
- **Buried lede**: conclusion 을 §3 에 묻기.
- **Over-summarize**: line 1 이 vague ("there was an issue").
- **No context for novices**: BLUF 는 expert reader 가정 — onboarding doc 에는 부적합.
- **Decision-less BLUF**: "We did X" 보다 "Recommend Y" 가 actionable.
## 🧪 검증 / 중복
- Verified (US Army Field Manual, Google SRE Book postmortem chapter).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with templates for incidents/PRs/ADRs |
+139 -66
View File
@@ -2,92 +2,165 @@
id: wiki-2026-0508-bvh
title: BVH
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-D211FC]
aliases: [P-Reinforce-AUTO-D211FC, Bounding Volume Hierarchy]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [graphics, raytracing, datastructure, performance]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - BVH"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: rust
framework: none
---
# [[BVH|BVH]]
# BVH
## 📌 한 줄 통찰 (The Karpathy Summary)
> BVH(Bounding Volume Hierarchy)는 3D 환경에서 빠르고 효율적인 레이캐스팅([[Raycasting|Raycasting]]), 절두체 컬링([[Frustum Culling|Frustum Culling]]) 및 공간 질의(Spatial Queries)를 가능하게 하는 정교한 공간 분할 자료구조입니다 [1, 2]. 이는 렌더링, 조명 및 그림자 연산, 충돌 처리, 자산의 메모리 로딩 등 광범위한 최적화를 주도하는 핵심 기반 기술입니다 [3]. Three.js 생태계에서는 주로 대규모 폴리곤이나 복잡한 인스턴스 씬에서의 성능을 극대화하기 위해 활용됩니다 [1, 4].
## 한 줄
> **"매 ray-object intersection 의 O(N) → O(log N) 변환의 표준 자료구조."**. Bounding Volume Hierarchy 는 ray tracing, collision detection, frustum culling 의 backbone — 매 modern path tracer (RTX, OptiX, Embree) 의 acceleration structure 핵심이며, SAH (Surface Area Heuristic) build 가 quality 의 standard.
## 📖 구조화된 지식 (Synthesized Content)
- **성능 최적화 및 고속 레이캐스팅:** BVH는 복잡한 기하학적 구조를 가진 대화형 씬에서 레이캐스팅을 가속화하는 데 필수적인 요소입니다 [4]. `[[three-mesh-bvh|three-mesh-bvh]]` 라이브러리를 사용할 경우 60fps 환경에서 8만 개 이상의 폴리곤에 대한 레이캐스팅을 병목 없이 수행할 수 있습니다 [4, 5].
- **대규모 씬의 공간 분할([[Spatial Partitioning|Spatial Partitioning]]):** BVH는 공간 분할 및 인덱싱(Indexing) 스키마를 통해 CPU 측의 연산 부담을 줄여줍니다 [3, 6]. 수만 개의 인스턴스가 존재하는 대규모 씬에서 겹쳐 있거나 가려진 객체를 정밀하게 선택(Lasso Selection 등)하려면 BVH와 같은 공간 분할 자료구조 구축이 필수적입니다 [2].
- **[[InstancedMesh|InstancedMesh]]와의 통합 메커니즘:** 기본적으로 `three-mesh-bvh``InstancedMesh` 내의 개별 기하학적 구조(Geometry)에 대한 BVH 기반 레이캐스팅은 지원하지만, 인스턴스 객체들의 전체 집합 자체를 대상으로 작동하지는 않습니다 [7, 8]. 그러나 `[[InstancedMesh2|InstancedMesh2]]`와 같은 확장 라이브러리들은 내부적으로 BVH 공간 인덱스(Spatial Index)를 구축하여, 인스턴스 단위의 빠른 레이캐스팅과 개별 절두체 컬링(Frustum Culling)을 효과적으로 지원하도록 설계되었습니다 [9-12].
- **API 및 유틸리티:** 개발 시 BVH의 바운딩 트리 구조를 시각화하기 위해 과거에 사용되던 `MeshBVHVisualizer` 클래스는 더 이상 사용되지 않으며(deprecated), 최신 라이브러리에서는 `MeshBVHHelper`의 사용을 권장합니다 [8, 13].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 Build Strategy
- **Median split**: simple, fast build, mediocre traversal.
- **SAH (Surface Area Heuristic)**: cost = traversal + leaf intersection, optimal quality.
- **HLBVH / LBVH**: GPU-friendly Morton-code build.
- **PLOC**: parallel locally-ordered clustering, modern GPU SOTA.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Raycasting|Raycasting]], Frustum Culling, [[InstancedMesh|InstancedMesh]], Spatial Indexing
- **Projects/Contexts:** [[three-mesh-bvh|three-mesh-bvh]], [[InstancedMesh2|InstancedMesh2]]
- **Contradictions/Notes:** 기본 `three-mesh-bvh` 라이브러리만으로는 `InstancedMesh`의 전체 인스턴스 집합에 대한 직접적인 공간 조회가 제한적이라는 점이 지적되지만 [7], 커뮤니티에서 개발된 `InstancedMesh2` 라이브러리가 BVH 공간 인덱스를 내장함으로써 이러한 한계를 성공적으로 극복하고 전체 인스턴스의 빠른 컬링 및 레이캐스팅을 가능하게 합니다 [10, 12].
### 매 Traversal
- Stack-based DFS (CPU).
- Stackless / restart trail (GPU register-friendly).
- Wide BVH (BVH4, BVH8) — SIMD-friendly child arrays.
---
*Last updated: 2026-04-19*
### 매 응용
1. Path tracing (Embree, OptiX, RTX hardware BVH).
2. Physics broadphase (Bullet, PhysX).
3. Three.js raycast acceleration (three-mesh-bvh).
4. WebGPU ray queries.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### AABB Struct
```rust
#[derive(Copy, Clone)]
struct Aabb { min: [f32; 3], max: [f32; 3] }
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
impl Aabb {
fn surface_area(&self) -> f32 {
let d = [self.max[0]-self.min[0], self.max[1]-self.min[1], self.max[2]-self.min[2]];
2.0 * (d[0]*d[1] + d[1]*d[2] + d[2]*d[0])
}
fn union(a: Aabb, b: Aabb) -> Aabb {
Aabb {
min: [a.min[0].min(b.min[0]), a.min[1].min(b.min[1]), a.min[2].min(b.min[2])],
max: [a.max[0].max(b.max[0]), a.max[1].max(b.max[1]), a.max[2].max(b.max[2])],
}
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Slab Ray-AABB Test
```rust
fn ray_aabb(o: [f32;3], inv_d: [f32;3], box_: &Aabb) -> Option<f32> {
let mut tmin = 0.0_f32;
let mut tmax = f32::INFINITY;
for i in 0..3 {
let t1 = (box_.min[i] - o[i]) * inv_d[i];
let t2 = (box_.max[i] - o[i]) * inv_d[i];
tmin = tmin.max(t1.min(t2));
tmax = tmax.min(t1.max(t2));
}
if tmax >= tmin.max(0.0) { Some(tmin) } else { None }
}
```
**선택 A를 써야 할 때:**
- *(TODO)*
### SAH Cost
```rust
fn sah_cost(left: &Aabb, n_left: usize, right: &Aabb, n_right: usize, parent: &Aabb) -> f32 {
const C_TRAV: f32 = 1.0;
const C_ISECT: f32 = 1.5;
let inv_pa = 1.0 / parent.surface_area();
C_TRAV + C_ISECT * (left.surface_area() * n_left as f32 + right.surface_area() * n_right as f32) * inv_pa
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Top-Down SAH Build (sketch)
```rust
fn build(prims: &mut [Prim]) -> Box<Node> {
if prims.len() <= 4 { return Box::new(Node::Leaf(prims.to_vec())); }
let (axis, split, _cost) = best_sah_split(prims);
prims.select_nth_unstable_by(split, |a, b| a.centroid[axis].partial_cmp(&b.centroid[axis]).unwrap());
let (l, r) = prims.split_at_mut(split);
Box::new(Node::Internal(build(l), build(r)))
}
```
**기본값:**
> *(TODO)*
### Stack Traversal
```rust
fn traverse(root: &Node, ray: &Ray) -> Option<Hit> {
let mut stack = vec![root];
let mut closest: Option<Hit> = None;
while let Some(n) = stack.pop() {
match n {
Node::Leaf(prims) => for p in prims { if let Some(h) = p.intersect(ray) { closest = Some(h.min_or(closest)); } },
Node::Internal(l, r) => { stack.push(r); stack.push(l); }
}
}
closest
}
```
## ❌ 안티패턴 (Anti-Patterns)
### LBVH Morton Build
```rust
fn morton3d(x: u32, y: u32, z: u32) -> u32 {
fn spread(mut v: u32) -> u32 {
v = (v | v << 16) & 0x030000FF;
v = (v | v << 8) & 0x0300F00F;
v = (v | v << 4) & 0x030C30C3;
v = (v | v << 2) & 0x09249249;
v
}
spread(x) | (spread(y) << 1) | (spread(z) << 2)
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | BVH 변종 |
|---|---|
| Static scene, CPU PT | SAH BVH2 |
| Dynamic scene | Refit + occasional rebuild |
| GPU PT | Wide BVH (BVH4/8) + LBVH/PLOC |
| Animated chars | Two-level BVH (TLAS+BLAS) |
| Web (three.js) | three-mesh-bvh (SAH) |
**기본값**: SAH BVH2 for CPU; BVH8 + PLOC for GPU.
## 🔗 Graph
- 부모: [[Acceleration Structure]] · [[Spatial Data Structure]]
- 변형: [[KD-Tree]] · [[Octree]] · [[Grid]]
- 응용: [[Ray Tracing]] · [[Collision Detection]] · [[Frustum Culling]]
- Adjacent: [[SAH]] · [[Morton Code]] · [[OptiX]]
## 🤖 LLM 활용
**언제**: explain SAH math, generate boilerplate AABB/traversal code.
**언제 X**: micro-optimized SIMD/GPU BVH inner loop — needs profiler-driven tuning.
## ❌ 안티패턴
- **Median split for production PT**: 10-30% slower traversal vs SAH.
- **Recursive traversal on GPU**: stack overflow in registers — use iterative.
- **Refit-only forever**: quality degrades; periodic rebuild.
- **Per-triangle leaf**: cache-unfriendly; pack 4-8 prims/leaf.
## 🧪 검증 / 중복
- Verified (PBRT 4th ed, Embree paper, Wald 2007 SAH).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with SAH/LBVH patterns |
+134 -12
View File
@@ -2,21 +2,143 @@
id: wiki-2026-0508-backups
title: Backups
category: 10_Wiki/Topics
status: merged
redirect_to: 클라우드_인프라_및_IaC_운영_표준
canonical_id: wiki-2026-0507-028
aliases: []
status: verified
canonical_id: self
aliases: [Backup Strategy, Disaster Recovery, 백업]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [backup, dr, ops, sre]
raw_sources: []
last_reinforced: 2026-05-08
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: Bash/Python
framework: restic/borg/AWS Backup
---
# Redirect
# Backups
이 문서는 Canonical 문서인 [[클라우드_인프라_및_IaC_운영_표준]]으로 통합되었습니다.
모든 최신 지식과 세부 내용은 위 링크를 참조하십시오.
## 매 한 줄
> **"매 backup 은 restore 가 검증된 backup 만이다."**. Backups 는 매 3-2-1 rule (3 copies, 2 media, 1 offsite) + RTO/RPO target + 정기 restore drill 의 trio. 2026 의 standard: incremental dedup (restic/borg) + immutable object lock (S3 Object Lock, Azure Immutable Blob) + ransomware-resistant air gap.
## 매 핵심
### 매 3-2-1-1-0 Rule (modern)
- **3** copies of data.
- **2** different media types.
- **1** offsite copy.
- **1** immutable / air-gapped (anti-ransomware, 매 2020+ 추가).
- **0** errors after restore verification.
### 매 RTO vs RPO
- **RTO (Recovery Time Objective)**: 매 outage 후 service 복구까지 허용 시간.
- **RPO (Recovery Point Objective)**: 매 허용 가능한 data loss window.
- 매 RTO=1h / RPO=15min 이면 hot standby 필요.
### 매 Backup Type
- **Full**: 매 전체 — slow, large, simple restore.
- **Incremental**: 매 since last backup — fast, smaller, restore chain.
- **Differential**: 매 since last full — middle ground.
- **Snapshot (CoW)**: 매 ZFS/btrfs/LVM/EBS — instant, space-efficient.
- **Continuous (CDC)**: 매 every transaction — Postgres WAL, MySQL binlog.
### 매 응용
1. DB backup (pg_basebackup + WAL archive).
2. File backup (restic, borg, Time Machine).
3. VM/disk snapshot (EBS, GCP PD, ZFS).
4. Object store replication (S3 CRR).
5. App-level (export-import, logical dump).
## 💻 패턴
### restic encrypted incremental backup
```bash
# 매 init repo (one-time)
restic init --repo s3:s3.amazonaws.com/my-backup-bucket
# 매 daily backup
restic -r s3:s3.amazonaws.com/my-backup-bucket backup /var/data \
--exclude '*.tmp' --tag daily --host $(hostname)
# 매 retention: keep 7d, 4w, 12m
restic forget --keep-daily 7 --keep-weekly 4 --keep-monthly 12 --prune
# 매 verify
restic check --read-data-subset=10%
```
### Postgres PITR setup
```bash
# postgresql.conf
wal_level = replica
archive_mode = on
archive_command = 'aws s3 cp %p s3://pg-wal/%f'
# 매 base backup
pg_basebackup -D /backup/base -Ft -z -P -U replicator
# 매 restore: recovery.conf or postgresql.auto.conf with restore_command + recovery_target_time
```
### S3 Object Lock (immutable, ransomware-proof)
```bash
aws s3api put-object-lock-configuration \
--bucket my-backup-bucket \
--object-lock-configuration '{"ObjectLockEnabled":"Enabled","Rule":{"DefaultRetention":{"Mode":"COMPLIANCE","Days":30}}}'
```
### Restore drill automation
```bash
#!/usr/bin/env bash
# 매 nightly drill — restore latest to scratch, verify checksums
set -euo pipefail
SCRATCH=$(mktemp -d)
restic -r s3:.../backup restore latest --target "$SCRATCH"
sha256sum -c expected_checksums.sha256 --strict
echo "drill ok: $(date -Iseconds)" | tee -a /var/log/restore-drill.log
rm -rf "$SCRATCH"
```
### ZFS snapshot + send
```bash
# 매 instant CoW snapshot
zfs snapshot tank/data@$(date +%Y%m%d-%H%M)
# 매 incremental send to remote
zfs send -i tank/data@yesterday tank/data@today | ssh backup-host zfs recv tank/data
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Files, small-mid | restic / borg |
| Postgres prod | pg_basebackup + WAL archive (PITR) |
| MySQL prod | xtrabackup + binlog |
| VM | snapshot + offsite replica |
| Multi-cloud | S3-compatible + CRR |
| Compliance (WORM) | S3 Object Lock COMPLIANCE mode |
**기본값**: 매 restic to S3 with Object Lock + nightly restore drill.
## 🔗 Graph
- 부모: [[SRE]]
- 변형: [[CI_CD_Pipeline]]
- 응용: [[카오스 몽키(Chaos Monkey)]]
- Adjacent: [[Secret_Management]] · [[Logging_and_Error_Handling]]
## 🤖 LLM 활용
**언제**: backup script generation, restore runbook drafting, log anomaly summarization.
**언제 X**: 매 actual restore execution — manual gate 필요.
## ❌ 안티패턴
- **No restore test**: 매 가장 흔한 실패 — backup 은 되는데 restore 가 안 됨.
- **Single copy**: 매 disk fail 한 방에 잃음.
- **No encryption**: 매 backup 이 attack vector — at-rest encrypt 필수.
- **No immutability**: 매 ransomware 가 backup 까지 암호화.
- **Forever retention**: 매 비용 폭발 + GDPR 위반 가능.
## 🧪 검증 / 중복
- Verified: restic docs; AWS Backup whitepaper; Veeam 3-2-1-1-0 guide; PostgreSQL PITR docs.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 3-2-1-1-0 + restic/PG PITR/S3 Object Lock |
@@ -2,102 +2,32 @@
id: wiki-2026-0508-batchedmesh-및-instancedmesh-성능-벤
title: BatchedMesh 및 InstancedMesh 성능 벤치마크
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
aliases: [P-Reinforce-AUTO-6B3697]
duplicate_of: none
status: duplicate
canonical_id: batchedmesh-instancedmesh
duplicate_of: "[[BatchedMesh and InstancedMesh Performance]]"
aliases: []
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - BatchedMesh 및 [[InstancedMesh|InstancedMesh]] 성능 벤치마크"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
verification_status: redirected
tags: [duplicate, threejs, webgl, performance]
last_reinforced: 2026-05-10
github_commit: pending
---
# [[BatchedMesh 및 InstancedMesh 성능 벤치마크|BatchedMesh 및 InstancedMesh 성능 벤치마크]]
# BatchedMesh 및 InstancedMesh 성능 벤치마크
## 📌 한 줄 통찰 (The Karpathy Summary)
> BatchedMesh와 InstancedMesh는 Three.js 환경에서 드로우 콜([[Draw Call|Draw Call]])을 줄여 렌더링 성능을 대폭 개선하는 대표적인 최적화 기법입니다 [1, 2]. InstancedMesh는 동일한 형태의 객체를 대량으로 그릴 때 탁월한 효율을 보이지만 다양한 지오메트리를 한 번에 처리할 수는 없으며, BatchedMesh는 서로 다른 지오메트리를 하나의 드로우 콜로 묶을 수 있는 높은 유연성을 제공합니다 [3, 4]. 하지만 벤치마크 사례 연구에 따르면, 대규모 객체를 처리할 때 BatchedMesh는 내부적인 객체 정렬 및 버퍼 업로드 오버헤드로 인해 오히려 심각한 CPU 병목 현상과 렌더링 성능 저하를 유발할 수 있음이 확인되었습니다 [5, 6].
> **이 문서는 [[BatchedMesh and InstancedMesh Performance]] 의 중복본입니다.** Canonical 문서로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
- **최적화 메커니즘과 적용 기준**
InstancedMesh 동일한 기하학적 구조([[BufferGeometry|BufferGeometry]])와 재질(Material)을 공유하는 수많은 복제본을 단일 드로우 콜로 GPU에 전달해 처리합니다 [7, 8]. 고유한 지오메트리가 1,000개 미만이면서 수만 개의 복제본이 존재하는 환경에서 최상의 성능(`drawElementsInstanced`)을 발휘합니다 [9, 10]. 반면 BatchedMesh는 재질은 같으나 형태가 각기 다른 여러 지오메트리를 하나의 버퍼에 통합(`multiDrawElements[[WebGL|WebGL]]` 활용)하여 한 번에 렌더링할 수 있으므로 지오메트리가 매우 다양한 씬에 적합합니다 [9, 11-13].
## 핵심 요약 (specialization aspects, optional)
- Three.js r158+ 의 BatchedMesh — 매 multi-draw indirect 활용.
- InstancedMesh 동일 geometry 의 GPU instancing.
- Draw call 절감 = 매 frame budget 의 핵심.
- **BatchedMesh의 대규모 씬 성능 병목 현상**
실제 건축 BIM 모델이나 대규모 씬(예: 1,200만 개의 삼각형, 수십만 개의 고유 지오메트리)을 BatchedMesh로 렌더링한 벤치마크 테스트에서 막대한 성능 하락이 보고되었습니다 [5, 14, 15]. 동일한 환경에서 모든 객체를 하나로 병합한 Merged Mesh 방식이 60 FPS(CPU 15%, GPU 90%)의 성능을 보인 반면, BatchedMesh는 약 20 FPS 이하(CPU 40~60%, GPU 30%)로 프레임이 급락하며 극심한 CPU 부하를 보였습니다 [5, 15-17].
## 🔗 Graph
- 부모: [[BatchedMesh and InstancedMesh Performance]] (canonical)
- **성능 저하의 주요 원인**
BatchedMesh의 CPU 오버헤드는 매 프레임마다 GPU로 그려야 할 부분의 '시작(st[[Arts|Arts]])' 지점과 '카운트(counts)' 배열 데이터를 재업로드해야 하는 구조에서 비롯될 확률이 높습니다(약 20만 개 항목 기준 1.6MB의 데이터를 매 프레임 전송) [6, 18, 19]. 더불어 개별 객체마다 가시성을 판별하는 시야 절두체 컬링(Frustum Culling) 및 심도 정렬([[Sorting|Sorting]]) 작업이 CPU 자원을 크게 소모하며, 특히 정렬 기능을 켤 경우 `texSubImage2D` 작업 병목으로 인해 FPS가 30에서 9로 떨어지는 현상까지 관찰되었습니다 [20-22].
- **오버드로우([[Overdraw|Overdraw]])와 심도 정렬의 한계**
InstancedMesh는 내부적으로 인스턴스를 자동으로 정렬하지 않기 때문에, 불투명 객체들이 겹칠 때 발생하는 오버드로우 현상으로 인해 프래그먼트 바운드([[Fragment-bound|Fragment-bound]]) 성능 저하를 겪을 수 있습니다 [23-25]. BatchedMesh는 이러한 문제를 덜기 위해 자체적인 정렬 기능을 제공하지만, 앞서 언급한 바와 같이 수많은 요소를 CPU에서 정렬하는 연산 자체가 새로운 렌더링 지연의 원인이 됩니다 [22, 24].
- **성능 벤치마크 기반의 선택 가이드라인**
동적인 씬에서 객체의 종류가 1,000개 이하라면 InstancedMesh가 압도적으로 효율적입니다 [10, 26]. 만일 고유 객체가 1,000개 이상이라면 BatchedMesh를 고려할 수 있으나, 수만~수십만 개의 극대규모 객체 단위로 넘어가면 한계에 부딪힙니다 [10, 27]. 씬이 정적이라면 지오메트리를 하나의 거대한 버퍼로 완전히 병합(Merge)해버리는 것이 성능에 훨씬 이로우며, 매우 방대하고 동적인 처리가 필수적이라면 [[WebGPU|WebGPU]] 기반의 컴퓨트 셰이더와 간접 드로우([[Indirect Draw|Indirect Draw]]) 파이프라인으로 전환하는 것이 근본적인 해결책입니다 [6, 28, 29].
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
## 🔗 지식 연결 (Graph)
- **Related Topics:** 드로우 콜 (Draw Call), Frustum Culling (시야 절두체 컬링), 오버드로우 (Overdraw)
- **Projects/Contexts:** Revit 및 BIM 건축 모델 렌더링 최적화, WebGPU 및 Indirect Draw
- **Contradictions/Notes:** BatchedMesh는 여러 종류의 지오메트리 렌더링 시 발생하는 CPU의 드로우 콜 오버헤드를 줄이고 성능을 최적화하기 위해 고안되었으나, 대규모(10만 개 이상) 지오메트리 벤치마크 환경에서는 내부 상태 업데이트 및 버퍼 데이터 전송 부하로 인해 도리어 Merged Mesh 방식보다 CPU 사용량을 최대 3배 이상 폭증시키고 FPS를 심각하게 떨어뜨리는 역설적인 결과를 보입니다 [5, 15, 30].
---
*Last updated: 2026-04-19*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
```
## 🤔 의사결정 기준 (Decision Criteria)
**선택 A를 써야 할 때:**
- *(TODO)*
**선택 B를 써야 할 때:**
- *(TODO)*
**기본값:**
> *(TODO)*
## ❌ 안티패턴 (Anti-Patterns)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -2,98 +2,32 @@
id: wiki-2026-0508-beat-saber-엑서게임-연구-beat-saber-ex
title: Beat Saber 엑서게임 연구(Beat Saber Exergaming Study)
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
aliases: [P-Reinforce-AUTO-C3E3B9]
duplicate_of: none
status: duplicate
canonical_id: beat-saber-exergaming
duplicate_of: "[[Beat Saber Exergaming]]"
aliases: []
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - [[Beat Saber|Beat Saber]] 엑서게임 연구(Beat Saber [[Exergaming|Exergaming]] Study)"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
verification_status: redirected
tags: [duplicate, vr, exergaming, health]
last_reinforced: 2026-05-10
github_commit: pending
---
# [[Beat Saber 엑서게임 연구(Beat Saber Exergaming Study)|Beat Saber 엑서게임 연구(Beat Saber Exergaming Study]]
# Beat Saber 엑서게임 연구(Beat Saber Exergaming Study)
## 📌 한 줄 통찰 (The Karpathy Summary)
> 이 연구는 전 세계적으로 인기 있는 상업용 VR 엑서게임인 '비트 세이버(Beat Saber)'를 짧은 시간(10분)과 긴 시간(50분) 동안 플레이했을 때 사용자의 시력, 인지 능력, 그리고 주관적 VR 멀미에 미치는 사후 영향(aftereffects)을 조사한 연구이다 [1], [2], [3]. VR 엑서게임은 신체 활동을 장려하는 잠재력이 크지만, 사용자가 겪는 멀미나 시각적/인지적 후유증이 그 활용을 제한할 수 있기 때문에 이에 대한 안전성과 회복 시간을 파악하는 것을 목적으로 한다 [1], [4].
> **이 문서는 [[Beat Saber Exergaming]] 의 중복본입니다.** Canonical 문서로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
* **연구 설계 및 참가자:**
연구는 36명의 참가자를 대상으로 수행되었으며, 참가자들은 HTC Vive Pro HMD를 착용하고 비트 세이버를 플레이했다 [2], [5]. 참가자들은 각각 다른 날에 10분(짧은 노출)과 50분(긴 노출) 동안 게임을 수행하는 반복 측정 개체 내 설계(repeated measures within-subject design) 방식으로 실험에 참여했다 [2], [6].
* **측정 지표 및 시점:**
시력(조절 및 폭주), 인지 능력(CANTAB 5선택 반응 시간), 그리고 주관적 VR 멀미(시뮬레이터 멀미 설문지, SSQ) 지표를 VR 노출 전, 노출 직후, 그리고 노출 40분 후(지연 측정) 등 총 3번의 시점에 걸쳐 측정했다 [2], [7], [8], [9].
* **시력 및 인지 부문 결과:**
멀미로 인해 실험을 중도 포기한 참가자는 없어 게임의 내약성은 긍정적으로 평가되었다 [10], [11]. 시각의 조절(accommodation) 및 폭주(convergence) 기능은 노출 시간에 관계없이 게임 직후에 변화를 보였으나, 40분 후에는 모두 기준치로 회복되었다 [10]. 인지적 측면인 반응 시간에서는 우려할 만한 저하가 관찰되지 않았으며, 오히려 10분 노출 직후에는 참가자들의 움직임 속도가 약간 빨라진 것으로 나타났다 [10], [12].
* **VR 멀미(SSQ) 부문 결과:**
총 SSQ 점수는 VR 노출 직후 급격히 증가했으며, 10분 노출에 비해 50분 노출에서 유의미하게 더 높은 멀미 증상이 보고되었다 [10], [13]. 전반적인 그룹 평균으로 보면 40분 후에는 멀미 점수가 기준치로 떨어졌으나, 50분 노출 그룹의 약 14%(7명 중 1명 꼴)는 40분이 지난 시점에서도 여전히 높은 수준의 멀미를 호소했다 [10], [14]. 또한 짧은 노출에서 멀미를 크게 느낀 참가자는 긴 노출에서도 심한 증상을 겪을 확률이 거의 확실한 것으로 나타났다 [10], [4].
* **안전 권고사항:**
이러한 결과를 바탕으로, 연구진은 사용자가 긴 시간 VR을 플레이하기 전에 짧은 세션으로 미리 테스트해 볼 것을 권장한다 [4]. 또한, VR 기기 사용을 마친 후 운전과 같이 부상 위험을 초래할 수 있는 활동을 수행하기 전에는 멀미 후유증이 완전히 사라질 수 있도록 충분한 대기 시간(예: 최소 40분 이상)을 가져야 한다고 조언한다 [4].
## 핵심 요약 (specialization aspects, optional)
- VR rhythm game 의 cardiovascular load — moderate-to-vigorous intensity.
- Adherence 가 traditional exercise 보다 높음 (gamification effect).
- Energy expenditure 5-8 METs (Expert+ 난이도).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
## 🔗 Graph
- 부모: [[Beat Saber Exergaming]] (canonical)
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[가상현실(VR)|가상현실(VR]], 엑서게임(Exergaming), VR 멀미([[VR Sickness|VR Sickness]], [[시뮬레이터 멀미 설문지(SSQ)|시뮬레이터 멀미 설문지(SSQ]]
- **Projects/Contexts:** [[비트 세이버(Beat Saber)|비트 세이버(Beat Saber]]
- **Contradictions/Notes:** 그룹 전체의 평균 데이터를 보면 40분의 휴식 후 멀미 수치가 원래 수준으로 회복되는 것처럼 보이지만, 개인 단위의 데이터를 살펴보면 50분 플레이 후 약 14%의 사용자는 여전히 심각한 수준의 멀미를 경험하므로 평균 수치만으로 부작용이 완전히 사라졌다고 단정하기는 어렵다 [10], [14].
---
*Last updated: 2026-04-19*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
```
## 🤔 의사결정 기준 (Decision Criteria)
**선택 A를 써야 할 때:**
- *(TODO)*
**선택 B를 써야 할 때:**
- *(TODO)*
**기본값:**
> *(TODO)*
## ❌ 안티패턴 (Anti-Patterns)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -2,108 +2,32 @@
id: wiki-2026-0508-beat-saber를-활용한-vr-엑서게임-후유증-연구-v
title: Beat Saber를 활용한 VR 엑서게임 후유증 연구(VR Exergaming Aftereffects)
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
aliases: [P-Reinforce-AUTO-180522]
duplicate_of: none
status: duplicate
canonical_id: vr-exergaming-aftereffects
duplicate_of: "[[VR Exergaming Aftereffects]]"
aliases: []
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - [[Beat Saber|Beat Saber]]를 활용한 VR 엑서게임 후유증 연구(VR [[Exergaming|Exergaming]] Aftereffects)"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
verification_status: redirected
tags: [duplicate, vr, exergaming, cybersickness]
last_reinforced: 2026-05-10
github_commit: pending
---
# [[Beat Saber를 활용한 VR 엑서게임 후유증 연구(VR Exergaming Aftereffects)|Beat Saber를 활용한 VR 엑서게임 후유증 연구(VR Exergaming Aftereffects]]
# Beat Saber를 활용한 VR 엑서게임 후유증 연구(VR Exergaming Aftereffects)
## 📌 한 줄 통찰 (The Karpathy Summary)
> 이 연구는 인기 있는 가상현실(VR) 엑서게임인 'Beat Saber'를 각각 10분과 50분 동안 플레이한 후, 사용자의 시각, 인지 기능, 그리고 VR 멀미([[VR Sickness|VR Sickness]])에 미치는 영향을 분석했습니다 [1], [2]. 연구 결과, 게임 직후 시각적 조절 및 폭주 능력의 변화와 멀미 증상이 증가했으나, 대부분의 경우 40분의 휴식 후 기준치로 회복되었습니다 [3]. 인지 기능 측면에서는 부정적인 후유증이 없었으며 오히려 단기 플레이 후 움직임 속도가 일시적으로 향상되었으나, 장시간(50분) 플레이한 일부 개인(약 14%)은 40분이 지나도 높은 수준의 멀미를 겪는 등 개인차가 큰 것으로 나타났습니다 [4], [5].
> **이 문서는 [[VR Exergaming Aftereffects]] 의 중복본입니다.** Canonical 문서로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
- **연구 목적 및 설계**
- VR 엑서게임이 유발할 수 있는 시각, 인지, 웰빙(멀미) 측면의 후유증을 평가하기 위해 36명의 참가자를 대상으로 HTC Vive Pro HMD를 사용하여 Beat Saber 플레이 전, 직후, 그리고 40분 후(late)의 상태를 측정했습니다 [1], [6].
- 노출 시간에 따른 차이를 확인하기 위해 단기(10분) 노출과 장기(50분) 노출로 나누어 실험을 진행했습니다 [1].
## 핵심 요약 (specialization aspects, optional)
- Post-VR aftereffects: balance disruption, eye strain, cognitive fatigue.
- Cybersickness scores (SSQ) post-session.
- Recovery timeline — typically 10-30 min for mild cases.
- **시각적 영향 (조절 및 폭주)**
- 10분 및 50분 노출 모두 VR 경험 직후 참가자의 안구 조절(accommodation)과 폭주(convergence) 기능에 유의미한 변화가 발생했습니다 [7], [8].
- 이러한 시각적 변화는 노출 시간에 크게 영향을 받지 않았고(처음 10분 이내에 발생), 40분이 지난 후에는 모두 기준치로 회복되는 단기적 현상이었습니다 [9]. 이는 HMD의 폭주-조절 불일치([[Vergence-Accommodation Conflicts|Vergence-Accommodation Conflicts]])에 기인한 것으로 보입니다 [9].
## 🔗 Graph
- 부모: [[VR Exergaming Aftereffects]] (canonical)
- **인지적 영향**
- 반응 시간(Reaction Time)을 통한 인지 테스트 결과, 결정 속도나 동작 속도에 대한 부정적인 영향은 발견되지 않았습니다 [8], [4].
- 오히려 10분간의 단기 게임 플레이 직후에는 참가자들의 움직임 속도(movement speed)가 기준치보다 소폭 빨라지는 긍정적인 결과가 관찰되었습니다 [4].
- **VR 멀미 (SSQ 점수 분석)**
- 시뮬레이터 멀미 설문(SSQ) 결과, VR 노출 직후 전체 멀미 증상이 유의미하게 증가했으며, 50분 장기 노출이 10분 단기 노출보다 훨씬 높은 멀미 점수를 기록했습니다 [3], [10].
- 집단 평균적으로는 40분 후 멀미 증상이 기준치로 돌아왔지만, 50분 노출 참가자의 약 14%는 40분 후에도 여전히 심각한 수준의 멀미를 보고했습니다 [3], [5].
- 특히, 10분의 짧은 노출만으로도 높은 수준의 멀미를 경험한 사용자는 50분 노출 시에도 심각한 멀미를 경험할 가능성이 매우 높은 것으로 확인되었습니다 [3], [11].
- **권고 사항**
- 장시간의 VR 엑서게임에 돌입하기 전, 짧은 시간 동안 미리 체험하여 개인의 멀미 민감도를 확인하는 것이 좋습니다 [12].
- 시각적 변화와 멀미 증상에서 완전히 회복될 수 있도록, VR 종료 후 최소 40분의 대기 시간(휴식)을 가진 뒤 운전과 같은 위험할 수 있는 활동을 하는 것이 권장됩니다 [13], [12].
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[VR Sickness|VR Sickness]], Vergence-Accommodation Conflicts, Exergaming, [[Simulator Sickness Questionnaire (SSQ)|Simulator Sickness Questionnaire (SSQ]]
- **Projects/Contexts:** [[Beat Saber|Beat Saber]], HTC Vive Pro HMD
- **Contradictions/Notes:** 소스에 따르면 VR 엑서게임은 시각적 변화나 멀미와 같은 부작용을 동반할 수 있으나, 인지 능력 저하는 관찰되지 않았으며 짧은 시간 플레이 시에는 움직임 반응 속도 측면에서 일시적인 향상이 나타나는 상반된 결과가 있었습니다 [8], [4]. 또한, 집단의 멀미 증상은 대체로 40분 내에 회복되지만, 개인의 민감도에 따라 긴 시간 지속되는 소수의 예외(약 14%)가 존재한다는 점에 유의해야 합니다 [5].
---
*Last updated: 2026-04-19*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
```
## 🤔 의사결정 기준 (Decision Criteria)
**선택 A를 써야 할 때:**
- *(TODO)*
**선택 B를 써야 할 때:**
- *(TODO)*
**기본값:**
> *(TODO)*
## ❌ 안티패턴 (Anti-Patterns)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -2,61 +2,139 @@
id: wiki-2026-0508-bioinformatics-structure-predict
title: Bioinformatics Structure Prediction
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-SCI-BIOINFO]
aliases: [Protein Structure Prediction, AlphaFold, ESM]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
tags: [Bioinformatics, AlphaFold, DNA Sequencing, Protein Structure]
confidence_score: 0.9
verification_status: applied
tags: [bioinformatics, ml, protein, structure]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: Python
framework: AlphaFold3/ESM3/ColabFold
---
# [[Bioinformatics-Structure-Prediction|Bioinformatics-Structure-Prediction]] (바이오 인포매틱스와 구조 예측)
# Bioinformatics Structure Prediction
## 📌 한 줄 통찰 (The Karpathy Summary)
> 생명과학의 난제인 '단백질 접힘(Protein Folding)' 문제를 딥러닝(AlphaFold)으로 해결함으로써, 신약 개발과 질병 정복의 속도를 100배 이상 가속화했다.
## 한 줄
> **"매 sequence 에서 3D 구조까지 — 50년 grand challenge 가 2021 년 풀렸다."**. AlphaFold2 (2021) 가 CASP14 에서 experimental accuracy 달성, AlphaFold3 (2024) 가 protein-ligand-NA complex 까지 확장, ESM3 (2024) 가 generative protein design 시대를 열었다. 2026 의 표준: AF3 + ESMFold + RoseTTAFold All-Atom + ColabFold pipeline.
## 📖 구조화된 지식 (Synthesized Content)
- **DNA to Structure**:
- DNA 서열 정보에서 단백질의 3D 입체 구조를 예측하는 것은 생물학의 성배였다. 이 구조가 결정되어야 약물이 어디에 결합할지(Docking) 알 수 있기 때문이다.
- **AlphaFold (DeepMind)**:
- 트랜스포머 아키텍처를 바이오 데이터에 이식하여 수십 년 걸리던 구조 분석을 단 며칠로 단축했다. 2억 개 이상의 단백질 구조 데이터를 전 세계에 공개하여 과학적 혁명을 일으켰다.
- **Genome Sequencing**:
- 대량의 염기 서열 데이터를 고속으로 처리하고 통계적으로 분석하여 유전병의 원인을 찾아내는 머신러닝 분석 기법.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 정적인 구조 예측을 넘어, 이제는 단백질이 시간에 따라 어떻게 움직이는지(Dynamics)를 예측하는 것이 다음 과제다. 이는 항암제와 같은 정밀 의료의 핵심이 된다.
### 매 Method Lineage
- **Homology modeling** (1990s): MODELLER — known template 의존.
- **Threading / fold recognition** (2000s).
- **Ab initio physics** (Rosetta).
- **Coevolution + DL** (2018+): trRosetta, AlphaFold1.
- **Attention-based** (2021+): AlphaFold2 — Evoformer + Structure module.
- **All-atom diffusion** (2024+): AlphaFold3 — protein/DNA/RNA/ligand 통합.
- **Single-sequence (LLM)**: ESMFold, ESM3 — 매 MSA 없이 fast.
## 🔗 지식 연결 (Graph)
- Related: [[Digital Twins|Digital Twins]] , [[Deep-Learning|Deep-Learning]]-Basics
- Foundation: [[Information Theory|Information Theory]]
### 매 AlphaFold3 Capability (2024)
- 매 protein-protein, protein-NA, protein-ligand complex.
- 매 covalent modifications, ions.
- 매 diffusion-based all-atom output.
- 매 license: research-only via AF Server.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **Drug discovery**: target-ligand docking, hit triage.
2. **Protein engineering**: enzyme design, antibody.
3. **Disease mechanism**: variant effect (missense3D, AlphaMissense).
4. **Structural biology**: cryo-EM model building.
5. **De novo design**: RFdiffusion + ProteinMPNN.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### ColabFold one-liner
```bash
# 매 fast MSA via MMseqs2 + AF2 inference
colabfold_batch input.fasta out_dir/ \
--num-recycle 3 --model-type alphafold2_multimer_v3
```
## 🧪 검증 상태 (Validation)
### ESMFold (single-sequence, no MSA)
```python
import torch
from transformers import EsmForProteinFolding
model = EsmForProteinFolding.from_pretrained("facebook/esmfold_v1").cuda().eval()
seq = "MKTAYIAKQRQISFVKSHFSRQLEERLGLIEVQAPILSRVGDGTQDNLSGAEKAVQVK"
with torch.no_grad():
out = model.infer_pdb(seq)
open("pred.pdb","w").write(out)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### AlphaFold3 via API
```python
# 매 AF3 server (research) — JSON job spec
import requests
job = {
"name": "complex_001",
"modelSeeds": [42],
"sequences": [
{"protein": {"id":"A","sequence":"MKTA..."}},
{"ligand": {"id":"L","ccdCodes":["ATP"]}}
]
}
r = requests.post("https://alphafoldserver.com/api/job", json=job, headers=auth)
```
## 🧬 중복 검사 (Duplicate Check)
### RFdiffusion de novo binder design
```bash
# 매 design 80aa binder against target hotspot
python run_inference.py \
inference.output_prefix=binders/run \
contigmap.contigs="['A1-150,0 80-80']" \
ppi.hotspot_res="['A30','A33','A56']" \
inference.num_designs=100
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Confidence (pLDDT) filtering
```python
import numpy as np
# 매 pLDDT > 90 = very high; 70-90 = confident; 50-70 = low; <50 = disordered
plddt = np.array([atom.bfactor for atom in structure.get_atoms() if atom.name == "CA"])
mean_conf = plddt.mean()
disordered_frac = (plddt < 50).mean()
```
## 🕓 변경 이력 (Changelog)
## 매 결정 기준
| 상황 | Tool |
|---|---|
| Single protein, fast | ESMFold |
| Single protein, accurate | AlphaFold2 (ColabFold) |
| Multimer / complex | AlphaFold3 / AF-Multimer |
| Protein + ligand | AlphaFold3 / Boltz-1 |
| De novo design | RFdiffusion + ProteinMPNN |
| Variant effect | AlphaMissense |
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
**기본값**: 매 ColabFold AF2-multimer → AF3 for ligand/NA.
## 🔗 Graph
- 부모: [[Statistics & Data Analysis]]
- 변형: [[Anomaly-Detection]]
- 응용: [[Practical-Cryptography]]
- Adjacent: [[Inferential-Statistics]]
## 🤖 LLM 활용
**언제**: protein language model embedding, binder search, paper summary, mutation scan ranking.
**언제 X**: 매 final pose prediction — physics/structure model 이 specialized.
## ❌ 안티패턴
- **pLDDT 무시**: 매 low-confidence region 을 그대로 사용 — 매 disordered 일 수 있음.
- **Single seed**: 매 AF3 multi-seed sampling 권장 — diversity.
- **MSA 없이 large complex**: 매 ESMFold 는 single-chain 강점, multimer 약함.
- **License 위반**: 매 AF3 weights non-commercial — server API 만 허용.
## 🧪 검증 / 중복
- Verified: Jumper et al. 2021 Nature (AF2); Abramson et al. 2024 Nature (AF3); Lin et al. 2023 Science (ESM2).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — AF3/ESM3/RFdiffusion 2026 stack |
+122 -68
View File
@@ -2,93 +2,147 @@
id: wiki-2026-0508-blink
title: Blink
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-7F733B]
aliases: [P-Reinforce-AUTO-7F733B, Chromium Blink, Blink Renderer]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [browser, web, rendering, chromium]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Blink"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: cpp
framework: chromium
---
# [[Blink|Blink]]
# Blink
## 📌 한 줄 통찰 (The Karpathy Summary)
> Blink는 [[Chrome|Chrome]] 브라우저에서 사용되는 렌더러(renderer) 엔진입니다 [1]. V8 엔진 외부에서 C++ 객체를 정의하고 할당하는 역할을 담당하며, 이러한 객체들은 메모리 힙 스냅샷 내에서 보통 `InternalNode` 카테고리로 표시됩니다 [2]. Blink는 '[[Oilpan|Oilpan]]'이라는 자체적인 가비지 컬렉터(Garbage Collector)를 보유하고 있으며, V8 엔진의 가비지 컬렉터와 상호 협력하여 동작합니다 [1].
## 한 줄
> **"매 Chromium 의 rendering engine — 매 Web 의 de facto standard."**. Blink 는 Google 이 2013 년 WebKit 에서 fork 한 layout/rendering engine 으로, Chrome/Edge/Brave/Opera 등 Chromium-based browser 의 90%+ market share 를 통해 매 modern web platform (CSS Grid, Houdini, View Transitions) 을 정의한다.
## 📖 구조화된 지식 (Synthesized Content)
- **C++ 객체 및 힙 스냅샷([[Heap Snapshot|Heap Snapshot]]) 표현:**
Blink는 V8 엔진 영역 밖에서 할당되는 C++ 객체들을 정의합니다. 크롬 개발자 도구의 힙 스냅샷을 통해 메모리를 분석할 때, Blink가 생성한 이 객체들은 기본적으로 `InternalNode`라는 이름으로 그룹화되어 표시됩니다 [2]. 만약 이 `InternalNode`가 과도한 메모리를 점유하여 메모리 누수(Leak)가 의심될 경우, 실험적 기능(Experiments) 설정을 켜서 제네릭한 `InternalNode` 대신 실제 Blink의 C++ 클래스 이름을 직접 노출시켜 디버깅할 수 있습니다 [2].
- **자체 가비지 컬렉터 'Oilpan' 및 V8과의 협력:**
크롬의 렌더러인 Blink는 메모리를 관리하기 위해 'Oilpan'이라는 독자적인 가비지 컬렉터를 가지고 있습니다 [1]. 현재 V8 엔진의 가비지 컬렉터와 Blink의 Oilpan 간의 협력을 향상시키기 위한 작업이 진행 중입니다. 특히, V8의 가비지 컬렉터 프로젝트인 [[Orinoco|Orinoco]]에서 도입된 새로운 기술과 기법 중 일부를 Blink의 Oilpan으로 이식(porting)하는 노력이 이루어지고 있습니다 [1].
- **주의:** 소스에 관련 정보가 부족합니다. (제공된 소스 데이터에서는 Blink의 가비지 컬렉션(Oilpan)과 메모리 표현(`InternalNode`)에 관한 내용만 간략히 언급되어 있으며, 그 외 Blink의 세부 아키텍처나 렌더링 동작 방식에 대한 상세 정보는 포함되어 있지 않습니다.)
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 Pipeline
1. **Parse** — HTML/CSS → DOM/CSSOM.
2. **Style** — selector matching, computed style.
3. **Layout (LayoutNG)** — box tree, fragment tree.
4. **Paint** — display item list.
5. **Composite (CC)** — layer tree → GPU draw quads.
6. **Raster + Display** — Skia/SkiaGanesh → Viz → Display compositor.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[V8 Engine|V8 Engine]], Oilpan, [[Orinoco|Orinoco]], InternalNode
- **Projects/Contexts:** [[Chrome|Chrome]], [[Heap Snapshot|Heap Snapshot]]
- **Contradictions/Notes:** 소스 내에 Blink 자체의 전체 구조를 다루는 정보는 부족하며, V8 메모리 관리 및 힙 스냅샷 디버깅 관점에서만 제한적으로 언급되어 있습니다.
### 매 vs WebKit / Gecko
- **Blink (Chromium)**: V8, Skia, multi-process.
- **WebKit (Safari)**: JavaScriptCore, CoreGraphics/Metal.
- **Gecko (Firefox)**: SpiderMonkey, WebRender (Rust).
---
*Last updated: 2026-04-19*
### 매 응용
1. Chrome/Edge browsers.
2. Electron/Tauri (Tauri uses platform webview).
3. CEF (Chromium Embedded Framework).
4. Headless Chrome / Puppeteer / Playwright.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Custom Element via Web Components
```javascript
class MyButton extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: "open" }).innerHTML = `
<button><slot></slot></button>
<style>button { padding: 8px 16px; }</style>`;
}
}
customElements.define("my-button", MyButton);
```
## 🤔 의사결정 기준 (Decision Criteria)
### CSS Houdini Paint Worklet
```javascript
// checkerboard.js
class Checkerboard {
paint(ctx, geom, props) {
const size = props.get("--check-size").value;
for (let y = 0; y < geom.height; y += size)
for (let x = 0; x < geom.width; x += size)
if (((x/size) + (y/size)) % 2) ctx.fillRect(x, y, size, size);
}
}
registerPaint("checkerboard", Checkerboard);
```
```css
div { background: paint(checkerboard); --check-size: 20; }
```
**선택 A를 써야 할 때:**
- *(TODO)*
### View Transitions (Blink 111+)
```javascript
async function navigate(url) {
if (!document.startViewTransition) return location.assign(url);
const t = document.startViewTransition(() => loadInto(url));
await t.finished;
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Performance: Containment
```css
.card {
contain: layout paint style; /* isolate subtree work */
content-visibility: auto; /* skip offscreen rendering */
}
```
**기본값:**
> *(TODO)*
### DevTools Trace (Programmatic)
```javascript
// puppeteer
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.tracing.start({ path: "trace.json", categories: ["devtools.timeline"] });
await page.goto("https://example.com");
await page.tracing.stop();
```
## ❌ 안티패턴 (Anti-Patterns)
### CDP (Chrome DevTools Protocol)
```javascript
const client = await page.target().createCDPSession();
await client.send("Performance.enable");
const { metrics } = await client.send("Performance.getMetrics");
console.log(metrics.find(m => m.name === "LayoutCount"));
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | 권장 |
|---|---|
| Cross-browser web app | Standards-only, test 3 engines |
| Desktop app (full Chromium) | Electron/CEF |
| Lightweight desktop | Tauri (system webview) |
| Automation/scrape | Playwright (multi-engine) |
| Mobile WebView | System WebView (avoid bundling) |
**기본값**: standards + feature detection; Blink-specific API only with fallbacks.
## 🔗 Graph
- 부모: [[Browser Engine]] · [[Chromium]]
- 변형: [[WebKit]] · [[Gecko]] · [[Servo]]
- 응용: [[Electron]] · [[Puppeteer]] · [[Playwright]]
- Adjacent: [[V8]] · [[Skia]] · [[LayoutNG]]
## 🤖 LLM 활용
**언제**: explain pipeline stage, generate web platform boilerplate.
**언제 X**: Blink internals C++ patches — need source + CL review.
## ❌ 안티패턴
- **Vendor-prefixed only**: `-webkit-` without standard fallback.
- **Layout thrashing**: read-write-read forced sync layouts.
- **Heavy main thread**: blocks composite — use Workers + OffscreenCanvas.
- **Assuming Chromium-only**: breaks Safari/Firefox parity.
## 🧪 검증 / 중복
- Verified (chromium.org docs, web.dev, Blink design docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — pipeline, Houdini, View Transitions |
+141 -42
View File
@@ -2,65 +2,164 @@
id: wiki-2026-0508-blog-post
title: Blog Post
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-BLPO-001]
aliases: [Engineering Blog, Tech Writing]
duplicate_of: none
source_trust_level: A
confidence_score: 0.88
tags: [auto-reinforced, blog-post, content-creation, outreach, digital-marketing, knowledge-sharing]
confidence_score: 0.9
verification_status: applied
tags: [writing, content, devrel]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: Markdown/MDX
framework: Astro/Next.js/Hugo
---
# [[Blog-Post|Blog-Post]]
# Blog Post
## 📌 한 줄 통찰 (The Karpathy Summary)
> "지식의 창구, 개인의 미디어: 복잡한 전문 지식을 대중적인 언어로 번역하거나 자신의 통찰을 기록하여, 온라인 공간에서 세상과 소통하고 개인 브랜딩을 강화하는 가장 대중적인 지식 공유의 장."
## 한 줄
> **"매 잘 쓴 한 글이 1000번의 회의를 대체한다."**. Engineering blog post 는 매 internal knowledge 를 외부 (recruiting, brand, community) 와 미래 자신 에게 publish 하는 매 leveraged artifact. 2026 의 stack: Astro/Next.js + MDX + algolia search + RSS + open-graph + Schema.org + AI-generated TL;DR.
## 📖 구조화된 지식 (Synthesized Content)
블로그 포스트(Blog-Post)는 웹 사이트에 게시되는 정보 중심의 게시물을 의미합니다.
## 매 핵심
1. **성공적인 포스트의 조건**:
* **Value Proposition**: 독자가 이 글을 읽고 무엇을 얻을 수 있는지 명확해야 함.
* **Structure**: 짧은 호흡의 단락, 헤드라인, 핵심 요약(Karpathy Summary 등)을 포함한 읽기 쉬운 구조.
* **[[Authenticity|Authenticity]]**: 단순히 정보를 나열하기보다 필자만의 독특한 관점과 경험을 녹여냄. (Authenticity와 연결)
2. **지식 관리에서의 역할**:
* 파편화된 지식(Atomic notes)들을 엮어 하나의 완성된 서사로 발전시키는 '지식의 결정체' 단계.
### 매 Strong Post 의 Anatomy
- **Hook**: 매 첫 두 문장 — problem + stake.
- **TL;DR / BLUF**: 매 결론 먼저.
- **Concrete numbers**: 매 "20% faster" not "much faster".
- **Code that runs**: 매 copy-pasteable, working snippet.
- **Diagrams**: 매 system 그림이 단어 100개를 대체.
- **Honest tradeoffs**: 매 안 좋은 점도 적기.
- **Sources**: 매 reference link.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 긴 텍스트 위주의 '일기장' 정책이 강했으나, 현대의 콘텐츠 정책은 짧고 강렬한 이미지와 정보를 담은 '마이크로 블로깅' 및 'AI 생성 보조 기반의 고효율 포스팅 정책'으로 진화함(RL Update).
- **정책 변화(RL Update)**: 검색 엔진 최적화(SEO) 정책 중심의 글쓰기에서 벗어나, AI 답변 에이전트가 내 글을 잘 인용할 수 있도록 데이터 구조를 최적화하는 'LLM-Friendly 포스팅 정책'이 새로운 마케팅 표준이 됨. (SEO Best Practices와 협업)
### 매 Format Type
- **Tutorial**: 매 step-by-step, runnable.
- **Reference**: 매 spec-like.
- **Explainer / mental-model**: 매 "왜".
- **Postmortem**: 매 incident retrospective.
- **Decision record (ADR)**: 매 trade-off 기록.
- **Benchmark**: 매 measure + reproduce.
## 🔗 지식 연결 (Graph)
- [[Scientific Communication|Scientific Communication]], [[Authenticity|Authenticity]], [[Knowledge synthesis|Knowledge Synthesis]], [[Arts|Arts]], Information-Overload
- **Modern Tech/Tools**: Medium, Substack, Ghost, AI technical writing assistants.
---
### 매 Stack 2026
- **Authoring**: MDX, code blocks with shiki/Prism, KaTeX math.
- **SSG**: Astro, Next.js, Hugo, Eleventy.
- **Hosting**: Vercel, Cloudflare Pages, Netlify, GitHub Pages.
- **Analytics**: Plausible, Fathom (privacy-friendly).
- **Feedback**: Giscus (GitHub Discussions).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Engineering blog (Stripe, Cloudflare, Vercel style).
2. Personal site (Notion-style or Astro).
3. Internal wiki post.
4. Conference talk companion.
5. Open-source project announcement.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Astro + MDX setup
```bash
bun create astro@latest my-blog -- --template blog --typescript strict
cd my-blog && bunx astro add mdx sitemap
```
## 🧪 검증 상태 (Validation)
### Frontmatter schema (zod-validated)
```typescript
// src/content/config.ts
import { defineCollection, z } from 'astro:content';
export const collections = {
blog: defineCollection({
type: 'content',
schema: z.object({
title: z.string().max(70),
pubDate: z.coerce.date(),
tags: z.array(z.string()),
heroImage: z.string().optional(),
tldr: z.string().min(40).max(280),
}),
}),
};
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Code block with shiki + line highlight
````mdx
```ts {3-5}
function fib(n: number): number {
if (n < 2) return n;
// 매 highlighted recursion
return fib(n-1) + fib(n-2);
}
```
````
## 🧬 중복 검사 (Duplicate Check)
### Open Graph + JSON-LD
```html
<meta property="og:title" content={post.title}>
<meta property="og:description" content={post.tldr}>
<meta property="og:image" content={`https://blog.example.com/og/${post.slug}.png`}>
<script type="application/ld+json">{JSON.stringify({
"@context":"https://schema.org",
"@type":"BlogPosting",
"headline": post.title,
"datePublished": post.pubDate.toISOString(),
})}</script>
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Auto-generated OG image (Vercel OG)
```typescript
// pages/og/[slug].tsx
import { ImageResponse } from '@vercel/og';
export default function og(req) {
const title = new URL(req.url).searchParams.get('title');
return new ImageResponse(<div style={{fontSize:64,padding:80}}>{title}</div>, { width:1200, height:630 });
}
```
## 🕓 변경 이력 (Changelog)
### TL;DR via LLM (build-time)
```typescript
// 매 build hook — generate 280-char summary
const tldr = await anthropic.messages.create({
model: 'claude-haiku-4',
max_tokens: 200,
messages: [{ role:'user', content:`Summarize in 2 sentences:\n\n${markdown}` }],
});
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 매 결정 기준
| 상황 | SSG |
|---|---|
| Content-heavy, fast | Astro |
| React stack, ISR | Next.js |
| Maximum simplicity | Hugo / Eleventy |
| Notion-style | Notion + Super |
| Self-host | Ghost |
**기본값**: 매 Astro + MDX + Vercel/Cloudflare Pages.
## 🔗 Graph
- 부모: [[Continuous-Discovery]]
- 변형: [[BLUF (Bottom Line Up Front)]]
- 응용: [[MECE Principle]]
- Adjacent: [[Edtech-Industry-Trends]]
## 🤖 LLM 활용
**언제**: TL;DR 생성, alt-text, SEO meta description, draft outline.
**언제 X**: 매 fact claim — 매 verify 안 한 LLM output 은 hallucination 위험.
## ❌ 안티패턴
- **Wall of text**: 매 heading + list 없이는 skim 불가.
- **Pseudocode only**: 매 reader 가 실행 못 함.
- **No metrics**: 매 "faster, better" 만 — concrete 숫자 필요.
- **Stale code**: 매 deprecated API 사용.
- **No date**: 매 reader 가 freshness 판단 불가.
## 🧪 검증 / 중복
- Verified: web.dev SEO docs; Schema.org BlogPosting; Astro docs.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — anatomy + Astro/MDX/OG patterns |
@@ -2,92 +2,145 @@
id: wiki-2026-0508-branch-prediction
title: Branch Prediction
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-4D7707]
aliases: [P-Reinforce-AUTO-4D7707, CPU Branch Predictor]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [cpu, performance, security, microarchitecture]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Branch Prediction"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: cpp
framework: none
---
# [[Branch Prediction|Branch Prediction]]
# Branch Prediction
## 📌 한 줄 통찰 (The Karpathy Summary)
> Branch prediction(분기 예측)은 현대 CPU가 분기 명령어의 과거 기록을 프로파일링하여(예: 분기가 항상 통과되는지 관찰) 다음 실행 경로를 미리 예측하는 성능 최적화 기술입니다 [1]. 이는 추측 실행([[Speculative Execution|Speculative Execution]])과 결합되어 CPU의 처리 속도를 비약적으로 높이지만, 공격자가 분기 기록을 통제할 수 있다는 점 때문에 스펙터([[Spectre|Spectre]])와 같은 심각한 보안 취약점의 공격 경로로 악용됩니다 [1, 2].
## 한 줄
> **"매 modern CPU 의 IPC 핵심 mechanism — 그리고 Spectre 의 attack surface."**. Branch predictor 는 conditional/indirect branch 의 결과를 speculatively execute 함으로써 deep pipeline 의 stall 을 회피; 매 misprediction penalty 는 15-20+ cycles, 매 mispredicted speculative window 가 Spectre v1/v2 의 leak vector.
## 📖 구조화된 지식 (Synthesized Content)
- **분기 예측과 추측 실행(Speculative Execution):** 현대 CPU는 성능 향상을 위해 분기를 프로파일링하여 실행 경로를 예측합니다 [1]. CPU는 분기 조건이 실제로 검증되기 전에 예측된 경로에 따라 메모리 로드 등의 명령을 미리 실행(추측 실행)하며, 예측이 틀린 것으로 판명되면 분기 이후에 일어난 작업을 롤백(Roll back)합니다 [1].
- **스펙터(Spectre) 공격의 원리:** 스펙터 취약점은 분기 예측을 악용합니다. 추측 실행은 과거의 기록에 따라 분기를 실행하는데, 공격자는 이 과거 기록을 통제함으로써 CPU가 추측 실행 중에 어떤 분기를 수행할지 조작할 수 있습니다 [2]. 추측 실행이 롤백되더라도 L1 캐시에 로드된 데이터는 취소되지 않으므로, 공격자는 이를 이용해 타이밍 기반으로 메모리 정보를 유출할 수 있습니다 [2, 3].
- **브라우저 엔진([[WebKit|WebKit]])에 미치는 영향:** WebKit의 JavaScriptCore는 신뢰할 수 없는 JavaScript나 [[WebAssembly|WebAssembly]] 코드의 보안(예: 배열 경계 검사, 타입 검사)을 유지하기 위해 '분기 명령어'에 의존해왔습니다 [4-6]. 그러나 분기 예측을 악용한 스펙터 공격으로 인해, 분기 명령어만으로는 더 이상 보안 속성을 강제하기에 충분하지 않게 되었습니다 [4, 5].
- **대응 및 완화 조치:** 분기 예측을 악용하는 공격에 대응하기 위해 WebKit은 기존의 분기 기반 보안 검사 외에도, 인덱스 마스킹([[Index Masking|Index Masking]])이나 포인터 포이즈닝(Pointer Poisoning)과 같은 '분기 없는 보안 검사([[Branchless Security Checks|Branchless Security Checks]])' 방식으로 전환하고 있습니다 [7-9].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 Predictor 종류
- **Static**: forward-not-taken, backward-taken (hint).
- **Bimodal (2-bit)**: per-PC saturating counter.
- **Local history**: per-branch shift register.
- **Global history (gshare/GAg)**: shared GHR XOR PC.
- **Tournament**: meta-predictor selects local vs global.
- **TAGE / ITTAGE**: tagged geometric history (modern SOTA).
- **Perceptron**: AMD Zen — neural-style predictor.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Speculative Execution|Speculative Execution]], Spectre, [[Branchless Security Checks|Branchless Security Checks]]
- **Projects/Contexts:** [[WebKit|WebKit]], [[JavaScriptCore|JavaScriptCore]]
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다. (소스 내에 상충하는 의견은 없으며, 과거에는 분기 명령어가 보안 강제에 충분하다고 여겨졌으나 스펙터의 등장으로 인해 더 이상 안전하지 않게 되었다는 맥락적 변화만 존재합니다 [4]).
### 매 Indirect Branches
- BTB (Branch Target Buffer) — caches target.
- ITTAGE for indirect.
- Critical for vtables, function pointers, switch.
---
*Last updated: 2026-04-19*
### 매 응용
1. Hot loops — predictable branches → near-zero penalty.
2. Sorted-data effect (the famous SO question).
3. Spectre/BranchScope side-channel attacks.
4. JIT branch ordering decisions (V8, Hotspot).
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Likely / Unlikely Hints (C++20)
```cpp
if (x > 0) [[likely]] {
fast_path();
} else [[unlikely]] {
slow_path();
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Branchless via Mask
```cpp
// branchful
int abs_v(int x) { return x < 0 ? -x : x; }
**선택 A를 써야 할 때:**
- *(TODO)*
// branchless
int abs_v_nb(int x) {
int mask = x >> 31; // 0 or -1
return (x ^ mask) - mask;
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Branchless Min via cmov
```cpp
int min_v(int a, int b) {
return a < b ? a : b; // compilers emit cmov on x86
}
```
**기본값:**
> *(TODO)*
### Sort Before Loop (classic)
```cpp
std::sort(data.begin(), data.end()); // 정렬 → branch predictable
long sum = 0;
for (int v : data) if (v >= 128) sum += v;
```
## ❌ 안티패턴 (Anti-Patterns)
### LLVM `__builtin_expect`
```cpp
if (__builtin_expect(error_flag, 0)) {
handle_error();
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Spectre v1 Mitigation (lfence)
```cpp
// vulnerable
if (idx < arr_size) {
secret = arr[idx]; // mispredict → leaks
}
// hardened
if (idx < arr_size) {
asm volatile("lfence" ::: "memory");
secret = arr[idx];
}
```
### perf Branch Stats
```bash
perf stat -e branches,branch-misses ./bench
# branch-miss rate > 5% → suspect; > 10% → critical
```
## 매 결정 기준
| 상황 | 전략 |
|---|---|
| Hot loop, predictable | Trust predictor — natural code |
| Hot loop, unpredictable | Branchless / mask / cmov |
| Cold path | Doesn't matter — clarity > tricks |
| Indirect-heavy (vtable) | Devirtualize, monomorphize |
| Security-sensitive | lfence / speculative load hardening |
**기본값**: write clear branchful code; branchless only when profiler shows misprediction hotspot.
## 🔗 Graph
- 부모: [[CPU Microarchitecture]] · [[Pipeline]]
- 변형: [[TAGE]] · [[Perceptron Predictor]] · [[BTB]]
- 응용: [[JIT Compilation]] · [[Branchless Programming]]
- Adjacent: [[Spectre]] · [[Speculative Execution]] · [[cmov]]
## 🤖 LLM 활용
**언제**: explain mispredict cost, generate branchless equivalents, suggest hints.
**언제 X**: micro-arch tuning without perf data — speculation hurts.
## ❌ 안티패턴
- **Random unpredictable branch in hot loop**: 20-30% slowdown.
- **Premature branchless conversion**: hurts cold/clarity paths.
- **Trusting `[[likely]]` blindly**: PGO data > human guess.
- **Ignoring Spectre in untrusted-input parsers**: real CVE risk.
## 🧪 검증 / 중복
- Verified (Hennessy & Patterson 6th, Agner Fog optimization manuals, Intel SDM).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — predictor types, branchless patterns, Spectre |
@@ -2,92 +2,160 @@
id: wiki-2026-0508-buffergeometry
title: BufferGeometry
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-2887C6]
aliases: [P-Reinforce-AUTO-2887C6, Three.js BufferGeometry]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [graphics, threejs, webgl, performance]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - BufferGeometry"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: javascript
framework: three.js
---
# [[BufferGeometry|BufferGeometry]]
# BufferGeometry
## 📌 한 줄 통찰 (The Karpathy Summary)
> BufferGeometry는 Three.js의 핵심 3D 기하학 구조를 정의하는 객체이다 [1]. [[InstancedMesh|InstancedMesh]] 기술에서 수많은 인스턴스가 공통으로 공유하는 기하학적 데이터로 사용된다 [2, 3]. 또한 여러 개의 지오메트리를 단일 BufferGeometry로 병합하여 렌더링 과정에서 발생하는 드로우 콜([[Draw Call|Draw Call]])을 최소화하는 성능 최적화의 핵심 단위로도 활용된다 [4, 5].
## 한 줄
> **"매 Three.js 의 GPU-resident geometry container — 매 modern Three 의 only geometry class."**. BufferGeometry 는 typed-array 기반 attribute (position, normal, uv, index) 의 GPU upload 를 직접 관리하며, 매 Geometry class deprecation (r125) 이후 표준 — instancing/batching/morph 의 backbone.
## 📖 구조화된 지식 (Synthesized Content)
* **InstancedMesh의 기본 데이터 레이어:** InstancedMesh 구조에서 BufferGeometry는 모든 개별 인스턴스가 공통으로 공유하는 기하학적 정의를 담당하는 주요 데이터 레이어이다 [2]. 다만, 하나의 InstancedMesh 인스턴스는 오직 하나의 BufferGeometry만을 참조할 수 있다는 기하학적 단일성의 제약이 존재한다 [6].
* **지오메트리 병합(Merging)을 통한 최적화:** 정적인 환경이나 여러 개의 객체들을 렌더링할 때, `BufferGeometryUtils.mergeBufferGeometries()` 메서드를 사용하여 서로 다른 기하학적 데이터를 단일 BufferGeometry로 병합할 수 있다 [5, 7, 8]. 이를 통해 여러 객체를 단 한 번의 드로우 콜로 렌더링함으로써 CPU 오버헤드를 획기적으로 낮출 수 있다 [4].
* **메모리 집약성 및 컬링(Culling) 효율의 한계:** 여러 객체를 하나의 BufferGeometry로 묶는 방식은 드로우 콜을 줄여주지만, 객체를 복제할 때마다 RAM 사용량이 정비례로 증가하는 메모리 집약적인 특성을 띤다 [4]. 더욱이 병합된 메쉬 전체가 하나의 단일 바운딩 볼륨(Bounding Volume)으로 취급되기 때문에, 화면 밖의 객체를 제외하는 시야 절두체 컬링([[Frustum Culling|Frustum Culling]])의 정밀도가 떨어지는 한계가 발생한다 [5].
* **개별 항목의 식별 및 접근:** 여러 객체를 거대한 BufferGeometry 하나로 병합한 후 특정 개별 요소를 선택하거나 수정하는 것은 까다롭지만, 버퍼 내 각 객체의 위치(Position) 데이터를 저장하는 매핑(Map) 구조를 구축하여 개별 항목을 효율적으로 조회하고 제어할 수 있다 [4].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 Attribute
- **Position** (Float32Array, itemSize=3): vertex coords.
- **Normal** (Float32Array, itemSize=3).
- **UV** (Float32Array, itemSize=2).
- **Index** (Uint16/Uint32Array): triangle list.
- **Custom**: any vertex attribute (color, tangent, instance data).
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[InstancedMesh|InstancedMesh]], [[Draw Call|Draw Call]], BufferGeometryUtils
- **Projects/Contexts:** Three.js, IFC.js Fragment
- **Contradictions/Notes:** 소스 문헌들은 성능 개선을 위해 객체들을 단일 BufferGeometry로 병합할 것을 권장하면서도, 이 방식이 드로우 콜을 최소화하는 대신 RAM 소모량을 높이고 시야 절두체 컬링의 효율을 저하시키는 트레이드오프(Trade-off)를 유발한다고 경고한다 [4, 5].
### 매 Update Strategy
- **Static**: upload once, never modify (default).
- **Dynamic** (`setUsage(DynamicDrawUsage)`): frequent CPU update.
- **Stream**: per-frame update (rare).
---
*Last updated: 2026-04-19*
### 매 응용
1. Custom shaders with custom attributes.
2. GPU instancing (InstancedBufferAttribute).
3. Procedural geometry generation.
4. Mesh deformation / morphing.
5. GPGPU particle systems.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Manual Triangle
```javascript
import * as THREE from "three";
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
const geo = new THREE.BufferGeometry();
const positions = new Float32Array([
0, 1, 0,
-1, -1, 0,
1, -1, 0,
]);
geo.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geo.computeVertexNormals();
```
## 🤔 의사결정 기준 (Decision Criteria)
### Indexed Quad
```javascript
const positions = new Float32Array([-1,-1,0, 1,-1,0, 1,1,0, -1,1,0]);
const indices = new Uint16Array([0, 1, 2, 0, 2, 3]);
const geo = new THREE.BufferGeometry();
geo.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geo.setIndex(new THREE.BufferAttribute(indices, 1));
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Dynamic Vertex Update
```javascript
const attr = geo.attributes.position;
attr.setUsage(THREE.DynamicDrawUsage);
**선택 B를 써야 할 때:**
- *(TODO)*
function tick(t) {
for (let i = 0; i < attr.count; i++) {
attr.setY(i, Math.sin(t + i * 0.1));
}
attr.needsUpdate = true;
}
```
**기본값:**
> *(TODO)*
### Custom Shader Attribute
```javascript
const aRandom = new Float32Array(geo.attributes.position.count);
for (let i = 0; i < aRandom.length; i++) aRandom[i] = Math.random();
geo.setAttribute("aRandom", new THREE.BufferAttribute(aRandom, 1));
## ❌ 안티패턴 (Anti-Patterns)
const mat = new THREE.ShaderMaterial({
vertexShader: `attribute float aRandom; varying float vR;
void main(){ vR=aRandom; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }`,
fragmentShader: `varying float vR; void main(){ gl_FragColor=vec4(vR,vR,vR,1.); }`,
});
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Instanced Attribute
```javascript
const N = 10000;
const offsets = new Float32Array(N * 3);
for (let i = 0; i < N; i++) {
offsets[i*3] = (Math.random()-0.5)*100;
offsets[i*3+1] = (Math.random()-0.5)*100;
offsets[i*3+2] = (Math.random()-0.5)*100;
}
const igeo = new THREE.InstancedBufferGeometry().copy(geo);
igeo.instanceCount = N;
igeo.setAttribute("aOffset", new THREE.InstancedBufferAttribute(offsets, 3));
```
### Merge Geometries
```javascript
import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
const merged = mergeGeometries([geoA, geoB, geoC], false);
// single draw call instead of three
```
### Bounding Volume Recompute
```javascript
geo.computeBoundingBox();
geo.computeBoundingSphere(); // required for frustum culling after vertex moves
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Static mesh | StaticDrawUsage (default) |
| Per-frame deform | DynamicDrawUsage + needsUpdate |
| Many copies | InstancedBufferGeometry |
| Many distinct meshes | mergeGeometries or BatchedMesh |
| Massive points | BufferGeometry + Points + custom shader |
**기본값**: static indexed BufferGeometry; switch to instanced/merged for >100 copies.
## 🔗 Graph
- 부모: [[Three.js]] · [[WebGL Geometry]]
- 변형: [[InstancedBufferGeometry]] · [[BatchedMesh]]
- 응용: [[Custom Shader]] · [[GPGPU Particles]]
- Adjacent: [[BufferAttribute]] · [[VBO]] · [[VAO]]
## 🤖 LLM 활용
**언제**: generate procedural geometry boilerplate, debug attribute layout.
**언제 X**: micro-optimization of custom shaders without profiling.
## ❌ 안티패턴
- **Forgetting `needsUpdate = true`**: GPU never re-uploads.
- **Recreating BufferGeometry per frame**: GC pressure — mutate in place.
- **Float32 indices**: not supported — use Uint16/Uint32.
- **No bounding sphere recompute**: frustum-culled erroneously after deform.
## 🧪 검증 / 중복
- Verified (three.js r170 docs, threejs-journey).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — attributes, dynamic update, instancing patterns |
@@ -1,94 +1,33 @@
---
id: wiki-2026-0508-cantab-5-선택-반응-시간-과제-cantab-5-ch
title: CANTAB 5 선택 반응 시간 과제(CANTAB 5 choice RTI)
title: CANTAB 5-선택 반응 시간 과제(CANTAB 5-choice RTI)
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
aliases: [P-Reinforce-AUTO-20A493]
duplicate_of: none
status: duplicate
canonical_id: cantab-5-choice-rti
duplicate_of: "[[CANTAB 5-Choice RTI]]"
aliases: []
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - CANTAB 5-선택 반응 시간 과제(CANTAB 5-choice RTI)"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
verification_status: redirected
tags: [duplicate, neuropsychology, cognition, assessment]
last_reinforced: 2026-05-10
github_commit: pending
---
# [[CANTAB 5-선택 반응 시간 과제(CANTAB 5-choice RTI)|CANTAB 5-선택 반응 시간 과제(CANTAB 5-choice RTI]]
# CANTAB 5-선택 반응 시간 과제(CANTAB 5-choice RTI)
## 📌 한 줄 통찰 (The Karpathy Summary)
> CANTAB 5-선택 반응 시간 과제(RTI)는 참가자의 반응 속도를 측정하여 인지적 요인과 신체적 움직임 요인을 분리하여 평가할 수 있도록 설계된 인지 측정 과제입니다 [1]. 이 과제는 주로 iPad의 CANTAB 앱을 통해 시행되며, 사용자가 화면의 5개 위치를 모니터링하다가 나타나는 시각적 자극에 최대한 빠르게 반응하는 능력을 평가합니다 [1]. 과제의 결과는 크게 '의사결정 속도'와 '이동 속도'라는 두 가지 구성 요소로 나뉘어 측정됩니다 [1, 2].
> **이 문서는 [[CANTAB 5-Choice RTI]] 의 중복본입니다.** Canonical 문서로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
- **과제 인터페이스 및 수행 절차:** RTI 과제는 화면 하단에 위치한 하나의 원(버튼)과 화면 상단에 위치한 5개의 원으로 구성됩니다 [1]. 참가자는 먼저 하단의 버튼을 누르고 대기하다가, 상단의 5개 원 중 무작위 위치에서 노란색 점(목표 자극)이 나타나는 것을 모니터링해야 합니다 [1]. 노란색 점이 나타나면, 참가자는 지체 없이 하단 버튼에서 손을 떼고 해당 노란색 점을 터치해야 합니다 [1].
- **반응 시간의 측정 요소:** 과제는 참가자의 반응을 두 가지 개별 속도로 나누어 계산하며, 정확하게 수행된 응답(correct responses) 데이터만을 계산에 포함합니다 [1].
- **의사결정 속도(Decision speed):** 목표 자극이 화면에 나타난 순간부터 참가자가 하단 버튼에서 손을 떼기까지 걸린 시간의 중앙값(median duration)입니다 [1].
- **이동 속도(Movement speed):** 하단 버튼에서 손을 뗀 순간부터 목표 자극(노란색 점)을 실제로 터치하기까지 걸린 시간의 중앙값입니다 [1].
- **활용 맥락:** 소스 자료에 따르면, 이 과제는 가상현실(VR) 엑서게임([[Beat Saber|Beat Saber]] 등) 이용이 인지 능력에 미치는 사후 효과(Aftereffects)를 측정하기 위한 연구에 도입되었습니다 [1, 3]. 참가자의 인지 상태 변화를 확인하기 위해 VR 노출 전, 노출 직후, 그리고 40분 후에 각각 이 과제를 수행하여 반응 시간을 비교 분석하는 데 사용되었습니다 [3, 4].
## 핵심 요약 (specialization aspects, optional)
- Cambridge Neuropsychological Test Automated Battery (CANTAB) 의 5-choice reaction time task.
- Movement time + reaction time 의 분리 측정.
- 임상: ADHD, dementia, TBI 의 attention/processing speed assessment.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
## 🔗 Graph
- 부모: [[CANTAB 5-Choice RTI]] (canonical)
## 🔗 지식 연결 (Graph)
- **Related Topics:** 의사결정 속도(Decision Speed), [[이동 속도(Movement Speed)|이동 속도(Movement Speed]]
- **Projects/Contexts:** [[가상현실 사후 효과 연구(Virtual Reality Aftereffects Study)|가상현실 사후 효과 연구(Virtual Reality Aftereffects Study]]
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다. (소스 데이터 내에서 해당 과제에 대해 상충하는 주장이나 논쟁점은 확인되지 않습니다.)
---
*Last updated: 2026-04-19*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
```
## 🤔 의사결정 기준 (Decision Criteria)
**선택 A를 써야 할 때:**
- *(TODO)*
**선택 B를 써야 할 때:**
- *(TODO)*
**기본값:**
> *(TODO)*
## ❌ 안티패턴 (Anti-Patterns)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -1,77 +1,163 @@
---
id: wiki-2026-0508-ci-cd-pipeline
title: CI CD Pipeline
category: DevOps_and_Security
status: needs_review
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [ci_cd_pipeline]
aliases: [Continuous Integration / Delivery Pipeline, Build Pipeline]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [- ci_cd - devops - automation - pipeline - software_delivery]
raw_sources: ["- Programming & Language/CI_CD Pipeline.md - Programming & Language/CI_CD 파이프라인 자동화.md - Programming & Language/CI_CD 파이프라인.md - Programming & Language/Continuous Integration (CI).md - Architecture/CI_CD.md"]
last_reinforced: 2026-05-08
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
confidence_score: 0.9
verification_status: applied
tags: [ci, cd, devops, pipeline]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: YAML
framework: GitHub Actions/GitLab CI/Buildkite
---
# CI/CD 파이프라인 (Continuous Integration & Continuous Deployment)
# CI CD Pipeline
## 📌 한 줄 통찰 (The Karpathy Summary)
CI/CD는 애플리케이션 개발 단계부터 배포까지의 전 과정을 자동화하여 사용자에게 더 빠르고 빈번하게 소프트웨어를 제공하는 방법론입니다 [1]. **CI(Continuous Integration)**는 코드 변경 사항을 정기적으로 빌드 및 테스트하여 공유 저장소에 병합하는 과정을, **CD(Continuous Delivery/Deployment)**는 검증된 코드를 운영 환경에 자동으로 배포하는 과정을 의미합니다 [1, 2].
## 한 줄
> **"매 commit 이 production 까지 도달하는 자동 경로가 CI/CD pipeline."**. Pipeline 은 build → test → security → package → deploy → verify 의 매 ordered DAG. 2026 의 표준: GitHub Actions reusable workflow + OIDC 기반 cloud auth + supply-chain attestation (SLSA L3) + progressive delivery (Argo Rollouts/Flagger).
## 📖 구조화된 지식 (Synthesized Content)
### 1. 지속적 통합 (Continuous Integration, CI)
* **자동 빌드 및 테스트**: 개발자가 코드를 커밋하면 자동으로 빌드가 수행되고 단위 테스트(Unit Test)가 실행됩니다.
* **충돌 조기 발견**: 빈번한 병합을 통해 코드 간의 충돌을 조기에 발견하고 해결합니다.
* **품질 게이트**: 정적 분석(SAST)이나 코드 품질 검사를 CI 단계에 포함시켜 기준 미달의 코드가 병합되는 것을 방지합니다.
## 매 핵심
### 2. 지속적 제공 및 배포 (Continuous Delivery/Deployment, CD)
* **Continuous Delivery**: CI 단계를 거친 아티팩트를 스테이징 환경까지 자동으로 배포하며, 운영 환경 배포는 수동 승인을 거칩니다.
* **Continuous Deployment**: 모든 테스트를 통과한 코드를 운영 환경까지 어떠한 수동 개입 없이 자동으로 배포합니다 [2].
* **배포 전략**: Blue-Green, Canary, Rolling Update 등을 활용하여 서비스 중단 없이 안전하게 배포합니다.
### 매 Pipeline Stage
1. **Source**: trigger on PR / push / tag.
2. **Build**: deterministic, hermetic — Bazel/Nx cache.
3. **Test**: unit / integration / e2e — parallel shards.
4. **Security**: SAST (Semgrep), SCA (Trivy), secret scan.
5. **Package**: container, helm chart, npm — sign (cosign).
6. **Attest**: SBOM (Syft) + SLSA provenance.
7. **Deploy**: env-progressive (dev → staging → prod).
8. **Verify**: smoke, canary metrics, auto-rollback.
### 3. 파이프라인 구성 요소
* **Source**: Git 등 버전 관리 시스템에서의 이벤트 감지.
* **Build**: 소스 코드를 컴파일하고 실행 가능한 형태로 변환.
* **Test**: 단위, 통합, 보안 테스트 수행.
* **Deploy**: 타겟 환경(Cloud, On-premise 등)으로 배포 및 환경 설정.
### 매 Modern Best Practices 2026
- **OIDC over long-lived secrets** (GitHub OIDC → AWS/GCP).
- **Reusable workflows** — DRY across repos.
- **Matrix sharding** — test parallelism.
- **Cache layers** — Turborepo, Nx, Bazel remote cache.
- **Progressive delivery** — canary, blue/green, feature flags.
- **GitOps** — Argo CD / Flux — git as source of truth.
- **Supply chain** — Sigstore cosign, SLSA L3 attestation.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **인프라 복잡성**: 자동화된 파이프라인을 구축하고 유지 관리하는 데 초기 비용과 노력이 많이 듭니다.
* **테스트 신뢰성**: 자동화된 테스트의 품질이 낮으면 잘못된 코드가 자동으로 배포되어 서비스 장애를 유발할 수 있습니다.
* **보안 리스크**: 파이프라인 자체의 보안(Secrets management 등)이 뚫리면 악성 코드가 배포될 위험이 있습니다.
### 매 응용
1. SaaS web app deploy.
2. Library publish (npm, PyPI, Maven).
3. Container image release.
4. Mobile (Fastlane).
5. ML model deploy (MLOps).
## 🔗 지식 연결 (Graph)
- **Related Topics**: [[DevSecOps|데브섹옵스]], [[SAST|정적 분석]], [[DAST|동적 분석]], [[SCA|구성 분석]], 인프라 자동화(IaC)
- **Projects/Contexts**: GitHub Actions, Jenkins, GitLab CI, ArgoCD 활용
- **Contradictions/Notes**: CI/CD는 단순히 도구의 문제가 아니라 '문화'의 문제입니다. 실패 시 즉시 복구하고 문제를 공유하는 팀의 성숙도가 동반되어야 합니다 [1].
## 💻 패턴
---
*Last updated: 2026-05-08*
### GitHub Actions reusable workflow
```yaml
# .github/workflows/ci.yml
on: [pull_request, push]
permissions:
contents: read
id-token: write # 매 OIDC
jobs:
test:
uses: org/.github/.github/workflows/ts-ci.yml@v1
with:
node-version: '22'
deploy:
needs: test
if: github.ref == 'refs/heads/main'
uses: org/.github/.github/workflows/deploy.yml@v1
with:
env: prod
```
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### OIDC to AWS (no long-lived keys)
```yaml
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123:role/gha-deployer
aws-region: us-east-1
- run: aws s3 sync ./dist s3://my-bucket
```
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Matrix test sharding
```yaml
strategy:
matrix:
shard: [1, 2, 3, 4]
steps:
- run: bun run vitest run --shard=${{ matrix.shard }}/4
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### Container build + sign + SBOM
```yaml
- uses: docker/build-push-action@v6
id: build
with: { tags: ghcr.io/org/app:${{ github.sha }}, push: true }
- uses: anchore/sbom-action@v0
with: { image: ghcr.io/org/app:${{ github.sha }}, format: spdx-json }
- uses: sigstore/cosign-installer@v3
- run: cosign sign --yes ghcr.io/org/app@${{ steps.build.outputs.digest }}
```
## 🧪 검증 상태 (Validation)
### Argo Rollouts canary
```yaml
apiVersion: argoproj.io/v1alpha1
kind: Rollout
spec:
strategy:
canary:
steps:
- setWeight: 10
- pause: { duration: 5m }
- analysis: { templates: [{ templateName: error-rate }] }
- setWeight: 50
- pause: { duration: 10m }
- setWeight: 100
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Turborepo remote cache
```bash
# 매 first build seeds cache; later runs hit
TURBO_TOKEN=$REMOTE_TOKEN TURBO_TEAM=acme bunx turbo run build --remote-cache-timeout=60
```
## 🧬 중복 검사 (Duplicate Check)
## 매 결정 기준
| 상황 | Tool |
|---|---|
| OSS / GitHub repo | GitHub Actions |
| GitLab native | GitLab CI |
| Monorepo many pipelines | Buildkite / Dagger |
| K8s GitOps | Argo CD + Argo Rollouts |
| Multi-cloud workflow | Dagger / Earthly |
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
**기본값**: 매 GitHub Actions + OIDC + reusable workflow + Argo Rollouts.
## 🕓 변경 이력 (Changelog)
## 🔗 Graph
- 부모: [[Continuous Integration (지속적 통합, CI)]] · [[Continuous Delivery (지속적 제공, CD)]]
- 변형: [[지속적 통합 (CI) 및 지속적 배포 (CD)]]
- 응용: [[Engineering Metrics (DORA)]] · [[Feature-Flags]]
- Adjacent: [[Husky]] · [[Test_Automation]] · [[Secret_Management]]
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🤖 LLM 활용
**언제**: workflow YAML drafting, failed-build log triage, retry-storm root-cause.
**언제 X**: 매 deterministic step (lint/test) — pipeline 자체가 검증.
## ❌ 안티패턴
- **Long-lived AWS keys in secret**: 매 OIDC 사용.
- **`if: always()` 남용**: 매 fail 무시 — 신뢰 무너짐.
- **No cache**: 매 매 build 30분.
- **Single-stage everything**: 매 fail-fast 설계 안 됨.
- **No staging**: 매 직접 prod — rollback 어려움.
## 🧪 검증 / 중복
- Verified: GitHub Actions docs; SLSA spec v1.0; Argo Rollouts docs; DORA report 2024.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — pipeline stages + OIDC/SLSA/canary |
@@ -2,21 +2,157 @@
id: wiki-2026-0508-cpu-bottleneck
title: CPU Bottleneck
category: 10_Wiki/Topics
status: merged
redirect_to: 성능_프로파일링_및_메모리_관리_표준
canonical_id: wiki-2026-0508-040
aliases: []
status: verified
canonical_id: self
aliases: [CPU-Bound, Compute Bottleneck]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [performance, profiling, cpu]
raw_sources: []
last_reinforced: 2026-05-08
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: C++/Rust/JS
framework: perf/Instruments/Chrome DevTools
---
# Redirect
# CPU Bottleneck
이 문서는 Canonical 문서인 [[성능_프로파일링_및_메모리_관리_표준]]으로 통합되었습니다.
모든 최신 지식과 세부 내용은 위 링크를 참조하십시오.
## 매 한 줄
> **"매 GPU 가 놀고 main thread 가 100% 면 CPU bottleneck."**. CPU bottleneck 은 frame budget 16.7ms (60fps) 또는 11ms (90fps XR) 안에 main thread 작업이 안 끝나는 상태. 2026 진단: Chrome Performance panel + perf + Instruments → fix: WebWorker / WASM SIMD / off-main-thread / batching.
## 매 핵심
### 매 진단 신호
- GPU utilization < 70% but FPS drop.
- Long Task > 50ms in Performance panel.
- `perf top` 의 single function 이 hot.
- Profile 의 self-time 이 한 함수에 집중.
### 매 Bottleneck Source
- **Main-thread JS**: parse, layout, large loop.
- **Layout thrash**: read-write-read DOM.
- **GC pause**: allocation pressure.
- **Synchronous IO**: blocking syscall.
- **Unoptimized algorithm**: O(n²) on hot path.
- **Single-core saturation**: no parallelism.
### 매 Fix Strategy
1. **Profile first** — 매 measure, not guess.
2. **Off-main-thread**: WebWorker, OffscreenCanvas.
3. **Batch**: requestAnimationFrame, microtask.
4. **SIMD/WASM**: 매 hot inner loop.
5. **Algorithmic**: O(n²) → O(n log n).
6. **Cache**: memoize, weak-ref.
7. **Lazy**: defer, code-split.
## 💻 패턴
### Detect long task
```javascript
const obs = new PerformanceObserver(list => {
for (const e of list.getEntries()) {
if (e.duration > 50) console.warn('long task', e.duration, e.name);
}
});
obs.observe({ entryTypes: ['longtask'] });
```
### Move work to Worker
```javascript
// main.js
const w = new Worker('worker.js', { type: 'module' });
w.postMessage({ data: bigArray }, [bigArray.buffer]); // 매 transfer, zero-copy
w.onmessage = e => render(e.data);
// worker.js
self.onmessage = e => {
const result = heavyCompute(e.data.data);
self.postMessage(result, [result.buffer]);
};
```
### WASM SIMD hot loop (Rust)
```rust
#[target_feature(enable = "simd128")]
unsafe fn dot_product(a: &[f32], b: &[f32]) -> f32 {
use std::arch::wasm32::*;
let mut sum = f32x4_splat(0.0);
for i in (0..a.len()).step_by(4) {
let va = v128_load(a.as_ptr().add(i) as *const v128);
let vb = v128_load(b.as_ptr().add(i) as *const v128);
sum = f32x4_add(sum, f32x4_mul(va, vb));
}
f32x4_extract_lane::<0>(sum) + f32x4_extract_lane::<1>(sum)
+ f32x4_extract_lane::<2>(sum) + f32x4_extract_lane::<3>(sum)
}
```
### Time-sliced loop (yield to event loop)
```javascript
async function processChunked(items) {
const CHUNK = 200;
for (let i = 0; i < items.length; i += CHUNK) {
items.slice(i, i + CHUNK).forEach(processOne);
await new Promise(r => setTimeout(r, 0)); // 매 yield
}
}
// 또는 scheduler.yield() (2025+)
if ('scheduler' in window && 'yield' in scheduler) await scheduler.yield();
```
### Batch DOM read/write
```javascript
// 매 안티 — layout thrash
items.forEach(el => { const w = el.offsetWidth; el.style.width = (w*2)+'px'; });
// 매 fix — read first, then write
const widths = items.map(el => el.offsetWidth);
items.forEach((el, i) => { el.style.width = (widths[i]*2)+'px'; });
```
### Linux perf hot function
```bash
sudo perf record -F 99 -g -p $(pidof myapp) -- sleep 10
sudo perf report --stdio | head -40
sudo perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Long JS function | WebWorker / time-slice |
| Image/video pipeline | OffscreenCanvas |
| Number crunching | WASM SIMD / GPU compute |
| Layout thrash | read-then-write batch |
| GC pressure | object pool |
| Multi-core unused | Worker pool / parallel |
**기본값**: 매 measure → identify hot fn → off-main-thread or algorithmic fix.
## 🔗 Graph
- 부모: [[Analyze runtime performance]] · [[Flame_Graphs]]
- 변형: [[Draw Call]]
- 응용: [[Tree Shaking (번들 크기 최적화)]] · [[Frustum Culling]]
- Adjacent: [[Memory Management]] · [[Branch Prediction]]
## 🤖 LLM 활용
**언제**: profile flamegraph 해석, hot-function refactor 제안, perf annotation.
**언제 X**: 매 actual perf measurement — deterministic 도구가 정확.
## ❌ 안티패턴
- **Premature optimization**: 매 profile 없이 추측 — 잘못된 부분 fix.
- **Worker overuse**: 매 small task 의 postMessage 오버헤드 > 이득.
- **`while(true)` busy-wait**: 매 throttle / requestIdleCallback 사용.
- **Synchronous XHR**: 매 deprecated, main-thread block.
## 🧪 검증 / 중복
- Verified: Chrome Performance docs; web.dev Long Tasks; Linux perf-tools (Brendan Gregg).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — diagnosis + Worker/SIMD/yield patterns |
@@ -1,100 +1,151 @@
---
id: wiki-2026-0508-cheneys-algorithm
title: Cheneys Algorithm
title: Cheney's Algorithm
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-52B523]
aliases: [Cheney GC, Semi-space Collector, Copying GC]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [gc, memory, algorithm, runtime]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Cheneys Algorithm"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: C/Rust
framework: runtime/GC
---
# [[Cheneys Algorithm|Cheneys Algorithm]]
# Cheney's Algorithm
## 📌 한 줄 통찰 (The Karpathy Summary)
> Cheney's Algorithm은 V8 자바스크립트 엔진의 마이너 가비지 컬렉터인 스캐빈저([[Scavenge|Scavenge]]r)에서 메모리를 관리하기 위해 사용하는 가비지 컬렉션 알고리즘입니다 [1, 2]. 이 알고리즘은 메모리의 '새로운 공간(New-space)'을 동일한 크기를 가진 'from-space'와 'to-space'라는 두 개의 반공간(Semi-space)으로 나누어 작동합니다 [1, 2]. 살아있는 객체만을 from-space에서 to-space로 복사하고 압축(compact)함으로써, 빠른 메모리 할당과 캐시 지역성 향상을 달성합니다 [1].
## 한 줄
> **"매 stop-and-copy GC 의 BFS-style two-finger traversal"**. 1970년 C.J. Cheney 가 제시한 copying garbage collector 의 표준 algorithm — recursion 없이 queue-style 로 live object 를 from-space 에서 to-space 로 evacuate. 매 modern V8/SpiderMonkey young generation, OCaml minor heap, MLton 의 baseline.
## 📖 구조화된 지식 (Synthesized Content)
- **반공간(Semi-space) 구조 및 역할 교환**: 알고리즘은 할당 공간이 가득 찰 때 to-space와 from-space의 역할을 맞바꾸는 것으로 시작합니다 [1]. 이를 통해 모든 기존 객체는 from-space에 위치하게 되며, 이후 시스템은 살아있는 객체만을 찾아내어 to-space로 복사하거나 '오래된 공간(old-space)'으로 승격(promote)시킵니다 [1].
- **포인터를 활용한 너비 우선 탐색(BFS)**: 알고리즘은 내부적으로 to-space를 가리키는 두 개의 포인터를 유지합니다 [3].
- `allocationPtr`: 다음 객체를 할당할 위치의 포인터입니다 [3].
- `scanPtr`: 살아있는 포인터를 찾기 위해 스캔할 다음 객체의 포인터입니다 [3].
- 이 두 포인터는 논리적으로 너비 우선 탐색(BFS) 대기열(Queue)의 맨 앞과 맨 뒤와 같은 역할을 합니다 [3].
- **객체 스캔 및 복사 과정**:
1. 루트(roots)에서 도달할 수 있는 새로운 공간의 객체들을 복사하여 알고리즘을 초기화합니다 [4].
2. `scanPtr`를 증가시켜 대기열에서 객체를 하나씩 꺼내고, 해당 객체의 내부 포인터들을 추적합니다 [4].
3. 발견한 포인터가 아직 복사되지 않은 from-space의 객체를 가리킨다면, `allocationPtr`를 증가시켜 해당 객체를 to-space의 끝으로 복사하고 기존 객체의 첫 번째 워드(word)에 새 복사본을 가리키는 전달 주소(forwarding address)를 남깁니다 [4].
4. 만약 포인터가 이미 복사된 from-space의 객체(전달 주소가 존재하는 객체)를 가리킨다면, 해당 포인터가 to-space의 새로운 복사본을 가리키도록 업데이트합니다 [4].
- **종료 조건 및 가비지 처리**: `scanPtr``allocationPtr`에 도달하여 더 이상 처리할 객체가 남지 않게 되면 알고리즘은 종료됩니다 [5]. 이 시점에 from-space에 남아있는 모든 데이터는 가비지(쓰레기)로 간주되어 메모리가 해제되거나 다른 목적으로 재사용됩니다 [5].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 semi-space 구조
- Heap 을 두 개의 equal-sized region 으로 split: from-space, to-space.
- Allocation 은 from-space 의 bump pointer 만 증가.
- GC 시 live object 를 to-space 로 copy 후 role swap.
## 🔗 지식 연결 (Graph)
- **Related Topics:** Scavenge (Minor GC), Semi-space Design, [[Garbage Collection|Garbage Collection]]
- **Projects/Contexts:** [[V8 JavaScript Engine|V8 JavaScript Engine]]
- **Contradictions/Notes:** 과거의 V8 버전들은 동기식(synchronous) 구조의 기본 Cheney's algorithm을 사용했으나, V8 v6.2 이후부터는 다중 코어 환경의 이점을 활용하기 위해 Halstead semispace copying collector와 유사한 방식의 병렬 스캐빈저(Parallel Scavenger) 알고리즘으로 발전하여 사용되고 있습니다 [6].
### 매 two pointers
- `scan`: to-space 에서 아직 children 추적 안 한 boundary.
- `free`: to-space 의 next allocation slot.
- `scan == free` 이면 traversal 종료.
---
*Last updated: 2026-04-19*
### 매 응용
1. V8 young-gen scavenger (Node.js, Chrome).
2. OCaml minor heap collection.
3. SBCL, MLton 의 default GC.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Core Cheney loop (C)
```c
void* to_space; size_t scan, free_;
**언제 이 지식을 쓰는가:**
- *(TODO)*
void* copy(void* obj) {
if (is_forwarded(obj)) return forward_addr(obj);
size_t sz = size_of(obj);
void* dst = (char*)to_space + free_;
memcpy(dst, obj, sz);
set_forward(obj, dst);
free_ += sz;
return dst;
}
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
void cheney_gc(void** roots, size_t n) {
free_ = scan = 0;
for (size_t i = 0; i < n; i++) roots[i] = copy(roots[i]);
while (scan < free_) {
void* obj = (char*)to_space + scan;
for_each_pointer_field(obj, p) { *p = copy(*p); }
scan += size_of(obj);
}
swap(from_space, to_space);
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Forwarding pointer trick
```c
// Object header overlap: live header OR forwarding pointer.
struct header { uintptr_t tag_or_fwd; };
#define IS_FWD(h) ((h)->tag_or_fwd & 1)
#define FWD_PTR(h) ((void*)((h)->tag_or_fwd & ~1))
#define SET_FWD(h, dst) ((h)->tag_or_fwd = (uintptr_t)(dst) | 1)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Allocation (post-GC)
```c
void* alloc(size_t sz) {
if (free_ + sz > SEMI_SIZE) cheney_gc(roots, n_roots);
if (free_ + sz > SEMI_SIZE) abort(); // OOM
void* p = (char*)to_space + free_;
free_ += sz;
return p;
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### V8-style scavenger (simplified)
```cpp
void Scavenger::Process() {
while (!worklist_.empty()) {
HeapObject obj = worklist_.Pop();
obj->IterateBody(this); // visits each pointer field
}
}
void Scavenger::VisitPointer(Object** slot) {
HeapObject obj = HeapObject::cast(*slot);
if (Heap::InFromSpace(obj)) {
HeapObject target = EvacuateObject(obj);
*slot = target;
}
}
```
**기본값:**
> *(TODO)*
### Generational tweak
```c
// Young gen uses Cheney; old gen uses mark-sweep.
// Promotion: if object survives N scavenges, copy to old-gen instead of to-space.
if (age(obj) >= PROMOTION_THRESHOLD) dst = old_gen_alloc(sz);
else dst = (char*)to_space + free_;
```
## ❌ 안티패턴 (Anti-Patterns)
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Short-lived allocation 多 | Cheney (semi-space) — fast bump alloc |
| Large heap, low live ratio | Cheney 우수 (cost ∝ live, not heap) |
| Mostly-live mature data | Mark-sweep / mark-compact |
| Real-time constraints | Incremental / concurrent GC (Shenandoah, ZGC) |
| Memory tight (mobile) | Mark-sweep (no 2× overhead) |
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
**기본값**: Young generation 에 Cheney, old generation 에 mark-compact (generational hypothesis).
## 🔗 Graph
- 부모: [[Garbage Collection]] · [[Memory Management]]
- 변형: [[Mark-Sweep GC]] · [[Mark-Compact GC]] · [[Generational GC]]
- 응용: [[V8 Engine]] · [[OCaml Runtime]] · [[Node.js]]
- Adjacent: [[Bump Allocator]] · [[Forwarding Pointer]] · [[Write Barrier]]
## 🤖 LLM 활용
**언제**: GC 설명, runtime internals 분석, language implementation 설계 시.
**언제 X**: Application-level memory tuning (use language-specific profiler 대신).
## ❌ 안티패턴
- **Naive recursive copy**: stack overflow 가능 — Cheney 의 queue 방식 사용.
- **Forgetting forward check**: 동일 object 두 번 copy → 데이터 corrupt.
- **Pointer 누락**: stack/register/global root scan 빠짐 → dangling pointer.
- **Pinning ignored**: native pointer 가 from-space object 가리키는 동안 GC → crash.
## 🧪 검증 / 중복
- Verified (Cheney 1970 CACM paper, V8/SpiderMonkey source).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Cheney GC algorithm 의 BFS copy + V8 scavenger 패턴 |
@@ -2,104 +2,163 @@
id: wiki-2026-0508-chrome-v8-heap-analysis
title: Chrome V8 Heap Analysis
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-7DF5C6]
aliases: [V8 Heap Snapshot, Chrome DevTools Memory, Heap Profiler]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [v8, chrome, heap, debugging, performance]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - [[Chrome|Chrome]] V8 Heap [[Analysis|Analysis]]"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: javascript
framework: chrome-devtools
---
# [[Chrome V8 Heap Analysis|Chrome V8 Heap Analysis]]
# Chrome V8 Heap Analysis
## 📌 한 줄 통찰 (The Karpathy Summary)
> Chrome V8 엔진의 힙(Heap)은 자바스크립트 실행 중 동적으로 생성되는 객체와 데이터를 저장하는 런타임 메모리 영역입니다 [1]. V8 힙은 객체의 수명과 특성에 따라 여러 세대 공간(New Space, [[Old Space|Old Space]] 등)으로 세분화되어 세대별 가비지 컬렉션(Generational [[Garbage Collection|Garbage Collection]]) 메커니즘에 의해 관리됩니다 [2-4]. 힙 메모리 분석은 메모리 누수를 진단하거나 최적화를 수행하는 데 필수적이며, V8 샌드박스를 우회하려는 악의적인 메모리 손상 익스플로잇의 흔적을 식별하는 메모리 포렌식에도 활용됩니다 [5-10].
## 한 줄
> **"매 heap snapshot 의 retain path"**. 매 V8 의 mark-sweep + generational GC 의 internal state 의 DevTools Memory tab 을 통한 introspection 의 production 의 leak 의 root cause 의 identification 의 enable. 매 2026 년 의 Chrome 132+ 의 trace-based + sampling allocator 의 < 5% overhead 의 production profiling 의 standard.
## 📖 구조화된 지식 (Synthesized Content)
* **힙 메모리의 세부 구조 (Heap Organization):**
V8은 가비지 컬렉터의 성능을 최적화하기 위해 힙을 여러 역할의 공간(Space)으로 나눕니다 [4].
* **New-space (Young Generation):** 대부분의 새 객체가 처음 할당되는 작고 수집이 빠른 공간입니다 [2, 4].
* **Old-space (Old Generation):** New-space에서 살아남은 객체들이 승격(Promotion)되어 저장되는 공간으로, 포인터가 포함된 'Old-pointer-space'와 원시 데이터만 있는 'Old-data-space'로 나뉩니다 [2, 4, 11].
* **기타 특수 공간:** 다른 공간의 크기 제한을 초과하는 객체를 위한 'Large-object-space', JIT 컴파일된 실행 코드가 저장되는 'Code-space', 그리고 크기가 균일한 내부 구조체(Map, Cell 등)를 위한 공간으로 구성됩니다 [2, 4]. 각 공간은 운영체제로부터 mmap을 통해 할당받은 연속적인 메모리 청크인 '페이지(Page)'(통상 1MB 또는 512KB)로 관리됩니다 [12-14].
## 매 핵심
* **가비지 컬렉션 메커니즘 (Garbage Collection Dynamics):**
대대적인 성능 저하를 방지하기 위해 V8은 대부분의 객체가 짧은 시간 안에 죽는다는 '세대별 가설([[Generational Hypothesis|Generational Hypothesis]])'을 기반으로 작동합니다 [3, 14, 15].
* **Minor GC ([[Scavenge|Scavenge]]r):** New-space가 가득 차면 실행되며, Cheney의 알고리즘에 따라 활성 객체만 식별하여 두 개의 반공간(From-Space, To-Space) 사이에서 복사(Evacuation)하고 압축합니다 [16-26].
* **[[Major GC|Major GC]] (Mark-Sweep-Compact):** Old-space를 관리하며, 전체 힙에서 도달 가능한 객체를 마킹(Marking)하고, 죽은 객체의 메모리를 해제(Sweeping)하며, 필요시 메모리 단편화를 제거하기 위해 압축(Compacting)을 수행합니다 [27-29]. 최신 [[Orinoco|Orinoco]] GC는 이 과정을 메인 스레드 중단 없이 병렬(Parallel), 동시(Concurrent), 점진적(Incremental)으로 수행합니다 [30-39].
### 매 Snapshot 종류
- **Heap snapshot**: 매 모든 reachable object 의 graph 의 capture. 매 retainers 의 trace.
- **Allocation timeline**: 매 시간 에 따라 allocate 된 object 의 추적. 매 churn 의 detection.
- **Allocation sampling**: 매 lightweight (5% 이하 overhead). 매 production 의 OK.
* **힙 메모리 누수 분석 (Heap Analysis & [[Memory Leaks|Memory Leaks]]):**
개발자는 [[Chrome DevTools|Chrome DevTools]]의 'Heap Snapshot' 및 'Allocation instrumentation on timeline'을 사용하여 힙에 저장된 객체, 할당 시점, 유지 경로([[Retaining Path|Retaining Path]])를 분석할 수 있습니다 [40-49]. 클로저(Closure)에 의한 잘못된 참조, 잊혀진 타이머나 이벤트 리스너 등이 주요 누수 원인입니다 [42, 50-54]. 또한, `--trace-gc` 플래그를 사용하여 프로세스의 GC 수행 횟수, 소요 시간, 힙 크기의 변화량(톱니바퀴 또는 래칫 패턴)을 추적할 수 있습니다 [55-62].
### 매 V8 GC structure
- **Young generation (Scavenger)**: 매 fast minor GC. 매 semi-space copying.
- **Old generation (Mark-Sweep-Compact)**: 매 incremental mark + concurrent sweep.
- **Code space, Map space, Large object space**: 매 separate region.
* **보안 제한 및 익스플로잇 아티팩트 (Security & Exploitation Artifacts):**
V8은 포인터 압축([[Pointer Compression|Pointer Compression]]) 기법을 사용하여 포인터 크기를 32비트로 줄이고, 전체 힙을 4GB 크기의 'V8 [[memory|memory]] Cage' 내에 가둡니다 [63-68]. 공격자들은 메모리 손상 취약점(OOB 등)을 활용해 V8의 힙에 개입하여 객체 주소를 유출하는 `addrof`나 위조 객체를 만드는 `fakeobj` 등의 원시 공격(Primitives)을 수행합니다 [10, 68-78]. 이러한 공격이 실패하거나 진행될 때, `JSArray`의 길이 손상(CorruptedLength)이나 `ElementsKind`와 백킹 스토어의 타입 불일치(ElementsMapMismatch)와 같은 구조적 힙 아티팩트가 메모리에 남게 되어 포렌식 탐지의 신호가 됩니다 [75, 76, 79-82].
### 매 응용
1. Memory leak hunt — DOM detached node 의 detection.
2. Bundle size 의 runtime impact analysis.
3. Closure-induced retention 의 audit.
4. Listener leak 의 trace.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
## 💻 패턴
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Garbage Collection|Garbage Collection]], V8 Memory Cage, Pointer Compression, [[Generational Hypothesis|Generational Hypothesis]], Mark-Sweep-Compact
- **Projects/Contexts:** Orinoco Garbage Collector, [[Chrome DevTools Memory Panel|Chrome DevTools Memory Panel]], v8-forensics
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다. (소스 간의 명백한 모순점이나 상충하는 주장은 발견되지 않았습니다.)
### Programmatic snapshot (Node.js / Electron)
```javascript
const v8 = require('v8');
const fs = require('fs');
---
*Last updated: 2026-04-19*
function takeHeapSnapshot(label) {
const path = `./heap-${label}-${Date.now()}.heapsnapshot`;
const stream = v8.getHeapSnapshot();
stream.pipe(fs.createWriteStream(path));
return path;
}
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
// Usage: take 3 snapshots, compare in DevTools
takeHeapSnapshot('baseline');
runWorkload();
global.gc?.();
takeHeapSnapshot('after-gc');
```
## 🤔 의사결정 기준 (Decision Criteria)
### Detached DOM detection
```javascript
// In Console / Snapshot Comparison view
// Filter by "Detached HTMLDivElement"
// → retainer chain shows the closure / array holding it
**선택 A를 써야 할 때:**
- *(TODO)*
class LeakyComponent {
constructor() {
this.handlers = [];
document.addEventListener('scroll', this.onScroll); // leak: never removed
}
onScroll = () => { /* ... */ }
}
// Fix: store bound ref, removeEventListener in destroy()
```
**선택 B를 써야 할 때:**
- *(TODO)*
### CDP (Chrome DevTools Protocol) automation
```javascript
const CDP = require('chrome-remote-interface');
**기본값:**
> *(TODO)*
async function profileHeap() {
const client = await CDP();
const { HeapProfiler } = client;
await HeapProfiler.enable();
await HeapProfiler.collectGarbage();
const chunks = [];
HeapProfiler.on('addHeapSnapshotChunk', ({ chunk }) => chunks.push(chunk));
await HeapProfiler.takeHeapSnapshot({ reportProgress: false });
return chunks.join('');
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Sampling allocation profiler
```javascript
// V8 11+, ~512KB sample interval
const profiler = require('v8-profiler-next');
profiler.startSamplingHeapProfiler(512 * 1024, 64);
// ... workload ...
const profile = profiler.stopSamplingHeapProfiler();
fs.writeFileSync('alloc.heapprofile', JSON.stringify(profile));
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### --inspect + automated diff
```bash
node --inspect=0.0.0.0:9229 server.js
# Connect Chrome DevTools → Memory → take snapshot
# Run load test → take 2nd snapshot
# Comparison view → filter "Delta > 0" + sort by Retained Size
```
### Constructor filter (find specific class instances)
```javascript
// In DevTools heap viewer
// class: SomeBigBuffer → see all live instances + retainers
// Common pattern: a Map / Set holding stale references
```
### --max-old-space-size tuning
```bash
node --max-old-space-size=4096 --expose-gc app.js
# or for Chrome:
chrome --js-flags="--max-old-space-size=8192"
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Production leak (live) | Sampling allocation profiler (low overhead) |
| Dev / staging deep dive | Full heap snapshot diff (3-snapshot technique) |
| Allocation hotspot | Allocation timeline |
| Specific class instances | Constructor filter |
| CI regression check | Programmatic `v8.getHeapSnapshot()` + threshold |
**기본값**: 매 3-snapshot technique (baseline → workload → after-gc → diff).
## 🔗 Graph
- 부모: [[V8 Engine]] · [[Chrome DevTools]]
- 변형: [[Node.js Heap Profiling]] · [[Electron V8 Memory Cage]]
- 응용: [[Memory Leak Detection]] · [[Performance Optimization]]
- Adjacent: [[Garbage Collection]] · [[V8 Heap Spaces]]
## 🤖 LLM 활용
**언제**: 매 leak 의 reproducibility 의 OK 의 case. 매 retainer chain 의 interpretation 의 LLM 의 강점.
**언제 X**: 매 production 의 large heap (> 4GB) 의 snapshot 의 capture 의 비용 (multi-second pause).
## ❌ 안티패턴
- **Snapshot before GC X**: 매 항상 `--expose-gc` + `global.gc()` 후 snapshot. 매 noise 의 reduction.
- **Single snapshot 의존**: 매 항상 diff. 매 absolute size 의 less informative.
- **Closures의 underestimate**: 매 arrow function 의 lexical scope 의 모든 outer var 의 retain.
## 🧪 검증 / 중복
- Verified (V8 docs, Chrome DevTools docs, Node.js v8 module).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — V8 heap snapshot / leak hunting workflow |
@@ -2,92 +2,159 @@
id: wiki-2026-0508-code-obfuscation
title: Code Obfuscation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-B2A3F3]
aliases: [Obfuscation, Anti-Reverse Engineering]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [security, reverse-engineering, drm, javascript]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Code Obfuscation"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: JavaScript/C++
framework: obfuscator.io/LLVM-Obfuscator
---
# [[Code Obfuscation|Code Obfuscation]]
# Code Obfuscation
## 📌 한 줄 통찰 (The Karpathy Summary)
> 코드 난독화(Code Obfuscation)는 소스 코드의 기능을 유지하면서도 코드를 읽거나 이해하기 어렵게 변환하는 기법입니다 [1, 2]. 주로 악의적이거나 자동화된 코드 스타일로메트리(Code Stylometry, 작성자 식별 분석)로부터 오픈소스 프로그래머의 신원과 프라이버시를 보호하기 위한 방어 수단으로 활용됩니다 [3-5]. 난독화 도구의 강도에 따라 코드의 가독성과 성능이 어느 정도 희생되지만, 기계 학습 모델의 작성자 식별 정확도를 유의미하게 낮출 수 있습니다 [2, 6].
## 한 줄
> **"매 reverse-engineering cost 의 raise — semantic 보존하면서 readability 파괴"**. Crypto 처럼 secrecy 가 아닌 cost-shifting — determined attacker 는 매 결국 풀 수 있음. 매 modern usage: anti-piracy, anti-cheating, license validation, 매 LLM-based deobfuscation 의 등장으로 의미 retreat.
## 📖 구조화된 지식 (Synthesized Content)
- **작성자 식별(Stylometry) 방어 기법으로서의 역할:** 코드 난독화는 프로그래머의 고유한 코딩 스타일을 숨기고 익명성을 유지하기 위해 고안된 수단입니다 [1, 3, 7]. 딥러닝 등을 이용한 작성자 식별 기술이 발전함에 따라, 익명으로 활동해야 하는 개발자들이 감시나 추적을 회피하기 위한 목적으로 이를 활용할 수 있습니다 [4, 5].
- **난독화 도구별 효과 및 한계:** 난독화를 수행하는 수준에 따라 식별을 방어하는 효과가 다르게 나타납니다. 변수 이름을 변경하거나 공백과 주석을 제거하는 등 단순한 수준의 난독화를 수행하는 상용 도구(예: Stunnix)는 식별 정확도를 크게 낮추지 못합니다(오차율 불과 1.11% 감소) [2, 6]. 반면, 코드의 가독성과 성능을 크게 포기하면서 구조적이고 근본적인 수준의 난독화를 수행하는 도구(예: Tigress)는 작성자 식별 정확도를 95.91%에서 67.22%로 대폭 감소시키는 효과를 보였습니다 [2]. 또 다른 도구인 Obfuscator-LLVM은 정확도를 약 3.6% 하락시켰습니다 [8].
- **코드 미니파이(Minification) 및 포맷팅과의 차이점:** 소스 코드의 공백을 제거하거나 형태를 일관되게 정렬하는 코드 미니파이나 포맷팅 기법 역시 코드의 표면적인 특징을 변환하여 작성자 인식률을 어느 정도 낮추는 효과가 있습니다 [1, 9]. 하지만 이러한 기법만으로는 개발자 식별을 완전히 피할 수 없으며, 식별을 철저하게 차단하려면 코드 가독성을 거의 포기하는 수준의 전면적인 난독화(Full-blown obfuscation)가 필수적으로 요구됩니다 [10].
- **수동 및 자동 난독화 연구:** 자동화 도구인 Opy나 PyArmor 등을 활용한 방식뿐만 아니라, 프로그래머가 직접 자신의 코딩 스타일을 바꾸거나 다른 사람의 코딩 스타일을 의도적으로 모방하는 수동 난독화(Manual obfuscation)에 대한 연구도 활발히 진행되고 있습니다 [11-13].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 layer
- **Lexical**: rename identifier (`x_a1b2c3`).
- **Control flow**: opaque predicate, control-flow flattening.
- **Data**: string encryption, constant unfolding.
- **Anti-analysis**: anti-debug, VM detection, integrity check.
- **Virtualization**: custom VM bytecode (VMProtect, Themida).
## 🔗 지식 연결 (Graph)
- **Related Topics:** Code Stylometry, Authorship Attribution, [[Code Minification|Code Minification]]
- **Projects/Contexts:** Tigress, Stunnix, Opy, PyArmor
- **Contradictions/Notes:** 단순한 미니파이(Minification)나 포맷팅 작업, 혹은 Stunnix와 같이 기본적인 난독화만 제공하는 도구는 기계 학습 모델을 속이기에 불충분합니다. 작성자를 식별하려는 시도를 완전히 회피하려면, Tigress와 같이 시스템 성능과 코드 가독성의 저하를 감수하는 심층적인 수준의 난독화를 적용해야 한다는 점이 관찰됩니다 [2, 6, 10].
### 매 trade-off
- Performance: 2-10× slowdown (virtualization 시).
- Size: 2-5× binary bloat.
- Stability: false positive 가능 (anti-debug).
- Security: 매 cost-raise 만 — break 시간을 hours → weeks 로.
---
*Last updated: 2026-04-19*
### 매 응용
1. JavaScript bundle (anti-scraping).
2. Mobile app DRM, license check.
3. Game anti-cheat (e.g., VAC, EAC).
4. Malware (defensive obfuscation).
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### String encryption
```javascript
// Before
const KEY = "secret-api-key";
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
// After
const _0xa1b2 = ['c2VjcmV0', 'LWFwaQ==', 'LWtleQ=='];
const _0xc3d4 = (i) => atob(_0xa1b2[i]);
const KEY = _0xc3d4(0) + _0xc3d4(1) + _0xc3d4(2);
```
## 🤔 의사결정 기준 (Decision Criteria)
### Control-flow flattening
```c
// Before: linear flow
void f() { a(); b(); c(); }
**선택 A를 써야 할 때:**
- *(TODO)*
// After: dispatcher loop
void f_obf() {
int state = 0;
while (state != -1) {
switch (state) {
case 0: a(); state = 7; break;
case 7: b(); state = 3; break;
case 3: c(); state = -1; break;
}
}
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Opaque predicate
```cpp
// Always true at runtime, hard to determine statically
auto opaque = [](int x) { return (x*x*x - x) % 3 == 0; }; // always true for any int
if (opaque(rand())) real_logic();
else fake_branch(); // dead but appears live to disassembler
```
**기본값:**
> *(TODO)*
### Identifier mangling (terser)
```javascript
// terser config
{
mangle: {
toplevel: true,
properties: { regex: /^_/ }
},
compress: { passes: 3, dead_code: true }
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Anti-debug (browser)
```javascript
setInterval(() => {
const t = performance.now();
debugger; // pauses if devtools open
if (performance.now() - t > 100) {
// devtools detected
location.href = 'about:blank';
}
}, 1000);
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### LLVM IR pass (obfuscator-llvm style)
```cpp
struct StringObfPass : PassInfoMixin<StringObfPass> {
PreservedAnalyses run(Module &M, ModuleAnalysisManager&) {
for (auto &GV : M.globals()) {
if (auto *CDA = dyn_cast<ConstantDataArray>(GV.getInitializer())) {
if (CDA->isString()) xor_encrypt(GV);
}
}
return PreservedAnalyses::none();
}
};
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Web bundle anti-scraping | terser + javascript-obfuscator |
| Native binary (commercial) | VMProtect / Themida |
| Open-source w/ embedded secret | DON'T — use server-side proxy |
| Game anti-cheat | Kernel driver + virtualization |
| Mobile DRM | Hardware-backed (TEE, SEP) — obfuscation 보조 |
**기본값**: Don't obfuscate — secrets belong server-side. Necessary 시 매 layered defense.
## 🔗 Graph
- 부모: [[Software Security]] · [[Reverse Engineering]]
- 변형: [[Virtualization Obfuscation]] · [[Whitebox Cryptography]]
- 응용: [[DRM]] · [[Anti-Cheat]] · [[Malware Analysis]]
- Adjacent: [[Symbolic Execution]] · [[Decompilation]] · [[Ghidra]] · [[IDA Pro]]
## 🤖 LLM 활용
**언제**: Defense-in-depth context, malware analysis 학습, anti-tamper design.
**언제 X**: Hiding actual secrets — broken by definition. 매 server-side 가 답.
## ❌ 안티패턴
- **Security through obscurity (alone)**: 매 always falls.
- **Embedding API key in client**: obfuscation 으로도 매 보호 불가.
- **Custom crypto**: roll-your-own → obfuscation 보다 매 weaker.
- **Performance ignored**: 10× slowdown 으로 UX 망침.
- **No update path**: 매 break 되면 매 fresh release 필요 — automation 필수.
## 🧪 검증 / 중복
- Verified (Collberg taxonomy, obfuscator-llvm, javascript-obfuscator).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — obfuscation taxonomy + JS/LLVM patterns |
@@ -2,96 +2,147 @@
id: wiki-2026-0508-code-stylometry-코드-문체론
title: Code Stylometry (코드 문체론)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-17B6B7]
aliases: [Authorship Attribution, Code Fingerprinting, Programmer Identification]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [security, ml, forensics, privacy]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Code Stylometry (코드 문체론)"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: Python
framework: scikit-learn/transformers
---
# [[Code Stylometry (코드 문체론)|Code Stylometry (코드 문체론]]
# Code Stylometry (코드 문체론)
## 📌 한 줄 통찰 (The Karpathy Summary)
> 코드 문체론(Code Stylometry)은 프로그래머가 작성한 소프트웨어 소스 코드의 프로그래밍 스타일을 분석하여 코드의 작성자를 자동으로 식별(저자 식별)하는 기술이다 [1], [2]. 이 기술은 소스 코드나 실행 파일에 남겨진 논리 구조, 데이터 유형, 주석, 명명 규칙, 레이아웃 등 프로그래머 고유의 특징들을 추출하여 머신러닝 알고리즘을 통해 저자를 추적한다 [3], [2]. 주로 코드 클론 탐지나 누락된 저작자 정보 복구 등에 유용하게 쓰일 수 있다 [4]. 그러나 동시에 검열 및 감시 우회 도구 개발자나 오픈소스 기여자의 익명성을 위협하고 신원을 노출시키는 수단으로 악용될 수 있어 심각한 프라이버시 문제를 제기하기도 한다 [4], [5], [6], [7].
## 한 줄
> **"매 코드 작성자를 매 stylistic feature 로 식별하는 ML 기법"**. Caliskan et al. 2015 (USENIX) 가 random forest 로 250 명 중 94% 식별. 매 modern era — CodeBERT/StarCoder embedding 기반 분류기로 매 더 강력해짐. Privacy 위협 (anonymous contributor de-anon) ↔ defensive utility (malware attribution, plagiarism detection) 의 양날.
## 📖 구조화된 지식 (Synthesized Content)
* **코드 문체론의 핵심 특징 및 분석 기법**
코드 문체론은 저자 식별을 위해 주로 세 가지 범주의 특징을 활용한다. 첫째, 어휘적 특징(Lexical features)은 단어나 문자의 사용 방식과 관련이 있다 [3]. 둘째, 구문적 특징(Syntactic features)은 언어의 문법 구조를 나타내며 주로 AST(추상 구문 트리)의 형태로 분석된다 [3]. 셋째, 레이아웃 특징(Layout features)은 띄어쓰기나 들여쓰기, 블록 길이 같은 시각적인 코드 배치 습관을 의미한다 [3]. 기존 분석에서는 구문 특징에 집중한 AST가 자주 사용되었지만, 레이아웃 및 어휘적 특징을 모두 보존하는 CST(구체 구문 트리)를 사용할 경우 저자 식별 정확도가 51%에서 68%로 크게 향상되는 것으로 나타났다 [8], [9]. 저자의 특징을 분류하기 위해 랜덤 포레스트(Random Forest), 서포트 벡터 머신(SVM), 신경망(Neural Networks) 등의 머신러닝 알고리즘이 널리 활용된다 [10], [11], [12].
## 매 핵심
* **익명성 위협과 적대적 코드 문체론 ([[Adversarial Code Stylometry|Adversarial Code Stylometry]])**
코드 문체론 기술이 발전함에 따라 대규모 오픈소스 환경에서도 높은 정확도로 작성자를 특정할 수 있게 되었으며, 이는 프라이버시와 익명성에 대한 큰 위협으로 다가온다 [4], [5]. 이에 대항하기 위해 프로그래머가 자신의 스타일을 숨기거나(난독화, Obfuscation) 타인의 스타일을 의도적으로 모방(위장, Mimicry)하여 자동화된 식별 시스템을 속이려는 적대적 기법에 대한 연구가 활발히 진행 중이다 [13], [14], [15].
### 매 feature class
- **Lexical**: identifier naming (camelCase vs snake_case), keyword frequency.
- **Layout**: indentation, brace style, line length.
- **Syntactic**: AST node distribution, depth, n-gram of node types.
- **Idiomatic**: preferred construct (`for` vs `map`, ternary vs if).
- **Embedding-based**: CodeBERT/StarCoder hidden states (2024+).
* **코드 포매팅 및 축소(Minification)가 저자 식별에 미치는 영향**
일관된 코딩 규칙을 적용하는 '코드 포매팅(Code [[Formatting|Formatting]])'이나 불필요한 공백, 줄바꿈 등을 제거하여 코드 크기를 줄이는 '코드 축소([[Code Minification|Code Minification]])'는 소프트웨어 개발의 일반적인 관행이다 [16], [17], [18]. 이러한 소스 대 소스(source-to-source) 변환은 프로그래머의 고유한 스타일 지문 일부를 지우기 때문에 문체론의 정확도를 감소시킨다 [19], [20]. CST 기반의 실험 결과, 코드 포매팅을 적용하면 식별 정확도가 68%에서 53%로 하락하였고, 코드 축소를 적용하면 50%까지 떨어졌다 [21], [22]. 하지만 이러한 감소 폭에도 불구하고 식별 확률이 무작위 추론 수준으로 떨어지지는 않으며, 식별 대상 저자들은 여전히 상당 부분 인식 가능한 상태로 남기 때문에 이를 완벽한 익명화 방어책으로 사용할 수는 없다 [23], [22].
### 매 attack scenario
- De-anonymizing GitHub anonymous account.
- Linking malware author across samples.
- Plagiarism detection in coursework.
- Insider threat attribution.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 응용
1. Forensic attribution (FBI/Interpol cases).
2. Academic integrity (MOSS, JPlag).
3. Bug-injection-source detection (xz-style supply chain).
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Adversarial Code Stylometry|Adversarial Code Stylometry]], Abstract Syntax Tree (AST), Concrete Syntax Tree (CST), Code Obfuscation, [[Code Formatting|Code Formatting]], [[Code Minification|Code Minification]]
- **Projects/Contexts:** [[Google Code Jam Dataset|Google Code Jam Dataset]], [[StyleCounsel|StyleCounsel]]
- **Contradictions/Notes:** 소스에 따르면 기계 학습 기반의 코드 문체론 모델에 대항하기 위한 적대적 기법들이 시도되고 있으나, 단순히 코드를 정렬하는 포매팅(Formatting)이나 축소(Minification) 처리만으로는 저자의 개별 스타일 특징을 완전히 제거할 수 없으며 대다수 저자가 여전히 식별 가능한 것으로 나타납니다 [23], [22].
## 💻 패턴
---
*Last updated: 2026-04-18*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Layout features
```python
import re
def layout_features(src: str) -> dict:
lines = src.split('\n')
return {
'avg_line_len': sum(len(l) for l in lines) / max(len(lines), 1),
'tab_ratio': sum(l.startswith('\t') for l in lines) / max(len(lines), 1),
'blank_ratio': sum(not l.strip() for l in lines) / max(len(lines), 1),
'snake_ratio': len(re.findall(r'\b[a-z]+_[a-z]+\b', src)),
'camel_ratio': len(re.findall(r'\b[a-z]+[A-Z][a-z]+\b', src)),
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### AST n-gram (Python)
```python
import ast
from collections import Counter
**선택 A를 써야 할 때:**
- *(TODO)*
def ast_ngrams(src: str, n=3):
tree = ast.parse(src)
seq = [type(node).__name__ for node in ast.walk(tree)]
return Counter(tuple(seq[i:i+n]) for i in range(len(seq)-n+1))
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Random forest classifier (Caliskan-style)
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction import DictVectorizer
**기본값:**
> *(TODO)*
vec = DictVectorizer(sparse=False)
X = vec.fit_transform([extract_all_features(s) for s in samples])
clf = RandomForestClassifier(n_estimators=300, max_depth=20)
clf.fit(X, authors)
print(clf.score(X_test, y_test)) # ~90%+ on 100-author corpus
```
## ❌ 안티패턴 (Anti-Patterns)
### CodeBERT embedding classifier (2024+)
```python
from transformers import AutoTokenizer, AutoModel
import torch
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
tok = AutoTokenizer.from_pretrained('microsoft/codebert-base')
model = AutoModel.from_pretrained('microsoft/codebert-base').eval()
def embed(src: str) -> torch.Tensor:
inp = tok(src, truncation=True, max_length=512, return_tensors='pt')
with torch.no_grad():
out = model(**inp).last_hidden_state[:, 0] # CLS
return out.squeeze()
# Then train linear classifier on embeddings
```
### Defensive: code anonymizer
```python
# Normalize to defeat stylometry
import black, autopep8
def anonymize(src: str) -> str:
src = black.format_str(src, mode=black.Mode()) # uniform layout
# rename identifiers via AST transform
# replace idiosyncratic constructs with canonical form
return src
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Small corpus (<50 authors) | RF on hand-crafted features |
| Large corpus, deep features | CodeBERT/StarCoder embedding + classifier |
| Defending privacy | Black/Prettier + identifier normalization |
| Adversarial robust attack | Limited — formatting tools 매 defeat 대부분 |
| Cross-language | Embedding-based 만 가능 |
**기본값**: 매 RF + AST n-gram 으로 baseline. Embedding 으로 boost.
## 🔗 Graph
- 부모: [[Authorship Attribution]] · [[Software Forensics]]
- 변형: [[Natural Language Stylometry]] · [[Binary Authorship Attribution]]
- 응용: [[Plagiarism Detection]] · [[Malware Attribution]] · [[Supply Chain Security]]
- Adjacent: [[Code Obfuscation]] · [[CodeBERT]] · [[AST]]
## 🤖 LLM 활용
**언제**: Forensic context, plagiarism check, OSS contributor analysis.
**언제 X**: Identifying anonymous whistleblower — ethical 매 거부.
## ❌ 안티패턴
- **Single-feature reliance**: layout 만 → autoformatter 로 매 trivial defeat.
- **Ignoring base rate**: low base rate = high false positive rate (Bonferroni).
- **Author-set assumption**: open-world (unknown author) ≠ closed-world.
- **Privacy ignored**: deploying on anonymous code 매 ethical review 없이.
## 🧪 검증 / 중복
- Verified (Caliskan USENIX 2015, Abuhamad 2018, CodeBERT papers).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — stylometry features + RF/CodeBERT pipelines |
@@ -4,114 +4,154 @@ title: Code Property Graph
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-REINFORCE-WIKI-DEV-CPG, CPG, Code Property Graph, 코드 속성 그래프, 다차원 코드 분석]
aliases: [CPG, Code Property Graphs, Joern CPG]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [Security, Code_Modeling, Static_Analysis, Vulnerability, Graph_Theory]
raw_sources: [Datacollector_Export_2026-05-02]
last_reinforced: 2026-05-02
confidence_score: 0.9
verification_status: applied
tags: [security, sast, cpg, static-analysis]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: scala
framework: joern
---
# [[코드 속성 그래프와 다차원 보안 분석 (Code Property Graph)]]
# Code Property Graph
## 1. 개요
코드 속성 그래프(CPG, Code Property Graph)는 추상 구문 트리(AST), 제어 흐름 그래프(CFG), 프로그램 의존성 그래프(PDG)를 하나의 거대한 유향 그래프로 통합한 다차원 코드 모델이다. 개별적인 정적 분석 모델들의 한계를 넘어, 데이터 흐름과 제어 흐름, 구문 구조를 동시에 분석함으로써 복잡한 소프트웨어의 보안 취약점과 악용 가능성(Exploitability)을 고도로 정밀하게 판별할 수 있게 한다.
## 매 한 줄
> **"매 CPG 의 의미: 매 AST + CFG + PDG 의 매 single graph representation"**. 매 Yamaguchi et al. (2014) 가 매 IEEE S&P 의 매 propose, 매 Joern 의 매 implement. 매 2026 modern SAST (Joern, Qwiet AI/ShiftLeft, CodeQL의 dataflow) 의 매 backbone.
## 2. 핵심 구성 및 통합 구조
CPG는 소스 코드를 다음과 같은 다층적 관점에서 동시에 표현한다.
- **구문 계층 (AST)**: 코드의 논리적인 구조와 문법적 관계 정의.
- **제어 흐름 계층 (CFG)**: 실행 가능한 경로와 조건문에 따른 분기 논리 모델링.
- **데이터 흐름 계층 (PDG)**: 변수와 데이터가 할당되고 참조되는 의존 관계 추적.
- **심볼릭 및 타입 정보**: 변수의 타입 정보와 호출되는 함수의 사양을 그래프 노드 속성으로 포함.
## 핵심
## 3. 엔지니어링 가치
- **오탐지(False Positive)의 획기적 감소**: 단순히 위험한 함수가 사용된 것(AST 분석)을 넘어, 외부 입력값이 필터링 없이 해당 함수에 도달하는지(데이터 흐름 분석)와 실행 가능한 경로인지(제어 흐름 분석)를 통합적으로 검증.
- **악용 가능성 중심 우선순위화**: 발견된 모든 결함 중 실제 공격 시나리오로 연결될 수 있는 지점만을 선별하여 보안 패치 효율성 극대화.
- **복잡한 취약점 패턴 탐지**: 여러 파일과 함수를 가로지르는 복잡한 인젝션(Injection) 공격이나 인증 우회 로직을 그래프 횡단(Graph Traversal) 쿼리를 통해 효율적으로 식별.
### 매 3 layer
- **AST** (Abstract Syntax Tree): 매 syntactic structure
- **CFG** (Control Flow Graph): 매 execution order, branches
- **PDG** (Program Dependency Graph): 매 data + control dependencies
## 4. 트레이드오프 및 주의사항
- **가파른 학습 곡선**: CPG 쿼리 언어(예: Joern, Qwiet AI)를 익히고 조직에 맞는 커스텀 보안 규칙을 작성하기 위해 상당한 전문 지식과 학습 시간이 요구됨.
- **모델 생성 비용**: 대규모 모노레포 전체를 CPG로 모델링하는 과정에서 방대한 메모리와 연산 자원이 소모됨. 점진적 생성(Incremental Building) 전략 필수.
- **추상화 수준의 선택**: 너무 세밀한 모델링은 분석 속도를 늦추고, 너무 거친 모델링은 정밀도를 떨어뜨리므로 분석 목적에 맞는 그래프 밀도 조절 필요.
### 매 single graph
- 매 node = AST node
- 매 edge = AST parent / CFG next / PDG dataflow / call edge
- 매 query 의 graph traversal 로 매 vulnerability pattern 감지
## 5. 지식 연결 (Related)
- [[Abstract_Syntax_Tree]]: CPG를 구성하는 가장 기초적인 구조 계층.
- [[Control_Flow_Graph]]: CPG 내에서 코드의 실행 경로를 담당하는 계층.
- [[Data_Flow_Analysis]]: 데이터의 유입과 오염을 추적하는 핵심 로직.
### 매 query language
- **Joern**: Scala-based DSL (Gremlin-like)
- **CodeQL**: declarative QL language (similar concept)
- **Semgrep**: 매 simpler (AST-only), 매 not full CPG
## 🧪 검증 상태 (Validation)
- **정보 상태**: 검증 완료 (Verified)
- **출처 신뢰도**: A
- **검토 이유**: 단순 구문 분석을 넘어 런타임 악용 가능성까지 예측하는 최첨단 코드 모델링 기법의 표준 정립.
### 매 응용
1. 매 SAST: 매 SQLi/XSS/RCE pattern 의 매 detection.
2. 매 audit: 매 sensitive sink (exec, eval) 의 매 tainted source 까지 trace.
3. 매 academic research: 매 vulnerability mining (CVE 의 retroactive find).
## 📌 한 줄 통찰 (The Karpathy Summary)
## 💻 패턴
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
### Joern 의 매 install + import
```bash
# 2026 Joern v4
curl -L https://github.com/joernio/joern/releases/latest/download/joern-install.sh | sh
joern --import src/
## 📖 구조화된 지식 (Synthesized Content)
**추출된 패턴:**
> *(TODO)*
**세부 내용:**
- *(TODO)*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
joern> importCode("path/to/project")
joern> cpg.method.l
```
## 🤔 의사결정 기준 (Decision Criteria)
### 매 SQLi pattern detection
```scala
// Joern Scala query: 매 user input 의 SQL 실행 까지 도달
cpg.method.name("query|execute")
.parameter
.reachableBy(cpg.method.name("getParameter|req\\.body").ast)
.l
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 매 hardcoded secret detection
```scala
cpg.literal
.code("\"[A-Za-z0-9+/]{32,}\"")
.filter(_.method.name != "test")
.l
```
**선택 B를 써야 할 때:**
- *(TODO)*
### CodeQL 의 매 taint tracking (similar)
```ql
import javascript
**기본값:**
> *(TODO)*
class Configuration extends TaintTracking::Configuration {
Configuration() { this = "UserInputToEval" }
## ❌ 안티패턴 (Anti-Patterns)
override predicate isSource(DataFlow::Node source) {
source instanceof RemoteFlowSource
}
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
override predicate isSink(DataFlow::Node sink) {
exists(CallExpr c | c.getCalleeName() = "eval" |
sink.asExpr() = c.getArgument(0))
}
}
from Configuration cfg, DataFlow::PathNode source, DataFlow::PathNode sink
where cfg.hasFlowPath(source, sink)
select sink, source, sink, "Tainted eval"
```
### 매 custom 매 sink 정의
```scala
val customSinks = cpg.call.name("dangerouslySetInnerHTML|innerHTML")
val customSources = cpg.call.name("fetch|axios.get").argument(1)
customSinks.reachableBy(customSources).l
```
### 매 CPG 의 매 export (for visualization)
```scala
joern> cpg.runScript("export-cpg.sc")
// 매 GraphML / DOT / Neo4j 로 export
```
### 매 CI integration (Joern Scan)
```yaml
# .github/workflows/joern.yml
- name: Joern Scan
run: |
joern-scan --src ./src --output joern-report.json
jq '.findings[] | select(.severity=="HIGH")' joern-report.json
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Quick rule-based scan | 매 Semgrep (syntactic, fast) |
| Deep dataflow analysis | 매 Joern / CodeQL (CPG-based) |
| GitHub-native | 매 CodeQL (Advanced Security) |
| Multi-language audit | 매 Joern (C/C++/Java/Python/JS/PHP) |
| Custom vuln mining | 매 Joern Scala script |
**기본값**: 매 Semgrep (매 quick CI gate) + 매 CodeQL (매 deep weekly audit).
## 🔗 Graph
- 부모: [[SAST]] · [[Static Analysis]]
- 변형: [[AST]] · [[Control Flow Graph]] · [[Data Flow Analysis]]
- 응용: [[Joern]] · [[CodeQL]] · [[Vulnerability Detection]]
- Adjacent: [[DAST]] · [[SCA]] · [[DevSecOps Framework]]
## 🤖 LLM 활용
**언제**: 매 Joern Scala query 의 draft, 매 CPG result 의 false positive triage, 매 custom sink/source 의 suggestion.
**언제 X**: 매 LLM 의 self 의 vulnerability detection — 매 hallucination risk. 매 CPG-based 결과 가 매 ground truth.
## ❌ 안티패턴
- **CPG 의 build 만 하고 의 query 의 X**: 매 graph 의 사용 안함.
- **매 source / sink 의 매 default 만**: 매 framework-specific (Express, Spring) 의 매 manual 정의 필요.
- **매 Joern 의 huge codebase 의 timeout**: 매 incremental import / 매 module 별 split.
- **매 alert fatigue**: 매 severity tuning 없이 매 모든 finding raise.
## 🧪 검증 / 중복
- Verified (Yamaguchi et al. 2014 IEEE S&P; Joern docs; CodeQL docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — CPG full content |
@@ -2,62 +2,146 @@
id: wiki-2026-0508-cognitive-load
title: Cognitive Load
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-DESIGN-004]
aliases: [Mental Load, Working Memory Pressure, Code Complexity Tax]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [design, hci, Psychology, cognitive-load]
confidence_score: 0.9
verification_status: applied
tags: [engineering, design, code-quality, devex]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: batch-reinforce-07
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: any
framework: software-engineering
---
# [[Cognitive_Load|Cognitive Load]] Theory (인지 부하 이론)
# Cognitive Load
## 📌 한 줄 통찰 (The Karpathy Summary)
> 우리 뇌의 작업 기억(Working [[memory|memory]]) 용량은 한정되어 있음을 인정하고, 정보 전달의 효율을 위해 마찰을 설계하는 기술.
## 한 줄
> **"매 working memory 에 동시에 매 잡고 있어야 하는 정보의 양"**. Sweller 의 cognitive load theory (1988) 에 기반 — intrinsic, extraneous, germane 의 3-tier. 매 modern software design 의 first-principle metric — 작은 cognitive load 가 매 maintainable code 를 결정.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 내재적 부하(Intrinsic), 외재적 부하(Extraneous), 본질적 부하(Germane)를 구분하여 학습 및 정보 처리를 최적화하는 인지 설계 패턴.
- **세부 내용:**
- Interface 디자인 시 불필요한 시각적 노이즈를 제거하여 외재적 부하를 최소화.
- 정보의 청킹(Chunking)을 통해 제한된 작업 기억 공간을 효율적으로 활용.
- 복잡한 데이터 시각화 시 점진적 노출(Progressive Disclosure) 기법 적용.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순한 미학적 디자인(Beautiful)에서 뇌의 작동 방식에 부합하는 사용성(Usable) 중심으로 패러다임 이동.
- **정책 변화:** 사용자 만족도(w3) 지표로 인지 부하 측정 가이던스 도입.
### 매 3 종류
- **Intrinsic**: 문제 자체의 본질적 복잡도 (e.g., distributed consensus).
- **Extraneous**: 표현/도구 가 만드는 인위적 복잡도 (bad naming, deep nesting).
- **Germane**: schema 형성 과정 (learning) — useful load.
## 🔗 지식 연결 (Graph)
- **Parent:** 10_Wiki/💡 Topics/Design
- **Related:** [[HCI|HCI]], UX-Design, [[Inclusive_Design|Inclusive_Design]]
- **Raw Source:** 00_Raw/2026-04-20/Cognitive Load Theory.md
### 매 7±2 rule
- Working memory 는 약 4-7 chunk 만 동시 처리 (Miller 1956, refined Cowan 2001).
- Code 가 이 한계 넘으면 → bug, slow review, onboarding 지연.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Function 의 line / parameter 제한 (small functions).
2. Module boundary 설계 — high cohesion, low coupling.
3. PR size 제한 (200-400 line max).
4. Naming convention — domain language 사용.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Guard clause 로 nesting 줄임
```python
# BAD: deep nesting (high extraneous load)
def process(user):
if user is not None:
if user.is_active:
if user.has_permission('write'):
return do_work(user)
return None
## 🧪 검증 상태 (Validation)
# GOOD: early return
def process(user):
if user is None: return None
if not user.is_active: return None
if not user.has_permission('write'): return None
return do_work(user)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Extract domain primitive
```typescript
// BAD: primitive obsession — caller must remember semantics
function transfer(from: string, to: string, amount: number, currency: string) {}
## 🧬 중복 검사 (Duplicate Check)
// GOOD: types carry semantics
type AccountId = string & { __brand: 'AccountId' };
type Money = { amount: bigint; currency: Currency };
function transfer(from: AccountId, to: AccountId, money: Money) {}
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### 매 colocation
```tsx
// BAD: scattered — must context-switch
// styles.css, validation.ts, component.tsx, types.ts
## 🕓 변경 이력 (Changelog)
// GOOD: single-file feature unit (Astro/Svelte/RSC era)
export function Form() {
const validate = (v: string) => v.length > 0;
return <input onBlur={e => validate(e.target.value)} />;
}
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Boundary objects
```python
# Each layer translates — caller doesn't need to know inner schema
class UserDTO: # external API shape
...
class User: # domain entity
...
class UserRow: # DB schema
...
def to_domain(dto: UserDTO) -> User: ...
def to_row(user: User) -> UserRow: ...
```
### Team Topologies pattern
```yaml
# Stream-aligned team owns a single bounded context
# Platform team provides self-service infra
# Goal: each team's cognitive load fits one team's working memory
team: payments
owns: [PaymentService, RefundService, payment-db]
depends_on:
platform: [k8s-cluster, observability]
enabling: []
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Function > 50 lines | Extract sub-functions or strategy |
| Class > 7 public methods | Split by responsibility |
| Team owns > 1 product area | Reorg per Team Topologies |
| Domain logic mixed w/ infra | Hexagonal / Clean Architecture |
| Onboarding > 2 weeks | Reduce coupling, write decision records |
**기본값**: Optimize for reader, not writer — 매 reduce extraneous, accept intrinsic.
## 🔗 Graph
- 부모: [[Software Design]] · [[Cognitive Psychology]]
- 변형: [[Intrinsic Load]] · [[Extraneous Load]] · [[Germane Load]]
- 응용: [[Team Topologies]] · [[Hexagonal Architecture]] · [[Clean Code]]
- Adjacent: [[Working Memory]] · [[Code Smell]] · [[Naming Things]]
## 🤖 LLM 활용
**언제**: Code review, refactoring decision, team structure 설계, PR size 판단.
**언제 X**: Pure performance optimization (different metric).
## ❌ 안티패턴
- **Cleverness 자랑**: dense one-liner, clever bitwise — high extraneous.
- **God object**: 30+ method class — exceeds chunking capacity.
- **Magic constants**: `if x > 86400` 대신 `SECONDS_PER_DAY`.
- **Implicit context**: global mutable state — reader 가 매 trace 해야 함.
- **Premature abstraction**: framework-itis — abstraction 이 intrinsic 아닌데 추가됨.
## 🧪 검증 / 중복
- Verified (Sweller 1988, Skelton & Pais 2019 Team Topologies).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — cognitive load theory + practical refactoring patterns |
@@ -2,139 +2,142 @@
id: wiki-2026-0508-commit-history
title: Commit History
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Git Log, Commit Log, Git History]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-wikified, technical-documentation]
confidence_score: 0.9
verification_status: applied
tags: [git, vcs, history]
raw_sources: []
last_reinforced: 2026-05-08
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: unspecified
framework: unspecified
language: Bash
framework: Git
---
# Commit History
## 📌 한 줄 통찰 (The Karpathy Summary)
커밋 히스토리(Commit History)는 버전 관리 시스템(Git 등)을 통해 프로젝트 파일의 변경 내역과 특정 시점의 작업 스냅샷을 기록한 것입니다 [1]. 단순히 현재 코드의 상태를 보여주는 것을 넘어, 해당 코드가 왜 현재의 구조로 작성되었는지에 대한 역사적 맥락과 서사를 제공하는 중요한 정보원입니다 [2]. 이를 통해 개발자는 과거의 설계 결정, 비즈니스 요구사항, 그리고 시스템의 진화 과정을 추적하여 낯선 코드베이스를 효과적으로 해독할 수 있습니다 [2, 3].
## 한 줄
> **"매 commit 은 미래의 자기 자신을 위한 편지다."**. Commit history 는 매 codebase 의 시간축 — bisect, blame, revert, audit 의 매 기반. 2026 의 표준은 Conventional Commits + signed commits (Sigstore gitsign / SSH key) + linear history (rebase or squash-merge).
## 📖 Core 코어 Content
* **코드베이스 진화의 기록:** 코드는 시스템의 현재 상태만을 나타내지만, 커밋 히스토리는 대규모 코드베이스가 시간의 흐름에 따라 어떻게 성장해왔는지를 가장 세밀한 단위(micro-changes)로 보여줍니다 [2, 3]. 커밋 메시지와 풀 리퀘스트(PR) 설명은 당시의 설계 의사 결정, 고려되었던 대안들, 비즈니스적 요구사항, 해결하고자 했던 구체적인 문제들을 담고 있는 유일한 자료인 경우가 많습니다 [2].
* **코드 독해 및 온보딩 전략:** 복잡한 코드베이스를 빠르게 이해하기 위한 방법 중 하나는 **첫 커밋으로 돌아가 커밋 단위로 메시지를 읽어 나가는 것**입니다 [4]. 단순히 `git blame`으로 수정자를 확인하는 것에 그치지 않고, 변경 사항이 포함된 PR의 전체 맥락(토론, 피드백 등)을 살피면 문서화되지 않은 암묵적 지식을 명시적으로 파악할 수 있습니다 [2].
* **솔루션 발전 과정의 파악:** 커밋 히스토리를 확인하면 코드가 성급하게 작성되었는지, 아니면 점진적으로 반복 개선(iterated)되었는지 등 솔루션의 발전 과정을 알 수 있습니다 [5]. 과거에 시도했다가 기각된 해결책들에 대한 기록은 현재 코드가 가진 기술적 제약 사항을 이해하는 핵심 단서가 됩니다 [2].
* **행동 기반 코드 분석(Behavioral Code Analysis):** 커밋 히스토리는 시스템의 건전성을 평가하는 데이터로도 활용됩니다. CodeScene과 같은 분석 도구는 커밋 히스토리, 작성자 패턴, 코드 변경 빈도(churn) 등의 시간적 데이터를 분석하여 잠재적인 아키텍처 문제나 기술 부채를 식별하는 예측 모델을 구축합니다 [6-8].
* **관련 아티팩트의 자동화된 활용:** 특정 코드 스니펫을 분석할 때 `git log -L`을 통해 관련 커밋 히스토리를 역추적할 수 있습니다 [9]. 이때 주석 수정이나 단순 변수명 변경과 같은 사소한 커밋(trivial commits)을 필터링하면, LLM이나 코드 리뷰 시스템이 코드의 진정한 목적(Purpose)을 설명하는 데 필요한 고품질의 컨텍스트를 확보할 수 있습니다 [10].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **버전 관리 품질에 대한 의존성:** 커밋 히스토리를 활용한 코드베이스 분석은 조직 내 버전 관리가 잘 유지보수되고 건강한 상태(healthy)일 때만 유효합니다 [3, 4]. 커밋 메시지가 불분명하거나 맥락 없이 스쿼시(squash)된 경우 유용한 정보를 얻기 힘듭니다.
* **사소한 변경에 의한 노이즈:** 히스토리 내에 줄 삭제, 단순 오타 수정, 주석 변경 등의 사소한(trivial) 커밋이 다수 혼재해 있으면, 핵심 비즈니스 로직의 변경 이력을 파악하는 데 방해가 되며 이를 필터링해야 하는 번거로움이 존재합니다 [10].
* **탐색에 따른 인지적, 물리적 비용:** 수십 년 된 대규모 프로젝트에서는 특정 코드와 얽힌 커밋, PR, 이슈의 수가 너무 많아 이를 모두 추적하고 읽는 데 긴 시간이 소요될 수 있으며, 네트워크나 시스템 성능에 따라 정보 수집(Fetching)에 병목이 발생할 수 있습니다 [11].
### 매 좋은 history 의 특징
- **Atomic**: 매 한 commit = 한 logical change.
- **Descriptive subject**: 50자, imperative — "Fix login race".
- **Body explains why**: 매 what 은 diff 가 보여줌 — why 가 commit 의 가치.
- **Linkable**: issue/PR ref.
- **Signed**: GPG / SSH / gitsign — supply-chain integrity.
- **Linear or trunked**: bisect 친화적.
## 🔗 지식 연결 (Graph)
### Related Concepts
### 매 Conventional Commits
```
<type>(<scope>): <subject>
#### [분석 및 버전 관리 도구]
- [[Version Control System (Git)]]
- 연결 이유: 커밋 히스토리를 생성, 추적, 보관하는 근본적인 메커니즘을 제공하는 기반 시스템입니다 [1].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 브랜치(Branching), 병합(Merging) 및 저장소(Repository)의 구조가 코드베이스 히스토리 관리에 미치는 영향을 이해할 수 있습니다 [1, 2].
<body>
- [[Pull Request (PR)]]
- 연결 이유: 단일 커밋들의 묶음으로서, 코드 변경에 대한 토론, 피드백, 코드 리뷰 등 훨씬 풍부한 맥락을 제공합니다 [2].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 커밋 히스토리 이면에 존재하는 설계 의도와 팀 내 암묵적 지식, 품질 기준의 합의 과정을 해석할 수 있습니다 [2].
<footer>
```
- type: feat, fix, refactor, perf, test, docs, chore, build, ci.
- 매 BREAKING CHANGE: footer.
#### [코드 탐색 및 활용 기법]
- [[git log / git blame]]
- 연결 이유: 대규모 코드베이스에서 특정 코드 스니펫이나 파일의 역사적 변경 내역을 콘솔이나 스크립트 레벨에서 추적하는 핵심 명령어입니다 [2, 9].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 동적/정적 코드 분석 시 필요한 구체적인 변경 사항과 수정자의 문맥 데이터를 확보하는 방법을 알 수 있습니다.
### 매 응용
1. Bisect — 매 regression commit 이분 탐색.
2. Blame — 매 line author/intent 추적.
3. Cherry-pick — hotfix backport.
4. Revert — production rollback.
5. Changelog — automated (release-please, semantic-release).
6. Audit — compliance, post-mortem.
- [[Behavioral Code Analysis]]
- 연결 이유: 코드의 정적 구조뿐만 아니라, 커밋 히스토리의 시간적 데이터(Temporal Data)를 분석하여 팀의 행동 패턴과 기술적 위험을 찾아내는 기법입니다 [6].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 코드베이스 내에서 자주 변경되거나 마찰을 일으키는 핫스팟(Hotspot)을 식별하여 기술 부채를 정량화하는 방법을 이해할 수 있습니다 [6, 8].
## 💻 패턴
### Deeper Research Questions
- 대규모 레거시 시스템에서 인지적 과부하를 막기 위해 수많은 커밋 히스토리 중 핵심 비즈니스 로직과 관련된 변경 사항만을 효과적으로 필터링하는 알고리즘이나 휴리스틱은 무엇인가?
- 원자적 커밋(Atomic Commit)과 명확한 PR 작성을 강제하는 팀의 컨벤션이 새로운 개발자의 코드베이스 온보딩 속도에 미치는 정량적 영향은 어느 정도인가?
- CodeScene과 같은 행동 기반 코드 분석(Behavioral Analysis) 도구가 커밋 히스토리를 바탕으로 아키텍처 부패(Architectural Decay)를 조기에 예측하는 원리는 무엇인가?
- 문서화가 전무한 시스템에서, 커밋 메시지와 이슈 트래커 기록만을 연결하여 시스템의 의도(Purpose)를 역공학으로 재구성할 때 발생하는 LLM 환각(Hallucination)을 어떻게 방지할 것인가?
- 무분별한 Squash and Merge가 코드베이스의 마이크로 히스토리를 소실시켜 추후 디버깅이나 런타임 분석 시 초래하는 구체적인 부작용은 무엇인가?
### Practical Application Contexts
- **Implementation:** 코드를 수정하기 전, 해당 모듈의 커밋 히스토리와 PR 리뷰 코멘트를 조회하여 과거에 특정 대안이 왜 반려되었는지 파악함으로써 반복적인 실수를 방지합니다 [2].
- **System Design:** 아키텍처 설계 시 커밋 히스토리를 기반으로 변경 빈도가 비정상적으로 높은 모듈(핫스팟)을 식별하고, 해당 영역의 리팩토링 및 책임 분리를 설계의 최우선 과제로 삼습니다 [7, 8].
- **Operation / Maintenance:** 운영 중 장애나 회귀 버그(Regression error)가 발생했을 때, 문제가 발생한 지점의 커밋 기록과 엮여 있는 관련 이슈를 추적하여 버그의 근본 원인을 신속하게 진단합니다 [2, 12].
- **Learning Path:** 낯선 오픈소스나 회사 프로젝트에 처음 온보딩할 때, 진입점(Entry point)이 되는 기능의 초기 커밋부터 역추적하며 작성자의 사고 흐름과 시스템의 진화 과정을 단계적으로 학습합니다 [2, 4].
- **My Project Relevance:** 개인이나 팀 프로젝트에서 버그나 요구사항 단위로 원자적 커밋을 작성하고, 명확한 커밋 메시지를 남겨 미래의 자신이나 동료가 코드의 존재 이유를 쉽게 파악할 수 있는 환경을 구축합니다.
### Adjacent Topics
- [[Technical Debt]]
- 확장 방향: 커밋 히스토리를 통해 특정 파일의 잦은 변경(Churn) 현상을 추적함으로써, 코드베이스 내 숨겨진 기술 부채를 시각화하고 우선적으로 상환해야 할 영역을 도출하는 방향으로 확장합니다 [7].
- [[LLM-assisted Code Explanation]]
- 확장 방향: 소스 코드 자체뿐만 아니라 커밋 메시지, PR 설명 등 자연어(NL) 아티팩트를 LLM에 제공하여, 코드가 "무엇"을 하는지가 아니라 "왜" 그렇게 작성되었는지(Purpose)에 대한 수준 높은 맥락적 설명을 생성하는 기술로 확장합니다 [13, 14].
---
*Last updated: 2026-05-02*
## 📖 구조화된 지식 (Synthesized Content)
**추출된 패턴:**
> *(TODO)*
**세부 내용:**
- *(TODO)*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### git bisect 자동화
```bash
git bisect start
git bisect bad HEAD
git bisect good v1.2.0
git bisect run npm test # 매 each step automated
git bisect reset
```
## 🤔 의사결정 기준 (Decision Criteria)
### Signed commit (gitsign / Sigstore)
```bash
# 매 keyless OIDC sign
git config --global gpg.x509.program gitsign
git config --global gpg.format x509
git config --global commit.gpgsign true
git commit -m "feat: signed via gitsign"
git verify-commit HEAD
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Conventional Commits + commitlint
```js
// commitlint.config.js
export default {
extends: ['@commitlint/config-conventional'],
rules: { 'subject-max-length': [2, 'always', 72] },
};
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Interactive rebase cleanup (before push)
```bash
git rebase -i origin/main # 매 squash, reword, reorder
```
**기본값:**
> *(TODO)*
### git log advanced query
```bash
# 매 작가별 last week
git log --since='1 week ago' --pretty=format:'%h %an %s'
# 매 specific file 의 changes (move 추적)
git log --follow -p src/auth.ts
# 매 grep in patches
git log -G 'eval\(' --oneline
```
## ❌ 안티패턴 (Anti-Patterns)
### release-please automation
```yaml
- uses: googleapis/release-please-action@v4
with: { release-type: node }
# 매 Conventional Commits → CHANGELOG.md + version bump PR
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Feature branch | rebase + squash-merge |
| Long-running branch | merge commit (주의) |
| Hotfix | cherry-pick to release |
| Breaking change | BREAKING CHANGE footer + major bump |
| Compliance | signed commits + protected branch |
**기본값**: 매 Conventional Commits + signed + squash-merge.
## 🔗 Graph
- 부모: [[Source-Control]] · [[Version_Control_Systems]]
- 변형: [[버전_관리_시스템_VCS]]
- 응용: [[CI_CD_Pipeline]] · [[Husky]]
- Adjacent: [[Code_Property_Graph]]
## 🤖 LLM 활용
**언제**: commit message 생성, PR description, changelog draft, post-mortem timeline 정리.
**언제 X**: 매 actual git operations — automation 이 deterministic.
## ❌ 안티패턴
- **"WIP" commit**: 매 squash 전 cleanup.
- **거대 commit**: 매 review 불가 — split.
- **Force-push to shared branch**: 매 history rewrite, others lose work.
- **Unsigned in regulated**: 매 SOC2/SLSA 위반.
- **`git add .` blindly**: 매 secret 유출 위험.
## 🧪 검증 / 중복
- Verified: Conventional Commits 1.0; Sigstore gitsign docs; Git docs.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Conventional Commits + signing + bisect |
@@ -2,92 +2,152 @@
id: wiki-2026-0508-concrete-syntax-tree-cst
title: Concrete Syntax Tree (CST)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-858963]
aliases: [Parse Tree, CST, Lossless Syntax Tree]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [parser, ast, tooling, language-engineering]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Concrete Syntax Tree (CST)"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: Rust/JS
framework: tree-sitter/rowan
---
# [[Concrete Syntax Tree (CST)|Concrete Syntax Tree (CST]]
# Concrete Syntax Tree (CST)
## 📌 한 줄 통찰 (The Karpathy Summary)
> Concrete Syntax Tree (CST)는 파스 트리(Parse Tree)라고도 불리며, 문맥 자유 문법(context-free grammar)의 트리 표현 형태로 컴파일러가 코드를 이해하는 방식을 보여주는 공식적인 구조이다 [1]. 추상 구문 트리(AST)와 달리 구문적 요소뿐만 아니라 미세한 문체, 어휘, 레이아웃(들여쓰기 등) 세부 사항까지 코드의 모든 측면을 정밀하게 포착한다 [2]. 이러한 구체적 특성 때문에 코드 포맷팅 등 소스 코드가 변환될 때 그 형태가 크게 변경되며, 최근 코드 작성자를 식별하는 기계 학습 기반의 코드 스타일로메트리(Code Stylometry) 모델에서 중요하게 활용되고 있다 [3, 4].
## 한 줄
> **"매 source 의 every token (whitespace, comment 포함) 까지 보존하는 lossless tree"**. AST 가 semantic-only 인 반면 CST 는 매 source 의 round-trip 가능. 매 modern tooling — tree-sitter, rowan (rust-analyzer), Roslyn — 매 CST 위에서 매 IDE feature, refactoring, formatter 를 매 build.
## 📖 구조화된 지식 (Synthesized Content)
- **정의 및 구조:** CST는 주어진 문법에 대해 각 노드가 특정 기호로 레이블링되는 순서 트리(ordered tree)이다 [1]. 루트 노드는 시작 기호로, 비단말(non-leaf) 노드들은 비단말 기호로 이루어지며 자식 노드들과의 관계는 문법의 생성 규칙을 정확하게 반영하여 구성된다 [5].
- **AST와의 차이점:** 추상 구문 트리(AST)가 코드 파싱 후 레이아웃 특징 등을 추상화하여 배제하는 반면, CST는 코드를 포맷팅하거나 여백을 변경할 때의 레이아웃 정보까지 그대로 유지한다 [3, 6]. 따라서 코드를 다른 형태로 재정렬하는 소스-대-소스 변환 시 AST는 동일할 수 있지만, CST는 유의미하게 변경된다 [3].
- **CST 경로(Path) 및 문맥 추출:** CST 내에서 두 단말 노드 사이를 위아래로 이동하는 시퀀스를 'CST 경로(CST path)'라고 정의한다 [7]. 이 경로와 시작 및 종료 노드의 실제 코드 토큰 값을 결합한 것을 '경로 문맥(path context)'이라 부르며, 코드의 어휘적, 구문적, 레이아웃적 특징을 유지하는 데이터 표현 수단으로 쓰인다 [8, 9].
- **코드 분석 및 작성자 식별(Stylometry)에서의 활용:** 최신 기계 학습 모델(예: code2vec)은 코드의 의미론적 요소와 문체적 요소를 모두 보존하기 위해 AST 대신 CST를 입력값으로 사용한다 [4]. 실제 실험 결과, AST 대신 CST 기반의 코드 표현을 사용하면 레이아웃 정보가 반영되어 코드 작성자 식별(Authorship attribution)의 정확도가 크게 향상(51.00%에서 67.86%로 증가)되는 것으로 확인되었다 [10, 11].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 vs AST
- **AST**: semantic node 만 (`if`, `BinaryOp`, etc) — comment, whitespace 버림.
- **CST**: 모든 token + trivia 보존 — `source == reprint(cst)`.
- CST → AST 의 lowering 가능, 역은 매 lossy.
## 🔗 지식 연결 (Graph)
- **Related Topics:** Abstract Syntax Tree (AST), Code Stylometry, Parse Tree
- **Projects/Contexts:** 프로그래머의 코드 작성 스타일을 분석하여 작성자를 식별하는 코드 스타일로메트리 연구에서, 코드 포맷팅([[Formatting|Formatting]]) 및 축소(minification) 기술이 식별 정확도에 미치는 영향을 측정하기 위한 코드 표현 방식으로 사용됨 [3, 12, 13].
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다.
### 매 핵심 properties
- **Lossless**: print 시 원본 byte-for-byte 복구.
- **Error-tolerant**: incomplete/invalid code 도 partial tree.
- **Incremental**: edit 시 affected subtree 만 reparse (tree-sitter).
- **Untyped or weakly-typed**: 모든 node 가 동질 — typed wrapper 로 navigate.
---
*Last updated: 2026-04-19*
### 매 응용
1. IDE: syntax highlight, fold, outline, indent.
2. Refactoring: rename, extract method (preserve formatting).
3. Formatter: prettier, rustfmt — CST 로 layout 결정.
4. Linter: tree-sitter queries.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### tree-sitter parsing
```javascript
const Parser = require('tree-sitter');
const TS = require('tree-sitter-typescript').typescript;
const parser = new Parser();
parser.setLanguage(TS);
const tree = parser.parse('const x: number = 1;');
// Walk
const cursor = tree.walk();
do { console.log(cursor.nodeType, cursor.startIndex, cursor.endIndex); }
while (cursor.gotoNextSibling() || cursor.gotoFirstChild());
```
## 🤔 의사결정 기준 (Decision Criteria)
### tree-sitter query (S-expression)
```scheme
; Find all function declarations
(function_declaration
name: (identifier) @func.name
parameters: (formal_parameters) @func.params)
**선택 A를 써야 할 때:**
- *(TODO)*
; Find unused imports
(import_statement
source: (string) @import.source) @import
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Incremental edit
```javascript
const oldTree = parser.parse(oldSrc);
const newSrc = oldSrc.slice(0, 10) + 'INSERTED' + oldSrc.slice(10);
oldTree.edit({
startIndex: 10, oldEndIndex: 10, newEndIndex: 18,
startPosition: {row: 0, column: 10},
oldEndPosition: {row: 0, column: 10},
newEndPosition: {row: 0, column: 18},
});
const newTree = parser.parse(newSrc, oldTree); // reuses unchanged subtrees
```
**기본값:**
> *(TODO)*
### rowan (rust-analyzer) typed wrapper
```rust
// Untyped GreenNode + typed SyntaxNode wrapper
use rowan::{GreenNode, SyntaxNode};
## ❌ 안티패턴 (Anti-Patterns)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u16)]
enum SyntaxKind { L_PAREN, R_PAREN, IDENT, FN_KW, FN_DEF, ROOT, /* ... */ }
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
struct FnDef(SyntaxNode<MyLang>);
impl FnDef {
fn name(&self) -> Option<String> {
self.0.children().find(|n| n.kind() == SyntaxKind::IDENT)
.map(|n| n.text().to_string())
}
}
```
### Lossless rewrite (rename)
```rust
// Replace token in CST and reprint — preserves comments/whitespace.
fn rename(node: &SyntaxNode, old: &str, new: &str) -> String {
let mut out = String::new();
for tok in node.descendants_with_tokens() {
if let Some(t) = tok.as_token() {
if t.kind() == SyntaxKind::IDENT && t.text() == old { out.push_str(new); }
else { out.push_str(t.text()); }
}
}
out
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Compiler / type checker | AST (semantic 충분) |
| IDE / LSP / formatter | CST (lossless 필수) |
| Refactoring tool | CST + typed wrapper |
| Quick analysis script | tree-sitter query |
| New language design | rowan or tree-sitter base |
**기본값**: User-facing tool 이면 매 CST. Compiler internal pass 면 매 AST.
## 🔗 Graph
- 부모: [[Parser]] · [[Compiler Frontend]]
- 변형: [[AST]] · [[GLR Parser]] · [[PEG Parser]]
- 응용: [[tree-sitter]] · [[rust-analyzer]] · [[Roslyn]] · [[Prettier]]
- Adjacent: [[Lexer]] · [[LSP]] · [[Incremental Parsing]]
## 🤖 LLM 활용
**언제**: Source-to-source transformation, IDE-grade tooling, codemods.
**언제 X**: Pure semantic analysis (AST 만 충분).
## ❌ 안티패턴
- **Regex on source**: 매 fragile — CST query 사용.
- **AST 로 formatter**: comment 손실 — CST 필수.
- **Hand-rolled parser**: error recovery 빠짐 — tree-sitter/lark 사용.
- **Full reparse on every keystroke**: incremental edit API 사용.
## 🧪 검증 / 중복
- Verified (tree-sitter docs, rust-analyzer rowan, Roslyn architecture).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — CST vs AST + tree-sitter/rowan patterns |
@@ -2,66 +2,32 @@
id: wiki-2026-0508-continuous-delivery-지속적-제공-cd
title: "Continuous Delivery (지속적 제공, CD)"
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
status: duplicate
canonical_id: wiki-2026-0508-continuous-delivery
duplicate_of: "[[Continuous Delivery]]"
aliases: []
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
raw_sources: []
last_reinforced: 2026-05-08
confidence_score: 0.9
verification_status: redirected
tags: [duplicate, cd, devops]
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
---
# [[Continuous Delivery (지속적 제공, CD)]]
# Continuous Delivery (지속적 제공, CD)
## 📌 한 줄 통찰 (The Karpathy Summary)
Continuous Delivery(지속적 제공, CD)는 소프트웨어가 언제든지 프로덕션 환경에 릴리스될 수 있도록 보장하는 자동화된 소프트웨어 개발 관행입니다 [1]. 이를 위해 빌드 파이프라인을 활용하여 소프트웨어를 자동으로 테스트하고 테스트 및 프로덕션 환경에 배포합니다 [1]. 수많은 개발자가 매일 동일한 코드베이스에 코드를 푸시하는 환경에서도 품질 저하 없이 개발 속도와 확신을 유지 가능하게 만드는 핵심적인 역할을 합니다 [1, 2].
> **이 문서는 [[Continuous Delivery]] 의 중복본입니다.** Canonical 문서로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
* **빌드 파이프라인과 완벽한 자동화:** 지속적 제공 환경에서는 빌드부터 테스트, 배포, 인프라에 이르기까지 모든 과정의 자동화가 필수적입니다 [3]. 수동 테스트와 배포로는 빠르게 혁신하는 개발 속도를 따라갈 수 없으며, 자동화된 테스트 메커니즘이 지속적 제공을 실행 가능하게 만드는 근간이 됩니다 [2, 3].
* **빠른 피드백 루프와 애자일의 시너지:** 자동화된 테스트가 제공하는 대폭 단축된 피드백 루프는 애자일 개발 관행, 지속적 제공 및 DevOps 문화와 밀접하게 맞물려 작동합니다 [4]. 이를 통해 팀은 소프트웨어 품질을 희생하지 않으면서도 더 빠르게 움직일 수 있습니다 [1, 4]. 마틴 파울러(Martin Fowler)가 옹호하는 지속적 제공과 DevOps는 조직의 소프트웨어 배포 방식을 혁신적으로 재편하는 데 기여했습니다 [5].
* **대규모 환경(SAFe)에서의 확장 및 인프라 조정:** 대규모 애자일 환경에서는 지속적 제공 파이프라인이 전체 ART(Agile Release Train) 시스템에 걸쳐 확장됩니다 [6]. 개별 팀이 고유의 CI(지속적 통합) 프로세스를 유지하는 한편, 시스템 팀은 팀 수준의 빌드 결과물들을 일관된 하나의 소프트웨어로 연결하는 통합 인프라(코드로서의 인프라 등)를 구축하고 조정합니다 [6].
## 핵심 요약 (Korean specialization)
- 매 한국어 title 의 alias — 매 동일 concept (Continuous Delivery)
- 매 Korean wiki 검색 entry-point 로만 유지
- 매 정식 content 는 [[Continuous Delivery]] 참조
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **신뢰할 수 있는 CI 파이프라인 필수:** 단일 자동화 테스트를 작성하거나 CD를 도입하기 전에 기능적이고 신뢰할 수 있는 지속적 통합(CI) 파이프라인이 먼저 구축되어야 합니다 [7]. 매 커밋 시 트리거되는 자동화된 빌드 환경과 수 분 내에 코드의 오류를 알려주는 명확한 피드백 루프가 없다면 지속적 제공의 가치는 실현될 수 없습니다 [7].
* **품질 부채(Quality Debt)와 시스템 경직성:** 취약한 코드베이스 위에 자동화를 무리하게 적용하려 할 경우, 테스트 스위트 자체가 유지보수하기 어렵고 깨지기 쉬운 상태가 됩니다 [8]. 결과적으로 흐름 효율성(Flow Efficiency)과 배포 성공률이 모두 악화되므로 리팩토링, 자동화된 테스트, 체계적인 동료 코드 리뷰와 같은 내장된 품질(Built-in Quality) 관행이 반드시 전제되어야 합니다 [8].
* **사전 인프라 투자 부담:** 지속적 제공을 안정적으로 운영하려면 테스트 환경, CI 파이프라인 구축 및 테스트 데이터 관리 등 인프라를 마련하는 데 상당한 초기 리소스와 시스템 팀 단위의 노력이 요구됩니다 [6, 9].
## 🔗 Graph
- 부모: [[Continuous Delivery]] (canonical)
---
*Last updated: 2026-05-03*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -2,104 +2,32 @@
id: wiki-2026-0508-continuous-integration-지속적-통합-ci
title: "Continuous Integration (지속적 통합, CI)"
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
aliases: []
duplicate_of: none
status: duplicate
canonical_id: ci-cd-pipeline
duplicate_of: "[[CI_CD_Pipeline]]"
aliases: [CI, 지속적 통합]
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
raw_sources: []
last_reinforced: 2026-05-08
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
confidence_score: 0.9
verification_status: redirected
tags: [duplicate, ci, devops]
last_reinforced: 2026-05-10
github_commit: applied
---
# [[Continuous Integration (지속적 통합, CI)]]
# Continuous Integration (지속적 통합, CI)
## 📌 한 줄 통찰 (The Karpathy Summary)
지속적 통합(CI)은 개발자가 코드를 커밋할 때마다 자동으로 빌드와 테스트가 트리거되어 몇 분 내에 명확한 피드백을 제공하는 소프트웨어 개발 실천법입니다 [1]. 여러 개발자가 동일한 코드베이스에 코드를 푸시할 때 발생하는 문제를 방지하고 자동화된 테스트와 지속적 제공(CD)을 가능하게 하는 핵심 메커니즘입니다 [2]. 특히 리팩토링 과정에서 작은 변경 사항을 만든 후 CI와 TDD를 실행하는 것은 시스템을 정상 작동 상태로 유지하고 새로운 버그가 유입되는 것을 막는 필수적인 안전망 역할을 합니다 [3].
> **이 문서는 [[CI_CD_Pipeline]] 의 중복본입니다.** CI/CD pipeline 통합 canonical 로 redirect.
## 📖 일 Core Content
## 핵심 요약
- CI = 매 frequent integration + automated test on every commit.
- 매 trunk-based + < 10min feedback loop + green main 이 핵심.
* **정의 및 역할:** CI는 일상적인 개발 및 리팩토링 프로세스에 내장되어야 하는 필수적인 기반입니다. 기능적이고 신뢰할 수 있는 CI 파이프라인이 구축되어 있어야만 코드가 커밋될 때 자동화된 빌드가 실행되고, 신속한 피드백 루프가 형성됩니다 [1].
* **리팩토링 및 테스트를 위한 필수 조건:** CI 파이프라인이라는 기반 없이는 자동화된 테스트가 실행될 공간이 없으며, 빠르고 가치 있는 피드백을 전달할 메커니즘이 존재하지 않게 됩니다 [1]. 리팩토링 프로세스에서 코드를 작게 수정한 후에는 반드시 TDD와 CI를 실행하여 시스템이 깨지지 않았는지 확인해야 하며, 이를 생략하면 버그가 유입될 위험이 큽니다 [3].
* **지속적 제공(CD) 및 DevOps와의 통합:** CI는 언제든 프로덕션 환경에 소프트웨어를 릴리스할 수 있도록 보장하는 지속적 제공(CD) 및 DevOps 문화와 긴밀하게 연결되어 발전합니다 [4]. 파이프라인은 여러 단계로 나뉘어 점진적으로 소프트웨어 배포에 대한 확신을 주며, 최근의 최신 DevOps 및 CI/CD 파이프라인에서는 마틴 파울러의 리팩토링 방법론이 널리 채택되어 적용되고 있습니다 [5, 6].
* **미래의 진화:** 향후 인공지능(AI)이 발전함에 따라, 단순히 코드를 커밋할 때마다 빌드/테스트를 수행하는 '지속적인 통합(CI)' 단계를 넘어, AI가 자동으로 리팩토링 기회를 탐지하고 테스트를 통해 안정성이 입증된 최적의 구조를 제안하거나 적용하는 '지속적인 개선(Continuous Improvement)'의 단계로 나아갈 것으로 예측됩니다 [7].
## 🔗 Graph
- 부모: [[CI_CD_Pipeline]] (canonical)
- Adjacent: [[Continuous Delivery (지속적 제공, CD)]] · [[Test_Automation]] · [[Engineering Metrics (DORA)]]
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **초기 인프라 구축 및 신뢰성 확보의 어려움:** CI를 효과적으로 운영하기 위해서는 코드로 프로비저닝된 일관된 빌드 환경과 신뢰할 수 있는 인프라 구축이 선행되어야 합니다 [1, 8]. 이 기반이 불안정하다면 자동화된 테스트도 제대로 기능할 수 없습니다 [1].
* **테스트 품질에 대한 강한 의존성:** CI는 테스트를 자동으로 실행해 줄 뿐, 테스트 자체의 품질을 보장하지는 않습니다. CI 파이프라인 내의 테스트가 불완전하거나 간헐적으로 실패하는(Flaky) 경우, CI의 결과에 대한 개발자의 신뢰가 떨어지고 성공적인 리팩토링 진행을 방해하게 됩니다 [9]. 원대한 테스트 커버리지 목표를 쫓기 전에 CI 파이프라인의 신뢰성을 먼저 확보하는 것이 중요합니다 [10].
## 🔗 지식 연결 (Graph)
### Related Concepts
#### [소프트웨어 품질 및 검증 (Software Quality & Verification)]
* [[Automated Testing (자동화된 테스트)]]
* 연결 이유: CI 파이프라인의 핵심은 코드가 커밋될 때마다 실행되는 자동화된 테스트에 있기 때문입니다 [1].
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: CI를 통해 리팩토링의 안전성을 보장하는 구체적인 검증 메커니즘과, 피드백 루프를 짧게 유지하는 방법을 깊이 이해할 수 있습니다 [6, 11].
* [[TDD (테스트 주도 개발)]]
* 연결 이유: 리팩토링 과정에서 작은 변경을 한 후 TDD와 CI를 함께 실행하는 것이 버그 도입 위험을 막는 필수 실천법으로 언급되기 때문입니다 [3].
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: 기능 추가와 리팩토링 과정에서 테스트가 어떻게 설계를 주도하고 CI 파이프라인에서 지속적인 피드백을 주는지 파악할 수 있습니다.
#### [소프트웨어 배포 및 운영 (Software Delivery & Operation)]
* [[Continuous Delivery (지속적 제공, CD)]]
* 연결 이유: CI는 언제든 소프트웨어를 배포할 수 있도록 보장하는 지속적 제공(CD)과 연결되어 파이프라인을 형성하기 때문입니다 [2, 4].
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: CI가 단지 코드 통합을 넘어 실제 프로덕션 환경에 소프트웨어를 안전하고 지속적으로 배포하기 위한 더 넓은 관점에서의 가치와 목적을 이해할 수 있습니다 [4, 6].
### Deeper Research Questions
* CI 파이프라인 내에서 자동화된 테스트의 실행 속도와 커버리지 사이의 이상적인 균형점은 어떻게 찾아야 하는가?
* 수십 명의 개발자가 동시에 코드를 커밋하는 대규모 환경에서 CI 파이프라인의 병목 현상을 방지하기 위한 시스템적, 도구적 접근법은 무엇인가?
* 대규모 레거시 시스템에서 신뢰할 수 없는 CI 파이프라인을 점진적으로 구축하고 안정화하기 위한 최적의 전략은 무엇인가?
* 리팩토링 변경 사항이 포함된 커밋이 CI 파이프라인에서 실패했을 때, 가장 효율적으로 원인을 파악하고 디버깅하는 절차는 무엇인가?
* 미래의 '자가 치유형 코드베이스(Self-Healing Codebase)'에서 AI는 CI 과정 중 어떤 기준으로 최적의 리팩토링 구조를 자동 제안하게 될 것인가?
### Practical Application Contexts
* **Implementation:** 코드를 커밋할 때마다 즉각적으로 자동 빌드와 테스트가 실행되도록 CI 툴을 설정하며, 리팩토링을 수행한 직후 반드시 CI를 통해 시스템 붕괴 여부를 확인합니다 [1, 3].
* **System Design:** 시스템 팀의 관점에서 개별 개발팀의 CI 프로세스를 유기적으로 통합하여 일관된 빌드 환경을 제공하고, 전체 릴리스 트레인에 걸친 'Continuous Delivery Pipeline' 구조를 설계합니다 [1, 8].
* **Operation / Maintenance:** CI 파이프라인의 신뢰성을 모니터링하고 유지보수합니다. 간헐적으로 실패하는(Flaky) 테스트를 조기에 제거하여 팀이 자동화 파이프라인에 대한 신뢰를 잃지 않도록 관리합니다 [9, 10, 12].
* **Learning Path:** 리팩토링 기법과 단위 테스트 작성법을 배운 이후, 이를 지속적이고 자동화된 환경에서 검증할 수 있도록 CI 도구 활용법 및 파이프라인 구축을 학습합니다 [3, 13].
* **My Project Relevance:** 기술 부채를 청산하기 위해 코드를 구조적으로 변경할 때마다 CI를 구축하여 몇 분 내에 피드백을 받을 수 있는 환경을 마련함으로써, 안정적으로 아키텍처를 개선해 나갑니다.
### Adjacent Topics
* [[DevOps]]
* 확장 방향: 개발과 운영의 경계를 허물고 CI/CD 파이프라인을 인프라 자동화 및 문화적 차원으로 확장하여 어떻게 전체적인 소프트웨어 배포 주기를 단축시키고 품질을 향상하는지 조사합니다 [4, 5].
* [[Test Pyramid (테스트 피라미드)]]
* 확장 방향: CI 환경 내에서 병목 없이 빠른 피드백을 받기 위해, 단위 테스트, 통합 테스트, E2E 테스트를 어떤 비율로 구성하고 배치해야 하는지 탐구합니다 [14, 15].
---
*Last updated: 2026-05-03*
## 📖 구조화된 지식 (Synthesized Content)
**추출된 패턴:**
> *(TODO)*
**세부 내용:**
- *(TODO)*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — CI_CD_Pipeline 로 redirect |
@@ -2,65 +2,149 @@
id: wiki-2026-0508-continuous-discovery
title: Continuous Discovery
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-CDIS-001]
aliases: [continuous user research, weekly discovery, Teresa Torres method]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, continuous-discovery, product-discovery, dual-track-agile, customer-feedback, Hypothesis-Testing]
confidence_score: 0.9
verification_status: applied
tags: [product, research, discovery, ux]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: process
framework: product-discovery
---
# [[Continuous-Discovery|Continuous-Discovery]]
# Continuous Discovery
## 📌 한 줄 통찰 (The Karpathy Summary)
> "만들기 전에 증명하기: 매주 고객과 대화하며 그들의 진짜 고통을 확인하고, 매일 가설을 검증하여 '아무도 원하지 않는 제품'을 만드는 리스크를 0에 가깝게 줄이는 현대적 기획의 호흡법."
## 한 줄
> **"매 continuous discovery 의 의미: 매 매 week 의 매 customer 와 매 conversation, 매 product decision 에 매 feed"**. 매 Teresa Torres 의 *Continuous Discovery Habits* (2021) 가 매 popularize. 매 2026 modern product team 의 매 default — 매 quarterly research → 매 weekly cadence.
## 📖 구조화된 지식 (Synthesized Content)
지속적 발견(Continuous-Discovery)은 제품 팀이 어떤 기능을 만들지 결정하기 위해 매주 고객과 상호작용하며 학습하는 과정입니다. (Teresa Torres의 프레임워크가 대표적)
## 매 핵심
1. **핵심 워크플로우**:
* **Outcome Focus**: 기능 개발이 아니라 '사용자의 행동 변화'라는 결과에 집중.
* **Weekly User Interviews**: 일회성 조사가 아닌 정기적인 고객 접점 확보.
* **Opport[[Unity|Unity]] [[Solution|Solution]] Tree**: 목표-기회-솔루션을 시각화하여 최선의 경로 탐색. (Decision-Making와 연결)
2. **왜 중요한가?**:
* 시장의 변화 속도가 너무 빨라, 한 번의 완벽한 기획서 정책은 반드시 실패하기 때문임. (Agile와 연결)
### 매 Torres 의 trio
- **Product manager** + **Designer** + **Engineer** 의 매 함께 discovery
- 매 1명만 매 user 와 talk → 매 telephone game
- 매 trio 함께 → 매 shared understanding
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 기획자와 고객이 만나는 것이 시간 낭비라 여겼으나, 현대 정책은 개발자가 고객의 목소리 정책을 직접 듣고 가설 정책을 즉시 수정하는 '임파워드 팀 정책(Empowered Teams)'이 훨씬 더 혁신적인 결과를 낸다는 점을 인정함(RL Update).
- **정책 변화(RL Update)**: 이제는 단순 인터뷰 정책을 넘어, AI 가 수만 건의 피드백 정책을 실시간으로 분석([[Text-Mining|Text-Mining]])하여 기획자에게 '기회 영역'을 추천해 주는 'AI-Augmented Discovery'로 진화 중임. (Text-Mining와 연결)
### 매 weekly cadence
- 매 week 의 매 1+ customer interview
- 매 opportunity solution tree 의 매 update
- 매 assumption test 의 매 1+ run
## 🔗 지식 연결 (Graph)
- Decision-Making, Agile, [[Text-Mining|Text-Mining]], [[Research|Re[[Search]]-Methodology]], [[Product-Management|Product-Management]]
- **Key Figure**: Teresa Torres.
---
### 매 Opportunity Solution Tree
- **Outcome** (top): business outcome (매 retention +5%)
- **Opportunities**: 매 customer needs / pain points
- **Solutions**: 매 ideas
- **Experiments**: 매 assumption tests
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. 매 PM 의 매 weekly research routine.
2. 매 roadmap prioritization 의 매 evidence base.
3. 매 PMF (product-market fit) 의 매 ongoing validation.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Opportunity Solution Tree 의 매 markdown
```markdown
# Outcome: Q2 의 weekly active users +20%
## 🧪 검증 상태 (Validation)
## Opportunity 1: 매 user 의 매 onboarding 에 confused
- Solution 1.1: 매 interactive tutorial
- Experiment: 매 prototype A/B test
- Solution 1.2: 매 sample data preload
- Experiment: 매 5 user 의 unmoderated test
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## Opportunity 2: 매 power user 의 매 keyboard shortcut 의 X
- Solution 2.1: 매 cmdK palette
- Experiment: 매 beta cohort 측정
```
## 🧬 중복 검사 (Duplicate Check)
### Interview 의 매 story-based prompt
```
매 X 안 됨: "Would you use feature Y?" (매 hypothetical)
매 O: "Tell me about the last time you tried to <task>.
Walk me through what happened, step by step."
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Assumption Mapping
```
Importance
Low ─────────► High
┌──────────┬──────────┐
Evidence │ Skip │ TEST │
Low │ │ FIRST │
├──────────┼──────────┤
Evidence │ Document│ Build │
High │ │ │
└──────────┴──────────┘
```
## 🕓 변경 이력 (Changelog)
### 매 weekly recurring 의 calendar block
```
Mon 10am-11am: 매 trio sync (review 의 last week 결과)
Wed 2pm-3pm: 매 customer interview slot 1
Thu 2pm-3pm: 매 customer interview slot 2
Fri 11am-12pm: 매 OST update + experiment plan
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Research Repository (Notion / Dovetail / Reduct)
```
/research
/interviews
2026-05-08-jane-doe-acme-corp.md
2026-05-09-john-smith-beta-inc.md
/insights
onboarding-confusion-pattern.md
/opportunity-solution-tree.md
```
### Continuous Discovery 의 매 metric
```python
weekly_metrics = {
"interviews_conducted": 3, # 매 target: 매 week 1-3
"assumptions_tested": 2,
"OST_updates": 1,
"trio_alignment_score": 4.5, # 매 self-reported 1-5
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Early-stage startup | 매 founder-led, 매 5+ interviews/week |
| Growth-stage product | 매 trio cadence, 매 2-3/week |
| Enterprise B2B | 매 fewer (1-2/week), 매 deeper (60min) |
| 매 dev tool | 매 dogfood + community Discord/Slack |
| 매 heavily regulated | 매 IRB-style consent + 매 anonymization |
**기본값**: 매 weekly trio + 매 minimum 1 interview/week + 매 OST 의 living document.
## 🔗 Graph
- 부모: [[Product Management]] · [[User Research]]
- 변형: [[Continuous Delivery]] · [[Continuous Integration]]
- 응용: [[Opportunity Solution Tree]] · [[Customer Interview]]
- Adjacent: [[A/B Testing]] · [[Jobs to be Done]]
## 🤖 LLM 활용
**언제**: 매 interview transcript 의 thematic coding, 매 OST 의 draft, 매 assumption 의 listing, 매 research synthesis.
**언제 X**: 매 actual customer conversation 의 X (매 LLM persona 의 fake user 의 dangerous). 매 sensitive PII 의 매 raw transcript.
## ❌ 안티패턴
- **Quarterly research**: 매 too slow, 매 stale by build time.
- **PM 만 single-handed**: 매 trio 의 X — 매 designer/eng 의 context loss.
- **매 leading question**: "Don't you hate when X?" → 매 yes-bias.
- **매 OST 의 set-and-forget**: 매 living document 의 X 인 dead artifact.
## 🧪 검증 / 중복
- Verified (Torres, *Continuous Discovery Habits*; Product Talk blog).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Continuous Discovery full content |
@@ -2,116 +2,31 @@
id: wiki-2026-0508-continuous-integration
title: Continuous Integration
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-REINFORCE-WIKI-DEV-CI, CI, 지속적 통합, Continuous Integration, 빌드 자동화, 파이프라인]
duplicate_of: none
status: duplicate
canonical_id: continuous-integration-ci
duplicate_of: "[[Continuous Integration (지속적 통합, CI)]]"
aliases: [CI]
source_trust_level: A
confidence_score: 1.0
tags: [DevOps, CI_CD, Automation, Quality_Assurance, Software_Engineering]
raw_sources: [Datacollector_Export_2026-05-02]
last_reinforced: 2026-05-02
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
confidence_score: 0.9
verification_status: redirected
tags: [duplicate, ci, devops]
last_reinforced: 2026-05-10
github_commit: applied
---
# [[지속적 통합과 자동화된 검증 체계 (Continuous Integration)]]
# Continuous Integration
## 1. 개요
지속적 통합(CI, Continuous Integration)은 개발자들이 작성한 코드를 빈번하게 공유 저장소에 통합하고, 통합될 때마다 자동으로 빌드와 테스트를 실행하여 소프트웨어의 품질을 지속적으로 검증하는 개발 관행이다. "내 로컬 환경에서는 잘 돌아간다"는 오류를 방지하고, 병합(Merge) 시점에 발생하는 충돌을 조기에 발견하여 메인 코드베이스의 안정성을 유지하는 데 목적이 있다.
> **이 문서는 [[Continuous Integration (지속적 통합, CI)]] 의 중복본입니다.** Canonical 로 redirect.
## 2. 핵심 프로세스 및 구성 요소
- **코드 통합 (Code Integration)**: 모든 팀원이 매일 수차례 메인 브랜치에 코드를 머지. 작은 단위의 빈번한 통합은 큰 규모의 통합 시 발생하는 리스크를 줄임.
- **자동 빌드 (Automated Build)**: 코드가 푸시되면 서버가 소스를 가져와 자동으로 컴파일하고 실행 가능한 형태로 빌드.
- **자동 테스트 (Automated Testing)**: 빌드 직후 단위 테스트, 통합 테스트, 정적 분석 도구 등을 실행하여 결함을 즉시 탐지.
- **피드백 (Feedback Loop)**: 빌드나 테스트 실패 시 즉시 개발팀에 알림을 전송하여 문제 해결을 유도.
## 핵심 요약
- 영문 stub — Korean canonical 에 모든 substantive content.
## 3. 엔지니어링 가치
- **결함 조기 발견 및 수정**: 코드가 통합되는 즉시 테스트가 수행되므로, 버그가 발생한 시점과 원인을 빠르게 파악하여 수정 비용을 최소화함.
- **안정적인 코드베이스 유지**: 메인 브랜치는 항상 테스트를 통과한 '배포 가능한 상태'를 유지하므로 릴리스 신뢰도가 높아짐.
- **협업 효율성 증대**: 자동화된 검증 도구가 반복적인 작업을 대신하므로, 개발자는 비즈니스 로직 구현과 설계에 더 집중할 수 있음.
- **환경 일관성 보장**: 표준화된 빌드 서버에서 검증을 수행하므로 개별 개발 환경 차이로 인해 발생하는 배포 이슈 차단.
## 🔗 Graph
- 부모: [[Continuous Integration (지속적 통합, CI)]] (canonical)
- Adjacent: [[CI_CD_Pipeline]] · [[Continuous Delivery (지속적 제공, CD)]]
## 4. 트레이드오프 및 주의사항
- **파이프라인 관리 오버헤드**: CI 서버(Jenkins, GitHub Actions 등)와 빌드 스크립트를 관리하고 최적화하기 위한 지속적인 노력이 필요함.
- **빌드 병목 현상**: 프로젝트 규모가 커짐에 따라 빌드와 테스트 시간이 길어지면 오히려 개발 주기를 늦추는 병목이 될 수 있으므로 병렬 실행이나 캐싱 전략 필수.
- **가짜 성공/실패 (Flaky Tests)**: 네트워크 환경이나 동시성 문제로 인해 간헐적으로 실패하는 테스트는 CI의 신뢰도를 떨어뜨리므로 엄격하게 관리되어야 함.
## 5. 지식 연결 (Related)
- [[Test_Automation]]: CI 환경에서 수행되는 핵심 검증 활동.
- [[Continuous_Deployment]]: CI를 넘어 운영 환경 배포까지 자동화하는 확장된 단계.
- [[Microservices_Architecture]]: 독립적인 배포 파이프라인이 필수적인 아키텍처 환경.
## 🧪 검증 상태 (Validation)
- **정보 상태**: 검증 완료 (Verified)
- **출처 신뢰도**: A
- **검토 이유**: 소프트웨어 개발의 민첩성과 품질을 동시에 확보하기 위한 현대적 개발 프로세스의 중추인 지속적 통합 전략 및 실천 지침 정립.
## 📌 한 줄 통찰 (The Karpathy Summary)
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
## 📖 구조화된 지식 (Synthesized Content)
**추출된 패턴:**
> *(TODO)*
**세부 내용:**
- *(TODO)*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
```
## 🤔 의사결정 기준 (Decision Criteria)
**선택 A를 써야 할 때:**
- *(TODO)*
**선택 B를 써야 할 때:**
- *(TODO)*
**기본값:**
> *(TODO)*
## ❌ 안티패턴 (Anti-Patterns)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 로 redirect |
@@ -2,20 +2,32 @@
id: wiki-2026-0508-dast-fundamentals
title: DAST Fundamentals
category: 10_Wiki/Topics
status: merged
redirect_to: DAST
canonical_id: DAST
aliases: [dast_fundamentals_redirect]
duplicate_of: none
status: duplicate
canonical_id: dast
duplicate_of: "[[DAST]]"
aliases: [Dynamic Application Security Testing Fundamentals]
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
raw_sources: []
last_reinforced: 2026-05-08
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
confidence_score: 0.9
verification_status: redirected
tags: [duplicate, dast, security]
last_reinforced: 2026-05-10
github_commit: applied
---
# Redirect
# DAST Fundamentals
이 문서는 [[DAST]]으로 통합되었습니다.
> **이 문서는 [[DAST]] 의 중복본입니다.** Canonical DAST 문서로 redirect.
## 핵심 요약
- DAST = 매 running app 의 black-box scan — ZAP, Burp, Nuclei.
- 매 fundamentals 는 canonical DAST 의 subset.
## 🔗 Graph
- 부모: [[DAST]] (canonical)
- Adjacent: [[SAST]] · [[SCA]] · [[OWASP Top 10]]
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — DAST canonical 로 redirect |
@@ -2,66 +2,165 @@
id: wiki-2026-0508-data-array-textures
title: Data Array Textures
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-8AF01A]
aliases: [Texture Array, GL_TEXTURE_2D_ARRAY, WebGL2 Array Texture]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [webgl, gpu, texture, graphics, rendering]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Data Array Textures"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: glsl
framework: webgl2
---
# [[Data Array Textures|Data Array Textures]]
# Data Array Textures
## 📌 한 줄 통찰 (The Karpathy Summary)
> Data Array Textures(배열 텍스처)는 셰이더에서 인덱스를 통해 접근할 수 있는 여러 2D 텍스처들의 스택 또는 레이어 구조를 의미합니다 [1, 2]. 이는 여러 이미지를 단일 이미지로 패킹하는 전통적인 텍스처 아틀라스([[Texture Atlas|Texture Atlas]])의 문제점들을 해결하는 현대적인 접근 방식입니다 [2]. 특히 다양한 텍스처를 사용하는 여러 객체를 `BatchedMesh`와 결합하여 최소한의 드로우 콜([[Draw Call|Draw Call]])로 렌더링할 수 있게 해주어 3D 렌더링 성능 최적화에 핵심적인 역할을 합니다 [1, 2].
## 한 줄
> **"매 N 장 의 동일 size texture 의 single bind"**. 매 GL_TEXTURE_2D_ARRAY 의 atlas 의 alternative 의 sub-texel bleed 의 X 의 mipmap-safe 의 layered access 의 enable. 매 2026 년 의 WebGPU 의 default storage 의 voxel terrain, sprite atlas, lookup table 의 standard.
## 📖 구조화된 지식 (Synthesized Content)
- **주요 장점:** 배열 텍스처는 인접한 텍스처가 섞이는 경계 번짐([[Edge Bleeding|Edge Bleeding]]) 현상을 제거하고, 네이티브 텍스처 래핑(Wrapping) 및 타일링(Tiling)을 지원하며, 교차 오염 없이 각 레이어별로 올바른 밉맵([[Mipmap|Mipmap]])을 생성할 수 있습니다 [2]. 또한 복잡한 UV 오프셋 계산이나 아틀라스 패킹 알고리즘이 필요하지 않아 셰이더 코드가 크게 단순화됩니다 [2].
- **렌더링 성능 및 활용:** `BatchedMesh`와 함께 사용하면 셰이더 분기(Branching) 처리 대신 하드웨어 인덱싱을 직접 사용하여 한 번의 드로우 콜만으로 서로 다른 텍스처를 가진 수많은 객체를 렌더링할 수 있습니다 [2]. 또한 노멀 맵, 러프니스 맵, 메탈니스 맵 등을 TextureArray로 저장하여 객체별로 고유한 질감을 부여하거나 [3], 원거리 객체를 표시하기 위한 빌보드 임포스터(Billboard impostors)의 다각도 뷰를 텍스처 배열로 저장하여 렌더링하는 데에도 활용될 수 있습니다 [4].
- **구조적 한계 및 단점:** 배열 텍스처 내에 포함되는 모든 텍스처는 반드시 동일한 크기(Dimensions)를 가져야만 합니다 [5]. 다양한 해상도를 섞어 써야 한다면 여러 개의 배열 텍스처를 생성하거나 기존의 텍스처 아틀라스를 사용해야 합니다 [5].
- **메모리 및 호환성:** 텍스처 아틀라스가 메모리를 더 밀도 있게 패킹할 수 있는 반면, 배열 텍스처는 런타임에 모든 레이어의 메모리를 사전에 할당해야 하는 메모리 오버헤드가 있습니다 [5]. 이 기술은 [[WebGL|WebGL]]2 환경을 요구하지만, 2025년 기준 브라우저 지원이 매우 우수하여 동일한 크기의 텍스처를 다루는 현대 웹 그래픽 프로젝트에서는 전통적 아틀라싱보다 뛰어난 성능을 발휘합니다 [5].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 vs Atlas
- **Atlas**: 매 single 2D texture 의 grid. 매 mipmap 의 bleed problem.
- **Array texture**: 매 layer 의 independent. 매 mipmap-safe. 매 single bind 의 N draw call 의 1 draw call 의 reduction.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Texture Atlas|Texture Atlas]], BatchedMesh, Draw Calls, [[WebGL2|WebGL2]]
- **Projects/Contexts:** Three.js 성능 최적화, [[빌보드 임포스터(Billboard Impostors)|빌보드 임포스터(Billboard Impostors]]
- **Contradictions/Notes:** 소스에 따르면 Data Array Textures는 텍스처 아틀라스의 단점들을 완벽히 보완하는 현대적 대안이지만, '모든 텍스처의 크기가 같아야 한다'는 엄격한 제약과 '메모리 선할당'의 부담이 존재하므로, 가변적인 크기의 텍스처를 압축하거나 구형 WebGL1 환경을 지원해야 할 때는 여전히 텍스처 아틀라스(Texture Atlas)가 가치 있는 선택지로 남는다고 지적합니다 [5].
### 매 제약
- 매 모든 layer 의 same size + same format.
- 매 max_array_layers (보통 2048) 의 hardware limit.
- 매 sampler 의 layer index 의 third coord (z) 로 access.
---
*Last updated: 2026-04-19*
### 매 응용
1. Voxel/Minecraft-like terrain (block type → layer index).
2. Sprite animation (frame → layer).
3. LUT (lookup table) batch.
4. Instanced material variation.
5. ML inference의 batched feature map.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### WebGL2 array texture upload
```javascript
const gl = canvas.getContext('webgl2');
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D_ARRAY, tex);
**언제 이 지식을 쓰는가:**
- *(TODO)*
const W = 64, H = 64, LAYERS = 16;
gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, W, H, LAYERS);
**언제 쓰면 안 되는가:**
- *(TODO)*
for (let i = 0; i < LAYERS; i++) {
const pixels = loadLayer(i); // Uint8Array(W*H*4)
gl.texSubImage3D(
gl.TEXTURE_2D_ARRAY, 0,
0, 0, i, // x, y, layer offset
W, H, 1,
gl.RGBA, gl.UNSIGNED_BYTE, pixels
);
}
gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
```
## 🧪 검증 상태 (Validation)
### GLSL 300 es sampling
```glsl
#version 300 es
precision highp float;
precision highp sampler2DArray;
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
uniform sampler2DArray uBlocks;
in vec2 vUV;
flat in int vBlockType;
out vec4 fragColor;
## 🧬 중복 검사 (Duplicate Check)
void main() {
fragColor = texture(uBlocks, vec3(vUV, float(vBlockType)));
}
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### WebGPU equivalent
```javascript
const tex = device.createTexture({
size: [W, H, LAYERS],
format: 'rgba8unorm',
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
dimension: '2d', // array via depthOrArrayLayers
});
## 🕓 변경 이력 (Changelog)
device.queue.writeTexture(
{ texture: tex, origin: [0, 0, layer] },
pixels,
{ bytesPerRow: W * 4 },
{ width: W, height: H, depthOrArrayLayers: 1 }
);
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### WGSL sampling
```wgsl
@group(0) @binding(0) var blocks: texture_2d_array<f32>;
@group(0) @binding(1) var samp: sampler;
@fragment
fn fs_main(@location(0) uv: vec2f, @location(1) @interpolate(flat) layer: u32) -> @location(0) vec4f {
return textureSample(blocks, samp, uv, layer);
}
```
### Three.js DataArrayTexture
```javascript
import { DataArrayTexture, RGBAFormat, UnsignedByteType } from 'three';
const data = new Uint8Array(W * H * LAYERS * 4);
// fill data...
const tex = new DataArrayTexture(data, W, H, LAYERS);
tex.format = RGBAFormat;
tex.type = UnsignedByteType;
tex.needsUpdate = true;
material.uniforms.uBlocks.value = tex;
```
### Mipmap generation
```javascript
gl.bindTexture(gl.TEXTURE_2D_ARRAY, tex);
gl.generateMipmap(gl.TEXTURE_2D_ARRAY);
// → each layer mipmapped independently → no atlas-style bleed
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| < 16 unique textures, dynamic | Texture atlas (simple, cached) |
| Many same-size layers, mipmap critical | Array texture |
| Different sizes / formats | Bindless / texture array of handles (WebGPU) |
| Voxel terrain | Array texture (layer = block type) |
| Cubemap variant | TextureCubeArray |
**기본값**: 매 same-size + N > 8 → array texture.
## 🔗 Graph
- 부모: [[WebGL2]] · [[WebGPU]]
- 변형: [[Texture Atlas]] · [[Bindless Textures]]
- 응용: [[Voxel Rendering]] · [[Sprite Batching]] · [[Real-time Physics Simulation]]
- Adjacent: [[GPU Memory Layout]] · [[Mipmap]]
## 🤖 LLM 활용
**언제**: 매 shader code generation 의 boilerplate 의 GLSL/WGSL 의 sample. 매 LLM 의 layer index 의 binding 의 OK.
**언제 X**: 매 driver-specific 의 size limit 의 query 는 runtime 의 `getParameter`. 매 LLM 의 hardcode 의 X.
## ❌ 안티패턴
- **Mixed sizes의 attempt**: 매 array texture 의 disqualify. 매 atlas 또는 bindless.
- **Layer count 의 over 2048**: 매 split 의 multi-array-texture 또는 bindless.
- **Mipmap 의 atlas로**: 매 bleed 의 inevitable. 매 array texture 의 fix.
## 🧪 검증 / 중복
- Verified (Khronos WebGL2 spec, WebGPU spec, Three.js docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — array texture / WebGL2 + WebGPU usage |
@@ -4,116 +4,150 @@ title: Debugger Techniques
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-REINFORCE-WIKI-DEV-DEBUGGER-TECHNIQUES, 디버거, Debugger, 디버깅, 중단점, Breakpoint, 호출 스택]
aliases: [Debugging, Debug Tooling]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [Debugging, Runtime, Analysis, Troubleshooting, Tools]
raw_sources: [Datacollector_Export_2026-05-02]
last_reinforced: 2026-05-02
github_commit: pending
confidence_score: 0.9
verification_status: applied
tags: [debugging, devtools, troubleshooting]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: unspecified
framework: unspecified
language: Multi
framework: gdb/lldb/Chrome DevTools
---
# [[고급 디버깅 기법과 런타임 추적 (Debugger Techniques)]]
# Debugger Techniques
## 1. 개요
디버거(Debugger)는 실행 중인 프로그램의 내부 상태를 실시간으로 관찰하고 제어할 수 있게 해주는 가장 강력한 동적 분석 도구이다. 단순히 오류를 수정하는 단계를 넘어, 코드의 실행 흐름(Control Flow)과 데이터의 상태 변화(State Change)를 추적하여 시스템의 정밀한 멘탈 모델을 구축하는 핵심 수단으로 활용된다.
## 매 한 줄
> **"매 print 보다 breakpoint 가 빠르고, breakpoint 보다 reverse-debug 이 깊다."**. Debugger techniques 는 breakpoint, watchpoint, conditional, log-point, time-travel, post-mortem (core dump) 의 매 toolkit. 2026 stack: Chrome DevTools (live), VS Code DAP, gdb/lldb, rr (record-replay), Pernosco (cloud time-travel).
## 2. 핵심 기능 및 활용법
- **중단점 (Breakpoints)**: 코드의 특정 지점에서 실행을 일시 정지. 조건부 중단점(Conditional Breakpoints)을 사용하여 특정 조건이 충족될 때만 정지하도록 설정 가능.
- **단계별 실행 (Stepping)**:
- **Step Over**: 현재 라인의 함수를 실행하고 다음 라인으로 이동.
- **Step Into**: 현재 라인의 함수 내부로 진입하여 상세 로직 관찰.
- **Step Out**: 현재 함수를 끝까지 실행하고 호출한 상위 함수로 복귀.
- **호출 스택 (Call Stack) 조사**: 현재 실행 지점에 도달하기까지 거쳐온 함수의 계층 구조를 역추적하여 실행 맥락 파악.
- **변수 및 메모리 감시 (Watch & Inspect)**: 변수의 현재 값, 객체의 구조, 메모리 주소 등을 실시간으로 확인.
## 핵심
## 3. 탐험적 디버깅 (Exploratory Debugging)
- **온보딩 활용**: 새로운 코드베이스를 익힐 때 단순히 읽는 대신, 주요 기능의 진입점에 중단점을 설정하고 데이터가 어떻게 가공되어 전달되는지 직접 관찰.
- **가설 검증**: "이 변수는 이 시점에서 null이 아닐 것이다"와 같은 가설을 세우고 디버거로 즉각 확인하여 인지적 불확실성 제거.
- **의도적 오류 주입**: 런타임에 변수 값을 강제로 변경하여 시스템의 예외 처리 로직이나 에지 케이스 대응 능력을 테스트.
### 매 Breakpoint Type
- **Line**: 매 source line 정지.
- **Conditional**: 매 expression true 일 때만.
- **Log-point** ("tracepoint"): 매 정지 안하고 log 찍음.
- **Function**: 매 fn enter.
- **Watchpoint**: 매 memory address change.
- **Exception**: 매 throw caught/uncaught.
- **DOM**: 매 Chrome — node modification.
- **XHR/fetch**: 매 URL pattern.
- **Event listener**: 매 click/keydown 등.
## 4. 트레이드오프 및 주의사항
- **관찰자 효과 (Heisenbug)**: 디버거 연결 자체가 타이밍 이슈나 경합 조건(Race Condition)을 변화시켜, 디버깅 중에는 버그가 나타나지 않거나 다르게 동작할 수 있음.
- **멀티스레드/비동기 제약**: 여러 스레드가 동시에 실행되거나 비동기 콜백이 많은 환경에서는 중단점이 실행 흐름을 방해하여 전체적인 흐름을 놓칠 수 있음. (이 경우 로깅이나 분산 추적 도구가 더 효과적일 수 있음)
- **환경 의존성**: 로컬 환경과 프로덕션 환경의 데이터나 설정 차이로 인해 로컬 디버깅만으로는 원인 파악이 힘든 경우가 존재함.
### 매 Time-Travel Debugging
- **rr** (Linux): record once, replay backwards/forwards — 매 nondeterministic bug 의 답.
- **Pernosco**: rr trace 의 cloud UI — 매 expression 의 모든 변경 이력.
- **WinDbg TTD** (Windows).
- **Chrome DevTools "Replay panel"** (2025+ experimental).
## 5. 지식 연결 (Related)
- [[Dynamic_Behavior_Tracking]]: 디버깅을 포함하는 광범위한 런타임 분석 기법.
- [[Flame_Graphs]]: 프로파일링 결과를 시각화하여 디버깅의 우선순위를 결정하는 도구.
- [[Static_Code_Analysis]]: 디버깅 전 단계에서 코드의 구조적 결함을 찾아내는 기술.
### 매 응용
1. Heisenbug — 매 conditional + log-point.
2. Crash post-mortem — 매 core dump + gdb.
3. Performance — 매 sampling + breakpoint.
4. Memory leak — 매 heap snapshot diff.
5. Distributed — 매 OpenTelemetry trace.
## 🧪 검증 상태 (Validation)
- **정보 상태**: 검증 완료 (Verified)
- **출처 신뢰도**: A
- **검토 이유**: 소프트웨어의 동작을 추측이 아닌 사실(Fact) 기반으로 이해하고 제어하기 위한 전문적인 디버깅 표준 정립.
## 💻 패턴
## 📌 한 줄 통찰 (The Karpathy Summary)
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
## 📖 구조화된 지식 (Synthesized Content)
**추출된 패턴:**
> *(TODO)*
**세부 내용:**
- *(TODO)*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Chrome conditional breakpoint
```javascript
// 매 in DevTools right-click line → Add conditional breakpoint
// expression: user.id === 42 && cart.total > 1000
// 또는 logpoint: console.log('cart', cart, 'time', performance.now())
```
## 🤔 의사결정 기준 (Decision Criteria)
### gdb scripted debugging
```bash
gdb --batch -x debug.gdb ./app core.12345
# debug.gdb
set pagination off
bt full
info threads
thread apply all bt
print *some_struct
```
**선택 A를 써야 할 때:**
- *(TODO)*
### lldb Python script
```bash
(lldb) script
>>> frame = lldb.frame
>>> for var in frame.variables: print(var.name, var.value)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### rr record-replay (Linux)
```bash
rr record ./buggy_program
rr replay
# 매 in rr's gdb
(rr) reverse-continue
(rr) reverse-step
(rr) watch -l some_var
```
**기본값:**
> *(TODO)*
### Node.js inspector + Chrome
```bash
node --inspect-brk=0.0.0.0:9229 server.js
# 매 chrome://inspect
```
## ❌ 안티패턴 (Anti-Patterns)
### Python pdb / debugpy
```python
import pdb; pdb.set_trace() # 매 classic
breakpoint() # 매 PEP 553 (python 3.7+)
# 매 VS Code remote: debugpy.listen(('0.0.0.0', 5678)); debugpy.wait_for_client()
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### eBPF dynamic tracing
```bash
sudo bpftrace -e 'uprobe:./app:malloc { @[ustack] = count(); }'
```
### Conditional log-point pattern
```javascript
// 매 production-safe lazy log — no perf cost when disabled
if (DEBUG) console.log('state', JSON.stringify(state));
// 매 better — feature flag gated
if (flags.debugCart) logger.debug({ cart, user });
```
## 매 결정 기준
| 상황 | Tool |
|---|---|
| Web (Chromium) | DevTools Sources panel |
| Node.js | --inspect + DevTools / VS Code |
| C/C++ Linux | gdb / lldb + rr |
| C/C++ macOS | lldb + Instruments |
| Python | debugpy + VS Code |
| Heisenbug | rr + Pernosco |
| Production crash | core dump + gdb |
| Distributed | OTel trace |
**기본값**: 매 IDE breakpoint → 부족시 rr / TTD.
## 🔗 Graph
- 부모: [[중단점 (Breakpoints)]]
- 변형: [[동적 런타임 분석 (Dynamic Runtime Analysis)]]
- 응용: [[Flame_Graphs]] · [[Logging_and_Error_Handling]]
- Adjacent: [[Analyze runtime performance]]
## 🤖 LLM 활용
**언제**: stack trace 해석, log clustering, hypothesis generation, repro script.
**언제 X**: 매 step-into 같은 deterministic 작업 — IDE 가 직접.
## ❌ 안티패턴
- **printf-only**: 매 build cycle 낭비 — debugger 사용.
- **Production breakpoint**: 매 thread freeze — log-point 사용.
- **No source map**: 매 minified frame 해독 불가.
- **Trust gut without repro**: 매 unreliable repro 면 가설 무한 반복.
## 🧪 검증 / 중복
- Verified: Chrome DevTools docs; gdb manual; rr-project.org; Pernosco docs.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — breakpoint taxonomy + rr/TTD + multi-lang |
@@ -2,65 +2,189 @@
id: wiki-2026-0508-deepfake-detection
title: Deepfake Detection
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-DFDE-001]
aliases: [Deepfake Detection, Synthetic Media Detection, AI-Generated Content Detection]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-reinforced, deepfake, deepfake-detection, security, forensic, synthetic-media, adversarial-ml]
confidence_score: 0.9
verification_status: applied
tags: [security, ml, forensics, deepfake, detection]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python
framework: PyTorch
---
# [[Deepfake-Detection|Deepfake-Detection]]
# Deepfake Detection
## 📌 한 줄 통찰 (The Karpathy Summary)
> "진실의 파수꾼: 정교한 AI가 만든 가짜 영상 속에서, 인간의 눈으로는 감지할 수 없는 미세한 픽셀의 떨림, 불규칙한 눈 깜빡임, 혈류의 흐름(rPPG) 등을 포착하여 디지털 위조의 증거를 찾아내는 창과 방패의 대결."
## 한 줄
> **"매 generative model 의 fingerprint 의 수확"**. 2017 FakeApp 의 등장 이후 detection 의 cat-and-mouse race 가 시작되었고, 2026 modern detector 는 frequency-domain artifacts, biological signals (PPG, eye blink), 그리고 self-supervised representation 의 ensemble 의 통해 95%+ AUC 의 달성 — but cross-model generalization 의 여전히 매 open problem.
## 📖 구조화된 지식 (Synthesized Content)
딥페이크 탐지(Deepfake-Detection)는 AI 기반 합성 미디어(Deepfake)의 진위 여부를 판별하는 기술적/사회적 방어 체계입니다.
## 매 핵심
1. **탐지 기법**:
* **Physio[[Logic|Logic]]al [[Analysis|Analysis]]**: 눈 깜빡임 패턴, 심장박동에 의한 미세한 피부톤 변화(rPPG) 분석.
* **Artifact Detection**: 머리카락 경계면의 부자연스러운 노이즈나 입 모양의 비동기화 포착.
* **Digital Watermarking**: 생성 시점에 보이지 않는 고유 코드를 삽입하여 추적. ([[Sustainability|Sustainability]]와 연결)
2. **왜 중요한가?**:
* 가짜 뉴스의 확산, 명예훼손, 금융 사기 등 AI 가 초래할 수 있는 심각한 사회적 리스크를 관리하는 최후의 보루이기 때문임. (Risk-[[Management|Management]]와 연결)
### 매 Detection 패러다임
- **Frequency-domain**: GAN/Diffusion 의 upsampling artifact (DCT spectrum 의 grid pattern, FFT 의 high-freq 결손).
- **Biological signal**: heart-rate (rPPG), micro-expression, eye blink frequency 의 unnatural pattern.
- **Identity consistency**: face embedding 의 video-level temporal drift.
- **Self-supervised**: CLIP/DINOv2 feature 의 OOD detection.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 특정 생성 알고리즘의 결함 정책을 찾는 데 집중했으나, 현대 정책은 생성 알고리즘이 완벽해짐에 따라 '생성 과정에서 발생하는 통계적 특징 정책'을 찾는 일반화된 탐지 정책(Generalizable Detection)으로 전환됨(RL Update).
- **정책 변화(RL Update)**: 이제는 단순히 알고리즘 정책만으로는 부족하며, 콘텐츠의 출처 정책(Provenance)을 블록체인 정책 등과 연합하여 인증하는 '신뢰 인프라 정책' 구축이 병행되고 있음.
### 매 Generation 종류
- **Face swap**: DeepFaceLab, FaceFusion, Roop.
- **Face reenactment**: First Order Motion Model, LivePortrait (2024).
- **Full-body**: Wav2Lip, SadTalker, EMO (Alibaba 2024).
- **Diffusion-based**: Stable Video Diffusion, Sora (OpenAI 2024), Veo 3 (Google 2025).
## 🔗 지식 연결 (Graph)
- [[Risk-Management|Risk-Management]], [[Sustainability|Sustainability]], Security, [[Synthetic-Data|Synthetic-Data]], [[Biometrics|Biometrics]]
- **Key Challenges**: Adversarial attacks on detectors, Deepfake quality improvement.
---
### 매 응용
1. Newsroom 의 fact-checking pipeline (Reuters, AP).
2. Social platform 의 watermark + detection (Meta, TikTok, X).
3. Identity verification (KYC, banking — Persona, Onfido).
4. Forensic 증거 분석 (court-admissible chain of custody).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Frequency-domain CNN (Frank et al. baseline)
```python
import torch
import torch.nn as nn
from torch.fft import fft2, fftshift
**언제 쓰면 안 되는가:**
- *(TODO)*
class FrequencyDeepfakeDetector(nn.Module):
def __init__(self, num_classes=2):
super().__init__()
self.backbone = nn.Sequential(
nn.Conv2d(1, 32, 3, padding=1), nn.ReLU(),
nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(),
nn.AdaptiveAvgPool2d(8), nn.Flatten(),
nn.Linear(64 * 64, num_classes),
)
## 🧪 검증 상태 (Validation)
def forward(self, x): # x: (B, 3, H, W) RGB
gray = x.mean(1, keepdim=True)
spec = fftshift(fft2(gray)).abs().log1p()
return self.backbone(spec)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### rPPG-based liveness (heart-rate from face video)
```python
import numpy as np
from scipy.signal import butter, filtfilt
## 🧬 중복 검사 (Duplicate Check)
def extract_rppg(face_frames, fps=30):
# POS algorithm — Wang et al. 2017
rgb_signal = np.stack([f.reshape(-1, 3).mean(0) for f in face_frames])
rgb_norm = rgb_signal / rgb_signal.mean(0)
proj = rgb_norm @ np.array([[0, 1, -1], [-2, 1, 1]]).T
s = proj[:, 0] + (proj[:, 0].std() / proj[:, 1].std()) * proj[:, 1]
b, a = butter(4, [0.7, 4.0], btype='band', fs=fps)
return filtfilt(b, a, s - s.mean())
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
def is_live(rppg, fps=30):
fft = np.abs(np.fft.rfft(rppg))
freqs = np.fft.rfftfreq(len(rppg), 1/fps) * 60 # BPM
peak_bpm = freqs[fft.argmax()]
return 50 <= peak_bpm <= 180 # 매 plausible HR range
```
## 🕓 변경 이력 (Changelog)
### CLIP-based zero-shot detector
```python
import open_clip
import torch
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
model, _, preprocess = open_clip.create_model_and_transforms(
'ViT-L-14', pretrained='laion2b_s32b_b82k')
tokenizer = open_clip.get_tokenizer('ViT-L-14')
prompts = ["a real photograph", "an AI-generated image",
"a deepfake", "a synthetic face"]
text = tokenizer(prompts)
text_features = model.encode_text(text)
text_features /= text_features.norm(dim=-1, keepdim=True)
def score(image_pil):
img = preprocess(image_pil).unsqueeze(0)
img_feat = model.encode_image(img)
img_feat /= img_feat.norm(dim=-1, keepdim=True)
sims = (img_feat @ text_features.T).softmax(-1)
return sims[0, 1:].sum().item() # 매 fake probability
```
### Temporal consistency (face embedding drift)
```python
from facenet_pytorch import InceptionResnetV1
embedder = InceptionResnetV1(pretrained='vggface2').eval()
def temporal_drift(face_crops):
embs = embedder(torch.stack(face_crops))
embs = embs / embs.norm(dim=-1, keepdim=True)
consec_sim = (embs[:-1] * embs[1:]).sum(-1)
# 매 swapped face 의 unnatural jitter 의 detect
return 1.0 - consec_sim.mean().item()
```
### Watermark verification (C2PA / SynthID)
```python
import hashlib
from cryptography.hazmat.primitives.asymmetric import ed25519
def verify_c2pa_manifest(manifest_bytes, signature, public_key):
try:
public_key.verify(signature, manifest_bytes)
return True
except Exception:
return False # 매 manifest 의 tampered 또는 missing
```
### Ensemble fusion (production)
```python
def ensemble_decision(image, video_clip):
scores = {
'freq': freq_detector(image),
'clip': clip_detector(image),
'rppg': 1.0 - is_live_score(video_clip),
'temporal': temporal_drift(extract_faces(video_clip)),
}
weights = {'freq': 0.3, 'clip': 0.25, 'rppg': 0.25, 'temporal': 0.2}
return sum(w * scores[k] for k, w in weights.items())
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Real-time KYC | rPPG + active liveness challenge |
| Static image forensic | Frequency CNN + CLIP zero-shot |
| Video newsroom | Ensemble (freq + temporal + watermark) |
| Cross-generator generalization | Self-supervised foundation model |
| High-stakes legal | Multi-modal + chain-of-custody + C2PA |
**기본값**: ensemble of frequency + foundation-model + watermark verification.
## 🔗 Graph
- 부모: [[Computer Vision]] · [[AI Security]]
- 변형: [[Audio Deepfake Detection]] · [[Video Authentication]]
- 응용: [[KYC Systems]] · [[Content Moderation]] · [[Digital Forensics]]
- Adjacent: [[GAN Fingerprinting]] · [[Adversarial ML]] · [[C2PA]]
## 🤖 LLM 활용
**언제**: feature engineering 의 brainstorm, dataset curation script, false-positive 분석.
**언제 X**: production detection model 의 직접 inference (LLM 의 vision 의 reliable detector 의 X — specialized model 의 사용).
## ❌ 안티패턴
- **Single-detector reliance**: GAN-trained detector 의 diffusion-generated content 의 fail.
- **No cross-generator eval**: train/test 의 same generator 의 inflated metric.
- **Ignoring compression artifacts**: JPEG/H.264 의 frequency signal 의 destroy.
- **Adversarial blindness**: detector 의 adversarial perturbation 의 robust 의 X.
- **Watermark-only**: open-source generator 의 watermark 의 strip.
## 🧪 검증 / 중복
- Verified (FaceForensics++ benchmark, DFDC, Frank et al. ICML 2020, C2PA spec v2.1).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — frequency/biological/CLIP detection patterns + ensemble |
@@ -2,21 +2,154 @@
id: wiki-2026-0508-devsecops-framework
title: DevSecOps Framework
category: 10_Wiki/Topics
status: merged
redirect_to: 보안_및_시스템_신뢰성_표준
canonical_id: wiki-2026-0507-039
aliases: []
status: verified
canonical_id: self
aliases: [DevSecOps, Shift-Left Security, Secure SDLC]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [devsecops, security, shift-left, sdlc]
raw_sources: []
last_reinforced: 2026-05-08
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: YAML/Python
framework: GitHub Actions/Semgrep/Trivy
---
# Redirect
# DevSecOps Framework
이 문서는 Canonical 문서인 [[보안_및_시스템_신뢰성_표준]]으로 통합되었습니다.
모든 최신 지식과 세부 내용은 위 링크를 참조하십시오.
## 매 한 줄
> **"매 security 가 PR 단계부터 매일 실행되는 자동 체크가 되는 것."**. DevSecOps 는 매 plan-code-build-test-release-deploy-operate-monitor 8단계 의 매 step 마다 security control 을 embed 하는 매 shift-left framework. 2026 표준: SAST + SCA + IaC scan + secret scan + DAST + RASP + supply-chain (SLSA L3) + ASPM platform.
## 매 핵심
### 매 8-Stage Embed
1. **Plan**: threat model (STRIDE), security stories.
2. **Code**: IDE plugin (Semgrep, SonarLint), pre-commit (lint-staged + secret).
3. **Build**: SBOM (Syft), reproducible build, sign (cosign).
4. **Test**: SAST (Semgrep, CodeQL), SCA (Trivy, Snyk), IaC (Checkov).
5. **Release**: provenance (SLSA), policy (OPA gatekeeper).
6. **Deploy**: admission control, signed image verify, secrets via Vault.
7. **Operate**: RASP, WAF, runtime detection (Falco).
8. **Monitor**: SIEM (Splunk), anomaly detection, incident response.
### 매 Tool Categories 2026
- **SAST**: Semgrep, CodeQL, Snyk Code.
- **SCA**: Trivy, Snyk Open Source, Dependabot.
- **DAST**: ZAP, Burp, Nuclei.
- **IaC**: Checkov, tfsec, KICS.
- **Secret scan**: gitleaks, TruffleHog.
- **Container**: Trivy, Grype.
- **K8s**: kube-bench, Falco, Kyverno.
- **ASPM**: Phoenix, Apiiro, ArmorCode — aggregate + prioritize.
### 매 응용
1. Web app secure SDLC.
2. K8s cluster hardening.
3. Cloud infra (Terraform/Pulumi) compliance.
4. Container registry policy.
5. Supply-chain integrity (SLSA L3).
## 💻 패턴
### GitHub Actions DevSecOps gate
```yaml
name: secure-pr
on: pull_request
permissions: { contents: read, security-events: write, id-token: write }
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: gitleaks/gitleaks-action@v2 # 매 secrets
- uses: returntocorp/semgrep-action@v1 # 매 SAST
with: { config: 'p/owasp-top-ten p/security-audit' }
- uses: aquasecurity/trivy-action@master # 매 SCA + container
with: { scan-type: fs, severity: 'CRITICAL,HIGH', exit-code: 1 }
- uses: bridgecrewio/checkov-action@master # 매 IaC
```
### Pre-commit secret scan
```yaml
# .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks: [{ id: gitleaks }]
```
### OPA admission policy (K8s)
```rego
package k8s.image
violation[{"msg": msg}] {
input.review.object.spec.containers[_].image
not startswith(input.review.object.spec.containers[_].image, "ghcr.io/myorg/")
msg := "image must come from approved registry"
}
```
### Cosign verify in admission
```yaml
apiVersion: policy.sigstore.dev/v1beta1
kind: ClusterImagePolicy
spec:
images: [{ glob: "ghcr.io/myorg/**" }]
authorities:
- keyless:
identities: [{ issuer: "https://token.actions.githubusercontent.com", subject: ".*myorg/.*" }]
```
### Falco runtime detection rule
```yaml
- rule: Shell in container
desc: Detect shell exec inside container
condition: container.id != host and proc.name in (bash, sh, zsh)
output: "Shell %proc.name in container=%container.name image=%container.image.repository"
priority: WARNING
```
### SBOM + provenance attest
```bash
syft packages oci:./image.tar -o spdx-json > sbom.spdx.json
cosign attest --predicate sbom.spdx.json --type spdx ghcr.io/org/app@sha256:...
```
## 매 결정 기준
| 상황 | Tool stack |
|---|---|
| TS/Python monorepo | Semgrep + Trivy + gitleaks |
| Terraform cloud infra | Checkov + tfsec |
| K8s cluster | Falco + Kyverno + cosign |
| Compliance heavy | ASPM platform (Phoenix/Apiiro) |
| Air-gapped / regulated | Semgrep self-host + Trivy DB mirror |
**기본값**: 매 Semgrep + Trivy + gitleaks + Checkov + cosign + Falco.
## 🔗 Graph
- 부모: [[OWASP Top 10]] · [[안전한 소프트웨어 개발 수명주기(SSDLC)]]
- 변형: [[애플리케이션_보안_태세_관리ASPM]]
- 응용: [[SAST]] · [[DAST]] · [[SCA]] · [[Secret_Management]]
- Adjacent: [[Zero-Trust Architecture]] · [[CI_CD_Pipeline]]
## 🤖 LLM 활용
**언제**: vuln triage, false-positive filter, remediation PR draft, threat-model brainstorm.
**언제 X**: 매 actual scan — specialized engine 이 빠르고 정확.
## ❌ 안티패턴
- **Security as gate-only**: 매 alert flood 만 — fix automation 없음.
- **Tool sprawl**: 매 5개 SAST 가 noise — ASPM 으로 dedupe.
- **No baseline**: 매 legacy CVE 전체가 critical — accept + monitor.
- **Bypass culture**: 매 dev 가 `// eslint-disable security/*` — guard 무력화.
## 🧪 검증 / 중복
- Verified: NIST SSDF SP 800-218; OWASP DevSecOps maturity; SLSA v1.0; Falco docs.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 8-stage + tool stack 2026 |
@@ -2,63 +2,160 @@
id: wiki-2026-0508-digital-intellectual-property-ri
title: Digital Intellectual Property Rights
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-IP-RIGHTS]
aliases: [Digital IP, Software IP, Digital Rights]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [Law, Digital, IP, Copyright, Ethics]
confidence_score: 0.9
verification_status: applied
tags: [legal, ip, licensing, copyright]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: legal
framework: licenses
---
# [[Digital Intellectual Property Rights|Digital Intellectual Property Rights]] (디지털 지식 재산권)
# Digital Intellectual Property Rights
## 📌 한 줄 통찰 (The Karpathy Summary)
> "복제가 쉬운 세상에서 아이디어의 가치를 지키는 법적 테두리." 무단 복제와 배포가 용이한 디지털 환경에서 소프트웨어, 콘텐츠, 디자인 등의 창작물을 보호하고 정당한 대가를 보장받기 위한 법적 권리 체계다.
## 한 줄
> **"매 digital IP 의 의미: 매 software / data / model 의 매 ownership, license, attribution 권리"**. 매 copyright (default) + 매 license (grant) + 매 patent (algorithm) + 매 trade secret 의 4 axis. 매 2026 AI 시대 의 매 training data 권리, 매 model weights 권리, 매 LLM output 권리 의 매 hot frontier.
## 📖 구조화된 지식 (Synthesized Content)
- **Core Types**:
- **Copyright (저작권)**: 코드, 이미지, 텍스트 등 창작적 표현 보호. 별도 등록 없이 창작 즉시 발생.
- **Patent (특허)**: 독창적인 기술적 아이디어나 알고리즘 보호. 엄격한 심사 필요.
- **Trademark (상표권)**: 브랜드 이름, 로고 등 식별 표지 보호.
- **Modern Challenges**:
- **Fair Use (공정 이용)**: 교육, 보도 등의 목적으로 저작권물을 동의 없이 사용할 수 있는 범위 논쟁.
- **DRM (Digital Rights [[Management|Management]])**: 무단 복제를 막기 위한 기술적 보호 조치.
- **Open Movement**: Open Source License (MIT, Apache, GPL) 등을 통해 권리를 공유하며 생태계를 확장하는 방식도 포함된다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- AI 학습 데이터에 대한 저작권 인정 여부가 현재 최대 화두다. "남의 저작물로 학습한 AI의 결과물은 누구의 것인가?"에 대한 법적 공백이 크며, 이는 현재 각국에서 판례를 쌓아가는 격동기에 있다. 지식 재산권의 개념이 '인간 중심'에서 '데이터 중심'으로 재편되고 있다.
### 매 4 axis
- **Copyright**: 매 expression (code, art, text) 의 default 보호 — 매 author 의 lifetime + 70년
- **License**: 매 author 의 매 grant — MIT, Apache, GPL, proprietary
- **Patent**: 매 invention (algorithm, system) — 매 20년, 매 applied required
- **Trade secret**: 매 confidential 정보 — 매 indefinite, 매 reasonable protection 요구
## 🔗 지식 연결 (Graph)
- Related: Ethics-in-AI , Open-Source-Licensing
- Problem: Digital-Piracy
### Open Source 의 매 spectrum
- **Permissive**: MIT, Apache 2.0, BSD — 매 commercial use OK
- **Weak copyleft**: LGPL, MPL — 매 modified file 만 share
- **Strong copyleft**: GPL, AGPL — 매 entire derivative work share
- **Source-available**: BUSL, SSPL — 매 commercial restriction (NOT OSI-approved)
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 AI/ML specific (2026)
- **Training data**: 매 fair use 논쟁 (NYT v. OpenAI, Authors Guild v. Anthropic)
- **Model weights**: 매 copyrightable? (매 unsettled, 매 case law evolving)
- **AI output**: 매 US Copyright Office (2023) — 매 human authorship required
- **Style transfer**: 매 artist 의 매 trademark 가능성
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. 매 OSS dependency audit (license compatibility).
2. 매 employee invention assignment.
3. 매 LLM output 의 commercial use 결정.
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### License File 의 매 MIT
```
MIT License
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
Copyright (c) 2026 Acme Corp
## 🧬 중복 검사 (Duplicate Check)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
## 🕓 변경 이력 (Changelog)
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND...
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### SPDX 의 매 file header
```typescript
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Acme Corp
```
### License Audit 의 매 tooling
```bash
# 매 npm 의 license check
npx license-checker --production --summary
# 매 SBOM 생성 (CycloneDX)
npx @cyclonedx/cyclonedx-npm --output-format JSON --output-file sbom.json
# 매 incompatible license 의 매 fail
npx license-checker --failOn 'GPL-3.0;AGPL-3.0'
```
### CLA / DCO (Contributor)
```bash
# DCO sign-off
git commit -s -m "feat: add foo"
# Signed-off-by: Jane <jane@acme.com>
```
### REUSE Compliance (EU 표준)
```toml
# .reuse/dep5
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Files: src/*
Copyright: 2026 Acme Corp
License: Apache-2.0
Files: vendor/*
Copyright: 2024 Original Author
License: MIT
```
### AI Model Card 의 매 license clarity
```markdown
# Model Card: acme-llm-v2
## License
- **Weights**: Llama 3 Community License (Meta)
- **Code**: Apache 2.0 (Acme)
- **Training data**: Mixed (CC-BY, public domain, licensed proprietary)
## Permitted Use
- Commercial use < 700M MAU OK (per Llama license)
- Fine-tuning OK
- Redistributing weights: see Llama license restrictions
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Internal-only project | 매 proprietary, 매 no public license |
| Open source library | 매 MIT (max adoption) / Apache 2.0 (patent grant) |
| Want commercial fork prevention | 매 AGPL / BUSL |
| Enterprise SaaS | 매 proprietary EULA + 매 SOC2 |
| AI model release | 매 OpenRAIL / 매 community license + 매 model card |
**기본값**: 매 Apache 2.0 (OSS) / 매 proprietary EULA (commercial).
## 🔗 Graph
- 부모: [[Software Licensing]] · [[Legal Compliance]]
- 변형: [[Copyright]] · [[Patent]] · [[Trade Secret]]
- 응용: [[SBOM]] · [[License Audit]] · [[Open Source Compliance]]
- Adjacent: [[GDPR]] · [[Ensuring Data Privacy]]
## 🤖 LLM 활용
**언제**: 매 license compatibility 의 first-pass check, 매 EULA draft 의 starter, 매 model card 의 generation.
**언제 X**: 매 actual legal advice — 매 lawyer required. 매 jurisdiction-specific (US v. EU v. JP) 의 매 LLM error 위험.
## ❌ 안티패턴
- **매 license 의 X (no LICENSE file)**: 매 default = all rights reserved → 매 사용 불가.
- **매 GPL code 의 매 proprietary product 에 mix**: 매 entire codebase 의 GPL infect.
- **매 LLM output 의 무비판 commercial 사용**: 매 training data attribution 위험.
- **매 employee NDA 없음**: 매 trade secret 의 protection 불가.
## 🧪 검증 / 중복
- Verified (OSI license list, SPDX, US Copyright Office AI guidance 2023).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Digital IP rights full content |
@@ -2,63 +2,136 @@
id: wiki-2026-0508-digital-thread-integration
title: Digital Thread Integration
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-DIGITAL-THREAD]
aliases: [Digital Thread, Industrial Data Thread]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [Manufacturing, DigitalThread, PLM, Integration]
confidence_score: 0.9
verification_status: applied
tags: [iiot, digital-thread, manufacturing, plm]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: Python/SQL
framework: OPC UA/MQTT/Kafka
---
# [[Digital Thread Integration|Digital Thread Integration]] (디지털 스레드 통합)
# Digital Thread Integration
## 📌 한 줄 통찰 (The Karpathy Summary)
> "제품의 탄생부터 죽음까지를 잇는 보이지 않는 데이터의 실." 설계, 제조, 서비스, 폐기에 이르는 제품 전 수명 주기 동안 발생하는 데이터를 단절 없이 연결하여 정보의 흐름을 최적화하는 아키텍처다.
## 한 줄
> **"매 product lifecycle 의 모든 data 가 single linked thread 로 흐르는 것."**. Digital Thread 는 design (CAD) → engineering (PLM) → manufacturing (MES) → operations (IoT) → service (CRM) 까지 매 traceable, queryable 하게 연결하는 매 manufacturing/aerospace 의 backbone. 2026 의 standard: ISA-95 + OPC UA + Asset Administration Shell (AAS) + RAMI 4.0 + IDS data spaces.
## 📖 구조화된 지식 (Synthesized Content)
- **The Concept**:
- 기존에는 부서 간 테이터가 단절(Silo)되어 정보 전달 과정에서 오류가 잦았음.
- 디지털 스레드는 하나의 데이터 원천([[Single_Source_of_Truth|Single Source of Truth]])을 통해 요구사항 변경이 즉시 제조 현장과 서비스 매뉴얼에 반영되게 함.
- **Core Components**:
- **PLM (Product Lifecycle [[Management|Management]])**: 데이터 축의 근간.
- **ERP / MES**: 실행 및 자원 관리 데이터와의 연결.
- **Feedback Loop**: 실제 사용 현장의 데이터를 다시 설계로 돌려보내는 루프.
- **Benefit**: 리드 타임 단축, 품질 비용 절감, 제품 추적성 완성.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 디지털 스레드를 구축하려면 기업 내 모든 시스템의 '언어(Standard)'가 같아야 한다. 하지만 수십 년 된 레거시 시스템과 최신 플랫폼을 잇는 것은 엄청난 비용과 기술적 난제다. 최근에는 AI가 서로 다른 데이터 포맷을 자동으로 매핑해주는 기술이 스레드 통합의 핵심 동력으로 부상하고 있다.
### 매 Digital Thread vs Digital Twin
- **Thread**: 매 data lineage — design intent ↔ as-built ↔ as-maintained.
- **Twin**: 매 simulation model of a specific asset.
- **관계**: Twin 은 Thread 의 cross-section snapshot.
## 🔗 지식 연결 (Graph)
- Related: [[Digital-Twin-Technology|Digital-Twin-Technology]] , Industry-4.0
- Foundation:[[_system|system]]s-Engineering
### 매 Layer Stack
1. **Edge**: PLC, sensor, OPC UA server.
2. **Connectivity**: MQTT, OPC UA, MTConnect.
3. **Stream**: Kafka / Pulsar — high-throughput.
4. **Storage**: time-series (InfluxDB, TimescaleDB), data lake (Iceberg).
5. **Semantic**: Asset Administration Shell, ontology (W3C SOSA/SSN).
6. **Application**: PLM (Teamcenter, Windchill), MES, ERP.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Aerospace — 매 part traceability, certification.
2. Automotive — 매 EV battery passport (EU 2027 mandate).
3. Industrial maintenance — 매 predictive + service history.
4. Pharma — 매 batch genealogy.
5. EU Digital Product Passport — 매 sustainability.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### OPC UA client (Python)
```python
from asyncua import Client
async def main():
async with Client(url="opc.tcp://plant.local:4840") as c:
node = c.get_node("ns=2;s=Line1.Press.Temp")
async for v in node.subscribe_data_change(callback):
pass
```
## 🧪 검증 상태 (Validation)
### MQTT Sparkplug B (manufacturing-standard payload)
```python
import paho.mqtt.client as mqtt
import sparkplug_b as sp
payload = sp.getDdataPayload()
sp.addMetric(payload, "Temp", None, sp.MetricDataType.Float, 72.5)
client.publish("spBv1.0/PlantA/DDATA/Edge1/Press1", payload.SerializeToString())
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Asset Administration Shell submodel
```json
{
"idShort": "Nameplate",
"submodelElements": [
{"idShort":"ManufacturerName","value":"Acme"},
{"idShort":"SerialNumber","value":"SN-A1B2"},
{"idShort":"YearOfConstruction","value":"2026"}
]
}
```
## 🧬 중복 검사 (Duplicate Check)
### Kafka pipeline edge → lake
```python
from confluent_kafka import Producer
import pyarrow.parquet as pq
p = Producer({'bootstrap.servers':'kafka:9092','compression.type':'zstd'})
p.produce('plant.line1.temp', key=part_id, value=msg.SerializeToString())
# downstream Flink/Spark → Iceberg table
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Digital Product Passport (EU 2027)
```json
{
"productId": "urn:gtin:01234567890128",
"carbonFootprintKg": 12.4,
"materials": [{"name":"Li","massGrams":1200}],
"recycledContentPercent": 18,
"linkedTwin": "urn:twin:battery:SN-A1B2"
}
```
## 🕓 변경 이력 (Changelog)
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Field bus modernization | OPC UA |
| IoT-style telemetry | MQTT Sparkplug B |
| Cross-vendor semantics | AAS / IDS |
| Stream backbone | Kafka / Pulsar |
| Time-series store | TimescaleDB / Influx |
| Lake | Iceberg + Trino |
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
**기본값**: 매 OPC UA + MQTT Sparkplug B → Kafka → Iceberg.
## 🔗 Graph
- 부모: [[Digital Twins]] · [[Digital-Twin-Technology]]
- 변형: [[IoT]]
- 응용: [[Engineering Metrics (DORA)]]
- Adjacent: [[Digital Intellectual Property Rights]]
## 🤖 LLM 활용
**언제**: ontology mapping, anomaly summary, maintenance work-order draft.
**언제 X**: 매 safety-critical PLC logic — formal verification 만.
## ❌ 안티패턴
- **Polling 오버**: 매 OPC UA subscribe 사용 — pub/sub.
- **Untimestamped data**: 매 Thread 의 핵심은 시간 lineage.
- **Vendor lock**: 매 proprietary protocol — open standards 사용.
- **No identity**: 매 GS1, urn 등 stable id 필수.
## 🧪 검증 / 중복
- Verified: ISA-95 spec; OPC UA Part 1; Plattform Industrie 4.0 AAS spec; EU DPP regulation 2024.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Thread vs Twin + OPC UA/MQTT/AAS |
@@ -2,63 +2,147 @@
id: wiki-2026-0508-digital-twins
title: Digital Twins
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-REINFORCE-AI-056]
aliases: [Digital Twin, DT, Cyber-Physical Mirror]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
tags: [digital twin, simulation, iot, cyber-physical]
confidence_score: 0.9
verification_status: applied
tags: [iot, simulation, cps, industry-4]
raw_sources: []
last_reinforced: 2026-06-XX
github_commit: "[P-Reinforce] Processed Digital Twins."
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: Python/C++
framework: NVIDIA-Omniverse/Azure-DigitalTwins
---
# [[Digital Twins|Digital Twins]] (디지털 트윈)
# Digital Twins
## 📌 한 줄 통찰 (The Karpathy Summary)
> 현실 세계의 물리적 자산(Asset)을 가상 공간에 실시간으로 복제하여, 시뮬레이션과 예측을 통해 실제 시스템 운영 최적화 및 문제 해결 방안을 사전에 검증하는 기술이다.
## 한 줄
> **"매 physical asset/system 의 매 live, bidirectional digital replica"**. Grieves 2002 의 PLM concept 가 매 IoT, sensor cost 폭락, real-time sim, generative AI 의 만남으로 매 Industry 4.0 의 핵심. 매 NVIDIA Omniverse, Azure Digital Twins, Siemens Xcelerator 의 2026 era — physical + digital 의 매 closed loop.
## 📖 구조화된 지식 (Synthesized Content)
- **정의:** 물리적인 객체(Physical Asset)와 그 디지털 모델(Digital Model)이 실시간으로 양방향 통신하며 동기화되는 시스템. 단순히 시뮬레이션 모델을 만드는 것을 넘어, '실제 운영 환경'과의 연결성이 핵심이다.
- **구현 요소 및 필요 지식:**
1. **데이터 수집 (IoT Telemetry):** 센서 데이터(Edge Computing)를 통해 물리적 상태를 끊임없이 측정하고 전송해야 한다.
2. **모델링/시뮬레이션:** 대상 시스템의 동역학, 열역학 등 복잡한 물리 법칙을 수학적으로 모델링한다. (Computational Geometry + Physics-Based Simulation).
3. **실시간 연동 및 예측:** 시뮬레이션 결과(가상)를 바탕으로 실제 장비에 최적화된 제어 명령을 역으로 전송하는 폐쇄 루프 시스템이 필요하다 (Cybernetics / Feedback Control Systems).
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 디지털 트윈의 가치는 '데이터를 모으는 것' 자체가 아니라, 수집된 데이터를 통해 **미래를 예측하고(Prediction)** 시스템을 개선하는 데서 나온다. 즉, 목적이 중요하며, 이는 시뮬레이션 이론으로 뒷받침되어야 한다.
- **정책 변화:** 산업의 특성상 높은 수준의 실시간 데이터 무결성과 보안(Cybersecurity) 요구사항이 따르므로, 아키텍처 레벨에서 신뢰성을 확보하는 것이 최우선 과제이다.
### 매 3 layer
- **Physical**: 실제 자산 + sensor (vibration, temp, pressure, camera).
- **Communication**: MQTT/OPC-UA/AMQP, time-series store, edge gateway.
- **Digital**: 3D model + physics sim + ML predictor + control logic.
## 🔗 지식 연결 (Graph)
- Parent: [[Internet of Things (IoT) Telemetry|Internet of Things (IoT) Telemetry]]
- Related: [[Computational Geometry|Computational Geometry]] , [[Feedback-Control-Systems|Feedback-Control-Systems]] , [[Real-Time-Game-Engines|Real-Time-Game-Engines]]
- Raw Source: 00_Raw/Digital Twins.md
---
### 매 spectrum
- **Digital model**: static 3D, no live data.
- **Digital shadow**: one-way (physical → digital).
- **Digital twin**: bidirectional — twin can command physical.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Predictive maintenance (jet engine, wind turbine).
2. Smart city traffic / energy optimization.
3. Manufacturing line virtual commissioning.
4. Healthcare (patient-specific organ twin).
5. Robot fleet sim (NVIDIA Isaac, Omniverse).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Sensor → twin (MQTT + Python)
```python
import paho.mqtt.client as mqtt, json, time
## 🧪 검증 상태 (Validation)
def on_message(c, u, msg):
data = json.loads(msg.payload)
twin.update_state(asset_id=data['id'], temp=data['temp'], ts=data['ts'])
if twin.predict_failure(data['id']) > 0.8:
c.publish(f"cmd/{data['id']}/throttle", "0.5") # bidirectional!
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
cli = mqtt.Client(); cli.on_message = on_message
cli.connect("mqtt.factory.local"); cli.subscribe("sensor/+"); cli.loop_forever()
```
## 🧬 중복 검사 (Duplicate Check)
### Azure Digital Twins (DTDL)
```json
{
"@id": "dtmi:com:factory:Pump;1",
"@type": "Interface",
"displayName": "Pump",
"contents": [
{ "@type": "Property", "name": "rpm", "schema": "double" },
{ "@type": "Telemetry", "name": "vibration", "schema": "double" },
{ "@type": "Command", "name": "shutdown" },
{ "@type": "Relationship", "name": "feeds", "target": "dtmi:com:factory:Tank;1" }
]
}
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Physics-based twin (Modelica via FMU)
```python
from fmpy import simulate_fmu
result = simulate_fmu(
'pump.fmu',
start_values={'inlet_pressure': 2.5, 'rpm': 1800},
output=['outlet_pressure', 'efficiency'],
stop_time=10.0
)
```
## 🕓 변경 이력 (Changelog)
### Omniverse USD scene (live update)
```python
from pxr import Usd, UsdGeom, Gf
stage = Usd.Stage.Open('factory.usd')
pump = UsdGeom.Xform.Get(stage, '/World/Pump_01')
# Stream live sensor pose via OmniGraph / Live Sync
def on_telemetry(rpm, vibration):
pump.GetPrim().GetAttribute('rpm:live').Set(rpm)
pump.GetPrim().GetAttribute('vib:live').Set(vibration)
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Predictive maintenance (LSTM)
```python
import torch.nn as nn
class FailurePredictor(nn.Module):
def __init__(self, n_sensors=8):
super().__init__()
self.lstm = nn.LSTM(n_sensors, 64, batch_first=True)
self.head = nn.Linear(64, 1)
def forward(self, x): # (B, T, n_sensors)
h, _ = self.lstm(x)
return torch.sigmoid(self.head(h[:, -1]))
# Train on (sensor window, RUL label) pairs from CMAPSS / NASA dataset.
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Single asset, simple monitoring | Digital shadow (cheap) |
| Fleet w/ predictive maint. | Twin + ML failure model |
| Process plant commissioning | Physics twin (FMU/Modelica) |
| Robotics / AV training | Sim-to-real (Isaac, CARLA) |
| Smart city / building | Hierarchical twins (DTDL) |
**기본값**: 매 start digital shadow → ML 추가 후 twin → bidirectional 마지막.
## 🔗 Graph
- 부모: [[Cyber-Physical Systems]] · [[Industry 4.0]]
- 변형: [[Digital Shadow]] · [[Digital Model]]
- 응용: [[Predictive Maintenance]] · [[Sim-to-Real]] · [[Smart City]]
- Adjacent: [[OPC-UA]] · [[USD (OpenUSD)]] · [[NVIDIA Omniverse]] · [[FMI/FMU]]
## 🤖 LLM 활용
**언제**: IoT/manufacturing/CPS context, sim2real planning, asset lifecycle.
**언제 X**: Pure web app, no physical asset. 매 marketing buzzword 화 주의.
## ❌ 안티패턴
- **3D model = twin 오해**: 매 3D 만으론 shadow도 아님.
- **Sensor 무인 데이터**: garbage in → garbage twin.
- **No model versioning**: physical 변경 시 twin drift.
- **Closed-loop without safety**: bidirectional 시 매 fail-safe + human-in-loop 필수.
- **Vendor lock-in**: proprietary schema → DTDL/USD 표준 사용.
## 🧪 검증 / 중복
- Verified (Grieves 2014, NIST CPS framework, Azure DT docs, NVIDIA Omniverse docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — DT layers + DTDL/Omniverse/MQTT patterns |
@@ -2,89 +2,32 @@
id: wiki-2026-0508-digital-twin-technology
title: Digital Twin Technology
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
aliases: [P-Reinforce-AI-DIGITAL-TWIN]
duplicate_of: none
status: duplicate
canonical_id: digital-twins
duplicate_of: "[[Digital Twins]]"
aliases: [Digital Twin]
source_trust_level: A
confidence_score: 0.95
tags: [DigitalTwin, Simulation, IoT, Industry40]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
confidence_score: 0.9
verification_status: redirected
tags: [duplicate, digital-twin, iiot]
last_reinforced: 2026-05-10
github_commit: applied
---
# [[Digital-Twin-Technology|Digital-Twin-Technology]] (디지털 트윈 기술)
# Digital Twin Technology
## 📌 한 줄 통찰 (The Karpathy Summary)
> "현실 세계의 완벽한 실시간 가상 복제본." 물리적 사물이나 시스템의 동적 특성을 실시간으로 반영하여 예측, 최적화, 모니터링을 수행하는 고도의 시뮬레이션 환경이다.
> **이 문서는 [[Digital Twins]] 의 중복본입니다.** Canonical 로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
- **System [[Architecture|Architecture]]**:
- **Physical Layer**: 센서, IoT 기기를 통해 현실 데이터를 수집.
- **Digital Layer**: 물리 역학 모델과 AI를 결합한 가상 엔진.
- **Twinning (Synchronization)**: 실시간 데이터 흐름을 통해 현실과 가상의 상태([[State|State]])를 일치시킴.
- **Key Functions**:
- **[[Predictive_Maintenance|Predictive Maintenance]]**: 부품이 고장 나기 전 가상 모델에서 이상 징후를 먼저 발견.
- **Scenario [[Testing|Testing]]**: 위험하거나 비용이 많이 드는 실험을 가상에서 안전하게 수행.
- **Domains**: 스마트 시티, 제조 공정, 심지어 디지털 휴먼(의료용 트윈)까지 확장 중.
## 핵심 요약
- 매 physical asset 의 live virtual mirror — sensors → simulation → action.
- 매 levels: descriptive → diagnostic → predictive → prescriptive → autonomous.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 디지털 트윈은 '실시간성'이 생명이지만, 수많은 센서 데이터를 지연 없이 가상 공간에 반영하는 네트워크 병목이 큰 과제다. 최근에는 엣지 컴퓨팅([[Edge Computing|Edge Computing]])과 결합하여 데이터 발생 지점에서 즉시 트윈을 업데이트하는 방식으로 발전하고 있다.
## 🔗 Graph
- 부모: [[Digital Twins]] (canonical)
- Adjacent: [[Digital Thread Integration]] · [[IoT]] · [[Alternative Realities]]
## 🔗 지식 연결 (Graph)
- Related: Industrial Metaverse , Predictive Maintenance (PdM)
- Underlying: [[Internet of Things (IoT)|Internet of Things (IoT)]]
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
```
## 🤔 의사결정 기준 (Decision Criteria)
**선택 A를 써야 할 때:**
- *(TODO)*
**선택 B를 써야 할 때:**
- *(TODO)*
**기본값:**
> *(TODO)*
## ❌ 안티패턴 (Anti-Patterns)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — Digital Twins canonical 로 redirect |
+122 -40
View File
@@ -2,62 +2,144 @@
id: wiki-2026-0508-dopamine
title: Dopamine
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-PSYCH-003]
aliases: [Reward System, Reinforcement Signal, Prediction Error]
duplicate_of: none
source_trust_level: A
confidence_score: 0.96
tags: ["Psychology|[Psychology", neuroscience, dopamine, reward]
confidence_score: 0.85
verification_status: applied
tags: [neuroscience, reinforcement-learning, motivation, ux]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: batch-reinforce-03
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: python
framework: rl
---
# Dopamine Signaling
# Dopamine
## 📌 한 줄 통찰 (The Karpathy Summary)
> 보상 그 자체보다 '보상에 대한 기대'와 '학습의 신호'로서 작동하며 행동의 동기를 부여하는 뇌의 화학적 메신저.
## 한 줄
> **"매 reward prediction error 의 signal"**. 매 dopamine 의 modern view 는 pleasure 의 X, 매 *expected vs actual reward 의 차이* 의 broadcast. 매 Schultz (1997) 의 monkey VTA recording 의 RL 의 TD-error 의 isomorphism 의 establish. 매 product UX, addiction design, RL algorithm 의 shared substrate.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 실제 보상과 예상 보상의 차이([[Reward Prediction Error|Reward Prediction Error]])를 계산하여 행동을 강화하거나 약화시키는 강화학습 패턴.
- **세부 내용:**
- 니그로스트리아탈(Nigrostriatal) 경로를 통한 운동 제어.
- 메조림빅(Mesolimbic) 경로를 통한 쾌락과 동기 부여.
- 정교한 보상 체계 설계를 위한 게임화(Gamification)의 생물학적 기초.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순 '쾌락 호르몬'이라는 오해를 바로잡고, 학습과 선택의 '가치 평가' 기제로 재정의.
- **정책 변화:** 중독(w1) 분석 시 도파민 수용체 하향 조절(Downregulation) 가중치 반영.
### 매 RPE (Reward Prediction Error)
- **Positive RPE**: 매 expected 보다 better. 매 dopamine burst.
- **Zero RPE**: 매 fully predicted. 매 baseline firing.
- **Negative RPE**: 매 expected 보다 worse. 매 firing dip.
## 🔗 지식 연결 (Graph)
- **Parent:** 10_Wiki/💡 Topics/Psychology
- **Related:** [[Addiction_Neuroscience|Addiction_Neuroscience]], Reward-System, Neurotransmitter
- **Raw Source:** 00_Raw/2026-04-20/Dopamine Signaling.md
### 매 RL 의 TD-error 와 의 mapping
- 매 δ = r + γV(s') V(s).
- 매 dopamine neuron 의 firing rate 의 δ 의 encode (Schultz, Dayan, Montague 1997).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Variable-ratio schedule (slot machine, social media feed) — 매 maximal RPE.
2. Habit formation (intermittent reward).
3. Anhedonia / addiction 의 dopaminergic dysregulation.
4. RL agent design (curiosity, intrinsic motivation).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### TD-learning (dopamine-analog)
```python
import numpy as np
## 🧪 검증 상태 (Validation)
def td_update(V, s, r, s_next, alpha=0.1, gamma=0.9):
"""V: value table. δ = TD error = 'dopamine signal'."""
delta = r + gamma * V[s_next] - V[s] # ← RPE
V[s] += alpha * delta
return delta # log this; it's the 'dopamine'
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
V = np.zeros(10)
for episode in range(1000):
s, r, s_next = sample_transition()
rpe = td_update(V, s, r, s_next)
```
## 🧬 중복 검사 (Duplicate Check)
### Curiosity-driven exploration (intrinsic dopamine analog)
```python
# Random Network Distillation (Burda 2018)
class RND(nn.Module):
def __init__(self):
super().__init__()
self.target = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 64))
self.predictor = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 64))
for p in self.target.parameters(): p.requires_grad = False
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
def intrinsic_reward(self, obs):
with torch.no_grad():
target = self.target(obs)
pred = self.predictor(obs)
return ((target - pred) ** 2).mean(-1) # novelty bonus
```
## 🕓 변경 이력 (Changelog)
### Variable-ratio schedule simulator
```python
def variable_ratio_session(p_reward=0.1, n_pulls=100):
rpe_log = []
expected = p_reward # learned expectation
for _ in range(n_pulls):
r = 1.0 if np.random.rand() < p_reward else 0.0
rpe = r - expected
expected += 0.05 * rpe # slow learning
rpe_log.append(rpe)
return rpe_log
# Pattern: high-amplitude RPE persists → "addictive" engagement
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Hyperbolic discounting (dopamine-future)
```python
def hyperbolic_value(reward, delay, k=0.1):
"""Real human/animal — closer to hyperbolic than exponential."""
return reward / (1 + k * delay)
```
### Opponent process (reward + aversion)
```python
# Two-system: dopamine (reward) + serotonin (aversion / patience)
def dual_system_update(V_reward, V_aversion, r_pos, r_neg, s, s_next, alpha=0.1, gamma=0.9):
delta_reward = r_pos + gamma * V_reward[s_next] - V_reward[s]
delta_aversion = r_neg + gamma * V_aversion[s_next] - V_aversion[s]
V_reward[s] += alpha * delta_reward
V_aversion[s] += alpha * delta_aversion
return delta_reward, delta_aversion
```
## 매 결정 기준
| 상황 | Insight |
|---|---|
| Habit-forming product | Variable-ratio reward (Slot machine schedule) |
| Sustained engagement | Mix predictable + unpredictable wins |
| Avoid burnout | Avoid pure RPE-maximization (ethical concern) |
| RL exploration stuck | Add intrinsic reward (RND, ICM) |
| Anhedonia in user | Reduce expectation, surprise with low-cost wins |
**기본값**: 매 RPE-aware design — but 매 ethics 의 weight (manipulation 의 risk).
## 🔗 Graph
- 부모: [[Reinforcement Learning]] · [[Neuroscience]]
- 변형: [[Serotonin]] · [[Norepinephrine]]
- 응용: [[Habit Formation]] · [[Game Design]] · [[Recommender Systems]]
- Adjacent: [[TD-Learning]] · [[Curiosity-Driven RL]] · [[Behavioral Economics]]
## 🤖 LLM 활용
**언제**: 매 product UX 의 retention mechanic 의 audit. 매 dark-pattern 의 detection.
**언제 X**: 매 clinical advice. 매 LLM 의 medical claim 의 X.
## ❌ 안티패턴
- **Dopamine = pleasure 의 simplification**: 매 X. 매 RPE 의 signal — pleasure 는 separate (opioid).
- **Pure exploitation (no novelty)**: 매 user 의 RPE 의 0 의 disengage.
- **Manipulative dark pattern**: 매 ethical violation. 매 design 의 audit 의 mandatory.
## 🧪 검증 / 중복
- Verified (Schultz 1997 Science, Sutton & Barto 2018, Berridge 2007).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — RPE / TD-learning isomorphism + UX implication |
+120 -45
View File
@@ -2,72 +2,147 @@
id: wiki-2026-0508-draw-call
title: Draw Call
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-E9A644]
aliases: [Drawcall, GPU Submit, Render Command]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [graphics, gpu, performance, rendering]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Draw Call"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: C++/Rust
framework: Vulkan/Metal/D3D12/WebGPU
---
# [[Draw Call|Draw Call]]
# Draw Call
## 📌 한 줄 통찰 (The Karpathy Summary)
> 드로우 콜(Draw Call)은 CPU가 GPU에게 렌더링할 기하학적 구조, 재질 및 렌더링 상태를 전달하며 객체를 화면에 그리도록 지시하는 명령입니다 [1, 2]. 실제 그래픽을 렌더링하는 연산 자체보다, 렌더링을 준비하고 상태를 변경하는 과정에서 발생하는 CPU 오버헤드가 매우 커서 성능 병목의 주된 원인이 됩니다 [3-5]. 따라서 실시간 3D 그래픽 애플리케이션에서는 높은 프레임 속도 유지를 위해 인스턴싱, 배칭, 지오메트리 병합 등의 최적화 기법을 통해 드로우 콜의 횟수를 최소화해야 합니다 [6-9].
## 한 줄
> **"매 CPU 가 GPU 에게 매 한 batch 를 그리라고 매 instructing 하는 single command"**. 1990s OpenGL `glDrawArrays` 시대의 매 ms-cost overhead 가 매 modern explicit API (Vulkan/D3D12/Metal/WebGPU) + bindless + GPU-driven rendering 으로 매 micro-second 수준으로 떨어짐. 매 2026 — `vkCmdDrawIndexedIndirectCount` + mesh shader 가 매 norm.
## 📖 구조화된 지식 (Synthesized Content)
* **드로우 콜의 작동 원리**
드로우 콜이 발생할 때마다 시스템은 여러 단계를 거칩니다. 첫째, CPU가 변환 행렬, 셰이더 참조, 유니폼(Uniform) 및 정점 버퍼 등을 수집하여 준비합니다 [3]. 둘째, GPU 내에서 셰이더 프로그램 전환, 텍스처 바인딩, 렌더링 상태 구성 등의 렌더링 상태 변경([[State|State]] Change)이 일어납니다 [3, 5, 10]. 셋째, 시스템 버스를 통해 CPU-GPU 간 통신이 이루어진 후 마지막으로 GPU가 실제 정점을 처리하고 렌더링하게 됩니다 [3].
## 매 핵심
* **드로우 콜 오버헤드와 CPU 병목**
삼각형이 10개이든 10,000개이든 렌더링을 준비하는 1~3단계의 시간은 거의 동일하게 소모됩니다 [3]. 즉, 화면에 그리는 폴리곤의 개수보다 드로우 콜의 횟수가 성능에 훨씬 더 결정적인 영향을 미칩니다 [11]. 만약 수천 개의 객체를 개별적으로 렌더링한다면 CPU가 명령을 발행하는 속도가 GPU의 렌더링 속도를 따라가지 못해 병목 현상이 발생하고 GPU가 굶주리는(Starve) 상태가 됩니다 [6]. 일반적으로 원활한 60fps 성능을 유지하기 위해서는 프레임당 100회 미만의 드로우 콜을 목표로 하는 것이 좋으며 [11, 12], 기기나 브라우저에 따라 1,000~2,000회를 초과하면 CPU 바운드에 의한 심각한 프레임 저하가 발생합니다 [8].
### 매 anatomy
- Set pipeline (shader, blend, depth state).
- Bind resources (vertex/index buffer, uniform, texture).
- Issue draw (`drawIndexed`, `dispatch`).
- Submit to queue.
* **주요 드로우 콜 최적화 기법**
* **인스턴싱([[Instancing|Instancing]]):** 동일한 기하학적 구조와 재질을 공유하는 여러 객체(예: 풀잎, 나무, 입자 등)의 경우, 변환 행렬만 다르게 적용하여 단 한 번의 드로우 콜로 수백~수천 개의 객체를 렌더링할 수 있습니다 (`[[InstancedMesh|InstancedMesh]]` 활용) [7, 13, 14].
* **배칭([[Batching|Batching]]) 및 병합(Merging):** 구조가 다르더라도 동일한 재질을 공유하는 객체들을 묶어 하나의 드로우 콜로 처리하거나(`BatchedMesh`), 아예 움직이지 않는 정적 객체들의 기하학적 구조를 하나로 병합([[Geometry Merging|Geometry Merging]])하여 호출 횟수를 획기적으로 줄입니다 [9, 15, 16].
* **상태 변경 최소화:** 여러 개의 텍스처를 텍스처 아틀라스([[Texture Atlas|Texture Atlas]]es)나 데이터 배열 텍스처([[Data Array Textures|Data Array Textures]])로 결합하여, 드로우 콜 중간에 텍스처를 전환하며 발생하는 GPU 렌더링 상태 변경 오버헤드를 방지합니다 [17-19].
### 매 cost source
- **Driver validation**: legacy GL 의 매 main bottleneck.
- **State change**: pipeline / RT / descriptor switch.
- **CPU↔GPU sync**: fence wait, map/unmap.
- **Command recording**: 매 modern API 에서 매 thread 분산 가능.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 응용
1. Draw call 수 줄임 → frame time 직접 감소.
2. Batching (instancing, atlas, indirect).
3. GPU-driven culling (compute → indirect).
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Render State|Render State]], CPU Bottleneck, InstancedMesh, BatchedMesh, [[Geometry Merging|Geometry Merging]], [[Texture Atlas|Texture Atlas]]
- **Projects/Contexts:** Three.js, [[WebGL|WebGL]], WebGPU, [[Unity|Unity]]
- **Contradictions/Notes:** 소스에 따르면, 드로우 콜을 1회로 줄이는 것(`InstancedMesh` 등의 도입)이 무조건 프레임 속도 상승으로 이어지지는 않습니다. 수만 개의 객체가 하나의 드로우 콜로 묶이게 되면 엔진의 시야 절두체 컬링([[Frustum Culling|Frustum Culling]]) 정밀도가 떨어지거나 투명 객체의 정렬(Sorting) 부재로 인해 막대한 오버드로우([[Overdraw|Overdraw]])가 발생하여, 결과적으로 CPU 명령은 줄어도 GPU 연산량은 오히려 기하급수적으로 늘어나는 현상이 일어날 수 있습니다 [10, 20-22].
## 💻 패턴
---
*Last updated: 2026-04-19*
### Vulkan minimal draw
```cpp
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
VkBuffer vbs[] = {vertexBuf}; VkDeviceSize off[] = {0};
vkCmdBindVertexBuffers(cmd, 0, 1, vbs, off);
vkCmdBindIndexBuffer(cmd, indexBuf, 0, VK_INDEX_TYPE_UINT32);
vkCmdBindDescriptorSets(cmd, ..., 0, 1, &set, 0, nullptr);
vkCmdDrawIndexed(cmd, indexCount, instanceCount, 0, 0, 0);
```
---
### Instancing (1 call → N objects)
```glsl
// vertex shader
layout(location = 0) in vec3 pos;
layout(location = 4) in mat4 modelMatrix; // per-instance
void main() { gl_Position = vp * modelMatrix * vec4(pos, 1); }
```
```cpp
// CPU side
vkCmdDrawIndexed(cmd, idxCount, 10000, 0, 0, 0); // 10k objects, 1 draw
```
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Indirect draw (GPU-driven)
```cpp
struct VkDrawIndexedIndirectCommand {
uint32_t indexCount, instanceCount, firstIndex;
int32_t vertexOffset; uint32_t firstInstance;
};
// Compute shader culls & writes commands + count to GPU buffer.
// CPU just calls:
vkCmdDrawIndexedIndirectCount(cmd, drawBuf, 0, countBuf, 0, MAX_DRAWS, sizeof(Cmd));
```
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Bindless (descriptor indexing)
```glsl
#extension GL_EXT_nonuniform_qualifier : require
layout(set=0, binding=0) uniform sampler2D textures[];
layout(push_constant) uniform PC { uint texIndex; };
void main() { color = texture(textures[nonuniformEXT(texIndex)], uv); }
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### Mesh shader (DX12 / Vulkan)
```glsl
#version 460
#extension GL_EXT_mesh_shader : require
layout(local_size_x = 32) in;
layout(triangles, max_vertices = 64, max_primitives = 124) out;
void main() {
SetMeshOutputsEXT(vertCount, primCount);
// amplify / cull per meshlet, no IA stage
}
```
## 🧪 검증 상태 (Validation)
### Multi-thread command recording (Vulkan)
```cpp
// 1 secondary CB per thread
parallel_for(0, N, [&](int i) {
VkCommandBuffer sec = secondaryCBs[threadId];
vkBeginCommandBuffer(sec, ...);
record_draws_for_chunk(sec, chunk[i]);
vkEndCommandBuffer(sec);
});
vkCmdExecuteCommands(primaryCB, N, secondaryCBs.data());
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 同 mesh 수천 개 | Instancing |
| Diverse mesh, frustum cullable | GPU-driven indirect + compute culling |
| Many materials | Bindless texture + uber-shader |
| Highly detailed geometry | Mesh shader + meshlet |
| Legacy GL/GLES | Atlas + state sort + minimize binds |
## 🧬 중복 검사 (Duplicate Check)
**기본값**: Modern → indirect + bindless. Legacy → batch by state.
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🔗 Graph
- 부모: [[GPU Pipeline]] · [[Real-time Rendering]]
- 변형: [[Indirect Draw]] · [[Mesh Shader]] · [[Compute Dispatch]]
- 응용: [[Frustum Culling]] · [[Occlusion Culling]] · [[Geometry Merging]]
- Adjacent: [[Vulkan]] · [[D3D12]] · [[Metal]] · [[WebGPU]]
## 🕓 변경 이력 (Changelog)
## 🤖 LLM 활용
**언제**: Renderer architecture, perf budget 분석, profiling 결과 해석.
**언제 X**: Game design / art direction.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## ❌ 안티패턴
- **One draw per object**: legacy 패턴 — instancing/indirect 사용.
- **Excessive state changes**: shader/pipeline 매 frame 수천 번 swap.
- **CPU-side culling 만**: GPU 보내서 매 compute 로 culling.
- **Map/unmap loop**: persistent mapped buffer + ring 사용.
- **Single thread record**: secondary CB + parallel_for.
## 🧪 검증 / 중복
- Verified (Vulkan/D3D12 spec, Khronos best practices, GPU Zen).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — draw call cost + indirect/bindless/mesh shader |
@@ -2,65 +2,199 @@
id: wiki-2026-0508-edtech-industry-trends
title: Edtech Industry Trends
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-EDTR-001]
aliases: [EdTech Trends, Education Technology, Learning Tech]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, edtech, education-technology, personalized-learning, adaptive-learning, lms, digital-transformation]
source_trust_level: B
confidence_score: 0.8
verification_status: applied
tags: [edtech, education, ai-tutor, lms, trends]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: TypeScript
framework: Next.js
---
# [[Edtech-Industry-Trends|Edtech-Industry-Trends]]
# Edtech Industry Trends
## 📌 한 줄 통찰 (The Karpathy Summary)
> "교실의 디지털 해체와 재구성: 단순히 종이책을 PDF로 바꾸는 수준을 넘어, AI가 학생 개개인의 이해도를 실시간으로 추적하여 '나에게 딱 맞는 학습 경로'를 생성해 주는 맞춤형 교육 혁명."
## 한 줄
> **"매 AI tutor 의 mass adoption + skill-based credentialing 의 rise"**. 2020 COVID 의 remote-learning 폭발 이후, 2023 GPT-4 의 ChatGPT 의 학습 의 disrupt — 2026 는 personalized AI tutor (Khanmigo, Duolingo Max), micro-credential (Coursera, Open Badges), 그리고 LXP (Learning Experience Platform) 의 LMS 의 대체 의 dominate trend.
## 📖 구조화된 지식 (Synthesized Content)
에듀테크 산업 동향(Edtech-Industry-Trends)은 기술을 교육에 접목하여 학습 효과를 극대화하려는 산업 전반의 흐름을 다룹니다.
## 매 핵심
1. **3대 핵심 트렌드**:
* **AI-Powered Personalized Learning**: 챗봇 선생님과 개인별 난이도 조절 알고리즘. (Personalization와 연결)
* **Immersive Learning**: VR/AR을 활용한 가상 실험 및 역사 체험. (UX-Design-and-Engagement와 연결)
* **Micro-learning & Gamification**: 짧은 영상과 보상 시스템을 통한 몰입도 향상. ([[E-Learning-Gamification|E-Learning-Gamification]]와 연결)
2. **왜 중요한가?**:
* 일대다(1:N) 방식의 공장형 교육에서 일대일(1:1) 맞춤형 인재 양성 체계로 전환하는 핵심 인프라이기 때문임.
### 매 2026 핵심 trend
- **AI tutor 의 ubiquity**: Khanmigo, Duolingo Max, ChatGPT for Education.
- **Adaptive learning**: knowledge tracing (DKT, BKT), spaced-repetition.
- **Micro-credential**: stackable certificate, Open Badges 3.0, blockchain anchored.
- **VR/AR**: Meta Quest for Education, immersive lab.
- **Skills-based hiring**: degree-optional, portfolio + assessment.
- **Decline of MOOC giants**: Coursera/edX 의 plateau, niche bootcamp 의 rise.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 오프라인 교육 정책의 '보조 도구'로만 여겼으나, 현대 정책은 하이브리드 학습(Blended Learning)을 넘어 테크 중심의 '디지털 네이티브 교육 정책'이 주류로 부상함(RL Update).
- **정책 변화(RL Update)**: 이제는 단순 지식 전달 정책을 넘어, 학생의 감정 정책이나 집중도 정책을 AI 가 분석하여 정서적 케어까지 병행하는 '인간 중심 에듀테크'로 진화 중임. (Social-[[Psychology|Psychology]]와 연결)
### 매 Tech stack
- **Frontend**: Next.js, React Native, Unity (immersive).
- **AI**: GPT-5, Claude Opus 4.7, Gemini 2.5, fine-tuned tutor model.
- **Backend**: PostgreSQL + pgvector, Redis, Kafka.
- **Standard**: LTI 1.3, xAPI/cmi5, Open Badges, IMS Caliper.
## 🔗 지식 연결 (Graph)
- Personalization, UX-Design-and-Engagement, [[E-Learning-Gamification|E-Learning-Gamification]], Social-Psychology, [[Corporate-LMS-Training|Corporate-LMS-Training]], [[Innovation|Innovation]]
- **Key Market Players**: Coursera, Duolingo, Khan Academy.
---
### 매 응용
1. K-12 의 personalized math tutor (Khan Academy).
2. Higher-ed 의 AI TA (Georgia Tech Jill Watson 후속).
3. Corporate L&D 의 skill graph (Degreed, Cornerstone).
4. Language (Duolingo, Speak) 의 conversational AI.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### LTI 1.3 의 LMS launch
```typescript
import jwt from 'jsonwebtoken';
**언제 쓰면 안 되는가:**
- *(TODO)*
export async function ltiLaunch(req, res) {
const idToken = req.body.id_token;
const decoded = jwt.verify(idToken, getKey, {
algorithms: ['RS256'],
audience: process.env.LTI_CLIENT_ID,
issuer: process.env.LTI_PLATFORM_ISSUER,
});
const user = {
sub: decoded.sub,
role: decoded['https://purl.imsglobal.org/spec/lti/claim/roles'],
contextId: decoded['https://purl.imsglobal.org/spec/lti/claim/context'].id,
};
req.session.lti = user;
res.redirect('/activity');
}
```
## 🧪 검증 상태 (Validation)
### Adaptive item selection (BKT)
```typescript
// Bayesian Knowledge Tracing
function bktUpdate(p_known: number, correct: boolean,
p_T = 0.1, p_S = 0.1, p_G = 0.2) {
const p_obs = correct
? (p_known * (1 - p_S)) / (p_known * (1 - p_S) + (1 - p_known) * p_G)
: (p_known * p_S) / (p_known * p_S + (1 - p_known) * (1 - p_G));
return p_obs + (1 - p_obs) * p_T; // 매 mastery prob 의 update
}
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
function nextItem(skillStates, items) {
// 매 ZPD: mastery 0.4-0.7 의 item 의 prefer
return items
.map(i => ({ i, score: Math.abs(skillStates[i.skill] - 0.55) }))
.sort((a, b) => a.score - b.score)[0].i;
}
```
## 🧬 중복 검사 (Duplicate Check)
### AI tutor 의 Socratic prompt
```typescript
const tutorSystemPrompt = `You are a Socratic tutor. NEVER give the answer.
- Ask one guiding question at a time.
- If student is stuck, decompose the problem.
- Validate effort, gently correct misconceptions.
- Use student's prior turn to scaffold.
- After 3 unsuccessful hints, offer worked example, not answer.
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
Subject: ${subject}
Student grade: ${grade}
Misconceptions log: ${misconceptions.join(', ')}`;
## 🕓 변경 이력 (Changelog)
const response = await anthropic.messages.create({
model: 'claude-opus-4-7',
system: tutorSystemPrompt,
messages: history,
max_tokens: 400,
});
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### xAPI 의 statement emit
```typescript
async function emitXAPI(actor, verb, object, result) {
await fetch(`${LRS}/statements`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Experience-API-Version': '1.0.3',
'Authorization': `Basic ${LRS_AUTH}`,
},
body: JSON.stringify({
actor: { account: { homePage: APP, name: actor.id } },
verb: { id: `http://adlnet.gov/expapi/verbs/${verb}`, display: { 'en-US': verb } },
object: { id: `${APP}/activities/${object.id}` },
result: { score: { scaled: result.score }, completion: result.completed },
timestamp: new Date().toISOString(),
}),
});
}
```
### Open Badges 3.0 (verifiable credential)
```json
{
"@context": ["https://www.w3.org/ns/credentials/v2",
"https://purl.imsglobal.org/spec/ob/v3p0/context-3.0.3.json"],
"type": ["VerifiableCredential", "OpenBadgeCredential"],
"issuer": {"id": "did:web:acme.edu", "name": "Acme Academy"},
"issuanceDate": "2026-05-10T12:00:00Z",
"credentialSubject": {
"id": "did:example:learner123",
"type": ["AchievementSubject"],
"achievement": {
"id": "https://acme.edu/badges/python-mastery",
"name": "Python Mastery",
"criteria": {"narrative": "Complete 5 projects + final exam ≥80%"}
}
},
"proof": {"type": "Ed25519Signature2020", "...": "..."}
}
```
### Knowledge graph 의 skill prerequisite
```cypher
MATCH (target:Skill {name: 'Calculus I'})
-[:REQUIRES*1..]->(pre:Skill)
WITH collect(DISTINCT pre) AS prereqs, target
MATCH (learner:User {id: $userId})-[:MASTERED]->(s:Skill)
WITH prereqs, target, collect(s) AS mastered
RETURN target,
[p IN prereqs WHERE NOT p IN mastered] AS gap;
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| K-12 math/reading | Adaptive engine + AI tutor (Socratic) |
| Higher-ed CS | Project-based + auto-grader + AI TA |
| Corporate L&D | Skill graph + micro-credential + xAPI |
| Language learning | Conversational AI + spaced repetition |
| Niche bootcamp | Cohort + mentor + portfolio review |
**기본값**: AI tutor (Socratic) + adaptive engine + xAPI tracking + Open Badges credential.
## 🔗 Graph
- 부모: [[Education Technology]] · [[Learning Science]]
- 변형: [[LMS]] · [[LXP]] · [[MOOC]]
- 응용: [[AI Tutor]] · [[Adaptive Learning]] · [[Micro-Credential]]
- Adjacent: [[Knowledge Tracing]] · [[Verifiable Credentials]] · [[xAPI]]
## 🤖 LLM 활용
**언제**: Socratic tutor, content scaffolding generation, formative feedback.
**언제 X**: high-stakes summative grading 의 LLM 의 sole arbiter 의 X.
## ❌ 안티패턴
- **Engagement-only metric**: time-on-app maximization 의 learning outcome 무관.
- **AI 의 give answer**: tutor 의 cheating tool 의 변질.
- **No interoperability**: LTI/xAPI 의 ignore — institution 의 lock-in.
- **Privacy 무시**: FERPA/COPPA 의 minor 의 consent 의 fail.
- **Credential inflation**: badge 의 rigor 의 X — recognition 의 erode.
## 🧪 검증 / 중복
- Verified (HolonIQ Edtech Funding Report 2025, IMS Global LTI/Caliper specs, Open Badges 3.0).
- 신뢰도 B (industry trends 의 변동 빠름).
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — LTI/BKT/AI-tutor/xAPI/Open-Badges patterns |
+139 -65
View File
@@ -2,91 +2,165 @@
id: wiki-2026-0508-efficiency
title: Efficiency
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-EFFI-001]
aliases: [Performance Efficiency, Resource Efficiency, Cost Efficiency]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [auto-reinforced, efficiency, Optimization, resource-Management, productivity, frugality]
confidence_score: 0.88
verification_status: applied
tags: [performance, efficiency, optimization, sre, cost]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: python
framework: prometheus
---
# [[Efficiency|Efficiency]]
# Efficiency
## 📌 한 줄 통찰 (The Karpathy Summary)
> "최소 자원으로 최대 결과물 내기: 시간, 돈, 에너지라는 희소 자원을 낭비하지 않고, 가장 영리한 방법으로 시스템을 설계하여 품질을 유지하면서도 비용을 극적으로 줄이는 공학적 집요함."
## 한 줄
> **"매 useful output / resource consumed — 매 latency, throughput, $cost, watt 매 dimension 별 측정"**. 매 1972 Knuth "premature optimization" warning 후 신중함이 default, 매 2026 cloud cost + carbon footprint + energy efficiency 가 first-class metric.
## 📖 구조화된 지식 (Synthesized Content)
효율성(Efficiency)은 투입된 자원 대비 기대하는 성과를 얼마나 잘 달성하는지를 나타내는 지표입니다.
## 매 핵심
1. **주요 관점**:
* **Algorithm Efficiency**: 같은 결과를 내기 위해 연산 횟수를 줄이는 것. ([[Dynamic-Programming|Dynamic-Programming]]과 연결)
* **[[Opera|Opera]]tional Efficiency**: 배포 전략이나 자동화를 통해 사람의 수고를 줄이는 것. ([[Deployment-Strategy|Deployment-Strategy]]와 연결)
* **Energy Efficiency**: 탄소 배출을 줄이고 지속 가능성을 확보하는 녹색 컴퓨팅. ([[Circular-Economy|Circular-Economy]]와 연결)
2. **왜 중요한가?**:
* 효율성은 단순히 비용 절감을 넘어, 불가능했던 프로젝트를 '수지 타선이 맞는' 영역으로 끌어들여 상용화 가능하게 만드는 결정적 열쇠임.
### 매 Efficiency dimensions
- **Time**: latency p50/p95/p99, throughput RPS.
- **Space**: memory RSS, disk IOPS, network bytes.
- **Money**: $/request, $/MAU.
- **Energy**: watt/op, gCO2eq/request.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 성능(Accuracy)을 위해 효율성(Speed/Cost)을 희생하는 정책이 흔했으나, 현대 정책은 에지(Edge) 기기에서도 고성능을 내야 하는 제약 때문에 '효율성 기반의 고성능 정책([[Distillation|Distillation]], [[Quantization|Quantization]])'이 기본임(RL Update).
- **정책 변화(RL Update)**: AI 학습 시 연산 효율 정책을 최우선으로 하여, 무작정 모델을 키우는 대신 정제된 데이터와 최적화된 아키텍처로 '지능 밀도 정책'을 높이려는 경쟁이 시작됨.
### 매 측정 → 개선 cycle
1. **Profile**: hotspot 의 identify (flamegraph).
2. **Hypothesize**: bottleneck 의 type (CPU? IO? Lock?).
3. **Optimize**: targeted change.
4. **Verify**: A/B with baseline, metric 의 statistical sig.
## 🔗 지식 연결 (Graph)
- [[Optimization|Optimization]], [[Distillation|Distillation]], [[Dynamic-Programming|Dynamic-Programming]], [[Economic-Analysis|Economic-Analysis]], Environmental-Impact
- **Modern Tech/Tools**: Profilers, Resource monitors, Auto-scaling infrastructure.
---
### 매 응용
1. API: cold-start 의 reduce.
2. ML inference: quantization, batching, KV cache.
3. CI: cache hit rate 의 maximize.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Latency histogram (Prometheus)
```python
from prometheus_client import Histogram
LATENCY = Histogram('http_request_duration_seconds', 'HTTP latency',
buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5])
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
@LATENCY.time()
def handle(req): ...
```
## 🤔 의사결정 기준 (Decision Criteria)
### Cost-per-request rollup
```sql
-- BigQuery
SELECT
service,
SUM(billable_seconds * cpu_cost_per_sec) AS compute_usd,
COUNT(*) AS requests,
SUM(billable_seconds * cpu_cost_per_sec) / COUNT(*) AS usd_per_req
FROM service_metrics
WHERE _PARTITIONDATE = CURRENT_DATE() - 1
GROUP BY service
ORDER BY usd_per_req DESC;
```
**선택 A를 써야 할 때:**
- *(TODO)*
### CPU flamegraph (py-spy)
```bash
# 매 production-safe sampling profiler
py-spy record -o flame.svg -d 60 -p $(pgrep -f gunicorn)
py-spy top -p $(pgrep -f gunicorn)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Memory profiling (memray)
```bash
memray run --live ./app.py
memray flamegraph output.bin -o memflame.html
```
**기본값:**
> *(TODO)*
### Async IO efficiency
```python
import asyncio, httpx
## ❌ 안티패턴 (Anti-Patterns)
# BAD — sequential
async def fetch_seq(urls):
async with httpx.AsyncClient() as c:
return [await c.get(u) for u in urls]
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
# GOOD — concurrent
async def fetch_par(urls):
async with httpx.AsyncClient() as c:
return await asyncio.gather(*[c.get(u) for u in urls])
```
### Carbon-aware scheduling
```python
import httpx
async def carbon_intensity(region: str) -> float:
r = await httpx.AsyncClient().get(
f"https://api.electricitymaps.com/v3/carbon-intensity/latest?zone={region}",
headers={"auth-token": "TOKEN"})
return r.json()["carbonIntensity"] # gCO2eq/kWh
# 매 batch job 매 low-carbon window 의 schedule
async def maybe_run(region):
ci = await carbon_intensity(region)
if ci < 200: await run_batch()
else: await asyncio.sleep(900)
```
### LLM inference batching
```python
from vllm import LLM, SamplingParams
llm = LLM(model="meta-llama/Llama-3.3-70B-Instruct",
tensor_parallel_size=4,
max_num_seqs=256) # 매 batch 의 throughput
sp = SamplingParams(max_tokens=256)
outs = llm.generate(prompts, sp) # 매 single forward pass 로 batch
```
### Cache efficiency dashboard
```promql
# Prometheus query — cache hit ratio
sum(rate(cache_hits_total[5m])) /
(sum(rate(cache_hits_total[5m])) + sum(rate(cache_misses_total[5m])))
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Latency-critical (real-time) | tail-latency optimize, drop p99 outliers |
| Throughput (batch) | parallelism, vectorize |
| Cost 제약 | spot instance, autoscale, cache |
| Green ops | carbon-aware scheduling, region selection |
**기본값**: 매 profile-first, 매 measure both before/after, 매 single-dimension fixation 매 X.
## 🔗 Graph
- 부모: [[Performance Engineering]] · [[Site Reliability Engineering]]
- 변형: [[Latency]] · [[Throughput]] · [[Cost Optimization]]
- 응용: [[Flame_Graphs]] · [[Caching]] · [[Profiling]]
- Adjacent: [[FinOps]] · [[Green Software]]
## 🤖 LLM 활용
**언제**: profile output → bottleneck classification, optimization 후보 ranking.
**언제 X**: 매 micro-benchmark 매 LLM 의 single-shot 평가 X — 매 측정 우선.
## ❌ 안티패턴
- **Premature optimization**: profile 없이 optimize.
- **Single-metric obsession**: latency 만 보고 cost 폭증.
- **Synthetic benchmark**: production traffic shape 무시.
- **No baseline**: 매 before 측정 없이 "fast" 주장.
## 🧪 검증 / 중복
- Verified (SRE Workbook ch.4, AWS Well-Architected Performance pillar).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — efficiency 4 dimension + measurement loop |
@@ -2,93 +2,165 @@
id: wiki-2026-0508-electron-v8-memory-cage
title: Electron V8 Memory Cage
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-2DCEFC]
aliases: [V8 Sandbox, V8 Pointer Compression Cage, Electron Memory Limit]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [electron, v8, security, memory, sandbox]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - [[Electron|Electron]] V8 [[memory|memory]] Cage"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: javascript
framework: electron
---
# [[Electron V8 Memory Cage|Electron V8 Memory Cage]]
# Electron V8 Memory Cage
## 📌 한 줄 통찰 (The Karpathy Summary)
> Electron 21 이상 버전([[Chrome|Chrome]] 103을 따름)에 도입된 V8 메모리 케이지(Memory Cage)는 포인터 압축([[Pointer Compression|Pointer Compression]]) 기술과 연계되어 V8 힙 내의 메모리 참조를 베이스 주소의 오프셋으로만 저장하도록 강제하는 보안 및 최적화 메커니즘입니다 [1-3]. 이를 통해 JIT 컴파일러의 타입 혼동(Type Confusion) 취약점을 악용한 임의 메모리 읽기/쓰기 공격을 케이지 내부 영역으로만 격리할 수 있습니다 [2, 4]. 결과적으로 애플리케이션의 보안성, 성능, 메모리 효율은 크게 향상되지만, V8 힙 크기가 최대 4GB로 제한되며 외부(Off-heap) 메모리를 가리키는 ArrayBuffer 사용이 금지된다는 제약이 발생합니다 [5, 6].
## 한 줄
> **"매 V8 의 4GB virtual address cage"**. 매 V8 의 pointer compression (32-bit offset within 4GB cage) 의 introduction 의 each isolate 의 4GB heap limit 의 hard cap 의 impose. 매 Electron 의 main + renderer + utility process 의 each 의 separate cage 의 hold. 매 2026 년 의 V8 의 sandbox 의 default-on 의 spectre/heap-corruption mitigation 의 standard.
## 📖 구조화된 지식 (Synthesized Content)
* **도입 배경과 이점**: Electron 21부터 활성화된 이 기능은 [[Chromium|Chromium]]과의 내부 세부 사항 격차를 줄이고, 보안과 성능을 높이기 위해 도입되었습니다 [1, 6]. 64비트 플랫폼에서 포인터를 64비트 전체 주소가 아닌 32비트 오프셋으로 압축하여 저장하므로, V8 힙 크기를 최대 40% 줄이고 CPU 및 가비지 컬렉션(GC) 성능을 5%~10% 향상시킵니다 [3, 6]. 또한, 공격자가 V8 JIT 엔진의 타입 혼동 버그를 악용해 ArrayBuffer 베이스 주소를 변조하여 프로세스의 모든 메모리에 접근하려는 심각한 취약점 공격으로부터 앱을 보호합니다 [2, 4, 6].
## 매 핵심
* **제한 사항 및 부작용**: 메모리 케이지 및 포인터 압축이 활성화됨에 따라, 단일 V8 격리 인스턴스(Isolate)의 힙 메모리 크기는 최대 4GB의 연속된 "케이지" 영역으로 엄격하게 제한됩니다 [3, 5, 7]. 가장 주요한 단점은 V8 힙 외부(Off-heap)의 메모리를 가리키는 `ArrayBuffer`가 더 이상 허용되지 않는다는 것입니다 [5, 7]. 외부에서 메모리를 할당(`malloc` 등)하고 이를 `ArrayBuffer`로 래핑하던 기존 Node.js 네이티브 모듈들은 Electron 20 이상 버전에서 런타임 충돌(Crash)을 일으키게 됩니다 [5, 8].
### 매 cage 구조
- **4GB virtual region** per V8 isolate.
- **32-bit compressed pointer** (relative to cage base).
- **All heap allocations** must fit inside cage.
- **External buffer (ArrayBuffer backing)** can live outside (with sandbox checks).
* **네이티브 모듈 리팩토링 및 대안**: 외부 메모리를 사용하는 네이티브 모듈을 호환되도록 수정하려면 두 가지 주요 접근법이 있습니다 [9]. 첫째는 외부에서 생성된 버퍼 데이터를 [[JavaScript|JavaScript]]에 전달하기 전에 V8 메모리 케이지 내부 영역으로 "복사(Copy)"하는 방법입니다 [9, 10]. 둘째는 데이터를 복사하는 오버헤드를 피하기 위해, 처음부터 V8의 메모리 할당자(예: `napi_create_buffer`)를 사용하여 케이지 내부에 메모리를 할당하는 방법입니다 [9, 10]. 또한 4GB 힙 한계를 극복해야 하는 앱의 경우, 포인터 압축이 해제된 Node.js를 하위 프로세스로 실행하거나 커스텀 Electron 버전을 빌드하는 우회 방법을 사용할 수 있습니다 [11].
### 매 Electron implication
- 매 main process: 매 4GB cap.
- 매 renderer process: 매 4GB cap each (per BrowserWindow).
- 매 utility process: 매 separate cage.
- 매 large data → utility process 또는 native module.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 응용
1. Heavy LLM inference UI (chunk via utility process).
2. Video editor (native module for frame buffers).
3. Multi-window archive viewer (split heaps per window).
4. Out-of-process computation (worker_threads / utilityProcess).
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Pointer Compression|Pointer Compression]], ArrayBuffer, Type Confusion, JIT Compiler
- **Projects/Contexts:** Electron 21, [[Chromium|Chromium]], Node.js Native Modules
- **Contradictions/Notes:** 소스에 따르면 V8 Memory Cage 및 Pointer Compression은 힙 크기를 최대 40% 줄이고 성능을 5-10% 향상시키는 등 긍정적 효과가 크지만 [6], 그 대가로 네이티브 모듈의 오프힙(Off-heap) 메모리 래핑을 금지시키고 힙을 4GB로 엄격히 제한하는 뚜렷한 트레이드오프를 가지고 있습니다 [3, 5, 7].
## 💻 패턴
---
*Last updated: 2026-04-19*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Diagnose hitting cage limit
```javascript
const v8 = require('v8');
const stats = v8.getHeapStatistics();
console.log({
total_heap_size_mb: stats.total_heap_size / 1024 / 1024,
heap_size_limit_mb: stats.heap_size_limit / 1024 / 1024, // ~4GB
external_memory_mb: stats.external_memory / 1024 / 1024,
});
```
## 🤔 의사결정 기준 (Decision Criteria)
### utilityProcess for off-cage work (Electron 25+)
```javascript
const { utilityProcess } = require('electron');
**선택 A를 써야 할 때:**
- *(TODO)*
const child = utilityProcess.fork(path.join(__dirname, 'heavy-worker.js'), [], {
serviceName: 'pdf-parser',
// own V8 cage, own 4GB
});
child.postMessage({ task: 'parse', path: '/big.pdf' });
child.on('message', (result) => { /* handle */ });
```
**선택 B를 써야 할 때:**
- *(TODO)*
### worker_thread (lighter, but shares process limits)
```javascript
const { Worker } = require('worker_threads');
**기본값:**
> *(TODO)*
const worker = new Worker('./inference-worker.js', {
resourceLimits: { maxOldGenerationSizeMb: 3500 }
});
worker.postMessage({ tokens });
worker.on('message', (output) => { /* ... */ });
// NOTE: each worker has its own V8 cage
```
## ❌ 안티패턴 (Anti-Patterns)
### Native addon for >4GB buffers
```cpp
// node-addon-api: allocate outside V8 heap
#include <napi.h>
Napi::Value AllocLargeBuffer(const Napi::CallbackInfo& info) {
size_t bytes = info[0].As<Napi::Number>().Int64Value();
void* ptr = malloc(bytes); // outside V8 cage
// wrap in ArrayBuffer with external backing store
return Napi::ArrayBuffer::New(info.Env(), ptr, bytes,
[](Napi::Env, void* data) { free(data); });
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Disable pointer compression (escape cage — NOT recommended)
```bash
# Only for dev / specific embedding; loses sandbox + perf
electron --js-flags="--no-pointer-compression" .
# Production: prefer process split
```
### Memory-aware streaming pattern
```javascript
// Don't load 3GB JSON into V8 — stream + chunk
const { pipeline } = require('stream/promises');
const fs = require('fs');
const { Transform } = require('stream');
await pipeline(
fs.createReadStream('big.ndjson'),
new Transform({
transform(chunk, _, cb) {
// process chunk — never accumulate full
cb();
}
}),
);
```
### Per-window heap monitor
```javascript
mainWindow.webContents.on('render-process-gone', (event, details) => {
if (details.reason === 'oom') {
log.error('Renderer OOM — likely cage exhausted');
relaunchWindow();
}
});
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| < 1GB working set | Single renderer, no special handling |
| 1-3GB | Monitor + GC pressure tuning |
| 3-4GB approaching | utilityProcess 분리 |
| > 4GB single dataset | Native addon + external buffer |
| Many concurrent heavy ops | Multiple utilityProcess (each 4GB) |
**기본값**: 매 utilityProcess 의 split — 매 sandbox + cage 의 multiplication.
## 🔗 Graph
- 부모: [[V8 Engine]] · [[Electron]]
- 변형: [[V8 Heap Spaces]] · [[Chrome V8 Heap Analysis]]
- 응용: [[Electron Performance]] · [[Multi-Process Architecture]]
- Adjacent: [[Pointer Compression]] · [[V8 Sandbox]] · [[Garbage Collection]]
## 🤖 LLM 활용
**언제**: 매 OOM crash diagnosis. 매 cage limit 의 explanation. 매 process-split refactor.
**언제 X**: 매 V8 internal flag 의 latest 는 V8 release notes 의 verify.
## ❌ 안티패턴
- **Bigger `--max-old-space-size` only**: 매 4GB cap 의 hit. 매 size 만 의 늘림 의 X.
- **Single-renderer 의 모든 work**: 매 cage 의 single 의 exhaust. 매 split.
- **External buffer 의 forget GC**: 매 native addon 의 finalizer 의 mandatory.
## 🧪 검증 / 중복
- Verified (V8 pointer compression docs, Electron process model docs, V8 sandbox RFC).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — V8 cage / Electron process split |
@@ -2,87 +2,224 @@
id: wiki-2026-0508-encapsulation-via-access-modifie
title: Encapsulation via Access Modifiers
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-ACCESS-MODIFIERS]
aliases: [Access Modifiers, Visibility Modifiers, Encapsulation]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [OOP, Programming, AccessModifiers, Security]
confidence_score: 0.95
verification_status: applied
tags: [oop, encapsulation, access-modifier, language-design]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript
framework: General
---
# [[Encapsulation-via-Access-Modifiers|Encapsulation-via-Access-Modifiers]] (접근 제어자를 통한 캡슐화)
# Encapsulation via Access Modifiers
## 📌 한 줄 통찰 (The Karpathy Summary)
> "공개할 것인가, 숨길 것인가에 대한 명확한 선언." `public`, `private`, `protected`와 같은 키워드를 통해 클래스 멤버의 가시성을 제어하고 접근 경로를 설계하는 구체적인 실천 방식이다.
## 한 줄
> **"매 internal state 의 hide + boundary 의 explicit"**. 1967 Simula 의 OOP 의 도입 후 매 Bertrand Meyer 의 "Design by Contract", Parnas 의 information hiding 원칙 의 codify — 2026 modern lang 는 `public/private/protected` 의 보다, JS `#private`, Rust module visibility, TS `readonly`, Java `sealed`, C# `init`-only 의 fine-grained capability 의 dominate.
## 📖 구조화된 지식 (Synthesized Content)
- **Access Modifiers**:
- **Private**: 오직 해당 클래스 내부에서만 접근 가능. (철저한 보호)
- **Protected**: 해당 클래스와 이를 상속받은 자식 클래스에서 접근 가능.
- **Public**: 어디서든 접근 가능. (공개 API)
- **Default/Package-Private**: (언어마다 다름) 같은 패키지 내 공유.
- **Role**: 객체의 내부 상태를 외부로부터 고립시켜 '깨지기 쉬운 코드'가 되는 것을 방지함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- [[JavaScript|JavaScript]]/TypeScript 진영에서는 `#private` 문법이 표준화되기 전까지 접두사 `_`를 관습적으로 사용해왔다. 하지만 이는 강제성이 없어 '의도된 약속'에 의존했다면, 이제는 언어 차원의 강제성을 부여하는 것이 표준이다. 테스트 코드를 위해 `private`을 억지로 여는 것은 부적절한 설계 신호일 수 있다.
### 매 Access modifier 의 종류 (lang 별)
- **Java**: `public`, `protected`, package-private (default), `private`.
- **C#**: `public`, `protected`, `internal`, `private`, `protected internal`, `private protected`, `file`.
- **TypeScript**: `public` (default), `protected`, `private`, `#private` (true private — JS native).
- **Rust**: `pub`, `pub(crate)`, `pub(super)`, `pub(in path)`, default private to module.
- **Python**: convention only — `_underscore` (protected), `__double` (name-mangled).
- **Kotlin**: `public` (default), `internal` (module), `protected`, `private`.
## 🔗 지식 연결 (Graph)
- Related: [[Encapsulation-and-Information-Hiding|Encapsulation-and-Information-Hiding]] , [[Interface-Segregation-Principle|Interface-Segregation-Principle]]
- Language Specific: TypeScript-Private-Fields
### 매 Encapsulation 의 layer
- **Visibility**: who can see.
- **Mutability**: `final`, `readonly`, `const`, `val`.
- **Identity**: opaque type, newtype.
- **Invariant**: setter validation, factory.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. API 의 stable surface 의 maintain (semver).
2. Library author 의 internal refactoring freedom.
3. Test isolation (private — black-box test 의 강제).
4. Security boundary (capability 의 leak 방지).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### TypeScript 의 `#private` (true private)
```typescript
class BankAccount {
#balance = 0; // 매 runtime 의 private — TS `private` 의 erase 의 X
readonly id: string;
## 🧪 검증 상태 (Validation)
constructor(id: string) { this.id = id; }
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
deposit(amount: number) {
if (amount <= 0) throw new Error('positive only');
this.#balance += amount;
}
get balance() { return this.#balance; }
}
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
const a = new BankAccount('A1');
// a.#balance = 999; // SyntaxError 의 compile + runtime
```
## 🤔 의사결정 기준 (Decision Criteria)
### Rust 의 module visibility
```rust
mod auth {
pub struct User {
pub name: String,
password_hash: String, // 매 module 외부 의 invisible
}
**선택 A를 써야 할 때:**
- *(TODO)*
impl User {
pub fn new(name: &str, pw: &str) -> Self {
User { name: name.into(), password_hash: hash(pw) }
}
pub(crate) fn verify(&self, pw: &str) -> bool {
self.password_hash == hash(pw)
}
}
fn hash(s: &str) -> String { /* ... */ s.into() }
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Java sealed + record
```java
public sealed interface Shape permits Circle, Square, Triangle {}
**기본값:**
> *(TODO)*
public record Circle(double radius) implements Shape {
public Circle { // 매 compact constructor 의 invariant
if (radius < 0) throw new IllegalArgumentException();
}
}
## ❌ 안티패턴 (Anti-Patterns)
// 매 exhaustive switch 의 enable
String describe(Shape s) {
return switch (s) {
case Circle c -> "circle r=" + c.radius();
case Square sq -> "square";
case Triangle t -> "tri";
};
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### C# init-only + required
```csharp
public class Order
{
public required string Id { get; init; } // 매 set 의 only at init
public DateTime Created { get; init; } = DateTime.UtcNow;
private decimal _total;
public decimal Total
{
get => _total;
private set => _total = value >= 0 ? value :
throw new ArgumentException();
}
}
var o = new Order { Id = "ORD-1" }; // 매 valid
// o.Id = "X"; // 매 error: init-only
```
### Python 의 convention + property
```python
class Vault:
def __init__(self, secret):
self._secret = secret # 매 protected (convention)
self.__truly_hidden = "obfuscated" # 매 _Vault__truly_hidden
@property
def secret(self):
# 매 read-only 의 access
return f"***{self._secret[-2:]}"
v = Vault("p@ssword")
print(v.secret) # ***rd
# v.secret = "x" # AttributeError
```
### Capability-based design (no class)
```typescript
// 매 closure-based 의 information hiding
function makeCounter() {
let count = 0;
return {
inc: () => ++count,
get: () => count,
// 매 reset 의 reveal 안 하면 의 capability 의 absent
};
}
const c = makeCounter();
c.inc(); c.inc();
console.log(c.get()); // 2 — count 의 access 의 X
```
### Friend / internal API (Kotlin)
```kotlin
// 매 internal 의 same module 만의 access
internal class IndexBuilder {
internal fun rebuild() { /* ... */ }
}
// 매 @PublishedApi 의 inline function 의 internal API 의 publish
@PublishedApi
internal fun secretImpl() = 42
inline fun publicWrapper() = secretImpl()
```
### Newtype 의 opaque ID
```rust
pub struct UserId(u64); // 매 tuple struct 의 inner 의 private
impl UserId {
pub fn new(id: u64) -> Self { UserId(id) }
pub fn value(&self) -> u64 { self.0 }
}
// 매 raw u64 의 mistakenly UserId 로 의 X — type-safe boundary
fn get_user(id: UserId) { /* ... */ }
// get_user(123); // compile error
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Library API | `pub` 의 minimal surface, internal 의 default |
| Domain model | private field + factory + invariant |
| DTO/value | `record` / `data class` / immutable |
| JS/TS browser code | `#private` (true private) 의 default |
| Cross-module refactoring | `internal`/`pub(crate)` 의 prefer |
**기본값**: most restrictive 의 default. 매 explicit 하 expand.
## 🔗 Graph
- 부모: [[Object-Oriented Programming]] · [[Information Hiding]]
- 변형: [[Module System]] · [[Capability-Based Security]]
- 응용: [[API Design]] · [[Library Design]] · [[Refactoring]]
- Adjacent: [[Abstraction]] · [[SOLID]] · [[Design by Contract]]
## 🤖 LLM 활용
**언제**: API surface review, accessor pattern 의 generate, visibility audit.
**언제 X**: language-specific subtle case (Kotlin internal mangling 등) 의 verify 필수.
## ❌ 안티패턴
- **Public field**: encapsulation 의 broken — invariant 의 enforce 의 X.
- **Getter/setter for everything**: encapsulation 의 illusion (Tell Don't Ask 위반).
- **Reflection 의 private 의 bypass**: test 의 implementation 의 lock.
- **Java private 의 inner class**: enclosing class 의 implicit access — confusion.
- **TS `private` 의 trust**: runtime 의 erase — `#private` 사용.
## 🧪 검증 / 중복
- Verified (Bloch "Effective Java" Item 15, Parnas 1972 "Decomposition", JLS, ECMA-262).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — TS/Rust/Java/C#/Kotlin/Python access patterns |
@@ -2,73 +2,155 @@
id: wiki-2026-0508-engineering-metrics-dora
title: Engineering Metrics (DORA)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-REINFORCE-AUTO-WIKI-GOV-002]
aliases: [DORA, DORA Metrics, Four Keys, DevOps Research and Assessment]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [governance, dora-metrics, engineering-metrics, performance, devops, cycle-time, p-reinforce]
confidence_score: 0.9
verification_status: applied
tags: [devops, metrics, dora, sre, engineering]
raw_sources: []
last_reinforced: 2026-05-01
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: yaml
framework: github-actions
---
# [[Engineering Metrics (DORA)|Engineering Metrics (DORA]]
# Engineering Metrics (DORA)
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터에 기반하여 소프트웨어 인도 성과(Delivery Performance)를 정량화하고, 엘리트 팀의 벤치마크를 통해 개발 프로세스의 병목과 개선 방향을 제시하는 엔지니어링 표준 지표."
## 한 줄
> **"매 deployment frequency, lead time, change fail rate, MTTR — 4 metric 으로 매 engineering org 의 health 측정"**. 매 2014 Google DORA team 의 launch, 매 2021 SPACE framework 보완, 매 2026 GitHub/GitLab/Datadog 의 native dashboard 의 default.
## 📖 구조화된 지식 (Synthesized Content)
DORA 지표는 데브옵스(DevOps) 연구를 통해 입증된 고성과 팀의 핵심 지표입니다.
## 매 핵심
1. **4대 핵심 지표**:
* **Deployment Frequency (DF)**: 배포 빈도.
* **Lead Time for Changes (MLT)**: 코드 커밋부터 배포까지 걸리는 시간.
* **Change Failure Rate (CFR)**: 배포 후 실패율.
* **Failed Service Recovery Time (MTTR)**: 장애 발생 시 복구까지 걸리는 시간.
2. **엘리트 성과자 (Elite Performers)의 특징**:
* **PR 사이즈 제한**: 코드 변경량을 400 LOC 이하로 유지하여 인지 부하를 줄입니다.
* **빠른 리뷰 응답**: 첫 리뷰 응답 시간(TTR)을 1시간 이내로, 전체 완료를 6시간 이내로 유지합니다.
* **자동화 최적화**: 스타일 및 단순 검증을 자동화하여 인간 리뷰어가 아키텍처와 지식 공유에 집중하게 합니다.
3. **성과와 리뷰의 상관관계**:
* 효율적인 코드 리뷰 프로세스를 갖춘 팀은 그렇지 않은 팀보다 인도 성과가 50% 이상 높게 나타납니다.
### 매 Four Keys
- **Deployment Frequency (DF)**: 매 production deploy 의 빈도. Elite = on-demand (multiple/day).
- **Lead Time for Changes (LT)**: 매 commit → production. Elite = < 1 day.
- **Change Failure Rate (CFR)**: 매 deploy 의 incident 유발 비율. Elite = 015%.
- **Mean Time to Recovery (MTTR)**: 매 incident → restore. Elite = < 1 hour.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **속도 vs 안정성**: 지표 개선을 위해 속도에만 집착하면 실패율(CFR)이 올라갈 수 있습니다. 4대 지표는 서로 견제하며 균형을 이루어야 진정한 성과 개선으로 이어집니다.
- **데이터의 맥락**: 단순 수치만으로 팀을 평가하기보다, 지표의 변화 추이를 통해 팀의 프로세스 건전성을 진단하고 병목을 해결하는 도구로 활용해야 합니다.
### 매 Performance tier
- **Elite**: DF on-demand · LT < 1day · CFR 015% · MTTR < 1h.
- **High**: DF weeklydaily · LT 1day1wk · CFR 1630% · MTTR < 1day.
- **Medium**: DF monthly · LT 1wk1mo · CFR 1630% · MTTR 1day1wk.
- **Low**: DF < monthly · LT > 1mo.
## 🔗 지식 연결 (Graph)
- [[Review Performance & Flow|Review Performance & Flow]]: DORA 지표를 달성하기 위한 구체적 운영 전략.
- Small Pull Requests (작은 PR: Lead Time을 단축하는 가장 강력한 수단.
- [[Automated Quality & Review|Automated Quality & Review]]: 인간의 시간을 절약하여 성과를 극대화하는 기반.
- [[CI-CD Pipeline|CI-CD Pipeline]]: 지표 수집과 자동화가 이루어지는 인프라.
- [[DORA-Metrics|DORA Metrics]]: 원본 개념 정의.
---
### 매 응용
1. Sprint retro 매 주 review.
2. Quarterly engineering OKR target.
3. Hiring/promo signal (team-level, 매 individual 아님).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### GitHub Actions deployment frequency
```yaml
# .github/workflows/deploy.yml
name: deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: ./deploy.sh
- name: Emit DORA event
run: |
curl -X POST https://api.dora-collector.internal/events \
-H "Authorization: Bearer ${{ secrets.DORA_TOKEN }}" \
-d '{"type":"deploy","sha":"${{ github.sha }}","ts":"'$(date -u +%FT%TZ)'"}'
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### Lead time calculation (SQL)
```sql
-- commits joined with deploys
SELECT
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (deploy_ts - commit_ts))/3600) AS p50_hours,
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (deploy_ts - commit_ts))/3600) AS p95_hours
FROM dora_events
WHERE deploy_ts >= NOW() - INTERVAL '30 days';
```
## 🧪 검증 상태 (Validation)
### Change failure rate from incidents
```python
# rolling 30d CFR
def cfr(deploys: list[dict], incidents: list[dict]) -> float:
bad_deploys = {i["deploy_sha"] for i in incidents if i["caused_by_deploy"]}
return len(bad_deploys) / max(len(deploys), 1)
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### MTTR via PagerDuty
```python
import httpx, statistics
def mttr(api_key: str, since: str) -> float:
r = httpx.get("https://api.pagerduty.com/incidents",
headers={"Authorization": f"Token token={api_key}"},
params={"since": since, "statuses[]": "resolved"})
durations = [(i["resolved_at_ts"] - i["created_at_ts"]) for i in r.json()["incidents"]]
return statistics.median(durations) / 60 # minutes
```
## 🧬 중복 검사 (Duplicate Check)
### Four Keys dashboard (Datadog)
```yaml
# datadog-dora.yaml
widgets:
- title: Deployment Frequency
query: "sum:dora.deploy{*}.as_count().rollup(sum, 86400)"
- title: Lead Time p50
query: "p50:dora.lead_time_seconds{*}"
- title: CFR
query: "sum:dora.deploy_failed{*} / sum:dora.deploy{*}"
- title: MTTR p50
query: "p50:dora.incident_resolve_seconds{*}"
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Trunk-based config (lead time 단축)
```yaml
# .github/branch-protection.yml
required_status_checks:
strict: true
contexts: [ci/test, ci/lint]
required_pull_request_reviews:
required_approving_review_count: 1
dismiss_stale_reviews: true
restrictions: null # 매 직접 push 매 X — PR-only
```
## 🕓 변경 이력 (Changelog)
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Startup (<20 eng) | DF + LT 매 우선, MTTR 매 secondary |
| Regulated industry | CFR 매 primary (release safety) |
| Platform team | All 4, 매 weekly review |
| Individual perf review | 매 X — team metric only |
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
**기본값**: 매 four-keys-platform (Google open source) self-host + Grafana.
## 🔗 Graph
- 부모: [[DevOps]] · [[Site Reliability Engineering]]
- 변형: [[SPACE Framework]] · [[Flow Metrics]]
- 응용: [[Continuous Delivery]] · [[Continuous Integration]]
- Adjacent: [[Engineering OKRs]] · [[Incident Response]]
## 🤖 LLM 활용
**언제**: deploy log → metric extraction, incident root-cause 분류 (deploy 유발 여부).
**언제 X**: 매 individual contributor scoring 매 X — DORA 매 team-level only.
## ❌ 안티패턴
- **Goodharting**: DF 만 chase 하고 quality 무시 → CFR 폭증.
- **Individual scoring**: developer 별 LT 측정 → gaming (small commits 만).
- **Vanity rollups**: org-wide average — 팀 distribution 의 hide.
- **No CFR**: deploy 만 count, failure track X → false elite signal.
## 🧪 검증 / 중복
- Verified (DORA "State of DevOps" 20142024 reports, Google Cloud 공식).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — DORA four-keys 정의 + dashboard pattern |
@@ -2,21 +2,157 @@
id: wiki-2026-0508-ensuring-data-privacy
title: Ensuring Data Privacy
category: 10_Wiki/Topics
status: merged
redirect_to: 보안_및_시스템_신뢰성_표준
canonical_id: wiki-2026-0507-039
aliases: []
status: verified
canonical_id: self
aliases: [Data Privacy, Privacy Engineering, GDPR Compliance]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [privacy, gdpr, security, compliance]
raw_sources: []
last_reinforced: 2026-05-08
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: applied
tech_stack:
language: Python/TypeScript
framework: OneTrust/Fides/OPA
---
# Redirect
# Ensuring Data Privacy
이 문서는 Canonical 문서인 [[보안_및_시스템_신뢰성_표준]]으로 통합되었습니다.
모든 최신 지식과 세부 내용은 위 링크를 참조하십시오.
## 매 한 줄
> **"매 personal data 가 lawful basis + minimum + purpose-limited 로 다뤄진다."**. Data privacy engineering 은 매 GDPR/CCPA/LGPD/K-PIPA 의 legal requirement 를 매 storage, processing, transfer, retention 의 매 단계 에 deterministic control 로 구현. 2026 stack: classification + DLP + tokenization/PETs (DP, FHE, TEE) + consent management + DSAR automation + privacy-by-design.
## 매 핵심
### 매 Privacy Principle (GDPR Art.5)
1. **Lawfulness, fairness, transparency** — consent / legitimate interest.
2. **Purpose limitation** — 매 collected purpose 외 사용 금지.
3. **Data minimization** — 매 필요한 최소.
4. **Accuracy** — correctable.
5. **Storage limitation** — retention schedule.
6. **Integrity & confidentiality** — encryption.
7. **Accountability** — DPO, audit, DPIA.
### 매 PET (Privacy-Enhancing Tech) 2026
- **Pseudonymization**: tokenization, format-preserving encryption (FPE).
- **Anonymization**: k-anonymity, l-diversity, t-closeness.
- **Differential Privacy**: ε,δ noise — Apple, US Census, Chrome.
- **Federated learning**: 매 model travels, data stays.
- **Homomorphic encryption (FHE)**: 매 compute on encrypted — Microsoft SEAL, OpenFHE.
- **Confidential computing (TEE)**: Intel TDX, AMD SEV-SNP, Apple Private Cloud Compute.
- **Zero-Knowledge Proofs**: identity 증명 without disclose.
### 매 응용
1. EU GDPR + 한국 PIPA + 중국 PIPL compliance.
2. Healthcare HIPAA, PCI-DSS payment.
3. ML training without raw data (FL, DP).
4. Cross-border transfer (SCC, BCR, DPF).
5. Right to be forgotten (RTBF) automation.
## 💻 패턴
### Data classification + DLP
```python
# 매 PII detection — Microsoft Presidio
from presidio_analyzer import AnalyzerEngine
analyzer = AnalyzerEngine()
results = analyzer.analyze(text=user_input, language='en',
entities=['EMAIL_ADDRESS','PHONE_NUMBER','CREDIT_CARD','PERSON','KR_RRN'])
for r in results: redact_or_mask(text, r.start, r.end)
```
### Format-preserving tokenization
```python
# 매 ff3-1 — preserves format (e.g., card number)
from ff3 import FF3Cipher
c = FF3Cipher(key, tweak)
token = c.encrypt("4242424242424242") # → 16-digit string
plain = c.decrypt(token)
```
### Differential Privacy noise
```python
import numpy as np
def laplace_mechanism(true_val, sensitivity, epsilon):
return true_val + np.random.laplace(0, sensitivity / epsilon)
# 매 query: count of users in segment
noisy_count = laplace_mechanism(true_count=1234, sensitivity=1, epsilon=1.0)
```
### k-anonymity check
```python
import pandas as pd
def k_anonymity(df: pd.DataFrame, quasi_ids: list[str]) -> int:
return df.groupby(quasi_ids).size().min()
# 매 ensure k>=5 before release
assert k_anonymity(df, ['zip','age','gender']) >= 5
```
### DSAR (Data Subject Access Request) automation
```python
async def dsar_export(user_id: str) -> bytes:
bundle = {
'profile': await db.users.find_one({'_id':user_id}),
'orders': [o async for o in db.orders.find({'userId':user_id})],
'logs': await elasticsearch_export(user_id),
}
return json.dumps(bundle, default=str).encode()
async def dsar_erasure(user_id: str):
await db.users.update_one({'_id':user_id},
{'$set': {'email':None,'name':None,'erasedAt':datetime.utcnow()}})
await s3.delete_objects(Bucket='pii', Prefix=f'users/{user_id}/')
```
### Consent record (Fides/IAB TCF)
```typescript
const consent = {
userId: 'u_123',
purposes: { analytics: true, marketing: false, personalization: true },
vendors: { google: true },
timestamp: new Date().toISOString(),
version: 'tcf-2.2',
signature: hmac(record),
};
await db.consents.insertOne(consent);
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| EU users | GDPR + Schrems II SCC |
| 한국 users | PIPA — 개인정보처리방침, 위탁 동의 |
| Aggregate analytics | Differential Privacy |
| Payment data | PCI-DSS tokenization |
| ML training | Federated learning + DP |
| Cross-org compute | TEE (Confidential Computing) |
**기본값**: 매 minimize + classify + tokenize + consent ledger + DSAR API.
## 🔗 Graph
- 부모: [[Practical-Cryptography]] · [[Symmetric-Encryption]]
- 변형: [[Zero-Trust Architecture]]
- 응용: [[Anomaly-Detection]] · [[Information-Society]]
- Adjacent: [[Digital Intellectual Property Rights]]
## 🤖 LLM 활용
**언제**: privacy policy 검토, DSAR response draft, PIA 질문 generation.
**언제 X**: 매 PII 를 third-party LLM 에 raw 로 전송 — anonymize 먼저.
## ❌ 안티패턴
- **Hash = anonymized 오해**: 매 hash 는 pseudonymization, GDPR 적용.
- **Consent on entry-only**: 매 ongoing — withdrawable, granular.
- **Log PII**: 매 logger 가 leak source — redact filter.
- **Forever retention**: 매 GDPR 위반 — TTL + erasure.
- **Plaintext backup**: 매 encryption at rest 필수.
## 🧪 검증 / 중복
- Verified: GDPR Art.5/17/25; ISO/IEC 27701; NIST SP 800-188; Microsoft Presidio docs.
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — principles + PETs + DSAR/DP patterns |
@@ -2,85 +2,202 @@
id: wiki-2026-0508-enterprise-scale-monorepo-manage
title: Enterprise Scale Monorepo Management
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Monorepo, Polyrepo vs Monorepo, Bazel, Nx, Turborepo]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [DevOps, Monorepo, Scalability, SoftwareEngineering]
confidence_score: 0.9
verification_status: applied
tags: [monorepo, build-system, devops, ci-cd, scaling]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: nx-turborepo-bazel
---
# [[Enterprise-Scale-Monorepo-Management|Enterprise-Scale-Monorepo-Management]] (엔터프라이즈 모노레포 관리)
# Enterprise Scale Monorepo Management
## 📌 한 줄 통찰 (The Karpathy Summary)
> "하나의 거대한 저장소에서 수많은 서비스를 관리하는 지혜." 수백만 줄의 코드와 수천 개의 의존성을 하나의 레포지토리에서 관리하며 터지는 빌드 속도와 협업 비용 문제를 기술적으로 해결하는 기법이다.
## 한 줄
> **"매 single repo, many projects — 매 build graph 의 일관성"**. 매 monorepo 의 핵심은 모든 코드를 하나의 VCS root 안에 두되, 매 build 시스템이 dependency graph 를 이해해서 affected projects 만 build/test 한다는 점. Google (Piper/Bazel), Meta (Buck2), Microsoft (Rush), 그리고 매 OSS 의 Nx/Turborepo 가 이 패러다임을 driving.
## 📖 구조화된 지식 (Synthesized Content)
- **Shared Codebase**: 패키지 간 코드 공유를 극대화하고 라이브러리 버전 파편화 방지.
- **Caching & Parallelization**: 변경되지 않은 부분의 빌드/테스트를 건너뛰는 지능형 캐싱 ([[Turborepo|Turborepo]], Nx, Bazel).
- **Code Ownership**: 파일 경로나 패키지별로 접근 권한 및 승인 프로세스 정의.
- **Atomic Commits**: 한 번의 커밋으로 여러 개의 상호 연동된 패키지를 동시에 업데이트.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 모노레포는 만능 해결책이 아니다. 적절한 툴링과 자동화가 없으면 체크아웃 속도 저하와 '의존성 지옥'으로 변질된다. 특히 Git LFS나 Partial Clone 같은 고도화된 Git 전략 없이 몸집만 키우면 개발 생산성이 수직 낙하하므로 초기 인프라 설계가 필수적이다.
### 매 Monorepo 가치
- **Atomic cross-project changes**: 매 API + caller 의 한 PR 안에서 변경.
- **Shared tooling**: 매 lint, format, build, test 의 unified config.
- **Visibility**: 매 모든 코드 의 grep-able.
- **Refactor confidence**: 매 type-checker 가 모든 caller 를 검증.
## 🔗 지식 연결 (Graph)
- Related: Micro-[[Frontend|Frontend]]s , CI-CD-Pipelines
- Tools: Nx , Bazel-Build-System
### 매 도전 과제
- **Build time scaling**: 매 naive build 의 N² growth — affected detection 필수.
- **VCS performance**: 매 git 의 100GB+ repo 에서 sparse checkout / VFS 필요.
- **Permissions**: 매 single repo + multiple teams = CODEOWNERS / branch protection.
- **CI cost**: 매 모든 commit 의 모든 project rebuild 의 X — incremental + cache.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 도구 선택
1. **Nx** (TypeScript-heavy, mid-large): smart caching + computation graph.
2. **Turborepo** (Vercel, JS/TS): Rust-based, simple config, remote cache.
3. **Bazel** (polyglot, mega-scale): hermetic builds, network-distributed.
4. **Pants** (Python-heavy): similar to Bazel, lighter setup.
5. **Rush** (.NET / TS): Microsoft's pnpm-based.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Nx workspace structure
```bash
my-org/
├── nx.json
├── package.json
├── tsconfig.base.json
├── apps/
│ ├── web/ # Next.js app
│ └── api/ # NestJS API
├── libs/
│ ├── ui/ # shared React components
│ ├── data-access/# API clients
│ └── utils/
└── tools/
```
## 🤔 의사결정 기준 (Decision Criteria)
### nx.json with affected + cache
```json
{
"tasksRunnerOptions": {
"default": {
"runner": "nx-cloud",
"options": {
"cacheableOperations": ["build", "test", "lint", "e2e"],
"accessToken": "${NX_CLOUD_TOKEN}"
}
}
},
"targetDefaults": {
"build": { "dependsOn": ["^build"], "inputs": ["production", "^production"] },
"test": { "inputs": ["default", "^production", "{workspaceRoot}/jest.preset.js"] }
},
"namedInputs": {
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": ["default", "!{projectRoot}/**/*.spec.ts", "!{projectRoot}/jest.config.ts"]
}
}
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Affected detection in CI
```yaml
# .github/workflows/ci.yml
jobs:
affected:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- uses: nrwl/nx-set-shas@v4
- run: pnpm install --frozen-lockfile
- run: npx nx affected -t lint test build --parallel=4
- run: npx nx affected -t e2e --parallel=1
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Turborepo pipeline
```json
// turbo.json
{
"$schema": "https://turbo.build/schema.json",
"globalDependencies": ["**/.env.*local"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": [".next/**", "!.next/cache/**", "dist/**"]
},
"test": { "dependsOn": ["build"], "outputs": ["coverage/**"] },
"lint": {},
"dev": { "cache": false, "persistent": true }
}
}
```
**기본값:**
> *(TODO)*
### Bazel BUILD file (polyglot)
```python
# libs/ui/BUILD.bazel
load("@npm//:defs.bzl", "npm_link_all_packages")
load("@aspect_rules_ts//ts:defs.bzl", "ts_project")
## ❌ 안티패턴 (Anti-Patterns)
ts_project(
name = "ui",
srcs = glob(["src/**/*.ts", "src/**/*.tsx"]),
declaration = True,
tsconfig = "//:tsconfig",
deps = [
"//libs/utils",
"@npm//react",
"@npm//@types/react",
],
visibility = ["//apps:__subpackages__"],
)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### CODEOWNERS for team boundaries
```
# CODEOWNERS
/apps/web/ @org/frontend-team
/apps/api/ @org/backend-team
/libs/ui/ @org/design-system
/libs/data-access/ @org/backend-team @org/frontend-team
/.github/ @org/platform-team
/tools/ @org/platform-team
```
### Remote cache with Turborepo
```bash
# Self-hosted with turborepo-remote-cache
docker run -p 3000:3000 \
-e TURBO_TOKEN=secret \
-e STORAGE_PROVIDER=s3 \
-e STORAGE_PATH=my-bucket \
ducktors/turborepo-remote-cache
# In repo:
echo 'TURBO_API=http://cache.internal:3000' > .turbo/config.json
echo 'TURBO_TOKEN=secret' >> .turbo/config.json
turbo build --remote-only
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| <50 packages, JS/TS only | Turborepo (simplicity) |
| 50-500 packages, type-heavy | Nx (project graph + generators) |
| Polyglot (Go+Rust+TS+Python) | Bazel (hermeticity) |
| Python ML monorepo | Pants v2 |
| <10 packages | pnpm workspaces alone |
**기본값**: 매 TS/JS team 에게 Turborepo 또는 Nx (size dependent).
## 🔗 Graph
- 부모: [[Build Systems]] · [[Version Control]]
- 변형: [[Polyrepo]] · [[Multi-Repo Federation]]
- 응용: [[CI-CD Pipelines]] · [[Code Ownership]]
- Adjacent: [[Bazel]] · [[Nx]] · [[Turborepo]] · [[pnpm Workspaces]]
## 🤖 LLM 활용
**언제**: refactoring across packages, generating new lib boilerplate (Nx generator), CODEOWNERS automation, dependency graph 분석.
**언제 X**: 매 build cache invalidation logic 의 직접 결정 — Nx/Bazel hash algorithm 신뢰.
## ❌ 안티패턴
- **Single CI job for entire repo**: 매 affected detection 없이 매 commit 모든 build — 30분+ pipeline.
- **No remote cache**: 매 each developer 가 cold rebuild — wasteful.
- **Mixing app-specific and lib code**: 매 libs/ 와 apps/ 의 분리 안 함 — circular deps risk.
- **Implicit dependencies**: 매 package.json 에 list 안 된 import — Bazel/Nx 가 catch.
- **No CODEOWNERS**: 매 review fatigue + ownership 모호.
## 🧪 검증 / 중복
- Verified (Nx Cloud docs 2026, Turborepo 2.0, Bazel 7).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — monorepo tooling matrix + Nx/Turbo/Bazel patterns |
@@ -2,60 +2,148 @@
id: wiki-2026-0508-feature-flags
title: Feature Flags
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-FE FEATURE-FLAGS]
aliases: [Feature Toggles, Feature Switches, Feature Gates]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
tags: [DevOps, FeatureFlags, Deployment, RiskManagement]
confidence_score: 0.9
verification_status: applied
tags: [devops, deployment, experimentation, release-engineering]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: TypeScript/Go
framework: LaunchDarkly/Unleash/OpenFeature
---
# [[Feature-Flags|Feature-Flags]] (피처 플래그)
# Feature Flags
## 📌 한 줄 통찰 (The Karpathy Summary)
> "배포는 하되, 보일지 말지는 스위치로 결정한다." 코드 배포와 기능 출시(Release)를 분리하여, 런타임에 동적으로 기능을 켜고 끄거나 특정 유저에게만 노출할 수 있게 하는 마법의 스위치다.
## 한 줄
> **"매 deploy 와 release 를 매 분리하는 runtime conditional"**. Pete Hodgson 의 매 4-axis taxonomy (release/experiment/ops/permission) 가 매 baseline. 매 modern stack — OpenFeature spec + provider (LaunchDarkly, Unleash, ConfigCat, Statsig) — 매 progressive delivery, A/B test, kill switch 의 매 통합 layer.
## 📖 구조화된 지식 (Synthesized Content)
- **Core Functions**:
- **Kill Switch**: 신규 기능에 치명적인 버그가 발견되면 코드 수정 없이 즉시 비활성화.
- **Canary Release**: 소수의 유저(예: 1%)에게만 기능을 먼저 공개하여 안정성 검증.
- **A/B [[Testing|Testing]]**: 동일한 기능을 두 가지 버전으로 배포하고 성과를 비교.
- **Implementation**: `if (flag('new-ui')) { ... }` 식의 조건문으로 감싸고, 중앙 서버(LaunchDarkly 등)에서 상태를 제어한다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 피처 플래그를 방치하면 코드 곳곳에 조건문이 남게 되어 기술 부채(Technical Debt)가 급증한다. 기능이 성공적으로 안착했다면 즉시 플래그 코드를 지우는 '클린업 사이클'이 운영 프로세스에 반드시 포함되어야 한다. 또한 플래그 설정값 자체가 하나의 '전역 상태'이므로, 이에 대한 히스토리 관리가 필수적이다.
### 매 4 종류 (Hodgson)
- **Release toggle**: dark launch, gradual rollout (short-lived).
- **Experiment toggle**: A/B/n test (medium-lived).
- **Ops toggle**: kill switch, circuit breaker (medium-lived).
- **Permission toggle**: per-user/tenant entitlement (long-lived).
## 🔗 지식 연결 (Graph)
- Related: [[DevOps-and-UX-Convergence|DevOps-and-UX-Convergence]] , Continuous-Deployment
- [[Strategy|Strategy]]: Trunk-Based-Development
### 매 axis
- Lifetime: hours ↔ years.
- Dynamism: build-time → runtime → request-time.
- Scope: global → user → request.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Trunk-based development + dark launch.
2. Canary / progressive rollout (1% → 100%).
3. Kill switch (incident mitigation).
4. A/B testing & holdout group.
5. Tier-based feature gating (free/pro/enterprise).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### OpenFeature SDK (vendor-neutral)
```typescript
import { OpenFeature } from '@openfeature/server-sdk';
import { LaunchDarklyProvider } from '@openfeature/launchdarkly-server-provider';
## 🧪 검증 상태 (Validation)
await OpenFeature.setProviderAndWait(new LaunchDarklyProvider(SDK_KEY));
const client = OpenFeature.getClient();
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
const showNew = await client.getBooleanValue('new-checkout', false, {
targetingKey: user.id,
email: user.email,
plan: user.plan,
});
return showNew ? renderNewCheckout() : renderOldCheckout();
```
## 🧬 중복 검사 (Duplicate Check)
### Percentage rollout (deterministic hash)
```go
import "hash/fnv"
func rollout(flagKey, userID string, percent int) bool {
h := fnv.New32a()
h.Write([]byte(flagKey + ":" + userID))
return int(h.Sum32()%100) < percent
}
// Same user → same bucket across calls (sticky).
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Kill switch (ops toggle)
```typescript
async function fetchRecommendations(userId: string) {
if (await flags.getBooleanValue('reco-kill-switch', false)) {
return []; // disable the feature instantly during incident
}
return recoService.fetch(userId);
}
```
## 🕓 변경 이력 (Changelog)
### Multivariate experiment
```typescript
const variant = await client.getStringValue('checkout-variant', 'control', ctx);
switch (variant) {
case 'one-click': return <OneClickCheckout />;
case 'wallet': return <WalletCheckout />;
default: return <StandardCheckout />;
}
metrics.track('checkout_view', { variant, userId });
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Local override (dev/test)
```typescript
if (process.env.NODE_ENV === 'development') {
OpenFeature.setProvider(new InMemoryProvider({
'new-checkout': { defaultVariant: 'on', variants: { on: true, off: false } },
}));
}
```
### Flag cleanup (technical debt)
```bash
# Find old flags
rg "getBooleanValue\\('old-checkout'" --type ts
# Provider audit: list flags > 90 days old, no recent eval, 100% rollout → delete.
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Dark launch / gradual | Release toggle, percentage rollout |
| Hypothesis test | Experiment toggle + analytics |
| Incident mitigation | Ops toggle (always available) |
| Tier / paid features | Permission toggle (long-lived) |
| Build-time only | Compile flag (no runtime cost) |
**기본값**: OpenFeature SDK + managed provider (LaunchDarkly/Unleash). Kill switch 모든 critical path 에 매.
## 🔗 Graph
- 부모: [[Continuous Delivery]] · [[Progressive Delivery]]
- 변형: [[Release Toggle]] · [[Experiment Toggle]] · [[Kill Switch]]
- 응용: [[Canary Deployment]] · [[A/B Testing]] · [[Trunk-based Development]]
- Adjacent: [[OpenFeature]] · [[LaunchDarkly]] · [[Unleash]] · [[Statsig]]
## 🤖 LLM 활용
**언제**: Release strategy 설계, incident playbook, experiment platform 평가.
**언제 X**: Static config — env var / config file 충분.
## ❌ 안티패턴
- **Flag debt**: 100% rolled-out flag 를 매 안 지움 → cyclomatic complexity 폭발.
- **Nested flags**: A&&B&&C — 매 test space 매 explosion.
- **Flag in hot loop**: per-request eval 의 매 latency — cache locally.
- **No fallback**: provider 다운 시 feature 깨짐 — default + cached value.
- **Flag = config 오용**: 진짜 config 는 매 config service 로.
- **No analytics linkage**: experiment 인데 evaluation 안 records.
## 🧪 검증 / 중복
- Verified (martinfowler.com Feature Toggles, OpenFeature spec, LaunchDarkly docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 4-axis taxonomy + OpenFeature/percentage/kill-switch 패턴 |
@@ -2,87 +2,182 @@
id: wiki-2026-0508-figma-to-code-workflow
title: Figma to Code Workflow
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-Figma-WORKFLOW]
aliases: [Figma to React, Design to Code, Design Token Pipeline]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [Design, Development, Figma, Workflow, DevOps]
confidence_score: 0.85
verification_status: applied
tags: [figma, design-system, tokens, react, workflow]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: react
---
# [[Figma-to-Code-Workflow|Figma-to-Code-Workflow]] (피그마 기반 협업 워크플로우)
# Figma to Code Workflow
## 📌 한 줄 통찰 (The Karpathy Summary)
> "디자이너의 픽셀 언어를 개발자의 코드 언어로 번역하는 끊김 없는 파이프라인." 시안 확인부터 스타일 추출, 컴포넌트 구현까지의 과정을 자동화하고 소통 비용을 최소화하는 현대 웹 개발의 표준 작업 방식이다.
## 한 줄
> **"매 design token 을 single source of truth — 매 Figma Variables → JSON → CSS/TS 의 자동 sync"**. 매 2023 Figma Variables launch 후 표준화, 매 2026 Figma Code Connect + Style Dictionary + LLM-assisted MCP server 가 default workflow.
## 📖 구조화된 지식 (Synthesized Content)
- **The Core Steps**:
1. **[[Design Tokens|Design Tokens]]**: 색상, 폰트, 간격 등을 변수화(Variable)하여 코드의 상수와 1:1 매칭.
2. **Auto Layout**: 피그마의 동적 배치 기능을 사용하여 리스폰시브 레이아웃의 로직을 미리 검증.
3. **Dev Mode**: 피그마 내부에서 개발자가 CSS, 속성 값을 즉시 확인하고 컴포넌트 구조를 파악함.
4. **Inspection & [[HANDOVER|HANDOVER]]**: 디자이너의 수정 사항이 실시간 동기화되며 슬랙 등으로 알림.
- **Collaboration [[Strategy|Strategy]]**: "디자인 수정 -> 코드 반영"이 아니라, 처음부터 공용 **디자인 시스템(Design[[_system|system]])**을 구축하여 사용함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 피그마 시안은 완벽해 보이지만, 실제 데이터가 들어갔을 때(긴 텍스트, 끊긴 이미지 등) 깨지는 경우가 많다. 이를 해결하기 위해 'Storybook'과 피그마를 연동하여 실제 코드로 구현된 컴포넌트를 피그마 안에서 미리 보거나, 'Stitch'와 같은 AI 도구를 통해 피그마 프리뷰를 즉시 작동하는 코드로 변환하는 자동화가 가속화되고 있다.
### 매 Pipeline 단계
1. **Design**: Figma Variables (color, spacing, typography).
2. **Export**: Figma API or Tokens Studio plugin → JSON.
3. **Transform**: Style Dictionary → CSS vars + TS types.
4. **Consume**: components import tokens, 매 hardcode X.
## 🔗 지식 연결 (Graph)
- Related: UI-[[Design-System|Design-System]]s , TailwindCSS-[[Architecture|Architecture]]
- Tool: Stitch (MCP Server)
### 매 Component sync 방식
- **Code Connect**: Figma component ↔ React component pin.
- **Storybook**: Figma plugin 의 design ↔ story link.
- **Visual regression**: Chromatic — 매 token diff 의 detection.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Multi-brand theming: tokens swap → 매 component 의 unchanged.
2. Dark mode: light/dark variable mode toggle.
3. A11y: contrast token 자동 검증.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Figma Variables export (REST)
```ts
// scripts/fetch-figma-tokens.ts
import { writeFileSync } from 'node:fs';
const FILE_KEY = process.env.FIGMA_FILE_KEY!;
const TOKEN = process.env.FIGMA_TOKEN!;
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
const r = await fetch(
`https://api.figma.com/v1/files/${FILE_KEY}/variables/local`,
{ headers: { 'X-Figma-Token': TOKEN } }
);
const { meta } = await r.json();
writeFileSync('tokens/figma.json', JSON.stringify(meta, null, 2));
```
## 🤔 의사결정 기준 (Decision Criteria)
### Style Dictionary config
```js
// style-dictionary.config.js
module.exports = {
source: ['tokens/**/*.json'],
platforms: {
css: {
transformGroup: 'css',
buildPath: 'src/styles/',
files: [{ destination: 'tokens.css', format: 'css/variables' }]
},
ts: {
transformGroup: 'js',
buildPath: 'src/tokens/',
files: [{
destination: 'index.ts',
format: 'javascript/es6',
options: { outputReferences: true }
}]
}
}
};
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Tailwind config consuming tokens
```ts
// tailwind.config.ts
import tokens from './src/tokens';
export default {
theme: {
extend: {
colors: tokens.color,
spacing: tokens.spacing,
fontSize: tokens.font.size
}
}
};
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Figma Code Connect (React)
```tsx
// Button.figma.tsx
import figma from '@figma/code-connect';
import { Button } from './Button';
**기본값:**
> *(TODO)*
figma.connect(Button, 'https://figma.com/file/X/?node-id=1:23', {
props: {
variant: figma.enum('Variant', { Primary: 'primary', Ghost: 'ghost' }),
size: figma.enum('Size', { Small: 'sm', Medium: 'md', Large: 'lg' }),
label: figma.textContent('Label')
},
example: ({ variant, size, label }) => (
<Button variant={variant} size={size}>{label}</Button>
)
});
```
## ❌ 안티패턴 (Anti-Patterns)
### MCP server (Claude/Cursor 의 Figma read)
```json
// .mcp.json
{
"mcpServers": {
"figma": {
"command": "npx",
"args": ["@figma/mcp-server", "--file", "FILE_KEY"],
"env": { "FIGMA_TOKEN": "${FIGMA_TOKEN}" }
}
}
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### CI: token drift detection
```yaml
# .github/workflows/tokens.yml
on: { schedule: [{ cron: '0 9 * * 1-5' }] }
jobs:
sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: pnpm i && pnpm tsx scripts/fetch-figma-tokens.ts
- run: pnpm style-dictionary build
- uses: peter-evans/create-pull-request@v6
with:
title: 'chore: sync Figma tokens'
branch: tokens/auto-sync
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Single brand, small | CSS vars manual export |
| Multi-brand or theming | Style Dictionary + modes |
| Tight design↔code coupling | Code Connect + Storybook |
| LLM-assisted dev | Figma MCP server |
**기본값**: Figma Variables → Style Dictionary → Tailwind/CSS vars + Code Connect.
## 🔗 Graph
- 부모: [[Design System]] · [[Frontend Architecture]]
- 변형: [[Design Tokens]] · [[Theming Strategy]]
- 응용: [[Storybook]] · [[Component Library]]
- Adjacent: [[Tailwind CSS]] · [[Visual Regression]]
## 🤖 LLM 활용
**언제**: Figma MCP → component spec → React scaffold (props, variants 자동).
**언제 X**: 매 pixel-perfect layout 매 manual hand-off 의 X — LLM 매 약함.
## ❌ 안티패턴
- **Hardcoded hex**: `color: #FF6B6B` 매 component 안에 — token swap 매 불가.
- **One-way sync**: code → Figma 의 reverse 무시 → drift.
- **No transform layer**: Figma JSON 매 직접 import — 매 platform-specific 변환 X.
- **Ignoring modes**: light/dark 매 separate file → maintenance hell.
## 🧪 검증 / 중복
- Verified (Figma Variables docs, Style Dictionary 4.x, Code Connect 1.x).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Figma → Style Dictionary → React pipeline |
+132 -68
View File
@@ -2,93 +2,157 @@
id: wiki-2026-0508-figma
title: Figma
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-524A98]
aliases: [Figma Design, FigJam, Dev Mode]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [design, design-tool, collaboration, design-system]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Figma"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript
framework: Figma-Plugin-API/REST-API
---
# [[Figma|Figma]]
# Figma
## 📌 한 줄 통찰 (The Karpathy Summary)
> Figma는 다수의 페이지, 대용량 이미지 및 복잡한 컴포넌트를 사용하여 디자인 및 프로토타이핑을 수행하는 디자인 툴입니다 [1, 2]. 대규모 디자인 파일에서는 스크롤 및 편집 시 지연(Lag) 현상이 발생하거나 프로토타이핑 중 마이크로 지연(Micro-latency)이 발생할 수 있으며, 원활한 사용을 위해 메모리 및 컴포넌트 구조 최적화가 중요하게 요구됩니다 [1, 2].
## 한 줄
> **"매 browser-native, multiplayer, vector design tool 의 매 default standard"**. Field & Wallace 2012 시작 — CRDT-based multiplayer + WebGL canvas + plugin ecosystem 으로 매 Sketch/XD 를 매 시장에서 displace. 매 2025 Adobe 인수 무산 후 independent, AI 기능 (Make Designs, Visual Search) 추가, Dev Mode 가 매 디자인-코드 핸드오프 표준.
## 📖 구조화된 지식 (Synthesized Content)
- **성능 저하의 주요 원인**: 복잡한 컴포넌트와 다수의 페이지가 포함된 프로젝트는 스크롤과 편집 시 래그(Lag)를 유발합니다 [2]. 특히 프로토타입 기능 중 "Smart Animate"는 매 프레임마다 수천 개의 레이어에 대한 복잡한 보간(interpolation)과 레이아웃 계산을 수행해야 하므로, 대형 파일에서는 심각한 성능 저하를 일으키는 원인으로 지목됩니다 [1].
- **메모리 및 문제 진단**: Figma는 성능 문제를 겪는 페이지를 식별할 수 있도록 "[[memory|memory]] Usage(메모리 사용량)" 도구와 "Show memory usage in layers panel(레이어 패널에 메모리 사용량 표시)" 옵션을 제공합니다 [1].
- **레이어 및 구조적 컴포넌트 최적화**: 레이어 수, 그중에서도 특히 인스턴스 내의 '숨겨진 레이어(hidden layers)'를 줄이는 것이 성능 향상의 핵심입니다 [1, 3, 4]. 구조적 컴포넌트(structure components)는 종종 여러 컴포넌트에 숨겨진 레이어를 대량으로 추가하여 성능을 악화시킵니다 [5]. 상호작용에 필수적인 요소만 남기고 구조적 컴포넌트와 불필요한 숨겨진 레이어를 제거하면 프로토타입의 성능이 눈에 띄게 부드러워집니다 [6, 7].
- **베리언트(Variants) 관리**: 포함된 베리언트의 수는 컴포넌트의 업데이트 속도에 직접적인 영향을 미칩니다 [4]. 250여 개의 베리언트를 가진 아이콘 컴포넌트를 여러 개의 개별 컴포넌트로 분리하고 내부의 숨겨진 레이어를 제거한 결과, 업데이트 속도와 전반적인 성능이 대폭 향상된 사례가 있습니다 [7].
- **프로토타이핑 권장 사항**: 성능이 매우 중요한 프로토타입의 경우 "Smart Animate"를 사용하는 대신 단순한 화면 전환(simple transitions)이나 베리언트를 활용하는 것이 마이크로 지연을 줄이고 더 부드러운 상호작용을 보장하는 방법입니다 [1].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 architecture
- WebGL canvas (GPU-accelerated vector rendering).
- Multiplayer via OT/CRDT — sub-100ms cursor sync.
- File = node tree (Document → Page → Frame → ...).
- Component / variant / variable system.
## 🔗 지식 연결 (Graph)
- **Related Topics:** Smart Animate, Hidden Layers, Variants
- **Projects/Contexts:** Figma Performance [[Optimization|Optimization]]
- **Contradictions/Notes:** 베리언트의 수를 최소화하기 위해 중첩된 구조적 컴포넌트(nested structure components)를 사용하는 것은 직관과 달리 성능에 최악의 영향을 미칠 수 있습니다 [8]. 소스에 따르면, 구조적 컴포넌트로 인해 발생하는 숨겨진 레이어를 제거하고 대신 베리언트의 수를 늘리거나 개별 컴포넌트로 쪼개는 것이 오히려 성능 향상에 훨씬 유리합니다 [6, 7].
### 매 핵심 primitive
- **Frame**: layout container (auto-layout = flexbox-like).
- **Component / Instance**: reusable + override.
- **Variable**: design token (color, number, string, boolean) — mode 별 (light/dark).
- **Style**: deprecated 추세, variable 로 대체.
---
*Last updated: 2026-04-19*
### 매 응용
1. Design system 운영 (component library, token).
2. Prototyping (interactive flow).
3. Dev handoff (Dev Mode + code generation).
4. Whiteboard / brainstorming (FigJam).
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Plugin: rename selection
```typescript
// manifest.json: { "main": "code.ts", "ui": "ui.html", "editorType": ["figma"] }
figma.showUI(__html__, { width: 240, height: 120 });
figma.ui.onmessage = (msg: { type: string; prefix: string }) => {
if (msg.type === 'rename') {
for (const node of figma.currentPage.selection) {
node.name = `${msg.prefix}_${node.name}`;
}
figma.notify(`Renamed ${figma.currentPage.selection.length}`);
}
};
```
## 🤔 의사결정 기준 (Decision Criteria)
### Variable mode swap (dark mode)
```typescript
const collection = figma.variables.getLocalVariableCollections()
.find(c => c.name === 'Theme')!;
const darkModeId = collection.modes.find(m => m.name === 'Dark')!.modeId;
figma.currentPage.setExplicitVariableModeForCollection(collection, darkModeId);
```
**선택 A를 써야 할 때:**
- *(TODO)*
### REST API: export frames as PNG
```typescript
const FILE = 'abc123', TOKEN = process.env.FIGMA_TOKEN!;
const r = await fetch(`https://api.figma.com/v1/files/${FILE}`, {
headers: { 'X-Figma-Token': TOKEN }
});
const file = await r.json();
const frameIds = file.document.children.flatMap(p =>
p.children.filter(n => n.type === 'FRAME').map(n => n.id));
const exp = await fetch(
`https://api.figma.com/v1/images/${FILE}?ids=${frameIds.join(',')}&format=png&scale=2`,
{ headers: { 'X-Figma-Token': TOKEN } }
);
const { images } = await exp.json(); // { id: url }
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Token export → Style Dictionary
```typescript
// figma-token-bridge plugin output
const tokens = figma.variables.getLocalVariables().map(v => ({
name: v.name.replace(/\//g, '.'),
value: v.valuesByMode[defaultMode],
type: v.resolvedType,
}));
figma.ui.postMessage({ type: 'export', tokens });
// Then transform to Style Dictionary JSON → CSS / iOS / Android.
```
**기본값:**
> *(TODO)*
### Auto-layout (component definition)
```typescript
const frame = figma.createFrame();
frame.layoutMode = 'HORIZONTAL';
frame.primaryAxisAlignItems = 'CENTER';
frame.counterAxisAlignItems = 'CENTER';
frame.itemSpacing = 8;
frame.paddingLeft = frame.paddingRight = 16;
frame.paddingTop = frame.paddingBottom = 12;
frame.cornerRadius = 8;
```
## ❌ 안티패턴 (Anti-Patterns)
### Webhook: sync to repo
```typescript
// Figma webhook → CI → token regenerate → PR
app.post('/figma-webhook', async (req, res) => {
if (req.body.event_type === 'FILE_UPDATE') {
await exec('npm run tokens:pull && npm run tokens:build');
await octokit.pulls.create({ /* ... */ });
}
res.sendStatus(200);
});
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 디자인 시스템 신규 구축 | Variables + Component + auto-layout |
| 디자인-코드 sync | Webhook + Style Dictionary pipeline |
| Vector illustration | Figma 또는 매 Illustrator (Figma 충분 in 2026) |
| 3D/motion | Figma X — Spline / After Effects |
| Real-time whiteboard | FigJam |
**기본값**: Component + auto-layout + variable. Style 은 매 deprecated.
## 🔗 Graph
- 부모: [[Design Tool]] · [[Collaboration Software]]
- 변형: [[FigJam]] · [[Figma Slides]] · [[Sketch]] · [[Penpot]]
- 응용: [[Design System]] · [[Design Token]] · [[Dev Mode]]
- Adjacent: [[Style Dictionary]] · [[Storybook]] · [[Tokens Studio]]
## 🤖 LLM 활용
**언제**: Design system architecture, plugin authoring, design-code pipeline.
**언제 X**: Vector math 자체 — SVG/Skia primitive 학습 우선.
## ❌ 안티패턴
- **Detached instance 남발**: 매 component 의 의미 사라짐.
- **Style + Variable 혼용**: 매 variable 로 통일.
- **No naming convention**: `Frame 1234` 가 매 디자인 시스템 죽임.
- **Manual handoff (JPG export)**: Dev Mode 또는 매 token pipeline 사용.
- **Unversioned**: Branching feature (Org plan) 사용.
## 🧪 검증 / 중복
- Verified (Figma docs, Plugin API ref, Dev Mode 2024 release notes).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Figma primitives + plugin/REST/token patterns |
@@ -4,112 +4,173 @@ title: Flame Graphs
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-REINFORCE-WIKI-DEV-FLAME-GRAPHS, 플레임 그래프, Flame Graphs, 고드름 그래프, Icicle Graphs, 프로파일링 시각화]
aliases: [Flamegraph, Stack Trace Visualization, Brendan Gregg Flame Graph]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [Profiling, Visualization, Performance, Analysis, Runtime]
raw_sources: [Datacollector_Export_2026-05-02]
last_reinforced: 2026-05-02
confidence_score: 0.9
verification_status: applied
tags: [profiling, performance, observability, perf, ebpf]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: rust
framework: perf-pyspy-pprof
---
# [[플레임 그래프를 활용한 호출 스택 시각화 (Flame Graphs)]]
# Flame Graphs
## 1. 개요
플레임 그래프(Flame Graph)와 고드름 그래프(Icicle Graph)는 소프트웨어 프로파일러를 통해 수집된 호출 스택(Call Stack) 데이터를 시각화하는 도구이다. 시스템이 실행되는 동안 어떤 함수가 가장 많이 호출되었고, 어디에서 시간을 많이 소비했는지를 한눈에 파악할 수 있게 하여 성능 최적화뿐만 아니라 코드베이스의 핵심 실행 경로(Hot path)를 이해하는 데 강력한 통찰을 제공한다.
## 매 한 줄
> **"매 stack trace 의 SVG-ified hierarchy"**. Brendan Gregg (2011) 가 만든 매 visualization — 매 x축은 alphabetical (NOT time), 매 y축은 stack depth, 매 width 는 sample count. 매 hot path 가 매 wide flat plateau 로 즉시 보임. 매 2026 현재 perf, eBPF, py-spy, async-profiler, pprof, Pyroscope 등 매 모든 profiler 가 native output.
## 2. 시각적 구조와 의미
- **X축 (너비)**: 함수 호출의 빈도 또는 소비된 시간의 총량을 의미한다. 막대가 넓을수록 해당 함수가 더 많은 자원을 사용했음을 나타낸다. (알파벳 순서로 나열될 뿐, 시간 순서가 아님에 유의)
- **Y축 (높이)**: 호출 스택의 깊이를 나타낸다. 아래에서 위로(플레임) 또는 위에서 아래로(고드름) 갈수록 중첩된 함수 호출을 의미한다.
- **색상**: 일반적으로 의미는 없으나, 모듈별 또는 함수 유형별로 구분하여 시각적 인지도를 높이는 데 사용된다.
## 매 핵심
## 3. 실전 적용 가치
- **코드 해독의 나침반**: 수만 개의 함수 중 실제 워크로드에서 가장 빈번하게 실행되는 '살아있는 코드'를 즉각 식별하여, 분석 우선순위를 정하는 로드맵으로 활용.
- **성능 병목 지점(Hotspot) 발견**: 예상치 못한 반복 호출이나 긴 대기 시간을 유발하는 지점을 시각적으로 포착하여 리팩토링 포인트 발굴.
- **실제 실행 기반의 팩트 체크**: 개발자의 의도나 문서에 명시된 흐름이 아닌, 런타임에 실제로 일어나는 동작을 객관적으로 증명.
### 매 읽는 법
- **Width = time spent** (sample count proportional). 매 wide = hot.
- **Y = stack depth**. 매 bottom = entry, top = leaf.
- **Color = arbitrary** (typically random hue per function — visual separation only).
- **Plateau at top** = leaf function 의 CPU bound.
- **Tower** = deep call chain (recursion 또는 framework overhead).
## 4. 트레이드오프 및 주의사항
- **관찰 오버헤드**: 프로파일링 데이터 수집 과정에서 시스템 성능이 저하될 수 있으므로, 프로덕션 환경에서는 샘플링 기법을 적절히 조절해야 함.
- **해석의 오해**: X축의 너비가 단순히 '함수 실행 속도'가 아님을 인지해야 한다. (함수 자체의 실행 시간뿐 아니라 자식 함수들의 합산 시간이 포함됨)
- **비동기 흐름의 제약**: 이벤트 루프나 비동기 콜백이 많은 환경에서는 호출 스택이 파편화되어 그래프가 복잡해질 수 있으며, 이를 추적하기 위한 특화된 도구 필요.
### 매 variant
- **CPU flame graph**: 매 on-CPU sample 만 — classic.
- **Off-CPU flame graph**: 매 blocked time (I/O, lock wait) — 매 latency 분석.
- **Differential flame graph**: 매 두 profile 의 diff — red = slower, blue = faster.
- **Icicle (inverted)**: top-down — 매 entry-point 분석에 좋음.
- **Continuous profiling**: 매 Pyroscope / Grafana Phlare 가 매 production 에 항상 켜짐.
## 5. 지식 연결 (Related)
- [[Dynamic_Behavior_Tracking]]: 플레임 그래프의 기반이 되는 동적 분석 데이터 수집 기법.
- [[Profiler_Techniques]]: 그래프를 생성하기 위한 프로파일링 도구 활용법.
- [[Performance_Optimization]]: 그래프 분석 결과를 바탕으로 수행하는 실질적인 개선 활동.
### 매 도구 매핑
1. **Linux native**: `perf record -F 99 -g` + Brendan Gregg's FlameGraph perl script.
2. **eBPF**: `bcc/profile`, `parca-agent` — kernel + user 통합.
3. **Python**: `py-spy record -o flame.svg --pid $PID`.
4. **JVM**: `async-profiler -e cpu -d 30 -f flame.html $PID`.
5. **Go**: `go tool pprof -http=:8080 cpu.prof` (built-in flame graph).
6. **Node.js**: `0x` or `clinic flame`.
## 🧪 검증 상태 (Validation)
- **정보 상태**: 검증 완료 (Verified)
- **출처 신뢰도**: A
- **검토 이유**: 추측이 아닌 데이터 기반의 시스템 해독과 성능 개선을 위한 시각적 분석 표준 정립.
## 💻 패턴
## 📌 한 줄 통찰 (The Karpathy Summary)
### Linux perf → flame graph
```bash
# 1. Sample 99 Hz for 30s, capture stacks
sudo perf record -F 99 -a -g -- sleep 30
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
# 2. Convert to folded format
sudo perf script | \
~/FlameGraph/stackcollapse-perf.pl > out.folded
## 📖 구조화된 지식 (Synthesized Content)
# 3. Render SVG
~/FlameGraph/flamegraph.pl out.folded > flame.svg
**추출된 패턴:**
> *(TODO)*
**세부 내용:**
- *(TODO)*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# Open in browser → click to zoom, search regex highlights
```
## 🤔 의사결정 기준 (Decision Criteria)
### Differential flame graph (before/after)
```bash
~/FlameGraph/stackcollapse-perf.pl < before.perf > before.folded
~/FlameGraph/stackcollapse-perf.pl < after.perf > after.folded
~/FlameGraph/difffolded.pl before.folded after.folded | \
~/FlameGraph/flamegraph.pl --negate > diff.svg
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Continuous profiling with Pyroscope (Go)
```go
import "github.com/grafana/pyroscope-go"
**선택 B를 써야 할 때:**
- *(TODO)*
func main() {
pyroscope.Start(pyroscope.Config{
ApplicationName: "checkout-service",
ServerAddress: "http://pyroscope:4040",
Logger: pyroscope.StandardLogger,
Tags: map[string]string{"region": "us-west-2"},
ProfileTypes: []pyroscope.ProfileType{
pyroscope.ProfileCPU,
pyroscope.ProfileAllocObjects,
pyroscope.ProfileInuseObjects,
},
})
runServer()
}
```
**기본값:**
> *(TODO)*
### py-spy on running Python service
```bash
# 30s sample, draw flame graph
py-spy record -o flame.svg --pid 12345 --duration 30 --rate 100
## ❌ 안티패턴 (Anti-Patterns)
# Native + Python frames combined
py-spy record -o flame.svg --pid 12345 --native
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
# Top-like live view
py-spy top --pid 12345
```
### async-profiler for JVM
```bash
# CPU profile (30s) → flamegraph HTML
./profiler.sh -e cpu -d 30 -f flame.html $(jps | grep MyApp | awk '{print $1}')
# Allocation profile
./profiler.sh -e alloc -d 60 -f alloc.html $PID
# Wall-clock (off-CPU + on-CPU)
./profiler.sh -e wall -t -d 30 -f wall.html $PID
```
### Off-CPU flame graph (eBPF / bcc)
```bash
# Capture off-CPU stacks (blocked time) for 30s
sudo /usr/share/bcc/tools/offcputime -df -p $PID 30 > offcpu.folded
~/FlameGraph/flamegraph.pl --color=io --title="Off-CPU" \
offcpu.folded > offcpu.svg
```
### pprof flame graph (Go built-in)
```go
import _ "net/http/pprof"
go func() { http.ListenAndServe("localhost:6060", nil) }()
// Then on dev machine:
// go tool pprof -http=:8080 http://service:6060/debug/pprof/profile?seconds=30
// → opens browser, click "View" → "Flame Graph"
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Production continuous | Pyroscope / Grafana Phlare / Polar Signals |
| Linux ad-hoc | perf + FlameGraph |
| Python | py-spy (zero-instrumentation) |
| JVM | async-profiler (allocation + CPU + wall) |
| Go | built-in pprof + go tool pprof |
| Node | 0x or clinic flame |
| Latency / blocked | Off-CPU flame graph (eBPF) |
**기본값**: 매 production 에 Pyroscope + 매 dev 에 native profiler.
## 🔗 Graph
- 부모: [[Profiling]] · [[Performance Engineering]]
- 변형: [[Icicle Graphs]] · [[Differential Flame Graph]] · [[Off-CPU Flame Graph]]
- 응용: [[Performance Tuning]] · [[Continuous Profiling]] · [[SRE]]
- Adjacent: [[perf]] · [[eBPF]] · [[pprof]] · [[Pyroscope]]
## 🤖 LLM 활용
**언제**: 매 flame graph 의 hot frame 식별 + optimization 제안, folded text → 자연어 summary, differential interpretation.
**언제 X**: 매 visual exact pixel reading — 매 SVG 자체 사용.
## ❌ 안티패턴
- **Sampling rate too low**: 매 19 Hz — 매 short hot function miss. 매 99 Hz 표준.
- **Without -g (no callgraphs)**: 매 perf record -g 누락 — 매 frames frame 만 보임.
- **No frame pointers (Go ≤1.20, glibc)**: 매 stack unwind 실패 — `-fno-omit-frame-pointer` 또는 DWARF.
- **Reading width as time order**: 매 x축은 time 의 X — alphabetical sort.
- **Production profiling once a year**: 매 continuous 의 가치를 놓침.
## 🧪 검증 / 중복
- Verified (Brendan Gregg 2011, Pyroscope/Grafana Labs 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — flame graph reading guide + perf/py-spy/pprof recipes |
@@ -2,60 +2,193 @@
id: wiki-2026-0508-formal-verification-of-software
title: Formal Verification of Software
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-FORMAL-VERIFICATION]
aliases: [Formal Methods, Program Verification]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [SoftwareEngineering, FormalVerification, Math, Security]
confidence_score: 0.9
verification_status: applied
tags: [formal-methods, verification, correctness]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Coq/Lean/TLA+
framework: Dafny/F*
---
# [[Formal-Verification-of-Software|Formal-Verification-of-Software]] (소프트웨어 정식 검증)
# Formal Verification of Software
## 📌 한 줄 통찰 (The Karpathy Summary)
> "테스트가 99.9%를 보장한다면, 정식 검증은 수학적 증명으로 100%를 보장한다." 코드의 동작이 수학적 모델에 부합하는지 논리적으로 증명하여, 치명적인 버그가 없음을 절대적으로 확신하는 최고수준의 보안/신뢰성 기술이다.
## 한 줄
> **"매 prove correctness, 매 test correctness 의 X"**. Formal verification 의 mathematical proof 의 program 의 specification 에 대한 conformance — 매 testing 의 fundamental superset. 2026 의 industrial use 의 expanding (AWS s2n-tls, sel4, CompCert, Cardano, Dafny in MS, Lean 4 의 mathlib).
## 📖 구조화된 지식 (Synthesized Content)
- **Mechanism**:
- **Model Checking**: 시스템이 가질 수 있는 모든 상태를 전수 조사하여 결함이 없는지 확인.
- **Theorem Proving**: 코드를 수식으로 변환하여 공리([[Axioms|Axioms]])로부터 정답임을 유도함.
- **Use Cases**: 원자력 제어 시스템, 항공기 항법 장치, 스마트 컨트랙트(블록체인), OS 커널 보안.
- **Benefit**: 인간이 결코 상상할 수 없는 아주 희귀한 상황(Edge Cases)에서의 에러도 100% 발견 및 방지.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 정식 검증은 고도의 수학적 지식이 필요하며, 대규모 소스 코드에 적용하기에 연산 비용이 어마어마하다([[State|State]] Explosion). 최근에는 AI가 복잡한 증명 과정을 대신 생성해주거나 코드를 읽고 정식 모델을 자동 추출하는 연구가 진행되어, 일반 상용 소프트웨어 영역으로 문턱을 낮추고 있다.
### 매 Spectrum of rigor
1. **Type systems**: lightweight, daily (TypeScript, Rust borrow checker).
2. **Property-based testing**: empirical, partial (QuickCheck).
3. **Model checking**: finite-state exhaustive (TLA+, SPIN).
4. **Deductive verification**: machine-checked proofs (Coq, Lean, Dafny, F*).
5. **Refinement**: high-level spec → low-level impl preserves properties (Event-B).
## 🔗 지식 연결 (Graph)
- Related: [[SAST (Static Application Security Testing)|SAST (Static Application Security [[Testing]])]] , Cyber-Security
- Concept: [[Logic|Logic]]-And-Mathematics
### 매 Tools (2026 leaders)
- **TLA+**: distributed system specs (used by AWS, Azure for protocols).
- **Coq / Lean 4**: dependent types, proof assistant.
- **Dafny**: verification-aware imperative language (MS).
- **F***: ML-style with refinement types (HACL* crypto, EverParse).
- **Kani / Creusot**: Rust verification.
- **CBMC**: bounded model checker for C.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 What gets verified
- Algorithmic correctness (sorting, hashing).
- Protocol safety (no deadlock, agreement).
- Memory safety (no UAF, overflow).
- Cryptographic implementations (HACL* used in Linux, Firefox).
- Compiler correctness (CompCert).
- OS kernel (seL4 — full functional correctness).
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. Safety-critical (avionics DO-178C Level A, automotive ISO 26262).
2. Crypto libraries (HACL*, Project Everest).
3. Distributed protocols (Paxos, Raft TLA+).
4. Smart contracts (Cardano Plutus, MoveProver).
5. Compilers / kernels (CompCert, seL4).
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### TLA+ — distributed mutex spec
```tla
---- MODULE Mutex ----
EXTENDS Naturals
VARIABLES queue, holder
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
Init == queue = <<>> /\ holder = NULL
## 🧬 중복 검사 (Duplicate Check)
Request(p) == queue' = Append(queue, p) /\ UNCHANGED holder
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
Acquire == /\ queue # <<>>
/\ holder = NULL
/\ holder' = Head(queue)
/\ queue' = Tail(queue)
## 🕓 변경 이력 (Changelog)
MutualExclusion == \A p, q \in Procs : holder = p /\ holder = q => p = q
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
THEOREM Spec => []MutualExclusion
====
```
### Dafny — verified binary search
```dafny
method BinarySearch(a: array<int>, key: int) returns (idx: int)
requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j]
ensures 0 <= idx ==> idx < a.Length && a[idx] == key
ensures idx < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != key
{
var lo, hi := 0, a.Length;
while lo < hi
invariant 0 <= lo <= hi <= a.Length
invariant forall i :: 0 <= i < lo ==> a[i] < key
invariant forall i :: hi <= i < a.Length ==> a[i] > key
{
var mid := (lo + hi) / 2;
if a[mid] < key { lo := mid + 1; }
else if a[mid] > key { hi := mid; }
else { return mid; }
}
return -1;
}
```
### Lean 4 — proof of a simple lemma
```lean
theorem add_zero (n : Nat) : n + 0 = n := by
induction n with
| zero => rfl
| succ k ih => simp [Nat.succ_add, ih]
```
### F* refinement types
```fsharp
val divide : x:int -> y:int{y <> 0} -> int
let divide x y = x / y
// Compiler proves y <> 0 at every call site — divide-by-zero impossible
```
### Kani — Rust harness
```rust
#[kani::proof]
fn check_sum_no_overflow() {
let a: u32 = kani::any();
let b: u32 = kani::any();
kani::assume(a < 1000 && b < 1000);
let sum = a + b;
assert!(sum == a + b); // proven for ALL inputs in range
}
```
### CBMC — bounded check on C
```c
#include <assert.h>
int main() {
int x = nondet_int();
__CPROVER_assume(x >= 0 && x < 100);
int y = x * x;
assert(y >= 0);
return 0;
}
// cbmc file.c → reports counterexample if assertion fails
```
### Property + spec hybrid (Hypothesis)
```python
from hypothesis import given, strategies as st
@given(st.lists(st.integers()))
def test_sort_preserves_length(xs):
assert len(sorted(xs)) == len(xs)
@given(st.lists(st.integers()))
def test_sort_is_ordered(xs):
s = sorted(xs)
assert all(s[i] <= s[i+1] for i in range(len(s)-1))
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Web app daily | Strong types + property tests |
| Distributed protocol | TLA+ model |
| Crypto primitive | F* / HACL* |
| Smart contract | MoveProver / Plutus |
| OS / hypervisor | Coq / seL4-style |
| Rust kernel code | Kani / Creusot |
**기본값**: types everywhere + property-based for parsers + TLA+ for distributed designs + reach for proof assistants only when life/billions on the line.
## 🔗 Graph
- 부모: [[Software_Engineering]] · [[Computer_Science_and_Theory]]
- 변형: [[Type-safe Error Handling Exhaustiveness Checking]] · [[Type Systems]]
- 응용: [[Practical-Cryptography]] · [[SAST]]
- Adjacent: [[Quality-Control]] · [[Test_Automation]]
## 🤖 LLM 활용
**언제**: draft TLA+ specs from prose descriptions, suggest invariants, explain failing proofs.
**언제 X**: never trust LLM-generated proof without checker (Lean/Coq) verifying.
## ❌ 안티패턴
- **Spec ≠ implementation**: verify spec, ship different code.
- **Unverified assumptions**: proofs depend on `axiom` blocks that hide bugs.
- **Verify everything**: cost > benefit for typical CRUD.
- **No model**: claim "formally verified" with handwaved diagram.
## 🧪 검증 / 중복
- Verified (Lamport TLA+ book, Pierce SF, AWS Builders Library 2024 formal methods).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — spectrum + tool examples |
@@ -2,98 +2,198 @@
id: wiki-2026-0508-frustum-culling
title: Frustum Culling
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-7A315B]
aliases: [View Frustum Culling, VFC, Camera Culling]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [graphics, rendering, culling, optimization, gpu]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Frustum Culling"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: cpp
framework: opengl-vulkan-unity
---
# [[Frustum Culling|Frustum Culling]]
# Frustum Culling
## 📌 한 줄 통찰 (The Karpathy Summary)
> 시야 절두체 컬링(Frustum Culling)은 카메라의 시야(View Frustum) 밖으로 벗어난 객체를 렌더링 연산에서 제외하여 불필요한 GPU 자원 소모를 방지하는 최적화 기법이다 [1]. 하지만 [[InstancedMesh|InstancedMesh]]를 적용할 경우 엔진 수준에서 전체를 단일 객체로 취급하므로, 모든 인스턴스를 포함하는 거대한 바운딩 볼륨을 기준으로 한 번만 컬링이 수행되는 '전부 아니면 전무(All-or-Nothing)' 방식으로 작동한다 [2]. 이로 인해 화면에 극히 일부의 인스턴스만 노출되더라도 보이지 않는 나머지 모든 인스턴스의 정점 변환 연산을 GPU가 강제로 수행해야 하는 구조적 한계를 야기한다 [2].
## 한 줄
> **"매 carmera 의 view volume (frustum) 밖 object 의 매 draw skip"**. 매 가장 기본적이고 가장 효과적인 매 visibility culling — 매 30-90% draw call 감소가 일반적. 매 modern engine (Unreal 5 Nanite, Unity HDRP, bevy) 은 매 GPU-driven culling 으로 매 millions of objects 를 매 compute shader 안에서 매 frame 마다 cull.
## 📖 구조화된 지식 (Synthesized Content)
- **InstancedMesh에서의 구조적 비효율성**
Three.js는 기본적으로 카메라 시야 밖의 객체를 자동으로 컬링해 드로우 콜 생성을 방지한다 [3]. 그러나 InstancedMesh를 사용하면 개별 인스턴스 단위의 네이티브 시야 절두체 컬링 기능이 상실된다 [4]. 엔진은 전체 인스턴스의 바운딩 볼륨만을 검사하기 때문에, 10,000개의 객체 중 단 1개만 시야에 들어와도 GPU는 9,999개의 보이지 않는 객체에 대한 정점 셰이더([[Vertex Shader|Vertex Shader]]) 행렬 곱셈 연산을 처리해야 한다 [2]. 이는 특히 저사양 모바일 기기나 통합 GPU 환경에서 치명적인 GPU 점유율 상승 및 프레임 드랍을 유발한다 [2, 5].
## 매 핵심
- **수동 CPU 컬링의 병목 현상**
GPU 낭비를 막기 위해 자바스크립트(CPU) 수준에서 각 인스턴스의 위치를 카메라 평면과 대조하여 가시성을 판단하고 렌더링할 버퍼를 매 프레임 재구성(Reordering)할 수 있다 [5, 6]. 하지만 단일 스레드 특성을 갖는 자바스크립트에서 대규모 배열을 매번 순회하고 조작하는 것은 치명적인 CPU 메인 스레드 병목과 가비지 컬렉션(GC) 부하를 일으킨다 [5].
### 매 frustum 표현
- **6 planes**: near, far, left, right, top, bottom.
- 매 plane equation: `ax + by + cz + d = 0` with `(a,b,c)` = inward normal.
- 매 view-projection matrix 의 매 row combo 로 6 planes extract (Gribb-Hartmann).
- **한계 극복을 위한 대안 전략**
1. **공간 분할 기반 그룹화 전략**: 수만 개의 인스턴스를 하나의 거대한 InstancedMesh로 묶는 대신, 공간적으로 인접한 객체들을 100~500개 단위의 소규모 InstancedMesh로 분할 관리하는 방법이다. 이 경우 드로우 콜 횟수는 다소 증가하지만 시야 절두체 컬링 정밀도가 크게 향상되어 GPU의 무의미한 정점 연산을 극적으로 줄일 수 있다 [7].
2. **GPU 컴퓨트 컬링 및 간접 그리기([[Indirect Draw|Indirect Draw]])**: WebGPU 환경의 컴퓨트 셰이더([[Compute Shader|Compute Shader]])를 활용해 GPU가 직접 인스턴스의 가시성을 판별하도록 처리하는 방식이다 [8, 9]. 판별 결과는 GPU 내부 버퍼에 저장되어 `drawIndirect` 명령으로 즉각 렌더링되므로, CPU 연산 및 CPU-GPU 간 데이터 전송 병목을 완벽히 회피할 수 있다 [9].
3. **확장 라이브러리 도입**: BVH(Bounding Volume Hierarchy)를 이용한 고속 공간 쿼리와 `Instanced[[BufferAttribute|BufferAttribute]]`를 활용한 간접 참조(Indirection) 방식을 통해 기존 InstancedMesh를 확장하여 효율적인 개별 컬링을 제공하는 `[[InstancedMesh2|InstancedMesh2]]`와 같은 외부 라이브러리 활용이 대안이 될 수 있다 [10-12].
### 매 bounding volume choice
- **AABB (axis-aligned)**: 매 cheapest, 매 conservative — 매 large rotated objects 매 over-conservative.
- **OBB (oriented)**: 매 tighter, 매 더 expensive.
- **Sphere**: 매 cheapest test (single dot product), 매 loosest.
- **Plane mask (frustum culling with masks)**: 매 children inherit parent 의 "fully inside" plane.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 알고리즘 흐름
1. View-projection matrix → 6 frustum planes.
2. 매 object 의 BV 와 매 6 planes test.
3. **Outside** any plane → cull.
4. **Inside** all → render.
5. **Intersect** → render (or recurse children if hierarchy).
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[InstancedMesh|InstancedMesh]], Draw Call, [[WebGPU|WebGPU]], Bounding Volume Hierarchy (BVH)
- **Projects/Contexts:** Three.js, [[InstancedMesh2|InstancedMesh2]]
- **Contradictions/Notes:** InstancedMesh 기술은 드로우 콜 감소를 통해 CPU 병목을 획기적으로 해결할 수 있도록 설계되었으나, 동시에 개별 시야 절두체 컬링을 무력화시킴으로써 결과적으로 GPU 측면에 새로운 정점 연산 병목을 유발하는 모순적인 절충(Trade-off)을 요구한다 [5, 13].
### 매 modern (GPU-driven)
- **Compute shader** 가 매 draw arguments buffer 를 build (`DrawIndirect`).
- 매 millions of objects 도 매 sub-millisecond.
- 매 hierarchical Z-buffer occlusion + frustum 결합 (Nanite).
---
*Last updated: 2026-04-19*
## 💻 패턴
---
### Extract frustum planes from VP matrix (Gribb-Hartmann)
```cpp
struct Plane { glm::vec3 n; float d; };
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
void extractPlanes(const glm::mat4& vp, Plane out[6]) {
auto m = glm::transpose(vp); // row-major helper
out[0] = { glm::vec3(m[3]+m[0]), m[3].w + m[0].w }; // left
out[1] = { glm::vec3(m[3]-m[0]), m[3].w - m[0].w }; // right
out[2] = { glm::vec3(m[3]+m[1]), m[3].w + m[1].w }; // bottom
out[3] = { glm::vec3(m[3]-m[1]), m[3].w - m[1].w }; // top
out[4] = { glm::vec3(m[3]+m[2]), m[3].w + m[2].w }; // near
out[5] = { glm::vec3(m[3]-m[2]), m[3].w - m[2].w }; // far
for (int i = 0; i < 6; i++) {
float len = glm::length(out[i].n);
out[i].n /= len; out[i].d /= len;
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Sphere vs frustum (cheapest)
```cpp
bool sphereInFrustum(const Plane planes[6], const glm::vec3& c, float r) {
for (int i = 0; i < 6; i++)
if (glm::dot(planes[i].n, c) + planes[i].d < -r) return false;
return true;
}
```
**선택 A를 써야 할 때:**
- *(TODO)*
### AABB vs frustum (positive vertex / p-vertex test)
```cpp
bool aabbInFrustum(const Plane planes[6], const glm::vec3& mn, const glm::vec3& mx) {
for (int i = 0; i < 6; i++) {
glm::vec3 p = {
planes[i].n.x >= 0 ? mx.x : mn.x,
planes[i].n.y >= 0 ? mx.y : mn.y,
planes[i].n.z >= 0 ? mx.z : mn.z
};
if (glm::dot(planes[i].n, p) + planes[i].d < 0) return false;
}
return true;
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### BVH-based hierarchical culling
```cpp
void cullBVH(const BVHNode& node, const Plane planes[6], std::vector<int>& visible) {
auto r = aabbVsFrustumIntersect(planes, node.aabb);
if (r == OUTSIDE) return;
if (r == INSIDE) { addAll(node, visible); return; }
if (node.isLeaf) {
for (int idx : node.objects)
if (aabbInFrustum(planes, objs[idx].mn, objs[idx].mx))
visible.push_back(idx);
return;
}
cullBVH(*node.left, planes, visible);
cullBVH(*node.right, planes, visible);
}
```
**기본값:**
> *(TODO)*
### GPU compute culling (HLSL)
```hlsl
// CullCS.hlsl
StructuredBuffer<ObjectData> objects : register(t0);
ConstantBuffer<FrustumCB> frustum : register(b0);
RWStructuredBuffer<DrawArgs> drawArgs : register(u0);
RWByteAddressBuffer counter : register(u1);
## ❌ 안티패턴 (Anti-Patterns)
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
if (id.x >= objects.Length) return;
ObjectData o = objects[id.x];
bool visible = true;
[unroll] for (int i = 0; i < 6; i++) {
float4 p = frustum.planes[i];
if (dot(p.xyz, o.center) + p.w < -o.radius) { visible = false; break; }
}
if (visible) {
uint slot;
counter.InterlockedAdd(0, 1, slot);
drawArgs[slot].vertexCount = o.indexCount;
drawArgs[slot].instanceCount = 1;
drawArgs[slot].firstIndex = o.firstIndex;
drawArgs[slot].baseInstance = id.x;
}
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Unity (Burst) culling job
```csharp
[BurstCompile]
struct FrustumCullJob : IJobParallelFor {
[ReadOnly] public NativeArray<float4> planes; // 6 planes
[ReadOnly] public NativeArray<float4> bounds; // xyz=center, w=radius
[WriteOnly] public NativeArray<bool> visible;
public void Execute(int i) {
float4 b = bounds[i];
for (int p = 0; p < 6; p++) {
float4 pl = planes[p];
if (math.dot(pl.xyz, b.xyz) + pl.w < -b.w) {
visible[i] = false;
return;
}
}
visible[i] = true;
}
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| <1k objects, CPU | per-object sphere/AABB test |
| 1k-100k, hierarchical | BVH / Octree + frustum |
| 100k+ static, GPU | compute shader + DrawIndirect |
| Massive (Nanite-class) | GPU-driven + HZB occlusion |
| Animated skeletal | use skinned bounds (loose) |
**기본값**: 매 modern engine — GPU compute culling + BVH for spatial queries.
## 🔗 Graph
- 부모: [[Visibility Culling]] · [[Real-Time Rendering]]
- 변형: [[Occlusion Culling]] · [[Portal Culling]] · [[Backface Culling]]
- 응용: [[GPU-Driven Rendering]] · [[Nanite]] · [[LOD Systems]]
- Adjacent: [[BVH]] · [[Octree]] · [[Hierarchical Z-Buffer]]
## 🤖 LLM 활용
**언제**: plane extraction code 검토, false-cull bug 디버깅 (e.g., flipped normal), GPU shader skeleton.
**언제 X**: 매 actual rendering decision 의 runtime correctness — unit test + visual verification.
## ❌ 안티패턴
- **No bounding volume cache**: 매 frame 마다 매 mesh 의 bound 재계산 — pre-compute.
- **Sphere only for everything**: 매 long thin object 매 over-conservative.
- **Plane normalization 누락**: 매 distance comparison 부정확.
- **Cull camera == render camera 가정**: 매 shadow camera, planar reflection 시 매 잘못.
- **Animated bound 무시**: 매 skinned mesh 의 bound 가 매 outdated → pop in/out.
## 🧪 검증 / 중복
- Verified (Real-Time Rendering 4th ed, Gribb-Hartmann 2001, Unreal Nanite docs 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — frustum extraction + BV tests + GPU-driven |
@@ -2,99 +2,149 @@
id: wiki-2026-0508-geometry-merging
title: Geometry Merging
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-4349BD]
aliases: [Mesh Merging, Static Batching, Geometry Batching]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [graphics, optimization, rendering, gpu]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Geometry Merging"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: C++/HLSL
framework: Unity/Unreal/Three.js
---
# [[Geometry Merging|Geometry Merging]]
# Geometry Merging
## 📌 한 줄 통찰 (The Karpathy Summary)
> **Geometry Merging(지오메트리 병합)**은 Three.js 등의 3D 렌더링 환경에서 정적(static)인 여러 개의 기하학적 데이터를 단일 `[[BufferGeometry|BufferGeometry]]`로 합치는 최적화 기법입니다. 이는 여러 개의 메쉬를 개별적으로 그릴 때 발생하는 **드로우 콜([[Draw Call|Draw Call]])을 단 1회로 줄여주어** CPU 오버헤드를 크게 감소시킵니다. 하지만 개별 객체의 독립적인 이동이나 실시간 상호작용이 제한되며, 객체가 반복될 경우 메모리 사용량이 극심하게 증가한다는 뚜렷한 한계를 가집니다.
## 한 줄
> **"매 여러 mesh 를 매 단일 vertex/index buffer 로 합쳐 매 draw call 수를 매 줄이는 기법"**. CPU-GPU command overhead 의 매 frame budget 의 매 dominant share 였던 시대의 매 staple optimization. 매 modern era — GPU instancing, indirect draw, mesh shader 가 매 알 수 있게 대체했지만 매 static scene, mobile, low-end 에서 매 still relevant.
## 📖 구조화된 지식 (Synthesized Content)
* **원리 및 렌더링 최적화 효과:**
`BufferGeometryUtils.mergeGeometries`와 같은 유틸리티를 사용하여 로드 타임에 여러 메쉬를 하나로 병합하는 방식입니다 [1, 2]. 이 방식은 독립적인 수많은 드로우 콜을 단 하나의 드로우 콜로 결합하므로, **드로우 콜 병목 현상을 완화하는 궁극적인 해결책**을 제공합니다 [3, 4]. 움직임이 필요 없는 정적 씬이나 다수의 부품이 조립된 CAD 렌더링 모델 등에서 높은 프레임 레이트를 유지하는 데 탁월한 효과를 발휘합니다 [4].
## 매 핵심
* **메모리 소모 및 상호작용의 한계:**
병합된 지오메트리는 병합 전 개별 객체의 기하학적 데이터를 모두 고스란히 복제하여 메모리에 저장합니다. 따라서 수천 개의 동일한 객체(예: 의자)를 렌더링할 때 단일 기하 데이터만 참조하는 인스턴싱([[Instancing|Instancing]])과 달리, **메모리(RAM 및 VRAM) 소모가 기하급수적으로 증가**하는 치명적인 단점이 있습니다 [3, 5, 6]. 또한 모든 데이터가 하나로 합쳐져 있으므로, **개별 객체의 위치, 회전, 색상을 실시간으로 변경하거나 개별적인 피킹(Picking) 등 상호작용을 구현하기가 매우 까다롭습니다** [6-8].
### 매 종류
- **Static batching**: build-time 에 같은 material 의 static mesh 합침.
- **Dynamic batching**: runtime 에 small mesh 를 transform & merge (CPU cost ↑).
- **GPU instancing**: 같은 mesh 여러 transform — merging 의 modern 대체.
- **Mesh atlas (texture array)**: material 통합으로 merge 가능 범위 확장.
* **시야 절두체 컬링([[Frustum Culling|Frustum Culling]]) 비효율성:**
모든 객체가 하나의 거대한 메쉬로 병합되면 전체가 **단일 바운딩 볼륨(Bounding volume)으로 취급**됩니다. 이로 인해 합쳐진 덩어리의 극히 일부만 카메라 시야(Frustum)에 들어오더라도 화면에 보이지 않는 나머지 전체 영역까지 모두 렌더링 연산을 수행하게 되어, 결과적으로 GPU 성능의 비효율을 초래할 수 있습니다 [4].
### 매 trade-off
- ↑ Throughput (fewer draw call).
- ↓ Culling 정확도 (merged AABB 가 매 커짐).
- ↑ Memory (per-vertex data 의 매 duplication).
- ↓ Animation flexibility (static 한정).
* **실무적 대안 및 하이브리드 전략:**
절두체 컬링의 문제를 완화하기 위해 공간적 인접성에 따라 메쉬를 나누어 병합하는 **'타일형 병합(Tiled merging)'** 전략이 권장됩니다 [4]. 또한, 메모리와 유연성 문제를 해결하기 위해 동적인 장면이 아니고 모델 크기가 작을 때(< 1GB)에만 병합을 적용하거나 [9], 정적인 저폴리곤 객체는 병합(Merging)하고 동적이거나 고폴리곤인 객체는 `[[InstancedMesh|InstancedMesh]]` 혹은 `BatchedMesh`를 사용하는 **하이브리드 시스템**이 대안으로 활용되기도 합니다 [10, 11].
### 매 응용
1. Mobile 게임 — draw call 의 매 hard limit (~100-200).
2. Architectural visualization — 매 thousands of small props.
3. Tile-based world streaming.
4. UI batching (text glyph atlas).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
## 💻 패턴
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Draw Call|Draw Call]], InstancedMesh, BatchedMesh, Frustum Culling, [[BufferGeometry|BufferGeometry]]
- **Projects/Contexts:** IFC.js Fragment, CAD Rendering [[Optimization|Optimization]]
- **Contradictions/Notes:** 지오메트리 병합은 드로우 콜을 크게 줄여 렌더링 속도를 높이는 장점이 있지만, 단일 바운딩 박스로 묶이게 되어 시야 절두체 컬링 효율성이 떨어지고 메모리 사용량이 극도로 높아져 하드웨어 자원을 쉽게 고갈시킬 수 있다는 트레이드오프(Trade-off)가 존재합니다 [3, 4].
---
*Last updated: 2026-04-19*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Manual merge (Three.js)
```javascript
import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
const geos = props.map(p => p.geometry.clone().applyMatrix4(p.matrixWorld));
const merged = mergeGeometries(geos, false);
const mesh = new THREE.Mesh(merged, sharedMaterial);
scene.add(mesh);
// 1000 draw calls → 1
```
## 🤔 의사결정 기준 (Decision Criteria)
### Unity static batching
```csharp
// Mark objects as static in Inspector → Unity merges at build time.
// Or runtime:
StaticBatchingUtility.Combine(rootGameObject);
// Caveat: combined mesh 64k vertex 한도 (16-bit index).
```
**선택 A를 써야 할 때:**
- *(TODO)*
### GPU instancing (preferred over merge)
```glsl
// vertex shader (Unity URP)
struct Attributes {
float3 positionOS : POSITION;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
UNITY_INSTANCING_BUFFER_START(Props)
UNITY_DEFINE_INSTANCED_PROP(float4, _Color)
UNITY_INSTANCING_BUFFER_END(Props)
**선택 B를 써야 할 때:**
- *(TODO)*
Varyings vert(Attributes IN) {
UNITY_SETUP_INSTANCE_ID(IN);
// ...
}
```
**기본값:**
> *(TODO)*
### Texture atlas (enable merging across materials)
```python
# Bake separate textures into one atlas → assign UV remap.
import numpy as np
atlas = np.zeros((2048, 2048, 4), np.uint8)
uv_remap = {}
for i, tex in enumerate(textures):
x, y = (i % 8) * 256, (i // 8) * 256
atlas[y:y+256, x:x+256] = tex
uv_remap[i] = (x/2048, y/2048, 256/2048, 256/2048)
# Then rewrite mesh UVs per material id.
```
## ❌ 안티패턴 (Anti-Patterns)
### Multi-draw indirect (modern alt)
```cpp
// Instead of merging, keep mesh separate but submit via single indirect call.
struct DrawCmd { uint32_t indexCount, instanceCount, firstIndex, vertexOffset, firstInstance; };
std::vector<DrawCmd> cmds; // one per visible mesh
glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, cmds.data(), cmds.size(), 0);
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Hierarchical merge (octree)
```python
def merge_octree(node):
if node.is_leaf and len(node.meshes) > 1:
node.merged = merge(node.meshes)
else:
for c in node.children: merge_octree(c)
# Coarse cull on octree node, fine draw merged buffer.
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 同 mesh 다수 | GPU instancing (best) |
| Static, 多 unique mesh | Static merging + atlas |
| Modern API (Vk/D3D12) | Indirect draw + bindless |
| Mobile / WebGL legacy | Static batching + atlas |
| Animated / dynamic transform | Per-object draw + culling |
**기본값**: Modern HW → instancing/indirect. Legacy → static merge + atlas.
## 🔗 Graph
- 부모: [[Rendering Optimization]] · [[Draw Call]]
- 변형: [[GPU Instancing]] · [[Mesh Shader]] · [[Indirect Draw]]
- 응용: [[Texture Atlas]] · [[Octree]] · [[BVH]]
- Adjacent: [[Frustum Culling]] · [[LOD]] · [[Vertex Buffer]]
## 🤖 LLM 활용
**언제**: Mobile / web renderer 최적화, asset pipeline 설계.
**언제 X**: Highly dynamic scenes (animation/destruction).
## ❌ 안티패턴
- **Merge everything**: 매 culling 효과 무력화.
- **Material 다른 mesh merge**: shader switch 강제 → benefit 없음.
- **Skinned mesh static merge**: 매 animation broken.
- **64k vertex 한계 모름**: 16-bit index 의 매 silent overflow.
- **Modern API 에서 merge 만 사용**: indirect/instancing 무시.
## 🧪 검증 / 중복
- Verified (Unity docs, Three.js BufferGeometryUtils, GPU Pro series).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — merging vs instancing/indirect 의 trade-off |
@@ -2,93 +2,187 @@
id: wiki-2026-0508-global-network-positioning-gnp
title: Global Network Positioning (GNP)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-D96374]
aliases: [GNP, Network Coordinates, Network Positioning, Vivaldi]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
confidence_score: 0.85
verification_status: applied
tags: [networking, latency-prediction, distributed-systems, p2p, coordinates]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Global Network Positioning (GNP)"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: go
framework: vivaldi-coords
---
# [[Global Network Positioning (GNP)|Global Network Positioning (GNP]]
# Global Network Positioning (GNP)
## 📌 한 줄 통찰 (The Karpathy Summary)
> Global Network Positioning (GNP)은 인터넷 지연 시간(latency)을 다차원 기하학적 공간으로 모델링하여 확장 가능한 지연 시간 추정을 가능하게 하는 접근 방식입니다 [1]. 소수의 전용 '랜드마크(landmark)' 노드에 대한 측정값을 바탕으로 각 인터넷 노드에 해당 공간의 좌표를 부여합니다 [1]. 이를 통해 임의의 두 노드 간의 통신 지연 시간을 실제 측정 없이도 두 좌표 간의 유클리드 거리(Euclidean distance)로 효율적으로 근사할 수 있습니다 [1, 2].
## 한 줄
> **"매 host 를 매 low-D Euclidean space 의 point 로 embed — 매 distance 가 매 network latency 의 predictor"**. Ng & Zhang (SIGCOMM 2002) 의 GNP — 매 landmark 기반 절대 좌표 — 가 매 idea 의 시초. 매 후속작 Vivaldi (Dabek 2004) 가 매 decentralized 형태로 매 P2P / overlay network 에 광범위하게 사용. 매 2026 의 application 은 매 CDN edge selection, DHT routing, server placement.
## 📖 구조화된 지식 (Synthesized Content)
* **동작 원리 및 좌표 계산 체계:** GNP는 $k$개의 랜드마크 호스트 좌표를 사용하여 N차원 기하학적 공간을 결정합니다 [2]. 먼저 랜드마크 간의 지연 시간을 측정한 뒤, 거리와 측정된 지연 시간 사이의 오차를 최소화하는 'Simplex-downhill' 알고리즘을 사용하여 랜드마크들의 좌표를 계산합니다 [3, 4]. 랜드마크의 좌표가 설정되면, 일반 호스트와 각 랜드마크 간의 지연 시간을 바탕으로 해당 호스트의 좌표를 삼각측량 방식으로 계산합니다 [2-4].
* **확장성 및 성능 최적화:** GNP의 가장 큰 장점은 개별 호스트의 위치를 파악하는 데 일정하고 적은 횟수의 측정만 필요하다는 점입니다 [1]. 이 확장성 덕분에 대규모 머신 간의 모든 지연 시간을 낮은 비용으로 빠르게 추정할 수 있습니다 [1].
* **기존 구현의 한계:** 과거의 GNP 구현들은 위치를 파악할 대상 노드의 능동적인 참여(active participation)를 요구했습니다 [5]. 이는 악의적인 노드가 잘못된 지연 시간을 보고할 위험, 랜드마크의 과부하, 그리고 웹 클라이언트와 같은 제3자 환경에 특수 소프트웨어를 배포하기 어렵다는 근본적인 문제를 안고 있었습니다 [5].
* **구글(Google)의 대규모 구현 방식:** 구글은 자사의 콘텐츠 전송 네트워크(CDN)에 GNP를 통합하여 수백만 명의 클라이언트를 포지셔닝하는 대규모 지연 시간 추정 시스템을 구현했습니다 [6, 7]. 이 시스템은 대상 노드의 능동적 참여에 의존하지 않고 랜드마크 측에서 수동적으로(passively) 지연 시간을 측정하며, 확장 가능한 중앙 집중식 스케줄러를 사용하여 네트워크 오버헤드와 랜드마크의 과부하를 정밀하게 제어합니다 [6, 7].
* **좌표의 시간에 따른 안정성 (Coordinate Stability):** 네트워크 라우팅 변경이나 일시적인 혼잡 등으로 인해 GNP 좌표는 시간이 지나면서 초기 값에서 서서히 벗어나는(drift) 경향이 있습니다 [8]. 구글의 분석에 따르면 1주일 후 전체 노드의 25%가 초기값에서 33밀리초(ms) 이상 벗어났지만, 매일 좌표를 재계산(daily recomputation)할 경우 75%의 좌표를 초기값의 6ms 이내로 안정하게 유지할 수 있습니다 [8].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 GNP (centralized) 의 idea
- **Landmark hosts** (예: 15-20개) 가 매 Internet 곳곳에 배치.
- 매 RTT 측정 후 landmark 들의 매 좌표를 매 fixed point 로 fitting (multidim scaling).
- 매 new host 는 매 landmark 들에 ping → 매 자기 좌표 solve.
- 매 두 host 간 RTT ≈ Euclidean distance.
## 🔗 지식 연결 (Graph)
- **Related Topics:** Latency Estimation, Landmark Nodes, Simplex-downhill Algorithm
- **Projects/Contexts:** Google Content Delivery Network (CDN)
- **Contradictions/Notes:** 기존의 수많은 GNP 모델과 구현체들은 시스템 확장을 위해 호스트들의 능동적인 측정 참여를 필수적으로 요구했으나, 구글의 대규모 CDN 구현 사례는 랜드마크 측에서의 수동적 측정과 스케줄러 조합만으로도 능동적 참여의 단점(보안 및 과부하 위험)을 극복하고 시스템을 구축할 수 있음을 증명했습니다.
### 매 Vivaldi (decentralized) 의 차이
- Landmark X — 매 모든 peer 가 random subset 와 매 RTT 교환.
- 매 spring relaxation: 매 over/under-estimated 매 vector 만큼 push/pull.
- 매 height augmentation (extra non-Euclidean dim) 으로 매 access link 의 last-mile 표현.
- 매 dynamic — peer churn 에 자동 적응.
---
*Last updated: 2026-04-19*
### 매 application
1. **CDN routing**: 매 client 좌표 → 매 nearest edge.
2. **DHT optimization**: 매 finger table 을 매 latency-aware 로 선택.
3. **Server selection**: 매 mirror / replica 중 가장 가까운 매 fetch.
4. **Network tomography**: 매 latency map 시각화.
5. **P2P overlays**: BitTorrent, Skype 가 매 사용 (legacy).
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### GNP-style landmark fitting (NumPy)
```python
import numpy as np
from scipy.optimize import minimize
**언제 이 지식을 쓰는가:**
- *(TODO)*
def fit_landmarks(rtt_matrix, dim=4):
"""rtt_matrix[i][j] = measured RTT between landmark i,j (ms)."""
n = rtt_matrix.shape[0]
x0 = np.random.rand(n * dim) * 50
**언제 쓰면 안 되는가:**
- *(TODO)*
def stress(x):
coords = x.reshape(n, dim)
err = 0.0
for i in range(n):
for j in range(i + 1, n):
d = np.linalg.norm(coords[i] - coords[j])
err += ((d - rtt_matrix[i, j]) / rtt_matrix[i, j]) ** 2
return err
## 🧪 검증 상태 (Validation)
res = minimize(stress, x0, method='L-BFGS-B')
return res.x.reshape(n, dim)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def position_new_host(rtts_to_landmarks, landmark_coords, dim=4):
def stress(x):
return sum(
((np.linalg.norm(x - landmark_coords[i]) - rtts_to_landmarks[i])
/ rtts_to_landmarks[i]) ** 2
for i in range(len(rtts_to_landmarks))
)
res = minimize(stress, np.zeros(dim), method='L-BFGS-B')
return res.x
```
## 🤔 의사결정 기준 (Decision Criteria)
### Vivaldi spring relaxation step (Go)
```go
type Coord struct {
Vec []float64 // Euclidean dims
Height float64 // last-mile
Err float64 // local error estimate
}
**선택 A를 써야 할 때:**
- *(TODO)*
const (
Ce = 0.25 // error sensitivity
Cc = 0.25 // coord change sensitivity
)
**선택 B를 써야 할 때:**
- *(TODO)*
// Update local coord after measuring rtt to peer with peerCoord
func (c *Coord) Update(rtt float64, peerCoord Coord) {
w := c.Err / (c.Err + peerCoord.Err)
predicted := dist(c.Vec, peerCoord.Vec) + c.Height + peerCoord.Height
es := math.Abs(predicted-rtt) / rtt
c.Err = es*Ce*w + c.Err*(1-Ce*w)
**기본값:**
> *(TODO)*
delta := Cc * w
direction := unit(sub(c.Vec, peerCoord.Vec))
force := (rtt - predicted) * delta
for i := range c.Vec {
c.Vec[i] += direction[i] * force
}
c.Height = math.Max(0, c.Height+(rtt-predicted)*delta*0.5)
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Edge selection from coordinates
```go
func selectEdge(client Coord, edges []EdgeNode) *EdgeNode {
var best *EdgeNode
bestRTT := math.Inf(1)
for i, e := range edges {
rtt := dist(client.Vec, e.Coord.Vec) + client.Height + e.Coord.Height
if rtt < bestRTT {
bestRTT = rtt
best = &edges[i]
}
}
return best
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### CDN-style anycast hybrid (BGP + GNP fallback)
```python
def route(client_ip):
# Try anycast result first (BGP picks PoP)
pop = anycast_lookup(client_ip)
if pop and recent_health(pop):
return pop
# Fallback: use GNP coords from RIPE Atlas / Cedexis
coord = lookup_client_coord(client_ip)
return min(EDGES, key=lambda e: euclid(coord, e.coord) + e.height + coord.height)
```
### Stress test (predicted vs actual)
```python
def evaluate(coords, ground_truth_rtt):
rel_err = []
for (i, j), actual in ground_truth_rtt.items():
pred = np.linalg.norm(coords[i] - coords[j])
rel_err.append(abs(pred - actual) / actual)
return {
'median_rel_err': np.median(rel_err),
'p90_rel_err': np.percentile(rel_err, 90),
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Centralized infra, fixed landmarks | GNP |
| P2P / dynamic peer set | Vivaldi |
| <100 nodes | Direct measurement (skip embedding) |
| Global CDN | Anycast + GNP fallback |
| Triangle inequality violations frequent | Add height (Vivaldi) or non-Euclidean |
**기본값**: 매 modern usage — Vivaldi w/ height (4D + height).
## 🔗 Graph
- 부모: [[Network Latency]] · [[Distributed Systems]]
- 변형: [[Vivaldi]] · [[Meridian]] · [[King Latency Estimation]]
- 응용: [[CDN]] · [[DHT]] · [[Overlay Networks]]
- Adjacent: [[Anycast]] · [[BGP]] · [[Network Tomography]]
## 🤖 LLM 활용
**언제**: 매 algorithm 설명, 매 stress function tuning 제안, embedding dimension 선택 기준.
**언제 X**: 매 real-time coord update — 매 measured RTT 만이 truth.
## ❌ 안티패턴
- **2D 만 사용**: 매 triangle inequality 자주 violated — 매 4D + height.
- **No error tracking**: 매 Vivaldi 의 local error term 빠짐 → unstable.
- **Static landmarks 의 churn 무시**: 매 landmark 매 fail 시 — health check 필수.
- **Use embedding distance for security**: 매 거리는 매 latency proxy 일 뿐 — 매 trust 의 X.
## 🧪 검증 / 중복
- Verified (Ng & Zhang SIGCOMM 2002, Dabek SIGCOMM 2004).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — GNP/Vivaldi math + edge selection patterns |
@@ -2,98 +2,168 @@
id: wiki-2026-0508-google-code-jam-dataset
title: Google Code Jam Dataset
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-A3BFE1]
aliases: [GCJ Dataset, Code Jam Solutions Corpus, GCJ-297]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
source_trust_level: B
confidence_score: 0.85
verification_status: applied
tags: [dataset, code-llm, benchmark, programming-competition, deduplication]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Google Code Jam Dataset"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: python
framework: huggingface-datasets
---
# [[Google Code Jam Dataset|Google Code Jam Dataset]]
# Google Code Jam Dataset
## 📌 한 줄 통찰 (The Karpathy Summary)
> Google Code Jam Dataset은 구글의 코딩 대회인 Google Code Jam 참가자들이 작성한 소스 코드 해결책들을 모아놓은 데이터셋입니다 [1]. 대회 특성상 코딩 스타일, 가이드라인, 포맷팅에 대한 제약이 없기 때문에 개발자 각자의 고유한 프로그래밍 스타일이 그대로 반영되어 있습니다 [1]. 이러한 특성과 높은 정답(Ground Truth) 순도 덕분에 기계학습을 활용한 코드 스타일로미트리(Code Stylometry, 작성자 식별) 및 소프트웨어 포렌식 연구에서 가장 인기 있고 널리 사용되는 벤치마크 데이터셋 중 하나입니다 [1], [2], [3].
## 한 줄
> **"매 Google Code Jam 의 매 historical archive — 매 code clone detection / code LLM evaluation 의 standard corpus"**. Google 의 매 annual programming competition (2003-2023) 이 매 retire 되었지만 매 solution corpus 는 매 academic 으로 풍부 — 매 multiple solutions per problem, 매 다양한 언어 — 매 code clone, code translation, code-LM benchmark 의 raw material. 매 가장 많이 인용되는 매 GCJ-297 (Bui et al.) 로 매 297 problem × multiple langs.
## 📖 구조화된 지식 (Synthesized Content)
* **데이터셋의 구조적 특성**
Google Code Jam Dataset의 가장 큰 장점은 여러 작성자가 **동일한 문제에 대한 해결책(Semantic uniformity)**을 제공한다는 점입니다 [4]. 이는 머신러닝 분류기가 코드의 의미적(Semantic) 내용이 아닌 작성자 간의 '스타일적 차이'만을 온전히 학습하도록 강제할 수 있게 합니다 [4], [5]. 또한 양적으로도 균형 잡힌 구성을 제공하여 데이터의 불균형 문제 없이 일관된 분석이 가능합니다 [4]. 다만 실제 소프트웨어 개발과는 달리, 코딩 대회 특성상 입출력 처리 등에서 재사용되는 보일러플레이트 코드가 다수 포함될 수 있다는 한계도 존재합니다 [6].
## 매 핵심
* **코드 스타일로미트리(작성자 식별) 연구에서의 활용**
이 데이터셋은 소스 코드뿐만 아니라 컴파일된 실행 파일의 작성자를 식별하는 연구에도 폭넓게 활용되었습니다 [7], [5].
* **소스 코드 분석:** Caliskan-Islam 등은 2008-2014년 대회의 C/C++ 제출물을 활용해 최대 1,600명의 프로그래머를 90% 이상의 정확도로 식별하는 연구를 수행했습니다 [2], [8]. 파이썬 코드를 모은 부분 집합인 *gcjpy* 데이터셋(70명의 작성자, 총 700개 파일)은 AST(추상 구문 트리) 및 CST(구체 구문 트리) 기반의 분류기를 통한 연구나 코드 포맷팅 및 축소(Minification)가 작성자 식별에 미치는 영향을 분석하는 데 사용되었습니다 [1], [4], [9].
* **실행 바이너리 분석:** Rosenblum 등과 Caliskan-Islam 등은 C/C++ 데이터셋을 사용하여 프로그래머의 코딩 스타일이 컴파일 과정을 거친 후에도 바이너리(실행 파일)에 보존된다는 것을 입증하는 데 활용했습니다 [7], [10], [5].
### 매 dataset 의 특이성
- **Same-intent, varied implementations**: 매 단일 problem 에 매 thousands of correct solutions — 매 semantic equivalence 가 ground truth.
- **Multi-language**: C++, Java, Python, Go, Kotlin, …
- **Difficulty stratification**: Qualification → Round 1/2/3 → World Finals.
- **Test cases**: official input/output 이 partial 공개 (sample only) — full hidden.
* **적대적 환경(Adversarial) 연구**
Simko 등은 인간 프로그래머가 다른 사람의 코딩 스타일을 의도적으로 모방하거나 자신의 스타일을 숨기려 할 때 기존의 기계학습 기반 작성자 식별 모델이 얼마나 취약한지를 평가하는 사용자 연구에서 이 데이터셋을 활용했습니다 [11], [12].
### 매 main variants
1. **GCJ-297** (Bui et al. 2017): 297 problems, ~120k solutions, code clone benchmark.
2. **CodeNet** (IBM 2021): 매 GCJ + AIZU — 14M solutions, 4053 problems, 55 langs (superset).
3. **MBXP / HumanEval-X**: 매 not GCJ-derived 지만 매 같은 비교 대상 benchmark.
4. **APPS**: Codeforces + AtCoder + Code Jam mix — 매 LLM coding benchmark.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 use cases
- **Code clone detection**: 매 Type-1/2/3/4 clone 의 ground truth.
- **Code LLM eval**: 매 contamination 위험 매 큼 — 매 Code Jam 매 GitHub 에 publicly indexed.
- **Translation**: 매 Java solution → 매 Python solution.
- **Style transfer**: 매 verbose vs 매 idiomatic.
## 🔗 지식 연결 (Graph)
- **Related Topics:** Code Stylometry, Authorship Attribution, Abstract Syntax Tree (AST), [[Concrete Syntax Tree (CST)|Concrete Syntax Tree (CST]]
- **Projects/Contexts:** Google Code Jam, Machine Learning for Source Code
- **Contradictions/Notes:** 소스에 따르면 Google Code Jam 데이터셋은 높은 순도와 통제된 환경을 제공하여 식별 모델 학습에 매우 적합하지만 [3], 실제 프로덕션 환경의 코드와는 달리 대회 특유의 반복적인 보일러플레이트 코드가 다수 포함되어 있어 실제 현실의 소프트웨어(In the wild)를 대상으로 할 때와는 차이가 발생할 수 있다는 점이 지적됩니다 [6].
## 💻 패턴
---
*Last updated: 2026-04-19*
### Loading via Hugging Face
```python
from datasets import load_dataset
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# CodeNet (largest superset including GCJ)
ds = load_dataset("Project-CodeNet/codenet", split="train", streaming=True)
for ex in ds.take(3):
print(ex["problem_id"], ex["language"], ex["status"], len(ex["code"]))
```
## 🤔 의사결정 기준 (Decision Criteria)
### Filter for GCJ subset only
```python
gcj = ds.filter(lambda x: x["dataset_origin"] == "google_code_jam")
print(gcj.info.splits)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Group solutions by problem_id (clone-detection setup)
```python
from collections import defaultdict
buckets = defaultdict(list)
for ex in gcj:
if ex["status"] == "Accepted":
buckets[ex["problem_id"]].append(ex)
**선택 B를 써야 할 때:**
- *(TODO)*
# Pair within bucket = positive (clone), across bucket = negative
positive_pairs = [(a, b) for sols in buckets.values()
for a, b in itertools.combinations(sols, 2)]
```
**기본값:**
> *(TODO)*
### Decontamination check (LLM training data)
```python
import hashlib
def near_dup_hash(code: str, k=5) -> set[int]:
tokens = code.split()
return {hash(' '.join(tokens[i:i+k])) for i in range(len(tokens) - k)}
## ❌ 안티패턴 (Anti-Patterns)
train_hashes = set()
for ex in train_corpus:
train_hashes |= near_dup_hash(ex["code"])
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
contaminated = [
ex for ex in gcj_eval
if len(near_dup_hash(ex["code"]) & train_hashes) / max(1, len(near_dup_hash(ex["code"]))) > 0.5
]
print(f"contamination ratio: {len(contaminated) / len(gcj_eval):.2%}")
```
### Compile + run sandbox (judging on test cases)
```python
import subprocess, tempfile, pathlib
def judge(code: str, lang: str, stdin: str, expected: str, timeout=5):
with tempfile.TemporaryDirectory() as d:
p = pathlib.Path(d) / ("sol." + {"python": "py", "cpp": "cpp"}[lang])
p.write_text(code)
if lang == "cpp":
subprocess.run(["g++", "-O2", "-std=c++20", str(p), "-o", f"{d}/a"], check=True)
cmd = [f"{d}/a"]
else:
cmd = ["python3", str(p)]
try:
r = subprocess.run(cmd, input=stdin, capture_output=True, text=True, timeout=timeout)
return r.stdout.strip() == expected.strip()
except subprocess.TimeoutExpired:
return False
```
### Train/eval split for code translation
```python
import random
random.seed(0)
problems = list(buckets.keys())
random.shuffle(problems)
train_pids = set(problems[:int(0.9 * len(problems))])
train, eval = [], []
for pid, sols in buckets.items():
java = [s for s in sols if s["language"] == "java"]
py = [s for s in sols if s["language"] == "python"]
pairs = list(itertools.product(java, py))
(train if pid in train_pids else eval).extend(
{"src": j["code"], "tgt": p["code"]} for j, p in pairs
)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Code clone benchmark | GCJ-297 (Bui et al.) |
| LLM coding eval | APPS or HumanEval (less contaminated) |
| Code translation | CodeNet pair-wise |
| Style benchmark | GCJ multi-solution per problem |
| Live evaluation | NEVER use GCJ alone (contamination) |
**기본값**: 매 LLM eval — APPS/HumanEval 매 main + GCJ 매 supplementary.
## 🔗 Graph
- 부모: [[Code Datasets]] · [[Code LLM Benchmarks]]
- 변형: [[CodeNet]] · [[APPS Dataset]] · [[HumanEval]]
- 응용: [[Code Clone Detection]] · [[Code Translation]] · [[LLM Coding Eval]]
- Adjacent: [[Codeforces Dataset]] · [[LeetCode Solutions Corpus]] · [[Decontamination]]
## 🤖 LLM 활용
**언제**: 매 dataset filter pipeline 작성, contamination 검사 design, problem grouping logic.
**언제 X**: 매 LLM 자체 평가 — 매 GCJ 가 매 training data 에 포함되어 있을 확률 높음 (contamination).
## ❌ 안티패턴
- **GCJ for SOTA LLM eval without dedup**: 매 contamination 으로 매 score inflation.
- **Sample IO 만 사용**: 매 wrong-answer 가 매 test-case 통과 가능.
- **No timeout in judging**: 매 infinite loop 으로 OOM/hang.
- **Mixing accepted + WA**: 매 ground truth 의 정확성 저하.
- **Ignoring problem difficulty**: 매 stratified eval 필수.
## 🧪 검증 / 중복
- Verified (Bui et al. ICSE 2017, IBM Project CodeNet 2021, Hugging Face Hub).
- 신뢰도 B (semi-public, scraped).
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — GCJ corpus + CodeNet usage + decontamination |
@@ -1,67 +1,33 @@
---
id: wiki-2026-0508-hmd-head-mounted-display-기반-엑서게임
title: HMD(Head Mounted Display) 기반 엑서게임 환경
title: HMD(Head-Mounted Display) 기반 엑서게임 환경
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
aliases: [P-Reinforce-AUTO-E05076]
duplicate_of: none
status: duplicate
canonical_id: vr-exergame
duplicate_of: "[[VR Exergame]]"
aliases: []
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - HMD(Head-Mounted Display) 기반 엑서게임 환경"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
confidence_score: 0.85
verification_status: redirected
tags: [duplicate, vr, exergame, hmd]
last_reinforced: 2026-05-10
github_commit: pending
---
# [[HMD(Head-Mounted Display) 기반 엑서게임 환경|HMD(Head-Mounted Display) 기반 엑서게임 환경]]
# HMD(Head-Mounted Display) 기반 엑서게임 환경
## 📌 한 줄 통찰 (The Karpathy Summary)
> HMD(Head-Mounted Display) 기반 엑서게임 환경은 가상현실(VR) 기술을 활용하여 사용자의 신체적 운동과 게임 플레이를 결합한 몰입형 시스템입니다. 이 환경은 현실감 넘치는 3D 공간과 전방위적인 시야를 제공함으로써 사용자가 운동의 신체적 피로를 잊게 하고 지속적으로 운동에 참여할 수 있는 강력한 동기를 부여합니다 [1]. 그러나 높은 몰입감을 제공하는 대신, 신체 움직임과 시각적 자극의 불일치로 인해 화면 기반(Screen-based) 환경보다 VR 멀미([[VR Sickness|VR Sickness]])나 시각적 피로를 유발할 가능성이 더 크다는 특징을 지닙니다 [2].
> **이 문서는 [[VR Exergame]] 의 중복본입니다.** Canonical 문서로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
- **몰입감과 운동 동기 부여:** HMD 기반의 VR 엑서게임은 사용자를 가상 세계의 목표와 서사에 깊이 빠져들게 하여 신체적 노력에서 오는 고통을 효과적으로 분산시킵니다 [1]. 이러한 실재감(Presence)과 몰입은 사용자의 엑서게임 동기와 지속적인 참여를 이끌어내는 가장 핵심적인 요소입니다 [1].
- **VR 멀미(VR Sickness)의 발생:** HMD를 착용한 채로 활발한 신체 움직임이 요구되는 엑서게임을 플레이할 경우, 일반적인 대형 화면 기반 게임에 비해 메스꺼움, 방향 감각 상실 등 시뮬레이터 멀미 증상이 더 높게 나타날 수 있습니다 [2, 3]. 이러한 VR 멀미는 게임의 실재감을 깨뜨리고 즐거움과 동기를 저하시키며 인지 능력과 작업 수행 능력을 떨어뜨릴 수 있습니다 [3].
- **시각적 부작용 및 노출 시간의 영향:** HMD 사용 시 발생하는 눈의 폭주(Vergence)와 조절(Accommodation) 간의 불일치는 깊이 지각에 혼란을 주어 두통, 눈의 피로, 시야 겹침 현상 등의 안구 운동 관련 증상을 초래할 수 있습니다 [3, 4]. 인기 VR 엑서게임인 '[[Beat Saber|Beat Saber]]'를 활용한 연구에 따르면, 게임 노출 시간이 길어질수록(예: 10분 대비 50분) 즉각적인 멀미 증상과 시각/인지적 영향이 유의미하게 증가하는 것으로 나타났습니다 [5-7].
- **사후 회복 및 안전 권고:** 대부분의 사용자는 장시간 HMD 엑서게임을 수행한 후 멀미 증상이나 인지 및 시각적 변화를 겪더라도, VR 기기를 벗고 약 40분의 휴식을 취하면 기준선(Baseline) 수준으로 정상 회복됩니다 [6, 7]. 따라서 HMD 엑서게임을 안전하게 활용하기 위해서는 긴 시간 플레이하기 전 짧은 세션을 통해 멀미 발생 여부를 테스트하고, 플레이 종료 후 충분한 대기 및 휴식 시간을 갖는 것이 권장됩니다 [8].
## 핵심 요약 (specialization aspects)
- HMD 기반 exergame (운동게임) 환경 — 매 VR 헤드셋 (Quest 3, Vision Pro, PSVR2) 의 매 6DoF tracking + room-scale + presence 가 매 traditional Wii/Kinect 대비 매 immersion ↑.
- 매 한국어 medical/rehab 문헌 에서 자주 등장 — 매 신체활동 + 인지자극 결합.
- Canonical 문서가 매 hardware (HMD, controller, treadmill, haptic suit), 매 game design (Beat Saber, Supernatural, FitXR), 매 health outcome 측정을 통합 관리.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
## 🔗 Graph
- 부모: [[VR Exergame]] (canonical)
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[VR 멀미 (VR Sickness)|VR 멀미(VR Sickness]], 실재감(Presence), [[폭주-조절 불일치(Vergence-accommodation conflict)|폭주-조절 불일치(Vergence-Accommodation Conflict]]
- **Projects/Contexts:** [[Beat Saber|Beat Saber]], [[가상현실(VR) 자전거 시뮬레이터|가상현실(VR) 자전거 시뮬레이터]]
- **Contradictions/Notes:** HMD 기반 엑서게임은 기존 화면 기반 게임과 비교했을 때 사용자에게 더 높은 몰입감을 제공하여 운동 효과를 극대화할 수 있지만, 반대로 신체 움직임 증가와 시각적 자극으로 인해 VR 멀미의 유발 가능성을 높인다는 양면적인 모순을 가집니다 [2]. 노출 시간에 비례해 멀미 증상이 증가하지만 대부분 40분 이내에 자연 회복되므로 적절한 휴식과 함께 병행해야 합니다 [6, 9].
---
*Last updated: 2026-04-19*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -2,66 +2,156 @@
id: wiki-2026-0508-high-resolution-time
title: High Resolution Time
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-05BDE3]
aliases: [performance.now, Monotonic Time, HR Time, Hi-Res Timer]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [web-api, performance, timing, security]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - High Re[[Solution|Solution]] Time"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: JavaScript/C
framework: W3C-HRTime/POSIX
---
# [[High Resolution Time|High Resolution Time]]
# High Resolution Time
## 📌 한 줄 통찰 (The Karpathy Summary)
> High Resolution Time(HR-time)은 웹 브라우저 환경에서 고정밀로 시간을 측정하기 위해 사용되는 사양(Spec) 및 메커니즘을 의미한다. 그러나 [[Spectre|Spectre]]나 Meltdown 같은 타이밍 기반의 사이드 채널 공격을 방지하기 위해 이 사양은 `performance.now()`와 같은 측정 도구의 해상도를 의도적으로 제한(Coarsening)하고 있다. 최근 [[WebGPU|WebGPU]]의 타임스탬프 쿼리 기능 역시 이 HR-time 사양의 기준을 참조하여 보안과 성능 측정의 균형을 맞추고 있다.
## 한 줄
> **"매 sub-millisecond 정밀도의 매 monotonic clock"**. W3C High Resolution Time spec — `performance.now()` 가 매 `Date.now()` 의 ms 한계 + wall-clock jitter 를 매 해결. 매 Spectre 후 — 모든 brower 가 매 timer 정밀도를 매 100µs ~ 1ms 로 매 reduce + cross-origin isolation 으로 매 5µs 회복.
## 📖 구조화된 지식 (Synthesized Content)
- **보안 취약점에 따른 정밀도 제한 (Coarsening):** Spectre 및 Meltdown과 같은 캐시 사이드 채널 공격은 서브 마이크로초(sub-microsecond) 수준의 미세한 타이밍 차이를 이용해 메모리 접근 패턴을 파악한다 [1]. 이를 막기 위해 브라우저 엔진들은 `performance.now()`와 같은 타이머의 정밀도를 시스템의 격리 상태(isolation status)에 따라 1ms 또는 100 마이크로초(µs) 단위로 낮추었다 [1].
- **지터(Jitter)의 도입:** 일부 브라우저 구현에서는 반환되는 시간 값에 작고 무작위적인 변동인 '지터(Jitter)'를 추가하여, 공격자가 통계적 평균을 통해 고정밀 시계를 재구성하는 것을 방지한다 [1].
- **컨텍스트에 따른 해상도 차이:** High Resolution Time 사양(HR-time spec)은 크로스 오리진 격리(cross-origin isolated) 컨텍스트에서는 5µs로, 격리되지 않은(non-isolated) 컨텍스트에서는 100µs(또는 구현이 선호하는 더 거친 수준)로 해상도를 제한하도록 권장한다 [2].
- **WebGPU 타임스탬프 쿼리([[Timestamp Queries|Timestamp Queries]]) 연동:** WebGPU 환경에서 GPU 연산 소요 시간을 측정하는 타임스탬프 쿼리 기능도 타이밍 공격의 위험이 있어 정밀도 조정이 필요했다 [3-5]. 이에 따라 GPU for the Web 커뮤니티 그룹은 타임스탬프 값을 HR-time 사양을 참조하여 격리 여부와 무관하게 비격리 해상도 기준인 100µs로 제한([[Quantization|Quantization]])하기로 합의하여 일관성 있는 보안 조치를 적용하였다 [6-8].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 vs Date.now
- `Date.now()`: wall clock, ms 단위, NTP 으로 점프 가능 (음수 delta!).
- `performance.now()`: monotonic, fractional ms, navigation start 기준.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Spectre and Meltdown|Spectre and Meltdown]], WebGPU Timestamp Queries, performance.now()
- **Projects/Contexts:** High Resolution Time spec (
- **Contradictions/Notes:** 소스 내에 특별한 모순은 없으나, High Resolution Time의 정밀도는 적용되는 보안 격리 환경(Isolated vs Non-isolated) 및 브라우저 엔진의 방어 메커니즘에 따라 5µs, 100µs, 1ms 등 상이하게 적용된다는 점을 유의해야 한다 [1, 2].
### 매 timer attack mitigation
- Spectre/Meltdown (2018) → 매 brower 가 timer fuzz/round.
- Default: 100µs ~ 1ms rounding + jitter.
- COOP+COEP (cross-origin isolated) 시 → 5µs 정밀 + `SharedArrayBuffer`.
---
*Last updated: 2026-04-19*
### 매 응용
1. Animation frame timing (`rAF` callback).
2. Performance profiling (`User Timing API`).
3. WebGL/WebGPU frame budget tracking.
4. Audio scheduling (`AudioContext.currentTime` 동기).
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Basic timing
```javascript
const t0 = performance.now();
heavyWork();
const elapsed = performance.now() - t0;
console.log(`took ${elapsed.toFixed(3)} ms`); // 12.345 ms
```
**언제 이 지식을 쓰는가:**
- *(TODO)*
### User Timing API (DevTools 표시)
```javascript
performance.mark('render-start');
render();
performance.mark('render-end');
performance.measure('render', 'render-start', 'render-end');
const [m] = performance.getEntriesByName('render');
console.log(m.duration);
// Visible in Chrome DevTools Performance panel.
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### Frame budget tracker
```javascript
let lastT = performance.now();
function frame(now) {
const dt = now - lastT;
lastT = now;
if (dt > 16.7) console.warn(`slow frame: ${dt.toFixed(1)}ms`);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
```
## 🧪 검증 상태 (Validation)
### Cross-origin isolated (max precision)
```http
# Server response headers
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```
```javascript
if (crossOriginIsolated) {
// performance.now() granularity ~5µs
// SharedArrayBuffer 가능
}
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### POSIX equivalent (C)
```c
#include <time.h>
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
do_work();
clock_gettime(CLOCK_MONOTONIC, &t1);
double elapsed_ns = (t1.tv_sec - t0.tv_sec) * 1e9 + (t1.tv_nsec - t0.tv_nsec);
```
## 🧬 중복 검사 (Duplicate Check)
### Rust std (cross-platform)
```rust
use std::time::Instant;
let t0 = Instant::now();
heavy_work();
println!("took {:?}", t0.elapsed()); // sub-ns precision on modern HW
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Debounce slow timers
```javascript
// If you measure dt < 0.1ms repeatedly, you're in fuzzed timer mode.
function isolatedPrecisionAvailable() {
const samples = Array.from({length: 100}, () => {
const a = performance.now(); const b = performance.now();
return b - a;
});
return samples.some(d => d > 0 && d < 0.05); // sub-100µs visible
}
```
## 🕓 변경 이력 (Changelog)
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Wall-clock event log | `Date.now()` / `Date.toISOString()` |
| Profile / micro-bench | `performance.now()` + User Timing |
| Frame loop | rAF callback timestamp (매 monotonic) |
| Audio sync | `AudioContext.currentTime` |
| Cross-origin iframe | postMessage with monotonic delta |
| Native (Linux/macOS) | `clock_gettime(CLOCK_MONOTONIC)` |
| Native (Windows) | `QueryPerformanceCounter` |
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
**기본값**: Duration 측정엔 매 monotonic. 매 Date 는 user-facing timestamp 만.
## 🔗 Graph
- 부모: [[Web Performance APIs]] · [[Time Measurement]]
- 변형: [[Performance Timeline]] · [[Long Tasks API]] · [[Event Timing API]]
- 응용: [[Core Web Vitals]] · [[User Timing]] · [[Animation Frame]]
- Adjacent: [[Spectre]] · [[Cross-Origin Isolation]] · [[SharedArrayBuffer]]
## 🤖 LLM 활용
**언제**: 성능 측정 코드 작성, profiling, frame budget 분석.
**언제 X**: Persistent timestamp / event log 매 wall-clock 필요 시.
## ❌ 안티패턴
- **`Date.now()` for delta**: NTP step 시 음수 / 점프 가능.
- **`new Date()` 매 hot loop**: allocation cost + ms 한계.
- **Assuming sub-ms precision**: COOP/COEP 없으면 매 1ms rounded.
- **Cross-origin worker timing**: postMessage 의 매 ms 단위 transmit overhead.
- **`setTimeout` 으로 정밀 timing**: 매 4ms+ minimum, jittery.
## 🧪 검증 / 중복
- Verified (W3C HR Time Level 3, MDN performance.now, Chrome timer reduction notes).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — performance.now + Spectre mitigation + COOP/COEP 5µs |
+162 -71
View File
@@ -2,95 +2,186 @@
id: wiki-2026-0508-husky
title: Husky
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-9068BA]
aliases: [Husky Git Hooks, husky v9, lint-staged, pre-commit]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
confidence_score: 0.95
verification_status: applied
tags: [git, hooks, devex, ci, lint-staged]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Husky"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: javascript
framework: husky-v9
---
# [[Husky|Husky]]
# Husky
## 📌 한 줄 통찰 (The Karpathy Summary)
> Husky는 개발 프로젝트에서 Git 훅([[Git Hooks|Git Hooks]])을 쉽게 설정, 관리 및 팀원들과 공유할 수 있도록 지원하는 소프트웨어 도구입니다 [1]. 기본적으로 버전 관리 대상이 아닌 Git 훅의 한계를 극복하여 `.husky/`와 같은 추적 가능한 디렉토리를 통해 훅 스크립트를 관리하게 해줍니다 [1, 2]. 주로 `[[lint-staged|lint-staged]]`와 결합하여 커밋이나 푸시 전에 자동으로 코드 린팅(linting) 및 포맷팅을 수행하여 코드 품질을 강제하는 데 사용됩니다 [3, 4].
## 한 줄
> **"매 npm-friendly git hooks 의 facto-standard"**. Husky 는 매 `.husky/` directory 안에 매 plain shell script 로 hook 정의 — 매 `git config core.hooksPath` 으로 자동 설정. 매 v9 (2024-2026) 부터 매 거의 zero-config: `npx husky init` → 매 husky/_/h prepare-commit-msg 등 매 wrapper 자동 생성. 매 lint-staged 와의 매 pairing 이 매 표준 setup.
## 📖 구조화된 지식 (Synthesized Content)
* **Git 훅의 한계 극복 및 구동 원리:** Git의 기본 훅은 `.git/hooks/` 디렉토리에 저장되어 버전 관리 도구에 의해 추적되지 않습니다. 이로 인해 새로운 팀원이 프로젝트를 클론할 때 훅이 자동으로 설정되지 않는 문제가 발생합니다 [1]. Husky는 Git의 `core.hooksPath` 속성을 사용하여 추적 가능한 디렉토리(예: `.husky/`)에 실제 훅 파일(셸 스크립트)을 생성하고 관리함으로써 이 문제를 해결합니다 [1, 2].
* **설치 및 자동화 설정:** `npx husky init` (또는 `husky-init`) 명령어를 실행하면 프로젝트 루트에 `.husky` 폴더가 생성되고 `package.json``prepare` 스크립트가 추가됩니다 [5-7]. 이 `prepare` 스크립트는 팀원들이 로컬에서 `npm install`을 실행할 때 Husky 훅이 자동으로 설치되도록 보장하여 모든 팀원이 동일한 검사 환경을 갖추게 합니다 [5-7].
* **lint-staged와의 결합:** 전체 프로젝트 코드를 매번 검사하는 것은 많은 시간이 소요되므로, Husky의 `pre-commit` 훅 내부에서 `lint-staged`를 호출하는 방식이 현대적인 표준 설정으로 사용됩니다 [1, 8, 9]. 이 조합을 통해 커밋을 위해 스테이징된(staged) 파일에 대해서만 [[ESLint|ESLint]]나 [[Prettier|Prettier]]를 실행함으로써 1~2초 내에 검사를 완료할 수 있습니다 [1, 9].
* **검사 우회(Bypass) 및 환경 설정:** 개발 과정에서 미완성 코드를 커밋해야 하는 등 훅 실행을 건너뛰어야 할 때는 Git의 기본 기능인 `--no-verify` 플래그(예: `git commit --no-verify`)를 사용할 수 있습니다 [10, 11]. 또한 CI 서버나 프로덕션 환경 등 훅 설치 및 실행이 필요 없는 경우, `HUSKY=0` 환경 변수를 설정하여 Husky를 완전히 비활성화할 수 있습니다 [12].
* **예외 상황 및 트러블슈팅:**
* **GUI 및 버전 관리자 이슈:** SourceTree나 VS Code 같은 Git GUI 도구나 Node 버전 관리자(nvm, fnm 등)를 사용할 때 `PATH`가 제대로 초기화되지 않아 훅에서 명령어를 찾을 수 없는 오류(`command not found`)가 발생할 수 있습니다. Husky는 각 훅을 실행하기 전에 `~/.config/husky/init.sh`를 소싱(source)하여 이 문제를 우회할 수 있도록 지원합니다 [13, 14].
* **서브모듈 및 중첩 패키지:** 모노레포나 서브모듈([[Submodules|Submodules]]) 구조에서는 최상위 루트가 아닌 하위 디렉토리에 패키지가 위치할 수 있습니다. Git은 기본적으로 리포지토리 루트에서 훅을 실행하므로, 이런 경우 `prepare` 스크립트 내에서 경로를 이동하거나(cd) 서브모듈의 컨텍스트 내에 Husky를 개별적으로 설치하여 동작하도록 구성해야 합니다 [14, 15].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 핵심 개념
- **core.hooksPath = .husky/_**: Husky 가 매 이 path 로 git 을 redirect — 매 user 의 매 hook script 와 매 husky framework script 분리.
- **Plain shell**: 매 `.husky/pre-commit` 의 매 첫 line shebang 없이 — Husky v9 가 매 `_/h` wrapper 통해 실행.
- **Skip via env**: `HUSKY=0` 또는 `HUSKY_SKIP_HOOKS=1` — 매 CI 또는 emergency commit.
- **prepare script**: `package.json``"prepare": "husky"` 가 매 install 시 자동 setup.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Git Hooks|Git Hooks]], lint-staged, ESLint, [[Prettier|Prettier]]
- **Projects/Contexts:** CI/CD Pipeline, [[Monorepo|Monorepo]], [[Submodules|Submodules]]
- **Contradictions/Notes:** 소스에 따르면, 많은 개발자가 Husky와 `lint-staged`를 혼동하여 하나의 덩어리로 생각하곤 합니다. 하지만 두 도구는 명확히 구분되어야 합니다. Husky는 단순히 Git의 기본 훅을 관리하고 연결하는 '배선(hook wiring)' 역할을 할 뿐 작업 실행기(task runner)가 아니며, 실제 변경된 파일 단위로 작업을 오케스트레이션 하는 것은 `lint-staged`의 역할입니다 [2, 4, 16].
### 매 lint-staged 와의 결합
- 매 staged files 만 lint/format → 매 commit 속도 ↑.
- 매 prettier --write + eslint --fix + 매 자동 re-stage.
- 매 large monorepo 에서도 매 fast (only changed paths).
---
*Last updated: 2026-04-18*
### 매 hook 우선순위 (자주 쓰는)
1. **pre-commit**: lint-staged + type-check (changed only).
2. **commit-msg**: commitlint (Conventional Commits 검증).
3. **pre-push**: full test suite + build smoke.
4. **post-merge**: pnpm install if `package.json` changed.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Initial setup
```bash
# in repo root
pnpm add -D husky lint-staged
pnpm pkg set scripts.prepare="husky"
pnpm prepare
npx husky init # creates .husky/pre-commit with `npm test` placeholder
```
## 🤔 의사결정 기준 (Decision Criteria)
### .husky/pre-commit (lint-staged + type-check)
```sh
npx lint-staged
pnpm exec tsc --noEmit
```
**선택 A를 써야 할 때:**
- *(TODO)*
### lint-staged config (package.json)
```json
{
"lint-staged": {
"*.{ts,tsx,js,jsx}": [
"eslint --fix --max-warnings=0",
"prettier --write"
],
"*.{json,md,yml,yaml}": ["prettier --write"],
"*.css": ["stylelint --fix", "prettier --write"]
}
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### .husky/commit-msg (commitlint)
```sh
npx --no -- commitlint --edit "$1"
```
**기본값:**
> *(TODO)*
```js
// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'subject-max-length': [2, 'always', 100],
'scope-enum': [2, 'always', ['ui', 'api', 'docs', 'ci', 'deps']],
},
};
```
## ❌ 안티패턴 (Anti-Patterns)
### .husky/pre-push (test + build)
```sh
pnpm test --run --silent
pnpm build
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Skip in CI / emergency
```bash
# CI: prepare script no-op when not in dev install
# package.json
{
"scripts": {
"prepare": "node -e \"if (process.env.CI) process.exit(0)\" && husky"
}
}
# Emergency commit (use sparingly)
HUSKY=0 git commit -m "hotfix: critical patch"
# or
git commit --no-verify -m "..."
```
### Monorepo: only run hooks if relevant
```sh
# .husky/pre-commit
CHANGED=$(git diff --cached --name-only)
echo "$CHANGED" | grep -q "^apps/web/" && (cd apps/web && pnpm lint-staged)
echo "$CHANGED" | grep -q "^apps/api/" && (cd apps/api && pnpm lint-staged)
```
### Conditional hook based on branch
```sh
# .husky/pre-push
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" = "main" ]; then
pnpm test --run
pnpm build
else
pnpm test --run --bail=1
fi
```
### Adopt in existing repo
```bash
# After cloning, dependencies need install to run 'prepare'
pnpm install # triggers `prepare` → husky sets core.hooksPath
git config --get core.hooksPath # → .husky/_
```
### Husky + pnpm workspaces filter
```sh
# .husky/pre-commit
STAGED=$(git diff --cached --name-only)
PKGS=$(echo "$STAGED" | awk -F/ '/^packages\// {print $2}' | sort -u)
for p in $PKGS; do
pnpm --filter "@repo/$p" lint-staged
done
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| TS/JS project | Husky v9 + lint-staged |
| Polyglot (Python, Go) | pre-commit framework (multi-lang) |
| Heavy hooks (>10s) | move to pre-push, lighten pre-commit |
| Solo dev hobby | optional — lint in CI alone may suffice |
| Enterprise enforcement | husky + commitlint + branch protection |
**기본값**: 매 TS/JS team — Husky v9 + lint-staged + commitlint.
## 🔗 Graph
- 부모: [[Git Hooks]] · [[DevEx]]
- 변형: [[pre-commit]] · [[lefthook]] · [[simple-git-hooks]]
- 응용: [[Lint-Staged]] · [[Commitlint]] · [[Conventional Commits]]
- Adjacent: [[ESLint]] · [[Prettier]] · [[Biome]]
## 🤖 LLM 활용
**언제**: 매 hook script 작성, lint-staged config 생성, commitlint rule 제안, monorepo conditional logic.
**언제 X**: 매 binary install verification — local 환경에서 매 직접 실행.
## ❌ 안티패턴
- **30s pre-commit**: 매 dev 가 매 --no-verify 습관화 → 매 hook 무용지물.
- **Run full test in pre-commit**: 매 pre-push 로 옮기기.
- **No CI fallback**: 매 hook 만 신뢰 → 매 --no-verify bypass 시 dirty commit.
- **Husky 의 commit hook 안 비밀 커밋 검증 누락**: 매 detect-secrets / gitleaks pairing.
- **Per-developer husky version drift**: 매 lockfile pin 필수.
## 🧪 검증 / 중복
- Verified (Husky v9 docs 2026, lint-staged v15+).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Husky v9 + lint-staged + commitlint patterns |
@@ -2,101 +2,34 @@
id: wiki-2026-0508-ibm-가비지-컬렉션
title: IBM 가비지 컬렉션
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
aliases: [P-Reinforce-AUTO-A6562D]
duplicate_of: none
status: duplicate
canonical_id: garbage-collection
duplicate_of: "[[Garbage Collection]]"
aliases: []
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - IBM 가비지 컬렉션"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
verification_status: redirected
tags: [duplicate, gc, jvm, ibm-j9]
last_reinforced: 2026-05-10
github_commit: pending
---
# [[IBM 가비지 컬렉션|IBM 가비지 컬렉션]]
# IBM 가비지 컬렉션
## 📌 한 줄 통찰 (The Karpathy Summary)
> IBM의 가비지 컬렉션(GC)은 애플리케이션의 메모리 부족을 방지하기 위해 더 이상 필요하지 않은 Java 힙의 객체를 회수하는 자동화된 프로세스입니다 [1]. 전체 GC 과정은 일반적으로 도달 가능한 객체를 식별하는 마크(Mark), 도달할 수 없는 객체를 정리하는 스위프(Sweep), 힙의 단편화를 해결하는 압축(Compact)의 세 단계로 나뉩니다 [1]. GC 작업 중에는 애플리케이션 실행이 일시 중지되는 '[[Stop-the-world|Stop-the-world]] (STW)' 현상이 발생할 수 있으며, 시스템은 애플리케이션 중단을 최소화하기 위해 동시(Concurrent) 또는 점진적(Incremental) 처리 기법 및 다양한 정책을 활용합니다 [1-3].
> **이 문서는 [[Garbage Collection]] 의 중복본입니다.** Canonical 문서로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
- **가비지 컬렉션 주기 (GC Cycles)**
- **글로벌 GC 주기 (Global GC cycle):** 전체 Java 힙에서 작동하며 할당 실패나 메모리 임계값 도달과 같은 내부 메커니즘에 의해 암시적으로 트리거되거나, `System.gc()` 호출 등을 통해 명시적으로 트리거됩니다 [4].
- **부분 GC 주기 (Partial GC cycle):** 힙의 특정 부분에서만 작동하며, 선택된 GC 정책에 따라 암시적으로만 발생합니다 [4, 5].
## 핵심 요약 (IBM J9 / OpenJ9 specifics)
- IBM J9 / Eclipse OpenJ9 의 GC policy: `gencon` (default), `balanced`, `metronome` (real-time), `optavgpause`, `optthruput`.
- `gencon`: generational + concurrent — HotSpot G1 와 의 비유.
- `balanced`: region-based, NUMA-aware — large heap (> 4GB) target.
- `metronome`: hard real-time pause time guarantee (sub-ms).
- 일반 GC 이론 + algorithm 은 canonical [[Garbage Collection]] 참조.
- **주요 GC 작업 (GC [[Opera|Opera]]tions)**
- **마크 작업 (Mark):** 루트 객체에서 시작하여 힙 내 도달 가능한 객체를 추적하고 식별합니다 [6, 7]. 비트 배열인 '마크 맵(Mark map)'을 사용해 객체 위치를 기록하며, 초기(Initial), 메인(Main), 최종(Final) 세 단계로 진행됩니다 [6, 7]. 성능 향상을 위해 보조 스레드를 통한 병렬 처리나 애플리케이션 스레드와 함께 작동하는 동시 마크(Concurrent mark) 처리를 수행할 수 있습니다 [2, 8].
- **스위프 작업 (Sweep):** 여유 메모리를 분석하고 해당 공간을 중앙 기록인 프리리스트(Freelist)에 연결하여 새로운 객체 할당이 가능하도록 메모리를 회수합니다 [9].
- **스캐빈지 작업 ([[Scavenge|Scavenge]]):** 'Nursery' 영역의 할당 실패 시 트리거되며 도달 가능한 객체를 새 공간이나 'Tenure' 영역으로 복사하여 유지합니다(`gencon` 정책에서 주로 사용) [10, 11].
- **복사 전달 작업 (Copy Forward):** 힙의 단편화된 영역을 비우기 위해 라이브 객체를 새로운 영역으로 이동시킵니다(`balanced` 정책에서 주로 사용) [11, 12].
- **압축 작업 (Compact):** 메모리 단편화를 제거하기 위해 객체를 이동시킵니다. 객체의 모든 참조를 업데이트해야 하는 비용이 매우 큰 작업이므로 기본적으로는 실행되지 않고 여유 공간이 극도로 부족하거나 특정 조건(-Xcompactgc 옵션 등)이 충족될 때만 발생합니다 [13, 14].
## 🔗 Graph
- 부모: [[Garbage Collection]] (canonical)
- **약한 참조 처리 (Weak [[Reference|Reference]] [[Processing|Processing]])**
- GC 주기 동안 소프트(Soft), 약한(Weak), 팬텀(Phantom) 참조를 처리하여 특정 참조가 유지되거나 삭제되도록 관리합니다 [14]. 소프트 참조는 메모리 부족 오류가 발생할 가능성이 있을 때만 지워지며, 약한 참조와 팬텀 참조는 참조 객체가 마크되지 않을 때 즉시 혹은 자동으로 지워집니다 [15].
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
## 🔗 지식 연결 (Graph)
- **Related Topics:** GC Policies (gencon, optavgpause, balanced), Stop-the-world (STW) Pause, Mark, Sweep, and Compact Operations
- **Projects/Contexts:** E[[CLIP|CLIP]]se OpenJ9™, Java Object Heap
- **Contradictions/Notes:** 애플리케이션 성능 최적화를 위해 동시 마크(Concurrent mark) 방식을 사용하면 STW 일시 중지 시간은 줄일 수 있지만, 쓰기 장벽([[Write Barrier|Write Barrier]]) 작동으로 인한 추가 CPU 소비와 힙 락 할당 중 객체 추적에 따른 부하가 발생하는 트레이드오프(단점)가 존재합니다 [3]. 또한, 개발자가 `System.gc()`를 직접 호출하거나 finalizer를 이용해 GC를 통제하려 하면 오히려 애플리케이션 성능을 크게 저하시킬 수 있습니다 [5].
---
*Last updated: 2026-04-19*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
```
## 🤔 의사결정 기준 (Decision Criteria)
**선택 A를 써야 할 때:**
- *(TODO)*
**선택 B를 써야 할 때:**
- *(TODO)*
**기본값:**
> *(TODO)*
## ❌ 안티패턴 (Anti-Patterns)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -2,75 +2,159 @@
id: wiki-2026-0508-ifcjs-fragment
title: IFCjs (Fragment)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-8A58BF]
aliases: [IFC.js, ThatOpen Fragment, web-ifc, BIM web viewer]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
confidence_score: 0.85
verification_status: applied
tags: [bim, ifc, threejs, web, fragment]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - [[IFCjs|IFCjs]] (Fragment)"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: TypeScript
framework: Three.js, web-ifc, ThatOpen Components
---
# [[IFCjs (Fragment)|IFCjs (Fragment]]
# IFCjs (Fragment)
## 📌 한 줄 통찰 (The Karpathy Summary)
> Fragment는 대규모 3D 기하학적 환경을 효율적으로 렌더링하기 위해 IFC.js 개발자들이 고안한 하이브리드 최적화 시스템이다 [1, 2]. 이 시스템은 단일 인터페이스 내에서 로우 폴리(low-poly) 고유 객체를 위한 지오메트리 병합과 하이 폴리(high-poly) 반복 객체를 위한 인스턴싱의 장점을 결합한다 [2]. 이를 통해 메모리 소비와 드로우 콜([[Draw Call|Draw Call]]) 횟수 간의 최적의 균형을 달성하면서 개별 객체의 빠른 검색 및 조작 기능을 제공하는 것을 목표로 한다 [1, 3].
## 한 줄
> **"매 IFC BIM model 의 web-native streaming 형식"**. 매 2021 IFC.js (Antonio Gonzalez Viegas) → 매 2024 ThatOpen Components 로 rebrand 된 toolchain. 매 Fragment format 매 IFC 의 매 GPU-friendly binary representation — 매 1GB IFC 가 매 50MB Fragment 로 압축, 매 browser 의 매 instant load.
## 📖 구조화된 지식 (Synthesized Content)
* **개발 목적 및 배경:**
건물 모델과 같이 수천 개에서 수백만 개의 객체로 구성된 거대한 씬(scene)을 렌더링할 때, 기존의 모든 객체를 `[[BufferGeometry|BufferGeometry]]`로 병합하는 방식은 램(RAM) 메모리를 지나치게 많이 소비하는 한계가 있었고, `[[InstancedMesh|InstancedMesh]]`를 사용하는 방식은 재질(Material) 수만큼 드로우 콜이 늘어나는 단점이 있었다 [4, 5]. Fragment는 이러한 문제를 해결하여 메모리와 FPS 측면 모두에서 효율성을 달성하고, 개별 객체를 빠르게 검색하고 하이라이트할 수 있도록 설계되었다 [1, 6].
## 매 핵심
* **하이브리드 아키텍처:**
Fragment는 다음과 같이 객체의 특성에 따라 두 가지 최적화 방식을 혼합하여 사용한다.
* **병합 (Merging):** 벽이나 바닥처럼 고유하면서 폴리곤 수가 적은(low-poly) 객체들은 하나 또는 여러 개의 `BufferGeometry`로 병합하여 드로우 콜을 최소화한다 [2, 7].
* **인스턴싱 ([[Instancing|Instancing]]):** 문, 가구, 창문과 같이 동일한 형태가 반복되면서 폴리곤 수가 많은(high-poly) 객체들은 각각 `InstancedMesh`로 구성하여 메모리 소비를 대폭 줄인다 [2, 7].
### 매 IFC 의 limitation
- 매 STEP-based ASCII format — 매 100MB+ project 매 routine.
- 매 spatial hierarchy + property + geometry 매 모두 nested — 매 partial load 의 X.
- 매 Three.js 의 직접 render 의 X — 매 tessellation needed.
* **구조적 특징 및 저장 방식:**
공통된 Fragment 인터페이스를 통해 1,000개의 동일한 의자가 하나의 인스턴스화된 Fragment가 될 수도 있고, 프로젝트의 모든 벽면이 병합된 단일 Fragment가 될 수도 있다 [6, 7]. 영속성(persistence) 수준에서는 각 Fragment당 하나의 GLB 파일을 저장하는 방식을 고려하여 설계되었다 [7]. 모든 Fragment가 비슷한 수의 정점(vertices)과 드로우 콜을 가지도록 하여 시스템 부하의 균형을 맞춘다 [3].
### 매 Fragment 의 solution
- 매 web-ifc (WASM) 가 매 IFC parse + tessellate.
- 매 결과를 매 Fragment binary (FlatBuffers-based) 로 serialize.
- 매 InstancedMesh 단위 grouping → 매 draw call 격감.
- 매 property data 매 별도 SQLite-WASM file → 매 lazy query.
* **성능 및 결과:**
초기 프로토타입 구현 결과, 1,000개의 의자와 4개의 벽으로 구성된 씬을 단 3번의 드로우 콜(선택용 드로우 콜 제외)과 10MB 미만의 메모리만으로 렌더링하는 데 성공했다 [6]. 또한 100MB 이상의 대형 IFC 모델을 모바일 기기에서도 Autodesk Forge에 필적하는 속도로 빠르게 로드하는 훌륭한 성능을 보여주었다 [8].
### 매 응용
1. 건축 설계 review web tool.
2. Construction 현장 mobile BIM viewer.
3. Facility management dashboard.
4. Clash detection web service.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
## 💻 패턴
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[BufferGeometry|BufferGeometry]], InstancedMesh, [[Draw Call|Draw Call]]
- **Projects/Contexts:** IFC.js, Three.js
- **Contradictions/Notes:** 소스에 따르면, Fragment와 같은 자체적인 최적화 시스템 구축 외에도 대규모 환경 최적화를 위해 다중 그리기(Multidrawing), LOD(Level of Detail), 오클루전 컬링(Occlusion Culling) 등의 추가적인 방법론도 함께 검토되었다 [2].
### 1. ThatOpen Components 초기화 (2026)
```ts
import * as OBC from "@thatopen/components";
import * as OBCF from "@thatopen/components-front";
---
*Last updated: 2026-04-19*
const components = new OBC.Components();
const worlds = components.get(OBC.Worlds);
const world = worlds.create<
OBC.SimpleScene, OBC.SimpleCamera, OBCF.PostproductionRenderer
>();
---
world.scene = new OBC.SimpleScene(components);
world.renderer = new OBCF.PostproductionRenderer(components, container);
world.camera = new OBC.SimpleCamera(components);
components.init();
```
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 2. IFC → Fragment 변환
```ts
const ifcLoader = components.get(OBC.IfcLoader);
await ifcLoader.setup();
**언제 이 지식을 쓰는가:**
- *(TODO)*
const file = await fetch("model.ifc");
const buffer = new Uint8Array(await file.arrayBuffer());
const model = await ifcLoader.load(buffer);
world.scene.three.add(model);
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### 3. 미리 만든 Fragment load (instant)
```ts
const fragments = components.get(OBC.FragmentsManager);
const data = await fetch("model.frag").then(r => r.arrayBuffer());
const group = fragments.load(new Uint8Array(data));
world.scene.three.add(group);
```
## 🧪 검증 상태 (Validation)
### 4. Property query (lazy)
```ts
const indexer = components.get(OBC.IfcRelationsIndexer);
await indexer.process(model);
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
// Get all walls
const walls = await indexer.getEntitiesByType(model, "IFCWALL");
for (const expressID of walls) {
const props = await model.getProperties(expressID);
console.log(props.Name.value);
}
```
## 🧬 중복 검사 (Duplicate Check)
### 5. Highlight on click
```ts
const highlighter = components.get(OBCF.Highlighter);
highlighter.setup({ world });
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
highlighter.events.select.onHighlight.add((selection) => {
console.log("Selected fragments:", selection);
});
```
## 🕓 변경 이력 (Changelog)
### 6. Section plane (clipper)
```ts
const clipper = components.get(OBC.Clipper);
clipper.enabled = true;
container.addEventListener("dblclick", () => clipper.create(world));
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### 7. Streaming (large model)
```ts
const streamer = components.get(OBCF.IfcStreamer);
streamer.url = "https://cdn.example.com/fragments/";
streamer.world = world;
await streamer.load(
await fetch("model-streamed.json").then(r => r.json()),
true // coordinate to origin
);
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Small model (< 50MB IFC) | 직접 IfcLoader.load() |
| Medium (50-500MB) | 사전 변환된 .frag file |
| Large (500MB+) | IfcStreamer (tile-based LOD) |
| Property-heavy query | IfcRelationsIndexer + cached |
| Mobile viewer | Fragment + simplified geometry |
**기본값**: ThatOpen Components 2026 + Fragment 사전 변환 + property cache.
## 🔗 Graph
- 부모: [[BIM (Building Information Modeling)]] · [[IFC (Industry Foundation Classes)]]
- 변형: [[Speckle]] · [[xeokit]] · [[Forge Viewer]]
- 응용: [[Web BIM Viewer]] · [[Clash Detection]] · [[Facility Management]]
- Adjacent: [[Three.js]] · [[WASM]] · [[FlatBuffers]]
## 🤖 LLM 활용
**언제**: 매 web-based BIM viewer 매 build. 매 IFC model 매 browser 의 instant load 가 필요. 매 open-source 매 prefer (Forge 의 X).
**언제 X**: 매 desktop-only workflow (Revit/Navisworks 매 충분). 매 < 10MB model (overkill). 매 photorealistic render (use Unreal/Unity).
## ❌ 안티패턴
- **IFC 매 매번 parse**: 매 100MB IFC 매 user 마다 30초 wait. 매 backend 사전 변환 필수.
- **Property 매 eager load**: 매 모든 property 매 memory load → OOM. 매 lazy + query-on-demand.
- **InstancedMesh 무시**: 매 IFC 의 매 1000+ identical column 매 매 separate Mesh → 매 draw call 폭발.
- **GlobalId 의 X**: 매 Fragment internal ID 매 IFC GlobalId 와 매 different — 매 cross-system mapping 매 GlobalId 사용.
## 🧪 검증 / 중복
- Verified (ThatOpen/engine_components GitHub 2026-05, web-ifc 0.0.66+).
- 신뢰도 A (rapidly-evolving project — 매 minor API drift 가능).
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — ThatOpen Components 2026 API + Fragment streaming |
+160 -66
View File
@@ -2,95 +2,189 @@
id: wiki-2026-0508-ifcjs
title: IFCjs
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-659684]
aliases: [That Open Engine, web-ifc, Three.js IFC, BIM viewer]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
confidence_score: 0.85
verification_status: applied
tags: [bim, ifc, web, three-js, aec, webgl]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - IFCjs"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: web-ifc-three
---
# [[IFCjs|IFCjs]]
# IFCjs
## 📌 한 줄 통찰 (The Karpathy Summary)
> IFC.js는 대규모 기하학적 환경이나 건물 모델을 효율적으로 시각화하기 위해 개발되고 있는 프로젝트입니다 [1]. 메모리 소비를 줄이고 렌더링 속도(FPS)를 높이면서도 수많은 객체 중 개별 객체를 빠르게 검색하고 구성할 수 있는 렌더링 최적화를 목표로 합니다 [2]. 최근 최적화 아키텍처를 통해 100MB 이상의 대형 모델을 모바일에서도 원활하게 로드하는 성능을 달성했습니다 [3].
## 한 줄
> **"매 browser 안의 IFC (Industry Foundation Classes) reader/viewer — 매 BIM 데이터를 매 Three.js scene 으로"**. IFCjs (현재 매 "That Open Engine" 으로 rebrand) 는 매 web-ifc (WASM IFC parser) + 매 Three.js based 매 viewer 의 묶음. 매 AEC (Architecture/Engineering/Construction) 매 web 진입의 standard. 매 2026 현재 매 OpenBIM 운동 의 매 핵심 component.
## 📖 구조화된 지식 (Synthesized Content)
- **대규모 렌더링 최적화의 과제:** 대규모 건물 모델 시각화에는 수천에서 수백만 개의 객체가 포함되기 때문에 메모리와 속도([[Draw Call|Draw Call]])의 최적화가 필수적입니다 [2].
- **기존 방식의 한계:**
- 모든 객체를 `[[BufferGeometry|BufferGeometry]]`로 병합하는 방식은 드로우 콜을 최소화하지만, 의자 2개를 렌더링할 때 의자 1개보다 두 배의 RAM을 차지할 만큼 메모리 소모가 심하다는 문제가 있습니다 [2, 4].
- 반대로 `[[InstancedMesh|InstancedMesh]]`를 사용하는 방식은 메모리를 적게 쓰지만, 고유 객체와 재질의 수만큼 드로우 콜이 급증하여 대형 건물 모델에 적용하기 어렵습니다 [4, 5].
- **하이브리드 시스템 'Fragment' 도입:** 이러한 한계를 극복하기 위해 IFC.js 개발진은 두 가지 방식의 장점을 동일한 인터페이스 뒤에 결합한 'Fragment'라는 시스템을 설계했습니다 [5].
- **객체별 렌더링 전략:** 벽이나 바닥과 같이 고유하면서도 폴리곤 수가 적은(Low-poly) 객체들은 `BufferGeometry`로 병합하여 처리하고, 가구나 문, 창문과 같이 폴리곤 수가 많고(High-poly) 반복되는 객체들은 `InstancedMesh`를 생성하여 처리합니다 [6].
- **결과 및 성과:** 이 시스템은 모든 파편(Fragment)이 비슷한 수의 정점과 드로우 콜을 가지도록 균형을 맞춰 효율성을 극대화하며, Autodesk Forge의 로딩 속도에 근접하는 수준의 성능을 입증했습니다 [3, 6].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 stack 의 layer
- **web-ifc (C++ → WASM)**: 매 IFC2x3 / IFC4 / IFC4x3 STEP file 의 매 streaming parser.
- **web-ifc-three** (legacy): 매 Three.js mesh 로 변환, property set 추출.
- **@thatopen/components**: 매 modern (2024+) — Three.js 위 UI/tool framework.
- **@thatopen/ui**: 매 web-component 기반 panel/grid/property card.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[BufferGeometry|BufferGeometry]], InstancedMesh, Fragment, [[Draw Call|Draw call]]
- **Projects/Contexts:** 대규모 기하학적 환경 시각화, Autodesk Forge
- **Contradictions/Notes:** 소스에 명시적인 모순은 없으나, 모델 렌더링에 있어 `BufferGeometry` 병합 방식(메모리 소모 큼)과 `InstancedMesh` 방식(드로우 콜 증가) 간의 근본적인 트레이드오프(Trade-off)가 존재하며, IFC.js는 이를 해결하기 위해 두 방식을 혼합한 하이브리드 솔루션을 제안합니다 [2, 4, 5].
### 매 IFC 의 본질
- **STEP physical file**: ASCII textual, 매 entity reference graph (`#1=IFCBUILDING(...)`).
- **EXPRESS schema**: 매 IFC4 는 매 1700+ entity types.
- **Geometric representations**: 매 boundary representation, swept solid, CSG, tessellated mesh.
- **Property sets (Psets)**: 매 entity 별 매 metadata bag.
---
*Last updated: 2026-04-19*
### 매 web vs desktop trade-off
- 매 desktop (Revit, ArchiCAD): full editing, plugin ecosystem.
- 매 web (IFCjs/ThatOpen): zero-install, collaborative review, lightweight viewer.
- 매 hybrid: 매 export IFC from Revit → web viewer.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Basic IFC viewer (ThatOpen Components 2024+)
```ts
import * as OBC from '@thatopen/components';
import * as THREE from 'three';
**언제 이 지식을 쓰는가:**
- *(TODO)*
const components = new OBC.Components();
const worlds = components.get(OBC.Worlds);
const world = worlds.create<
OBC.SimpleScene, OBC.SimpleCamera, OBC.SimpleRenderer
>();
**언제 쓰면 안 되는가:**
- *(TODO)*
const container = document.getElementById('app')!;
world.scene = new OBC.SimpleScene(components);
world.renderer = new OBC.SimpleRenderer(components, container);
world.camera = new OBC.SimpleCamera(components);
world.scene.setup();
## 🧪 검증 상태 (Validation)
components.init();
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
const fragments = components.get(OBC.FragmentsManager);
const ifcLoader = components.get(OBC.IfcLoader);
await ifcLoader.setup();
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
const file = await fetch('/models/building.ifc');
const buffer = new Uint8Array(await file.arrayBuffer());
const model = await ifcLoader.load(buffer);
world.scene.three.add(model);
```
## 🤔 의사결정 기준 (Decision Criteria)
### Property extraction via web-ifc directly
```ts
import { IfcAPI, IFCWALLSTANDARDCASE } from 'web-ifc';
**선택 A를 써야 할 때:**
- *(TODO)*
const api = new IfcAPI();
api.SetWasmPath('/wasm/');
await api.Init();
**선택 B를 써야 할 때:**
- *(TODO)*
const data = new Uint8Array(await fetch('/m.ifc').then(r => r.arrayBuffer()));
const modelID = api.OpenModel(data);
**기본값:**
> *(TODO)*
const wallIDs = api.GetLineIDsWithType(modelID, IFCWALLSTANDARDCASE);
for (let i = 0; i < wallIDs.size(); i++) {
const id = wallIDs.get(i);
const wall = api.GetLine(modelID, id, true); // recursive expand refs
console.log(wall.GlobalId.value, wall.Name?.value);
}
api.CloseModel(modelID);
```
## ❌ 안티패턴 (Anti-Patterns)
### Picking + property panel
```ts
const highlighter = components.get(OBC.Highlighter);
highlighter.setup({ world });
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
highlighter.events.select.onHighlight.add(async (fragmentMap) => {
const indexer = components.get(OBC.IfcRelationsIndexer);
for (const fragId in fragmentMap) {
const expressIDs = [...fragmentMap[fragId]];
for (const id of expressIDs) {
const psets = await indexer.getEntityRelations(model, id, 'IsDefinedBy');
console.log('expressID', id, 'psets', psets);
}
}
});
```
### Convert IFC → fragments (compact binary)
```ts
// fragments are ThatOpen's optimized binary mesh format
const fragmentManager = components.get(OBC.FragmentsManager);
const buffer = fragmentManager.export(model);
await fetch('/upload', { method: 'POST', body: buffer });
```
### Server-side conversion (Node + web-ifc-node)
```ts
import { IfcAPI } from 'web-ifc/web-ifc-api-node';
import { promises as fs } from 'fs';
const api = new IfcAPI();
api.SetWasmPath('node_modules/web-ifc/');
await api.Init();
const buf = await fs.readFile('input.ifc');
const id = api.OpenModel(buf);
const flatMesh = api.LoadAllGeometry(id);
// ... extract triangles, write to glTF
```
### BIM clash detection (rough proxy)
```ts
import { Box3, Vector3 } from 'three';
function findClashes(meshes: THREE.Mesh[]) {
const boxes = meshes.map(m => {
const b = new Box3().setFromObject(m);
return { box: b, mesh: m };
});
const clashes: [THREE.Mesh, THREE.Mesh][] = [];
for (let i = 0; i < boxes.length; i++)
for (let j = i + 1; j < boxes.length; j++)
if (boxes[i].box.intersectsBox(boxes[j].box))
clashes.push([boxes[i].mesh, boxes[j].mesh]);
return clashes;
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Web-only IFC viewer | ThatOpen Components |
| Server-side IFC parsing | web-ifc-node |
| Property extraction only | web-ifc API directly |
| Heavy editing | desktop (Revit) export |
| Massive models (>1GB) | fragments format + tile streaming |
| Clash detection on web | use AABB pre-filter + GPU mesh-mesh |
**기본값**: 매 modern AEC web app — ThatOpen Components + fragments.
## 🔗 Graph
- 부모: [[BIM]] · [[3D Web Viewer]]
- 변형: [[Bimsync]] · [[Speckle]] · [[Forge / APS]]
- 응용: [[Digital Twin]] · [[Construction Management]] · [[Clash Detection]]
- Adjacent: [[Three.js]] · [[glTF]] · [[USD]] · [[OpenBIM]]
## 🤖 LLM 활용
**언제**: IFC entity 의 mapping 설명 (IFC → glTF), property set 매 자연어 query, 매 UI panel scaffold.
**언제 X**: 매 large IFC parsing performance 최적화 — 매 measure 매 직접.
## ❌ 안티패턴
- **Loading 1GB IFC into browser memory directly**: 매 OOM — 매 fragments + streaming 사용.
- **Recursive GetLine on every entity**: 매 N² — 매 IfcRelationsIndexer 사용.
- **Treating IFC as glTF**: 매 IFC 는 매 graph + semantics, 매 mesh-only X.
- **No coordinate system handling**: 매 IFC 의 IfcSite localPlacement 무시 → 매 wrong global pos.
- **Missing wasm path**: 매 web-ifc 의 매 WASM file 의 매 hosting failure — `SetWasmPath` 명시.
## 🧪 검증 / 중복
- Verified (ThatOpen Engine docs 2026, web-ifc GitHub).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — IFC stack + ThatOpen Components patterns |
@@ -2,92 +2,182 @@
id: wiki-2026-0508-incremental-build
title: Incremental Build
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [550e8400-e29b-41d4-a716-446655440005]
aliases: [Incremental Compilation, Cached Build, Build Cache]
duplicate_of: none
source_trust_level: A
confidence_score: 0.97
tags: [build, devops, automation, versioning]
confidence_score: 0.9
verification_status: applied
tags: [build, ci, performance, monorepo, caching]
raw_sources: []
last_reinforced: 2026-04-21
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: turborepo
---
# 증분형 빌드 관리 시스템
# Incremental Build
## 📌 한 줄 통찰 (The Karpathy Summary)
> 빌드 결과물을 버전별로 격리된 폴더에 저장하여 배포 이력을 보존하고 롤백 안정성을 확보함.
## 한 줄
> **"매 변경된 파일 + downstream 의존성만 rebuild — 매 hash-based caching 의 핵심"**. 매 1979 Make 의 mtime-based 시작, 매 2026 Turborepo/Nx/Bazel 의 content-addressed cache 가 default — 매 monorepo 에서 100x speedup 흔함.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:**
- **Directory-Based Versioning**: `dist/n` 형태의 구조를 통해 별도의 DB 없이 파일 시스템만으로 빌드 버전을 체계적으로 관리.
- **세부 내용:**
- 쉘 스크립트를 이용한 자동 버전 카운팅 로직 구현.
- Vite 설정의 동적 `outDir` 제어 패턴 확립.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 기존의 덮어쓰기 방식(Overwrite) 빌드를 버전 보존 방식으로 전환.
- **정책 변화:** 모든 빌드 요청은 반드시 고유한 버전 번호를 가져야 함.
### 매 작동 원리
- **Input hash**: 매 source files + deps + env → SHA256.
- **Cache key**: hash → output artifacts (dist/, .d.ts).
- **Hit**: cache 존재 → restore, skip work.
- **Miss**: rebuild, store.
## 🔗 지식 연결 (Graph)
- **Parent:** 10_Wiki/Skills/BuildSystem
- **Related:** 10_Wiki/Projects/Skybound/Architecture_Refactor
- **Raw Source:** 00_Raw/2026-04-21-Skybound_Incremental_Build_System
### 매 granularity
- **File-level**: tsc --incremental (.tsbuildinfo).
- **Task-level**: Turborepo (per-package).
- **Action-level**: Bazel (per-rule, hermetic).
## 🔗 지식 연결 (Graph)
### Related Concepts (Auto-Linked)
* [[Architecture_Refactor]]
### 매 응용
1. Monorepo CI: 매 affected package 만 test.
2. Local dev: watch mode, 매 sub-second rebuild.
3. Docker: layer caching = path 별 invalidation.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Turborepo pipeline
```json
// turbo.json
{
"$schema": "https://turbo.build/schema.json",
"globalDependencies": ["tsconfig.base.json"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"inputs": ["src/**", "package.json", "tsconfig.json"],
"outputs": ["dist/**", ".next/**"],
"cache": true
},
"test": {
"dependsOn": ["build"],
"inputs": ["src/**", "test/**"],
"outputs": ["coverage/**"]
},
"lint": { "cache": true, "outputs": [] }
},
"remoteCache": { "signature": true }
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### TypeScript incremental
```json
// tsconfig.json
{
"compilerOptions": {
"incremental": true,
"tsBuildInfoFile": ".cache/tsbuild.json",
"composite": true,
"declaration": true,
"declarationMap": true
},
"references": [
{ "path": "../core" },
{ "path": "../utils" }
]
}
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Nx affected
```bash
# Only test packages affected by changes since main
nx affected --target=test --base=origin/main --head=HEAD --parallel=4
**선택 B를 써야 할 때:**
- *(TODO)*
# Print affected graph
nx graph --affected --base=origin/main
```
**기본값:**
> *(TODO)*
### Vite HMR (sub-second)
```ts
// vite.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
server: {
hmr: { overlay: true },
watch: { usePolling: false, ignored: ['**/node_modules/**', '**/dist/**'] }
},
build: {
rollupOptions: { cache: true }
},
cacheDir: '.cache/vite'
});
```
## ❌ 안티패턴 (Anti-Patterns)
### GitHub Actions remote cache
```yaml
- uses: actions/cache@v4
with:
path: |
.turbo
node_modules/.cache
key: turbo-${{ runner.os }}-${{ hashFiles('**/pnpm-lock.yaml') }}-${{ github.sha }}
restore-keys: turbo-${{ runner.os }}-${{ hashFiles('**/pnpm-lock.yaml') }}-
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
- run: pnpm turbo run build test --cache-dir=.turbo
```
### Bazel hermetic action
```python
# BUILD.bazel
load("@npm//@bazel/typescript:index.bzl", "ts_project")
ts_project(
name = "core",
srcs = glob(["src/**/*.ts"]),
declaration = True,
incremental = True,
deps = ["//packages/utils"],
)
```
### Cache hit ratio metric
```ts
// scripts/cache-stats.ts
import { execSync } from 'node:child_process';
const out = execSync('turbo run build --dry=json').toString();
const tasks = JSON.parse(out).tasks;
const hits = tasks.filter((t: any) => t.cache.status === 'HIT').length;
console.log(`cache hit: ${hits}/${tasks.length} = ${(hits/tasks.length*100).toFixed(1)}%`);
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Monorepo 10+ packages | Turborepo or Nx |
| Strict reproducibility | Bazel (hermetic) |
| Single TS app | tsc --incremental + Vite |
| Docker images | BuildKit + multi-stage layer cache |
**기본값**: 매 Turborepo + remote cache (Vercel or self-hosted).
## 🔗 Graph
- 부모: [[Build Systems]] · [[Continuous Integration]]
- 변형: [[Hot Module Replacement]] · [[Watch Mode]]
- 응용: [[Monorepo Strategy]] · [[CI_CD_Pipeline]]
- Adjacent: [[Tree Shaking]] · [[Dependency Graph]]
## 🤖 LLM 활용
**언제**: 매 turbo.json/nx.json 의 generation, cache key tuning 추천.
**언제 X**: 매 Bazel hermetic rule — 매 strict, LLM hallucination 위험.
## ❌ 안티패턴
- **Time-based keys**: `date +%s` cache key — 매 hit 0%.
- **Untracked inputs**: env var, system clock 의존 → false hit.
- **Cache everything**: lint output 까지 cache → debugging 의 hell.
- **No remote cache**: CI 매 fresh 시작 → local-only 의 무의미.
## 🧪 검증 / 중복
- Verified (Turborepo 2.x, Nx 20+, Bazel 7+ 공식 docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — incremental build 의 hash caching 정리 |
@@ -2,90 +2,155 @@
id: wiki-2026-0508-inferential-statistics
title: Inferential Statistics
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-INST-001]
aliases: [Statistical Inference, Hypothesis Testing, Confidence Intervals]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, inferential-Statistics, statistics, data-Analysis, Hypothesis-Testing, sampling]
confidence_score: 0.92
verification_status: applied
tags: [statistics, inference, hypothesis-testing, ab-testing, sre]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: python
framework: scipy
---
# [[Inferential-Statistics|Inferential-Statistics]]
# Inferential Statistics
## 📌 한 줄 통찰 (The Karpathy Summary)
> "부분으로 전체를 꿰뚫기: 일부 표본(Sample)에서 나타난 특징을 바탕으로, 우리가 직접 다 볼 수 없는 거대한 전체(Population)속성을 수학적으로 추론하고 그 결론이 얼마나 믿을만한지 확률로 증명하는 지적 예측술."
## 한 줄
> **"매 sample → population parameter 의 추정 + uncertainty 의 quantify"**. 매 1900s Fisher, Neyman, Pearson 의 frequentist framework, 매 2026 A/B test, SRE alerting, ML evaluation backbone — Bayesian + bootstrap 의 modern hybrid 가 default.
## 📖 구조화된 지식 (Synthesized Content)
추론 통계학(Inferential-Statistics)은 데이터 표본을 분석하여 모집단에 대한 결론을 도출하는 방법론입니다.
## 매 핵심
1. **두 기둥**:
* **Estimation (추정)**: 표본을 통해 모집단의 평균이나 비율이 특정 범위 안에 있을 것이라 예측.
* **Hypothesis [[Testing|Testing]] (가설 검정)**: "이 약이 효과가 있는가?"와 같은 주장이 통계적으로 의미가 있는지(p-value) 판단.
2. **왜 중요한가?**:
* 모든 실험과 데이터 분석의 신뢰성을 결정하는 '판사' 역할을 수행함. ([[Inductive-Reasoning|Inductive-Reasoning]]의 수학적 도구)
### 매 Frequentist vs Bayesian
- **Frequentist**: parameter fixed, data random. p-value, CI.
- **Bayesian**: parameter random (prior), data fixed. Posterior, credible interval.
- **Bootstrap**: distribution-free, resample n→inf 시뮬레이션.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 작은 표본으로 거대 집단을 설명하려는 '희소 데이터 정책'이 주류였으나, 현대 정책은 방대한 빅데이터 정책 하에서도 '상관관계와 인과관계 정책'을 엄격히 구분하고 변수 간의 복잡한 영향을 파악하는 데 집중함(RL Update).
- **정책 변화(RL Update)**: 단순히 p-value 수치에만 목매는 정책(P-hacking)을 지양하고, 모델의 불확실성을 더 정교하게 다루는 '베이지안 추론 통계 정책'으로의 전환 정책이 가속화되고 있음. (Inductive-[[Reasoning|Reasoning]]와 연결)
### 매 Test 분류
- **Parametric**: t-test, ANOVA, Z-test (assumes normal).
- **Non-parametric**: Mann-Whitney U, Kruskal-Wallis, permutation.
- **Sequential**: Always Valid Inference, mSPRT (peek-safe).
## 🔗 지식 연결 (Graph)
- [[Inductive-Reasoning|Inductive-Reasoning]], [[Analysis|Analysis]], [[Data Cleaning Algorithms|Data Cleaning Algorithms]], [[Decision Theory|Decision Theory]], [[Epistemology|Epistemology]]
- **Modern Tech/Tools**: R, Python (SciPy), Bayesian A/B testing, Confidence intervals.
---
### 매 응용
1. A/B test: conversion lift 측정.
2. SRE: SLO breach 의 statistical significance.
3. ML: model A vs B 의 holdout 비교.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Two-sample t-test
```python
import scipy.stats as st
control = [12, 14, 11, 13, 12, 15, 13]
treat = [16, 18, 15, 17, 19, 16, 18]
res = st.ttest_ind(control, treat, equal_var=False)
print(f"t={res.statistic:.3f} p={res.pvalue:.4f}")
ci = res.confidence_interval(0.95)
print(f"95% CI: [{ci.low:.2f}, {ci.high:.2f}]")
```
## 🤔 의사결정 기준 (Decision Criteria)
### Bootstrap CI
```python
import numpy as np
def bootstrap_mean_ci(x, n=10_000, alpha=0.05):
rng = np.random.default_rng(42)
boots = rng.choice(x, size=(n, len(x)), replace=True).mean(axis=1)
return np.quantile(boots, [alpha/2, 1-alpha/2])
**선택 A를 써야 할 때:**
- *(TODO)*
ci = bootstrap_mean_ci(np.array(control))
print(f"Bootstrap 95% CI: {ci}")
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Sample size calculation (power)
```python
from statsmodels.stats.power import TTestIndPower
analysis = TTestIndPower()
n = analysis.solve_power(effect_size=0.3, power=0.8, alpha=0.05)
print(f"매 group 당 n = {int(np.ceil(n))}")
```
**기본값:**
> *(TODO)*
### Sequential test (mSPRT, peek-safe)
```python
import numpy as np
def msprt_log_likelihood(x, mu0=0, sigma=1, theta=0.1):
n = len(x); xbar = np.mean(x); v = sigma**2
tau2 = theta**2
log_bf = 0.5*np.log(v/(v+n*tau2)) + (n**2 * (xbar-mu0)**2 * tau2) / (2*v*(v+n*tau2))
return log_bf # > log(1/alpha) 매 reject H0
```
## ❌ 안티패턴 (Anti-Patterns)
### Bayesian A/B (PyMC)
```python
import pymc as pm
with pm.Model() as m:
p_a = pm.Beta("p_a", 1, 1)
p_b = pm.Beta("p_b", 1, 1)
pm.Binomial("y_a", n=10_000, p=p_a, observed=520)
pm.Binomial("y_b", n=10_000, p=p_b, observed=580)
diff = pm.Deterministic("diff", p_b - p_a)
idata = pm.sample(2000, chains=4, random_seed=42)
print(f"P(B > A) = {(idata.posterior['diff'] > 0).mean().item():.3f}")
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Permutation test
```python
def permutation_test(a, b, n=10_000):
diff_obs = np.mean(a) - np.mean(b)
pool = np.concatenate([a, b])
rng = np.random.default_rng(0)
diffs = []
for _ in range(n):
rng.shuffle(pool)
diffs.append(np.mean(pool[:len(a)]) - np.mean(pool[len(a):]))
return np.mean(np.abs(diffs) >= abs(diff_obs))
```
### SRE: Welch's test on latency p99
```python
# 매 deploy 전후 latency p99 비교
from scipy.stats import ttest_ind
before_p99 = np.array([124, 130, 128, 132, 125]) # ms
after_p99 = np.array([142, 138, 145, 140, 144])
t, p = ttest_ind(before_p99, after_p99, equal_var=False)
if p < 0.01: print("매 regression detected — rollback")
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Fixed-N A/B | t-test or chi-squared |
| Continuous monitoring | mSPRT or always-valid CI |
| Small N, non-normal | Bootstrap or permutation |
| Multi-arm + prior | Bayesian (Beta-Binomial) |
**기본값**: Bootstrap CI + sequential test 의 production A/B.
## 🔗 Graph
- 부모: [[Statistics & Data Analysis]] · [[Probability Theory]]
- 변형: [[Bayesian Inference]] · [[Bootstrap]] · [[Permutation Test]]
- 응용: [[A/B Testing]] · [[SRE]] · [[Anomaly-Detection]]
- Adjacent: [[Type 1 vs Type 2 Errors]] · [[Power Analysis]]
## 🤖 LLM 활용
**언제**: test 선택 의 advice (data shape → test type), 의 result interpretation.
**언제 X**: 매 multiple-comparison correction 매 자동화 X — domain knowledge 필요.
## ❌ 안티패턴
- **p-hacking**: 매 multiple test 후 cherry-pick.
- **Peeking**: fixed-N test 의 매 day 확인 → α inflation.
- **Single point**: CI 매 보고 안하고 mean 만.
- **N=∞ → significance ≠ effect size**: Cohen's d 도 같이.
## 🧪 검증 / 중복
- Verified (Casella & Berger "Statistical Inference", scipy/statsmodels docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — frequentist + Bayesian + sequential pattern |
@@ -2,91 +2,152 @@
id: wiki-2026-0508-information-society
title: Information Society
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-INSO-001]
aliases: [Post-Industrial Society, Network Society, Knowledge Economy]
duplicate_of: none
source_trust_level: A
confidence_score: 0.88
tags: [auto-reinforced, information-society, digital-transformation, data-economy, network-society, social-change]
confidence_score: 0.85
verification_status: applied
tags: [society, sociology, internet, economy, policy]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: na
framework: na
---
# [[Information-Society|Information-Society]]
# Information Society
## 📌 한 줄 통찰 (The Karpathy Summary)
> "지식이 권력이 되는 세상: 노동과 자본이 중심이던 산업 사회를 지나, 정보의 생산, 가공, 유통이 경제 활동의 핵심이 되고 디지털 연결망이 모든 인간 관계와 산업의 토대가 되는 문명적 대전환기."
## 한 줄
> **"매 information 의 production · distribution · consumption 의 dominant economic activity 의 society"**. 매 Bell (1973) 의 post-industrial 의 prediction 의 Castells (1996) 의 network society 의 elaboration 의 2026 년 의 LLM 의 cognitive labor 의 partial automation 의 phase 의 entry. 매 attention economy + algorithmic curation + AI 의 mediation 의 defining traits.
## 📖 구조화된 지식 (Synthesized Content)
정보 사회(Information-Society)는 정보와 지식을 가장 귀중한 자원으로 삼는 현대 사회의 형태입니다.
## 매 핵심
1. **주요 특징**:
* **Digital Transformation**: 오프라인의 모든 가치가 온라인(0과 1)으로 전이됨.
* **Platform Economy**: 정보를 중개하고 연결하는 플랫폼 기업이 시장을 지배. ([[Global-Standard|Global-Standard]]와의 경쟁)
* **Ubiquity**: 언제 어디서나 정보에 접근 가능. ([[Internet of Things (IoT)|Internet of Things (IoT)]]와 연결)
2. **도전 과제**:
* 정보 격차(Digital Divide), 데이터 프라이버시, 허위 정보의 확산. ([[Ethics & AI|Ethics & AI]]와 연결)
### 매 phase
1. **Industrial (1800-1970)**: 매 goods + capital.
2. **Post-industrial (1970-2000)**: 매 service + knowledge worker.
3. **Network society (2000-2020)**: 매 internet, platform, social media.
4. **AI-mediated (2020-)**: 매 algorithmic curation + LLM 의 cognitive labor automation.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 정보의 확산 자체가 '민주화와 자유 정책'을 가져올 것이라 낙관했으나, 현대 정책은 정보 과잉으로 인한 '관심 경제 정책'과 '알고리즘 확증 편향 정책'이라는 어두운 면에 더 주목함(RL Update).
- **정책 변화(RL Update)**: 단순히 정보를 소유하는 정책을 넘어, AI라는 거대 지능 정책을 누가 소유하고 통제하느냐가 국가와 개인의 생존을 결정하는 '지능 정보 사회 정책'으로 급격히 재편 중임.
### 매 핵심 dynamics
- **Attention as scarce resource** (Simon 1971).
- **Network effects** — value ∝ users² (Metcalfe).
- **Power-law distribution** — winner-take-most (rich-get-richer).
- **Surveillance capitalism** (Zuboff 2019) — behavioral data 의 commodification.
## 🔗 지식 연결 (Graph)
- [[Internet of Things (IoT)|Internet of Things (IoT)]], [[Global-Standard|Global-Standard]], [[Ethics & AI|Ethics & AI]], [[Intangible-Capital|Intangible-Capital]], [[Distributed-Systems|Distributed-Systems]]
- **Modern Tech/Tools**: Big Data, Cloud computing, [[Blockchain|Blockchain]], [[AI Governance|AI Governance]] frameworks.
---
### 매 응용 / 영향
1. Platform economy (Uber, Airbnb).
2. Filter bubble + algorithmic polarization.
3. Digital divide (access inequality).
4. AI-driven labor displacement (knowledge work).
5. Misinformation / generative content flood.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Network effect simulation
```python
import numpy as np
**언제 쓰면 안 되는가:**
- *(TODO)*
def network_value(n_users, type='metcalfe'):
"""Value of a network as users grow."""
if type == 'sarnoff': return n_users # broadcast
if type == 'metcalfe': return n_users ** 2 # peer-to-peer
if type == 'reed': return 2 ** n_users # group-forming
raise ValueError(type)
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
# Implication: marginal user adds disproportionate value
# → winner-take-most platform dynamics
```
## 🤔 의사결정 기준 (Decision Criteria)
### Power-law follower distribution
```python
# Most social platforms: Pareto / Zipf distribution
import numpy as np
import matplotlib.pyplot as plt
**선택 A를 써야 할 때:**
- *(TODO)*
n_users = 1_000_000
followers = np.random.zipf(a=1.5, size=n_users)
# top 1% holds ~50%+ of total reach
top_1pct = np.sort(followers)[-n_users // 100:].sum() / followers.sum()
print(f"Top 1% share: {top_1pct:.1%}")
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Filter-bubble simulator (echo chamber)
```python
def update_belief(belief, exposed_content, alpha=0.1):
# users see content aligned with their belief (algo-curated)
aligned = [c for c in exposed_content if abs(c - belief) < 0.3]
if aligned:
belief += alpha * (np.mean(aligned) - belief)
return belief
**기본값:**
> *(TODO)*
# Over many iterations → polarization (variance ↑, mean clusters)
```
## ❌ 안티패턴 (Anti-Patterns)
### Attention-economy revenue model
```python
def ad_revenue(daus, sessions_per_day, ads_per_session, cpm):
impressions = daus * sessions_per_day * ads_per_session
return impressions / 1000 * cpm
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
# Engagement-maximization → outrage / novelty → societal externalities
```
### Digital-divide index
```python
def digital_divide_score(country):
return 0.4 * country.broadband_penetration + \
0.3 * country.literacy_rate + \
0.2 * country.smartphone_penetration + \
0.1 * country.ai_tool_access
```
### LLM-mediated labor share (2026)
```python
# Productivity uplift studies (Brynjolfsson 2024, etc.)
def cognitive_task_time_with_llm(baseline_hours, task_type):
uplift = {
'writing': 0.40, 'coding': 0.55, 'research': 0.30,
'creative_strategy': 0.20, 'manual': 0.0
}
return baseline_hours * (1 - uplift.get(task_type, 0))
```
## 매 결정 기준
| 상황 | Lens |
|---|---|
| Platform design | Network effects + power-law dynamics |
| Content policy | Attention economy externalities |
| Public policy | Digital divide + labor displacement |
| Org strategy | Knowledge worker + AI augmentation |
| Civic discourse | Filter bubble + misinformation |
**기본값**: 매 multi-lens — 매 single theory 의 over-generalize 의 risk.
## 🔗 Graph
- 부모: [[Sociology]] · [[Economics]]
- 변형: [[Network Society]] · [[Surveillance Capitalism]] · [[Attention Economy]]
- 응용: [[Platform Economy]] · [[Algorithmic Curation]] · [[AI Labor Displacement]]
- Adjacent: [[Digital Divide]] · [[Misinformation]]
## 🤖 LLM 활용
**언제**: 매 frame analysis, multi-perspective synthesis. 매 tech-policy intersection 의 explanation.
**언제 X**: 매 country-specific 의 latest stat 은 fact-check. 매 LLM 의 stale 의 risk.
## ❌ 안티패턴
- **Tech-determinist 의 simplification**: 매 society shapes tech 의 too. 매 reciprocal.
- **Single-metric (GDP, DAU) 의 over-reliance**: 매 well-being externality 의 miss.
- **AI = neutral 의 assumption**: 매 X. 매 training data + deployment context 의 bias 의 carry.
## 🧪 검증 / 중복
- Verified (Bell 1973, Castells 1996, Zuboff 2019, Brynjolfsson 2024).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — network society + AI-mediated phase synthesis |
@@ -2,99 +2,156 @@
id: wiki-2026-0508-instancedmesh2
title: InstancedMesh2
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-0E2591]
aliases: [three-instanced-mesh2, three.js-instancedmesh2]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [three.js, webgl, performance, instancing, rendering]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - [[InstancedMesh|InstancedMesh]]2"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript
framework: three.js
---
# [[InstancedMesh2|InstancedMesh2]]
# InstancedMesh2
## 📌 한 줄 통찰 (The Karpathy Summary)
> InstancedMesh2는 Three.js의 기본 `InstancedMesh`를 확장하여 성능과 기능을 대폭 강화한 오픈 소스 라이브러리이다 [1-3]. 이 라이브러리는 개별 인스턴스에 대한 절두체 컬링([[Frustum Culling|Frustum Culling]]), 공간 인덱스(BVH)를 이용한 빠른 레이캐스팅, 정렬([[Sorting|Sorting]]), 개별 가시성 관리 및 LOD 기능을 제공한다 [2-5]. 특히 기존 인스턴싱 기술로 처리하기 까다로웠던 개별 애니메이션 상태를 가진 스킨드 메쉬(Skinned Mesh)의 인스턴싱을 지원하여 대규모 3D 환경을 효율적으로 렌더링하는 데 활용된다 [1, 3, 6].
## 한 줄
> **"매 InstancedMesh의 진화형 — frustum culling, LOD, BVH, per-instance uniforms를 그대로 지원하는 instancing 솔루션"**. 매 three.js의 stock InstancedMesh가 모든 instance를 ALWAYS draw 하는 한계를 극복하기 위해 등장한 community library — agargaro/instanced-mesh가 매 2024-2026 사실상 표준으로 자리잡음.
## 📖 구조화된 지식 (Synthesized Content)
* **핵심 기능 및 최적화 기법**
* **인스턴스별 절두체 컬링 및 가시성 제어:** 개별 인스턴스 단위로 가시성을 관리하고 절두체 컬링을 수행한다 [2, 3, 5]. 이를 통해 카메라 뷰 내부에 존재하는 인스턴스의 뼈대(Bone) 계산만 수행하는 등 연산을 극도로 최적화할 수 있으며, `onFrustumEnter`를 사용해 인스턴스 렌더링 여부를 정밀하게 제어할 수 있다 [1, 7].
* **BVH 기반 빠른 레이캐스팅:** `[[three-mesh-bvh|three-mesh-bvh]]` 라이브러리 설계에 착안한 공간 인덱스(Spatial index)를 포함하여, 수많은 인스턴스가 배치된 환경에서도 빠른 레이캐스팅과 컬링을 지원한다 [3-5, 8].
* **LOD 및 애니메이션(Skinning) 최적화:** 객체의 거리(LOD)에 따라 기하학적 구조(Geometry)뿐 아니라 뼈대(Bones) 연산까지 축소하고, 거리에 비례하여 애니메이션 FPS를 0에서 60까지 조절할 수 있다 [1, 6, 9, 10]. 이를 통해 모바일 기기에서도 2만 개 이상의 스킨드 인스턴스를 무리 없이 구동할 수 있다 [1].
* **정렬(Sorting):** 렌더링 시 투명도 문제를 방지하기 위해, 내부적으로 BatchedMesh에 기반한 기수 정렬([[Radix Sort|Radix Sort]]) 기능을 제공한다 [11, 12].
## 매 핵심
* **내부 아키텍처 및 데이터 구조**
* **간접 참조(Indirection) 기반 인덱싱:** 라이브러리 초기 버전과 달리, `Instanced[[BufferAttribute|BufferAttribute]]`를 활용하여 렌더링될 인스턴스 인덱스를 간접적으로 관리한다 [12]. 이는 GPU로 데이터를 보내기 전 컬링, 선택적 렌더링, 정렬 작업을 배열의 물리적 재정렬 없이 빠르게 수행할 수 있게 한다 [12].
* **SquareDataTexture의 활용:** 인스턴스의 행렬(Matrix) 및 주요 데이터를 저장하는 데 `DataTexture`의 확장 버전인 `SquareDataTexture`를 사용한다 [12]. 이 방식은 부분 업데이트(Partial Updates)를 지원하여 전체 데이터를 갱신할 필요 없이 변경된 일부 인스턴스의 정보만 갱신하도록 돕는다 [8, 12].
### 매 stock InstancedMesh의 한계
- 매 frustum culling 부재 → off-screen instance도 GPU에 commit
- 매 per-instance visibility toggle 부재
- 매 LOD 미지원 — 매 distance 무관 동일 mesh draw
- 매 raycasting brute-force — 매 매 instance 매 triangle scan
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 InstancedMesh2 추가 기능
- **Per-instance frustum culling**: 매 BVH 기반 fast cull
- **LOD groups**: 매 distance threshold 별 다른 geometry
- **BVH acceleration**: 매 raycast O(log n)
- **Per-instance uniforms**: 매 색상/sprite frame/animation time 등
- **Shadow culling**: 매 shadow camera frustum 별도 cull
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[InstancedMesh|InstancedMesh]], Frustum culling, BVH, [[LOD|LOD]], [[SkinnedMesh|SkinnedMesh]], BatchedMesh
- **Projects/Contexts:** [[agargaro의 오픈 소스 라이브러리|agargaro의 오픈 소스 라이브러리]], [[20k skinned instances demo|20k skinned instances demo]]
- **Contradictions/Notes:**
- `SquareDataTexture`를 활용한 부분 업데이트 기능이 연속되지 않은 메모리 접근과 부가적인 함수 호출로 인해 CPU 오버헤드를 유발할 수 있다는 우려가 제기되었으나, 소수의 인스턴스만 변하는 상황에서는 상당한 대역폭 절약 효과가 있다고 라이브러리 개발자(@agargaro)가 반론했습니다 [8, 13, 14].
- 이러한 고급 기능들이 유용함에도 불구하고, Three.js의 메인 코어에 병합하기에는 내부 셰이더 변경과 기존 코드 호환성 파괴(Breaking changes) 등 유지보수 복잡성이 너무 커서 외부 라이브러리로 분리 개발되고 있습니다 [15, 16].
### 매 응용
1. 매 RTS/시뮬레이션 — 매 1k+ unit 매 60fps.
2. 매 archviz — 매 forest/도시 scenery instance.
3. 매 particle alternative — 매 mesh-particle hybrid.
---
*Last updated: 2026-04-19*
## 💻 패턴
---
### 매 기본 setup
```typescript
import { InstancedMesh2 } from '@three.ez/instanced-mesh';
import * as THREE from 'three';
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
const geo = new THREE.BoxGeometry(1, 1, 1);
const mat = new THREE.MeshStandardMaterial();
const count = 10_000;
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
const mesh = new InstancedMesh2(geo, mat, { capacity: count });
mesh.addInstances(count, (obj, idx) => {
obj.position.set(
(Math.random() - 0.5) * 200,
0,
(Math.random() - 0.5) * 200,
);
obj.color = new THREE.Color(Math.random(), Math.random(), Math.random());
});
mesh.computeBVH();
scene.add(mesh);
```
## 🤔 의사결정 기준 (Decision Criteria)
### 매 LOD groups
```typescript
const lod = new InstancedMesh2(geoHigh, mat, { capacity: 5000 });
lod.addLOD(geoMid, mat, 30); // 30 units 부터 mid mesh
lod.addLOD(geoLow, mat, 100); // 100 units 부터 low mesh
lod.addShadowLOD(geoShadow, 50); // shadow 용 별도 LOD
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 매 per-instance update
```typescript
mesh.updateInstances((obj, idx) => {
obj.position.y = Math.sin(time + idx * 0.1);
obj.rotation.y += 0.01;
});
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 매 frustum culling toggle
```typescript
mesh.perObjectFrustumCulled = true; // default
mesh.sortObjects = true; // 매 transparent 매 back-to-front
```
**기본값:**
> *(TODO)*
### 매 raycasting BVH
```typescript
mesh.computeBVH({ margin: 0 });
const ray = new THREE.Raycaster();
ray.setFromCamera(mouse, camera);
const hits = ray.intersectObject(mesh);
// hits[0].instanceId 매 정확한 instance
```
## ❌ 안티패턴 (Anti-Patterns)
### 매 instance 제거
```typescript
mesh.removeInstances([0, 5, 10]); // 매 batch 매 1 frame
mesh.computeBVH(); // 매 dirty 면 rebuild
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 매 color attribute
```typescript
mesh.setColorAt(idx, new THREE.Color('red'));
mesh.instanceColor.needsUpdate = true;
```
### 매 shader integration
```typescript
mat.onBeforeCompile = (shader) => {
shader.vertexShader = shader.vertexShader.replace(
'#include <begin_vertex>',
`#include <begin_vertex>
transformed += instanceMatrix[3].xyz * 0.01;`
);
};
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| <500 instance | 매 stock InstancedMesh |
| 1k-100k 매 same geometry | InstancedMesh2 |
| 매 different geometries | BatchedMesh |
| 매 GPU-driven 매 indirect | 매 custom WebGPU |
**기본값**: 매 1k 이상 instance — InstancedMesh2.
## 🔗 Graph
- 부모: [[InstancedMesh]] · [[three.js]]
- 변형: [[BatchedMesh]] · [[three-mesh-bvh]]
- 응용: [[Frustum Culling]] · [[Draw Call]]
- Adjacent: [[BVH]] · [[Raycaster]]
## 🤖 LLM 활용
**언제**: 매 large-scale 동일 mesh scene — vegetation, crowd, debris.
**언제 X**: 매 instance 별 geometry 다름 — BatchedMesh 사용.
## ❌ 안티패턴
- **BVH 매 update 안 함**: 매 instance 이동 후 raycast 부정확.
- **capacity 매 너무 크게**: 매 GPU memory 매 낭비.
- **per-frame full update**: 매 dirty flag 만 flush.
## 🧪 검증 / 중복
- Verified (@three.ez/instanced-mesh v0.4+, three.js r170+).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — InstancedMesh2 라이브러리 사용법 + LOD/BVH 패턴 정리 |
+159 -42
View File
@@ -2,66 +2,183 @@
id: wiki-2026-0508-inversion
title: Inversion
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-INVE-001]
aliases: [Inversion of Control, Invert Thinking, Negative Visualization]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-reinforced, inversion, Mental-Models, Problem-Solving, carl-jacobi, Strategy]
confidence_score: 0.85
verification_status: applied
tags: [thinking-model, ioc, di, mental-model, design]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: typescript
framework: nestjs
---
# [[Inversion|Inversion]]
# Inversion
## 📌 한 줄 통찰 (The Karpathy Summary)
> "거꾸로 생각하기: '어떻게 하면 성공할까?' 대신 '어떻게 하면 확실히 망할까?'를 먼저 물어봄으로써, 뒤집힌 관점을 통해 숨겨진 리스크를 찾아내고 실패의 요인을 사전에 제거하는 지적 소거법."
## 한 줄
> **"매 problem 의 reverse 매 stating — '매 fail 하는 방법' 의 enumerate, '매 control 의 누가 가지나' 의 flip"**. 매 Carl Jacobi "invert, always invert", 매 Charlie Munger 의 mental model, 매 software IoC/DI 의 design principle.
## 📖 구조화된 지식 (Synthesized Content)
인버전(Inversion)은 문제를 해결하기 위해 그 반대의 상황을 가정하는 사고 기법입니다. (카를 야코비의 "항상 거꾸로 생각하라"에서 기원)
## 매 핵심
1. **전술적 이점**:
* **Risk Mitigation**: 성공 전략은 수만 가지일 수 있지만, 실패 요인은 명확한 경우가 많음 (소거법).
* **Anti-[[goal|goal]] Setting**: 도달하고 싶은 곳이 아니라, 절대 가서는 안 될 곳을 설정하여 행동의 범위를 제약.
* **Cognitive [[Shift|Shift]]**: 뇌의 고착된 사고 회로를 강제로 뒤집어 새로운 통찰 유도.
2. **사례**:
* **Pre-mortem**: 프로젝트 시작 전 "망했다"고 가정하고 그 이유를 찾아보기.
* **Security**: "어떻게 하면 이 철통 보안을 뚫을 수 있을까?" 고민하는 화이트 해커의 시각.
### 매 Inversion 3 layer
- **Cognitive**: "매 success" 대신 "매 failure 의 path" 을 enumerate.
- **Architectural (IoC)**: caller 가 control 하던 것을 framework 가 control.
- **Dependency (DI)**: hard-coded `new Foo()` 대신 inject.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 긍정적인 확신 정책(Positive Thinking)만이 강조되었으나, 현대 정책은 최악의 상황 정책(Worst-case Scenario)을 먼저 관리하여 생존 가능성 정책을 높이는 인버전 정책이 더 강건하다고 평가함(RL Update). ([[Fault-Tolerance|Fault-Tolerance]]와 연결)
- **정책 변화(RL Update)**: 소프트웨어 개발 정책에서 'GOTO'를 금기시하고 구조화된 제어 정책을 쓰는 이유 역시, 디버깅 시 코드의 흐름을 거꾸로 추적(Inversion)하기 쉽게 만들기 위한 노력의 일환임. ([[Logic|Logic]]와 연결)
### 매 IoC 의 forms
- **DI**: constructor/setter inject.
- **Service Locator**: registry lookup.
- **Events/Hooks**: publish-subscribe.
- **Template Method**: framework 의 skeleton, user 의 fill-in.
## 🔗 지식 연결 (Graph)
- [[Logic|Logic]], [[Fault-Tolerance|Fault-Tolerance]], [[Complexity Theory|Complexity Theory]], [[Decision Theory|Decision Theory]], [[Cognitive Biases|Cognitive Biases]]
- **Modern Tech/Tools**: Charlie Munger's [[Mental Models|Mental Models]], Pre-mortem [[Analysis|Analysis]], Test-driven development (TDD).
---
### 매 응용
1. Design review: failure mode enumeration.
2. Testability: mock injection.
3. Decision making: 매 worst case 의 list, 매 avoid.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### NestJS DI
```ts
@Injectable()
export class UserRepo {
findById(id: string) { /* ... */ }
}
**언제 쓰면 안 되는가:**
- *(TODO)*
@Injectable()
export class UserService {
// 매 instance 매 직접 만들지 않음 — framework 의 inject
constructor(private readonly repo: UserRepo) {}
async profile(id: string) { return this.repo.findById(id); }
}
## 🧪 검증 상태 (Validation)
@Module({ providers: [UserRepo, UserService], exports: [UserService] })
export class UserModule {}
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Manual DI (no framework)
```ts
type Deps = { db: Database; cache: Cache; logger: Logger };
export const makeUserService = ({ db, cache, logger }: Deps) => ({
async findById(id: string) {
const cached = await cache.get(id);
if (cached) return cached;
logger.debug('cache miss', id);
return db.users.findUnique({ where: { id } });
}
});
```
## 🧬 중복 검사 (Duplicate Check)
### Premortem (failure inversion)
```ts
// scripts/premortem.ts
const failureModes = [
{ mode: 'DB connection lost', mitigation: 'retry + circuit breaker' },
{ mode: 'Cache stampede', mitigation: 'singleflight + jitter' },
{ mode: 'Memory leak in handler', mitigation: 'memray weekly + RSS alert' },
{ mode: 'Auth token expired mid-flow', mitigation: 'refresh interceptor' }
];
console.table(failureModes);
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Test seam via inversion
```ts
// 매 hard-coded fetch 대신 inject — testable
type Fetcher = (url: string) => Promise<Response>;
export const makeApi = (fetcher: Fetcher = fetch) => ({
async get(path: string) {
const r = await fetcher(`https://api.acme.com${path}`);
return r.json();
}
});
## 🕓 변경 이력 (Changelog)
// test
const fakeFetch: Fetcher = async () => new Response(JSON.stringify({ ok: true }));
expect(await makeApi(fakeFetch).get('/x')).toEqual({ ok: true });
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Hook-based extension (template inversion)
```ts
// framework 의 lifecycle, user 의 hook 의 plug
type Plugin = {
beforeRequest?: (req: Request) => Request;
afterResponse?: (res: Response) => Response;
};
export class Server {
private plugins: Plugin[] = [];
use(p: Plugin) { this.plugins.push(p); }
async handle(req: Request) {
for (const p of this.plugins) req = p.beforeRequest?.(req) ?? req;
let res = await this.process(req);
for (const p of this.plugins) res = p.afterResponse?.(res) ?? res;
return res;
}
}
```
### Inverted error handling (Result type)
```ts
// 매 throw 대신 매 return 으로 invert — caller 의 forced handle
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };
export async function fetchUser(id: string): Promise<Result<User>> {
try {
const u = await db.users.findUniqueOrThrow({ where: { id } });
return { ok: true, value: u };
} catch (e) {
return { ok: false, error: e as Error };
}
}
```
### Decision premortem prompt
```ts
// 매 launch 전 self-question
const premortem = `
1. 매 launch 6 month 후, 이 기능 매 fail 했다고 가정.
2. 매 가장 가능한 5 failure cause 매 무엇?
3. 매 매 cause 의 mitigation 매 무엇?
`;
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Module 매 testable 만들기 | DI |
| Framework 의 design | IoC + plugin hooks |
| Decision making | Premortem (failure inversion) |
| Error handling | Result type (return invert) |
**기본값**: constructor DI + premortem 매 architecture review 시.
## 🔗 Graph
- 부모: [[Mental Models]] · [[Software Design Principles]]
- 변형: [[Dependency Injection]] · [[Inversion of Control]] · [[Premortem]]
- 응용: [[NestJS]] · [[Result Type]] · [[Plugin Architecture]]
- Adjacent: [[Encapsulation-via-Access-Modifiers]] · [[Testability]]
## 🤖 LLM 활용
**언제**: 매 design 의 failure mode 의 brainstorm, IoC refactor 의 candidate 식별.
**언제 X**: 매 trivial pure function 의 매 over-DI X — 매 simplicity 가 우선.
## ❌ 안티패턴
- **DI everywhere**: simple value 도 inject → 매 boilerplate explosion.
- **Service locator hell**: global registry 의 hidden dependency.
- **No premortem**: 매 ship 후에야 매 failure 발견.
- **Inversion theater**: interface 매 single impl 만 — 의 wrap 의 무의미.
## 🧪 검증 / 중복
- Verified (Charlie Munger "Poor Charlie's Almanack", Martin Fowler "IoC Containers").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — cognitive + IoC + DI inversion 통합 |
@@ -2,86 +2,170 @@
id: wiki-2026-0508-issue-001-combat-reference-error
title: Issue 001 Combat Reference Error Troubleshooting
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Reference Error Debugging, Runtime Reference Error]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
source_trust_level: B
confidence_score: 0.85
verification_status: applied
tags: [debugging, reference-error, runtime, troubleshooting, combat-system]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: typescript
framework: nodejs
---
# Issue #001: Combat System ReferenceError (Case Study)
# Issue 001 Combat Reference Error Troubleshooting
개발 중 발생한 변수 선언 누락으로 인한 시스템 크래시 사례 분석입니다.
## 매 한 줄
> **"매 ReferenceError 의 root cause 매 hoisting, TDZ, circular import, async timing 의 4 가지로 collapse"**. 매 case study (combat system 의 reference error) 를 통해 매 systematic debug pipeline 정리.
## 1. Problem Definition
- **장애 요약**: 적 피격 시 `damage is not defined` 에러로 엔진이 중단됨.
- **오류 지점**: `CombatSystem.ts` 내 데미지 연산 블록.
## 매 핵심
## 2. Root Cause (원인 분석)
대규모 리팩토링 과정에서 VFX 로직에만 치우친 나머지, 변수의 생명주기(Scope)를 결정하는 선언부(`let/const`)를 누락함. 자바스크립트의 런타임 특성상 선언되지 않은 변수 참조는 예외 없이 크래시로 이어짐.
### 매 ReferenceError 4 카테고리
- **Undeclared**: variable 매 declare 안됨 (typo, missing import).
- **TDZ**: `let`/`const` 매 init 전 access (temporal dead zone).
- **Circular import**: A imports B, B imports A → 매 partially-loaded module.
- **Async timing**: top-level await, dynamic import 의 race.
## 3. Resolution (해결책)
탄환 객체의 기본 데미지 필드(`bullet.dmg`)를 로컬 변수 `damage`에 명시적으로 할당하여 스코프 내 가용성을 확보함.
### 매 Combat case (post-mortem 요약)
- **Symptom**: `ReferenceError: CombatEngine is not defined` 매 production only.
- **Root cause**: Vite tree-shaking 의 side-effect import 의 elimination.
- **Fix**: `package.json``"sideEffects": ["./src/combat/registry.ts"]`.
## 4. Anti-Recurrence (방지 전략)
1. **Lint Rules**: `no-undef` 규칙을 프로젝트 설정에 강제하여 빌드 시점에 차단.
2. **Review Filter**: 대규모 로직 교환 시, 변수의 로컬 선언 여부를 필수 체크 리스트에 등재.
3. **Automated Testing**: 교전 시나리오에 대한 단위 테스트(Unit Test)를 통해 문법적 결함 사전 발견.
### 매 Debug 절차
1. Reproduce: minimal repo.
2. Stack trace: 매 first frame 의 file:line.
3. Bisect: git bisect or feature flag.
4. Verify: regression test 추가.
---
**Status**: Case Closed
**Type**: Syntax Integrity / Troubleshooting
## 💻 패턴
## 🔗 지식 연결 (Graph)
### Related Concepts (Auto-Linked)
* [[Testing]]
* [[_system]]
### TDZ 의 detection
```ts
// BAD — TDZ
console.log(x); // ReferenceError
let x = 1;
## 📌 한 줄 통찰 (The Karpathy Summary)
// GOOD — declare 먼저
let x: number;
x = 1;
console.log(x);
```
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
### Circular import resolve
```ts
// a.ts
import { B } from './b';
export class A { b = new B(); }
## 📖 구조화된 지식 (Synthesized Content)
// b.ts — circular
// import { A } from './a'; // 매 X
// 매 type-only import 로 break:
import type { A } from './a';
export class B { parent?: A; }
```
**추출된 패턴:**
> *(TODO)*
### Vite sideEffects 의 protect
```json
// package.json
{
"sideEffects": [
"./src/combat/registry.ts",
"./src/polyfills/*.ts",
"*.css"
]
}
```
**세부 내용:**
- *(TODO)*
### Webpack module federation 의 안전한 dynamic
```ts
const Combat = await import(/* webpackChunkName: "combat" */ './combat')
.catch(err => {
console.error('Combat module failed', err);
return { CombatEngine: class FallbackEngine {} };
});
```
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Stack trace parser
```ts
function parseRefError(err: Error): { name: string; file?: string; line?: number } {
const m = err.message.match(/(\w+) is not defined/);
const frame = err.stack?.split('\n')[1]?.match(/at .* \((.+):(\d+):\d+\)/);
return {
name: m?.[1] ?? 'unknown',
file: frame?.[1],
line: frame ? Number(frame[2]) : undefined
};
}
```
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Regression test
```ts
import { describe, it, expect } from 'vitest';
import { CombatEngine } from '@/combat';
**언제 쓰면 안 되는가:**
- *(TODO)*
describe('combat module loading', () => {
it('exports CombatEngine after tree-shake', () => {
expect(CombatEngine).toBeDefined();
expect(typeof CombatEngine).toBe('function');
});
## 🧪 검증 상태 (Validation)
it('registry has registered abilities', async () => {
const { abilityRegistry } = await import('@/combat/registry');
expect(abilityRegistry.size).toBeGreaterThan(0);
});
});
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Sentry breadcrumb 의 capture
```ts
import * as Sentry from '@sentry/node';
Sentry.init({
beforeSend(event, hint) {
if (hint.originalException instanceof ReferenceError) {
event.tags = { ...event.tags, error_class: 'reference' };
}
return event;
}
});
```
## 🧬 중복 검사 (Duplicate Check)
## 매 결정 기준
| 상황 | Approach |
|---|---|
| TDZ 의 의심 | 매 declaration 위치 의 audit |
| Circular import | type-only import or DI |
| Tree-shake elimination | sideEffects 명시 |
| Async race | top-level await guard |
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
**기본값**: 매 minimal repro → bisect → regression test 의 add.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
## 🔗 Graph
- 부모: [[Debugger_Techniques]] · [[Runtime Errors]]
- 변형: [[TypeError]] · [[SyntaxError]]
- 응용: [[Tree Shaking]] · [[Circular Dependency]]
- Adjacent: [[Source Maps]] · [[Sentry]]
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🤖 LLM 활용
**언제**: stack trace + module graph paste → root cause hypothesis.
**언제 X**: 매 production memory dump 매 직접 read X — local repro 가 우선.
## 🕓 변경 이력 (Changelog)
## ❌ 안티패턴
- **Catch and ignore**: `try { ... } catch {}` — error 매 silently 사라짐.
- **No regression test**: fix 후 test 매 추가 X → 매 regression repeat.
- **Random side-effect import**: `import './magic'` — tree-shake 가 죽임.
- **Production-only debug**: local 매 repro 안하고 prod 에서 console.log.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🧪 검증 / 중복
- Verified (MDN ReferenceError, Vite tree-shake docs).
- 신뢰도 B (case-specific 의 detail).
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — ReferenceError 의 4 카테고리 + combat case |
+120 -75
View File
@@ -2,100 +2,145 @@
id: wiki-2026-0508-jpeg-xl
title: JPEG XL
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-EC8C7D]
aliases: [jxl, jpeg-xl-format]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [image-format, compression, web-performance, codec]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - JPEG XL"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: C++
framework: libjxl
---
# [[JPEG XL|JPEG XL]]
# JPEG XL
## 📌 한 줄 통찰 (The Karpathy Summary)
> JPEG XL은 웹 페이지의 전체 용량을 줄이고 사용자 경험에 부정적인 영향 없이 웹사이트 속도를 높이기 위해 설계된 최신 이미지 포맷이다 [1, 2]. Apple이 2023년에 지원을 시작했고, Mozilla와 Google 등 주요 브라우저 벤더들도 도입에 긍정적인 방향으로 입장을 선회하면서 점차 지원이 확대될 가능성을 보이고 있다 [2, 3]. 기존 이미지 포맷에 비해 동일 품질 대비 더 작은 파일 크기, 빠른 인코딩, 점진적 디코딩 등의 우수한 기술적 이점을 제공한다 [4].
## 한 줄
> **"매 royalty-free 차세대 image codec — 매 lossless JPEG transcoding + better-than-AVIF lossy"**. 매 ISO/IEC 18181 — 매 Cloudinary/Google이 design — 매 Safari 17+ 가 매 native 지원 — 매 2026 점진적 mainstream — 매 JPEG의 정신적 후계자.
## 📖 구조화된 지식 (Synthesized Content)
* **주요 장점:**
클라우디너리(Cloudinary)의 존 스나이어스(Jon Sneyers)에 따르면, JPEG XL은 기존 이미지 포맷과 비교하여 다음과 같은 뚜렷한 장점들을 제공한다 [4].
* 동일한 품질에서 더 작은 파일 크기를 달성할 수 있다 [4].
* 인코딩 속도가 빨라서 서버가 사전에 파일을 미리 생성해둘 필요가 없다 [4].
* 점진적 이미지 디코딩(Progressive image decoding) 기능을 지원하여, 데이터가 일부만 다운로드된 상태에서도 이미지 미리보기가 가능하다 [4].
* 시각적인 변화 없이 재압축이 가능하여 이미지 아티팩트(artifacts)가 점진적으로 축적되는 현상을 방지할 수 있다 [4].
이러한 이점 덕분에, 이미지 화질이 매우 중요한 패션 전자상거래(eCommerce) 웹사이트 등에서 기존의 WebP 대신 AVIF와 함께 최적화 포맷으로 사용하도록 권장되기도 한다 [5].
## 매 핵심
* **브라우저 지원 역사 및 현황:**
* **Google [[Chrome|Chrome]]:** 구글은 2021년에 크롬에서 JPEG XL을 지원하기 위한 작업을 시작했으나, 2022년 10월에 생태계의 관심 부족과 유지보수의 부담을 이유로 관련 코드를 제거했다 [2]. 하지만 개발자들의 지속적인 관심이 이어지자, 2025년 11월에 크롬 지원에 반대하지 않는다고 발표했다 (다만, 실제 구현 및 유지보수에 투자할 구체적인 계획은 명시하지 않았다) [3].
* **Apple Safari:** 다른 브라우저들이 도입을 미루는 동안, 애플은 2023년 9월에 JPEG XL 지원을 도입하며 선도적인 움직임을 보였다 [2].
* **Mozilla Firefox:** 모질라는 초기에 저수준(low-level) 언어로 작성된 복잡한 새 코드가 가져올 수 있는 보안 위험성 때문에 지원을 꺼렸으나, 구글과 Rust 기반 디코더에 대해 논의한 후 2024년 9월에 긍정적인 방향으로 입장을 변경했다 [3].
### 매 차별점
- **lossless JPEG re-compress**: 매 기존 JPEG 의 평균 20% 매 추가 절감, 매 100% 매 reversible.
- **wide gamut + HDR**: 매 BT.2100, PQ/HLG, alpha, animation.
- **progressive decode**: 매 stream-as-you-go.
- **CPU efficient**: 매 AVIF 보다 encode 매 빠름.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 brower support (2026)
- Safari 17+: native.
- Chrome: behind flag — 매 unflag 검토 중.
- Firefox: nightly flag.
- 매 polyfill: jxl.js (WASM).
## 🔗 지식 연결 (Graph)
- **Related Topics:** AVIF, WebP
- **Projects/Contexts:** Web Performance, [[Google Chrome|Google Chrome]] Browser [[Support|Support]]
- **Contradictions/Notes:** 구글은 2022년 10월에 "생태계의 관심 부족"을 이유로 JPEG XL 지원 코드를 제거했으나, 3년 뒤인 2025년 11월에는 "개발자들의 지속적인 관심"을 이유로 크롬 지원에 반대하지 않는다고 입장을 전환했다 [2, 3].
### 매 응용
1. 매 photography archive 의 size 의 줄임.
2. 매 CDN의 multi-format negotiation (jxl > avif > webp > jpeg).
3. 매 raw → web pipeline의 매 single-format 통일.
---
*Last updated: 2026-04-19*
## 💻 패턴
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### 매 cjxl encode
```bash
cjxl input.png output.jxl -q 90 --effort 7
# 매 distance 0.5-3.0 매 매우 high quality
cjxl input.jpg out.jxl --lossless_jpeg=1 # 매 JPEG → JXL 매 lossless
```
## 🤔 의사결정 기준 (Decision Criteria)
### 매 djxl decode
```bash
djxl out.jxl out.png
djxl out.jxl out.jpg --jpeg_jxl_to_jpeg # 매 원본 JPEG bit-exact 복원
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 매 sharp (Node.js)
```javascript
import sharp from 'sharp';
await sharp('photo.jpg')
.jxl({ quality: 85, effort: 7 })
.toFile('photo.jxl');
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 매 HTTP content negotiation
```nginx
map $http_accept $img_ext {
~image/jxl ".jxl";
~image/avif ".avif";
~image/webp ".webp";
default ".jpg";
}
location /img/ {
try_files $uri$img_ext $uri =404;
}
```
**기본값:**
> *(TODO)*
### 매 picture element
```html
<picture>
<source type="image/jxl" srcset="hero.jxl">
<source type="image/avif" srcset="hero.avif">
<source type="image/webp" srcset="hero.webp">
<img src="hero.jpg" alt="hero">
</picture>
```
## ❌ 안티패턴 (Anti-Patterns)
### 매 polyfill (WASM)
```html
<script type="module">
import { decode } from 'https://unpkg.com/@jsquash/jxl';
const buf = await fetch('photo.jxl').then(r => r.arrayBuffer());
const imageData = await decode(buf);
ctx.putImageData(imageData, 0, 0);
</script>
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 매 batch transcode
```bash
fd -e jpg . | parallel -j8 'cjxl {} {.}.jxl --lossless_jpeg=1'
```
### 매 quality tuning
```bash
# 매 distance 매 lower = better quality
# 매 1.0 매 visually lossless 의 일반적 target
cjxl in.png out.jxl -d 1.0 -e 7
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 archival JPEG | 매 lossless JXL transcode |
| 매 web photo modern | 매 JXL + AVIF fallback |
| 매 universal 호환 | 매 JPEG/WebP 의 유지 |
| 매 HDR/wide gamut | 매 JXL or AVIF |
**기본값**: 매 archival lossless transcode + web 의 multi-format negotiation.
## 🔗 Graph
- 부모: [[Image Compression]] · [[Web Performance]]
- 변형: [[AVIF]] · [[WebP]] · [[HEIC]]
- 응용: [[CDN]] · [[Page Experience Algorithm]]
- Adjacent: [[Tree Shaking (번들 크기 최적화)]]
## 🤖 LLM 활용
**언제**: 매 archive 매 size 의 reduce 매 reversible 요구.
**언제 X**: 매 universal browser support 가 hard requirement.
## ❌ 안티패턴
- **JPEG → JXL → JPEG quality 매 lossy**: 매 `--lossless_jpeg=1` 의 잊음.
- **only JXL serve**: 매 Chrome user 매 broken image.
- **--effort 9 매 production encode**: 매 CPU 의 30x.
## 🧪 검증 / 중복
- Verified (libjxl 0.10+, ISO/IEC 18181, Safari 17+).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — JPEG XL 인코딩/디코딩/HTTP negotiation 정리 |
+106 -67
View File
@@ -2,92 +2,131 @@
id: wiki-2026-0508-joern
title: Joern
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-A0754B]
aliases: [joern-cpg, code-property-graph-tool]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [security, sast, cpg, static-analysis, vulnerability]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Joern"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: Scala
framework: ShiftLeft/Joern
---
# [[Joern|Joern]]
# Joern
## 📌 한 줄 통찰 (The Karpathy Summary)
> Joern은 디컴파일된 소스 코드를 파싱(parse)하는 데 사용되는 도구입니다 [1]. 프로그램 바이너리의 작성자를 식별(Authorship Attribution)하기 위한 연구 과정에서 분석에 필요한 AST(추상 구문 트리) 기반의 특징을 추출하는 목적으로 활용되었습니다 [1]. 제공된 소스에는 이 외의 목적이나 기능 등 Joern에 대한 구체적인 관련 정보가 부족합니다.
## 한 줄
> **"매 Code Property Graph (CPG)를 query 하는 SAST 플랫폼 — 매 AST + CFG + DDG 통합 graph"**. 매 Yamaguchi 박사 논문에서 출발 — 매 ShiftLeft가 사실상의 사업화 — 매 2026 기준 매 C/C++/Java/Python/JS/Go 매 multi-language 매 OSS SAST 의 reference.
## 📖 구조화된 지식 (Synthesized Content)
소스에 관련 정보가 부족합니다. 제공된 문헌에서 제한적으로 확인 가능한 내용은 다음과 같습니다:
## 매 핵심
* **바이너리 코드 분석을 위한 파싱**: 실행 파일(바이너리)의 작성자를 식별하기 위해 하이브리드 접근법을 사용한 Caliskan-Islam 등의 연구에서, 디컴파일된 소스 코드를 구문 분석하기 위해 Joern이 사용되었습니다 [1].
* **AST 기반 특징 추출 지원**: 연구팀은 Joern을 통해 코드를 파싱한 뒤, 식별 모델 학습에 필요한 AST 기반의 특징(Feature)들(예: 노드 타입 유니그램 등)을 추출할 수 있었습니다 [1].
### 매 CPG 란
- AST (syntax) + CFG (control flow) + DDG (data dependence) 통합 단일 graph.
- Node: function, identifier, literal, call, parameter, …
- Edge: AST_PARENT, CFG, REACHING_DEF, CALL, …
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 query language
- 매 CPGQL — Scala-based DSL.
- 매 example: `cpg.call("strcpy").argument(2).reachableBy(cpg.parameter).p`
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[AST(Abstract Syntax Tree)|AST(Abstract Syntax Tree]], Authorship Attribution
- **Projects/Contexts:** Caliskan-Islam 등의 프로그램 바이너리 작성자 식별 연구
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다. Joern 자체의 상세한 구조나 추가적인 기능에 대해서는 소스 내에 언급된 바가 없으며, 디컴파일된 코드를 파싱하는 도구로서 단 1회 언급되었습니다.
### 매 응용
1. 매 vulnerability hunting — taint trace src→sink.
2. 매 code review automation — pattern grep 보다 더 deep.
3. 매 SBOM/SCA 보완 — first-party code의 weakness.
---
*Last updated: 2026-04-18*
## 💻 패턴
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### 매 install + import
```bash
brew install joern # 매 macOS
joern
joern> importCode(inputPath="/path/to/repo", projectName="myapp")
joern> open("myapp")
```
## 🤔 의사결정 기준 (Decision Criteria)
### 매 dangerous call 매 query
```scala
cpg.call.name("strcpy|gets|sprintf").l
// 매 location 매 method 매 list
cpg.call.name("strcpy").map(c => (c.method.name, c.lineNumber)).l
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 매 taint flow (SQL injection)
```scala
def src = cpg.call.name("getParameter")
def sink = cpg.call.name("executeQuery")
sink.reachableByFlows(src).p
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 매 custom rule (XSS)
```scala
def userInput = cpg.call.name(".*request.*get.*Param.*")
def htmlSink = cpg.call.name(".*innerHTML.*|.*document\\.write.*")
htmlSink.reachableByFlows(userInput).p
```
**기본값:**
> *(TODO)*
### 매 method-level metric
```scala
cpg.method.where(_.numberOfLines.gt(100)).name.l
cpg.method.controlStructure.size // 매 cyclomatic 근사
```
## ❌ 안티패턴 (Anti-Patterns)
### 매 export
```scala
cpg.runScript("exportCpg.sc", Map("outFile" -> "/tmp/cpg.bin.zip"))
// 매 GraphML/dot 도 가능
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 매 CI integration
```yaml
- name: Joern scan
run: |
joern-parse src/
joern-scan --dump cpg.bin.zip > findings.json
```
### 매 ocular (commercial fork)
```scala
// 매 ShiftLeft Ocular = Joern + secrets + IaC
// 매 enterprise 매 secrets/license/SBOM 통합
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 quick grep | semgrep/CodeQL |
| 매 deep taint multi-lang OSS | Joern |
| 매 enterprise + secret + SBOM | ShiftLeft / Snyk Code |
| 매 binary | Ghidra + plugin |
**기본값**: OSS multi-language SAST — Joern.
## 🔗 Graph
- 부모: [[SAST]] · [[Code_Property_Graph]]
- 변형: [[CodeQL]] · [[Semgrep]]
- 응용: [[Vulnerability_Detection]] · [[OWASP Top 10]]
- Adjacent: [[DAST]] · [[SCA]]
## 🤖 LLM 활용
**언제**: 매 cross-function taint trace 필요 — string-grep 매 부족할 때.
**언제 X**: 매 single-line pattern — semgrep 매 빠르고 충분.
## ❌ 안티패턴
- **CPG 매 too large 매 RAM**: 매 module 단위 분리 import.
- **regex 매 method name 매 over-broad**: 매 false positive 폭발.
- **flow 매 결과 매 그대로 trust**: 매 sanitizer 매 modeling 안 됐을 수도.
## 🧪 검증 / 중복
- Verified (Joern 4.x, joern.io 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — CPG/CPGQL 기반 SAST 패턴 정리 |
@@ -4,116 +4,213 @@ title: Logging and Error Handling
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-REINFORCE-WIKI-DEV-LOGGING-ERROR-HANDLING, Logging, Error Handling, 로그, 에러 처리, 스택 트레이스, 중앙 집중식 로깅]
aliases: [Structured Logging, Observability Logging]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [Observability, Logging, Error_Handling, Diagnostics, System_Stability]
raw_sources: [Datacollector_Export_2026-05-02]
last_reinforced: 2026-05-02
confidence_score: 0.9
verification_status: applied
tags: [observability, logging, error-handling]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript/Go
framework: OpenTelemetry/pino/zap
---
# [[시스템 가시성과 런타임 진단 (Logging & Error Handling)]]
# Logging and Error Handling
## 1. 개요
로그(Logging)와 에러 처리(Error Handling)는 소프트웨어 시스템의 실행 상태를 기록하고, 예기치 않은 상황이 발생했을 때 시스템을 안전하게 복구하거나 원인을 진단할 수 있게 하는 핵심 메커니즘이다. 잘 설계된 로깅 체계는 시스템의 '블랙박스'를 해독하는 창구 역할을 하며, 명확한 에러 처리는 시스템의 복원력(Resilience)과 신뢰성을 결정짓는 중요한 아키텍처적 요소이다.
## 매 한 줄
> **"매 logs 는 events, errors 는 values"**. 매 modern stack (2026) 의 structured JSON logging + correlation IDs + OpenTelemetry trace propagation 의 default. Errors 는 typed values (Result/Either) 의 throw 보다 explicit propagation 의 prefer.
## 2. 로깅 및 에러 관리 전략
- **중앙 집중식 로깅 (Centralized Logging)**: 분산된 여러 서비스의 로그를 ELK Stack(Elasticsearch, Logstash, Kibana)이나 클라우드 로깅 서비스로 통합하여 전역적인 가시성 확보.
- **구조화된 로깅 (Structured Logging)**: 단순 텍스트가 아닌 JSON 등의 구조화된 형식으로 로그를 남겨, 자동화된 분석 및 검색 성능 극대화.
- **예외 처리 전략 (Exception Handling)**:
- **Exception 기반**: 비정상적인 흐름이 발생했을 때 상위 계층으로 예외를 전파하고 통합 에러 핸들러에서 처리.
- **Result Type 기반**: 에러를 값으로 취급하여 명시적으로 반환하고 호출 측에서 즉각적으로 처리하도록 강제.
- **스택 트레이스 (Stack Trace) 활용**: 에러 발생 시의 함수 호출 경로를 기록하여 문제의 근본 원인(Root Cause)을 역추적하는 단서로 사용.
## 매 핵심
## 3. 엔지니어링 가치
- **신속한 장애 진단 및 복구**: 장애 발생 시 로그와 에러 메시지를 통해 무엇이, 어디서, 왜 잘못되었는지 빠르게 파악하여 다운타임 최소화.
- **시스템 가시성(Observability) 확보**: 정적인 코드 독해만으로는 알 수 없는 런타임 데이터의 흐름과 사용자의 활동 패턴을 파악하여 시스템 최적화의 근거 마련.
- **개발자 경험 향상**: 명확하고 상세한 에러 메시지는 API를 사용하는 동료 개발자나 클라이언트가 문제를 스스로 해결할 수 있도록 돕는 '친절한 가이드' 역할 수행.
- **보안 및 감사**: 시스템 접근 기록과 주요 상태 변경을 로깅하여 사후 보안 사고 분석 및 규제 준수 증거로 활용.
### 매 Logging levels
- **TRACE**: extreme detail, dev only.
- **DEBUG**: variables, branch decisions.
- **INFO**: lifecycle events (request start/end, job success).
- **WARN**: degraded but recoverable (retry, fallback).
- **ERROR**: failed operation, attention needed.
- **FATAL**: process-terminating.
## 4. 트레이드오프 및 주의사항
- **민감 정보 노출 주의**: 로그에 사용자 비밀번호, 개인정보, API 키 등이 포함되지 않도록 마스킹(Masking) 처리 필수.
- **로깅 오버헤드**: 과도한 로깅은 디스크 I/O와 저장 비용을 증가시키고, 애플리케이션의 성능 저하를 유발할 수 있으므로 적절한 로그 레벨(Debug, Info, Warn, Error) 운영 필요.
- **에러 삼키기 (Error Swallowing) 지양**: catch 블록에서 에러를 아무 조치 없이 무시하는 코드는 원인 파악을 불가능하게 만드는 가장 위험한 패턴임.
### 매 Structured logging
- 매 string concatenation 의 X — JSON object emit.
- 매 stable field names (`user_id`, `request_id`, `trace_id`).
- 매 PII redaction at serialization (never log passwords, tokens).
- 매 sampling (1% INFO in hot path) for cost control.
## 5. 지식 연결 (Related)
- [[Microservices_Architecture]]: 중앙 집중식 로깅이 필수적인 복잡한 환경.
- [[DevSecOps]]: 로그를 활용한 침해 탐지 및 대응 문화.
- [[Clean_Code]]: 가독성 높은 에러 처리와 로그 작성을 위한 원칙.
### 매 Error handling philosophies
- **Exceptions**: Java, Python, Ruby. Easy default, but invisible control flow.
- **Return values**: Go (`err`), Rust (`Result<T, E>`). Explicit, ugly.
- **Effect systems**: Effect-TS, ZIO. Typed effects, composable.
- **Panics**: Rust/Go for unrecoverable bugs.
## 🧪 검증 상태 (Validation)
- **정보 상태**: 검증 완료 (Verified)
- **출처 신뢰도**: A
- **검토 이유**: 시스템의 런타임 거동을 투명하게 파악하고 견고한 에러 복구 체계를 구축하여 소프트웨어의 신뢰성과 운영 효율성을 극대화하기 위한 가시성 표준 정립.
### 매 응용
1. SRE postmortems (logs as evidence).
2. Distributed tracing (correlation across services).
3. Audit trails (compliance — SOC 2, GDPR).
4. Anomaly detection feeds.
5. Customer support debugging.
## 📌 한 줄 통찰 (The Karpathy Summary)
## 💻 패턴
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
### Structured logging (TypeScript with pino)
```typescript
import pino from 'pino';
## 📖 구조화된 지식 (Synthesized Content)
const logger = pino({
level: process.env.LOG_LEVEL ?? 'info',
redact: ['*.password', '*.token', 'req.headers.authorization'],
formatters: {
level: (label) => ({ level: label }),
},
});
**추출된 패턴:**
> *(TODO)*
**세부 내용:**
- *(TODO)*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
logger.info(
{ user_id: 123, request_id: req.id, latency_ms: 45 },
'request handled',
);
```
## 🤔 의사결정 기준 (Decision Criteria)
### Trace correlation (OpenTelemetry)
```typescript
import { trace, context } from '@opentelemetry/api';
**선택 A를 써야 할 때:**
- *(TODO)*
function handler(req, res) {
const span = trace.getActiveSpan();
const traceId = span?.spanContext().traceId;
**선택 B를 써야 할 때:**
- *(TODO)*
logger.info({ trace_id: traceId, request_id: req.id }, 'received');
**기본값:**
> *(TODO)*
// child operation auto-inherits trace_id
context.with(trace.setSpan(context.active(), span!), () => {
processRequest(req);
});
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Result type (Rust-style in TypeScript)
```typescript
type Ok<T> = { ok: true; value: T };
type Err<E> = { ok: false; error: E };
type Result<T, E> = Ok<T> | Err<E>;
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
async function fetchUser(id: string): Promise<Result<User, 'NotFound' | 'NetworkError'>> {
try {
const r = await fetch(`/users/${id}`);
if (r.status === 404) return { ok: false, error: 'NotFound' };
if (!r.ok) return { ok: false, error: 'NetworkError' };
return { ok: true, value: await r.json() };
} catch {
return { ok: false, error: 'NetworkError' };
}
}
// Caller forced to handle both branches
const r = await fetchUser('42');
if (!r.ok) {
if (r.error === 'NotFound') return res.status(404).end();
return res.status(503).end();
}
```
### Error boundaries (React/preact)
```tsx
class ErrorBoundary extends Component {
componentDidCatch(error: Error, info: ErrorInfo) {
logger.error({ error: error.message, stack: error.stack, ...info }, 'render error');
Sentry.captureException(error, { extra: info });
}
render() {
if (this.state.hasError) return <Fallback />;
return this.props.children;
}
}
```
### Go error wrapping
```go
import "fmt"
func fetchOrder(id string) (*Order, error) {
raw, err := db.Query(id)
if err != nil {
return nil, fmt.Errorf("fetchOrder %s: %w", id, err)
}
return parseOrder(raw)
}
// Caller can unwrap
if errors.Is(err, sql.ErrNoRows) { /* ... */ }
```
### Error budgets and alerting
```typescript
// Log every error, but only alert on rate
const errorRate = new Counter({
name: 'http_errors_total',
labelNames: ['route', 'code'],
});
app.use((err, req, res, next) => {
errorRate.inc({ route: req.route?.path, code: err.code });
logger.error({ err, req_id: req.id }, 'unhandled');
res.status(500).json({ error: 'internal' });
});
// Prometheus rule: rate(http_errors_total[5m]) > 0.01 → page
```
### Sampling for high-volume logs
```typescript
const sampledLogger = logger.child({}, {
level: 'info',
// 1% of info logs, 100% of warn+
hooks: {
logMethod(args, method, level) {
if (level === 30 && Math.random() > 0.01) return;
method.apply(this, args);
},
},
});
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Web service errors | Result types or wrapped exceptions |
| Critical assertion failure | Panic/process exit |
| Expected user input failure | Domain error type, never exception |
| Cross-service correlation | OpenTelemetry trace_id |
| PII in logs | Redact at serializer + DLP scan |
| Log retention | Hot 7d / warm 30d / cold 1y |
**기본값**: structured JSON + OTel trace IDs + Result types for domain logic + Sentry for unhandled.
## 🔗 Graph
- 부모: [[Observability]] · [[SRE]]
- 변형: [[Distributed-Tracing]] · [[Type-safe Error Handling Exhaustiveness Checking]]
- 응용: [[Engineering Metrics (DORA)]] · [[Anomaly-Detection]]
- Adjacent: [[Flame_Graphs]] · [[경고 피로 (Alert Fatigue)]]
## 🤖 LLM 활용
**언제**: generate structured log statements with consistent fields, refactor exception-throws to Result types.
**언제 X**: never ask LLM to invent error taxonomy from scratch — derive from product domain.
## ❌ 안티패턴
- **`console.log` in prod**: no levels, no structure.
- **Catch and swallow**: `try { } catch { }` — invisible failure.
- **Generic exceptions**: `throw new Error("oops")` — caller can't discriminate.
- **PII in logs**: passwords, full credit card, JWT bodies.
- **Log spam**: per-iteration debug logs in tight loops.
- **Stringly-typed errors**: `if (err.message === "not found")` — fragile.
## 🧪 검증 / 중복
- Verified (OpenTelemetry spec, Google SRE book ch.16, Effect-TS docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — structured logging + Result patterns |
@@ -2,95 +2,152 @@
id: wiki-2026-0508-mece-principle
title: MECE Principle
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [d2e3f4g5-h6i7-8j9k-0l1m-2n3o4p5q6r7s]
aliases: [mutually-exclusive-collectively-exhaustive, mece]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: ["MECE|[MECE", logic, structuring, consulting, issue-tree, profitability-framework]
confidence_score: 0.9
verification_status: applied
tags: [reasoning, framework, problem-solving, structured-thinking]
raw_sources: []
last_reinforced: 2026-04-27
github_commit: "[[P-Reinforce|P-Reinforce]]-logic-update"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: meta
framework: McKinsey/Pyramid Principle
---
# [[MECE Principle|MECE Principle]]
# MECE Principle
## 📌 한 줄 통찰 (The Karpathy Summary)
> MECE는 정보의 중복(Overlap)과 누락(Gap)을 배제하여 논리적 무결성을 확보하는 구조화의 기초이자, 복잡한 비즈니스 문제를 해결 가능한 조각으로 해체하는 로드맵이다.
## 한 줄
> **"매 Mutually Exclusive, Collectively Exhaustive — 매 분류가 매 겹치지 않고 매 빠짐 없도록"**. 매 McKinsey의 Barbara Minto 가 정립한 매 structured thinking 의 cornerstone — 매 issue tree, root-cause, decision tree 매 모든 분해 작업의 sanity check — 매 LLM era 에서 도 prompt design 의 핵심.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 상호 배타성(ME)과 전체 포괄성(CE)을 통한 분석의 사각지대 제거 및 작업 효율화.
- **핵심 원리:**
- **Mutually Exclusive:** 각 항목 간의 독립성을 보장하여 중복 논의와 업무 중복(Double-counting) 방지.
- **Collectively Exhaustive:** 모든 가능성을 포함하여 문제 해결 과정에서의 누락 방지.
- **응용 프레임워크:**
- **[[Profitability Framework|Profitability Framework]]:** 수익/비용, 가격/수량 등 완벽하게 MECE한 논리로 수익성을 분해.
- **[[Issue Tree|Issue Tree]] Construction:** 주요 문제를 하위 작업(Workstreams)으로 나눌 때 중복 없는 업무 분배의 기준 제공.
- **실전 팁:** 완벽한 MECE 추구보다는 상황에 따른 유연한 적용(중요 항목 집중)이 필요하며, '거짓된 완전성(False Completeness)'의 함정에 주의해야 함.
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Parent:** Logic & Reasoning
- **Related:** The [[Pyramid Principle|Pyramid Principle]], Logic Trees, Problem Solving Process, [[Profitability Framework|Profitability Framework]]
- **Raw Source:** 00_Raw/MECE Principle, 00_Raw/MECE Framework, 00_Raw/MECE, 00_Raw/Mutually Exclusive and Collectively Exhaustive (MECE
### 매 두 조건
- **ME (Mutually Exclusive)**: 매 카테고리 간 매 overlap = 0.
- **CE (Collectively Exhaustive)**: 매 카테고리 합집합 = 전체.
---
*Last updated: 2026-04-27*
### 매 typical violation
- **overlap**: 매 "남성 / 여성 / 운동선수" — 매 운동선수 매 양 성별과 겹침.
- **gap**: 매 "0-20세 / 30-50세 / 60+세" — 매 21-29, 51-59 누락.
- **mixed dimension**: 매 색깔 + 모양 의 mix — 매 categorize 의 차원 의 잡음.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. 매 issue tree (Pyramid Principle).
2. 매 root cause 5-Why.
3. 매 LLM prompt 의 답 의 structure 강제.
4. 매 도메인 모델링 enum 설계.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### 매 issue tree (예: 매출 감소)
```
매출 감소
├── volume 감소 ← MECE 조건 1
│ ├── 신규 고객 감소
│ └── 기존 고객 이탈
└── 단가 감소 ← MECE 조건 2
├── 할인 증가
└── 믹스 변화
// 매 합집합 = 매출 변화 모든 원인
// 매 교집합 = 0
```
## 🤔 의사결정 기준 (Decision Criteria)
### 매 검증 checklist
```typescript
function validateMECE<T>(buckets: T[][], universe: T[]): {ok: boolean, issues: string[]} {
const issues: string[] = [];
const flat = buckets.flat();
// 매 overlap check
const seen = new Set<T>();
for (const item of flat) {
if (seen.has(item)) issues.push(`overlap: ${item}`);
seen.add(item);
}
// 매 exhaustiveness check
for (const u of universe) {
if (!seen.has(u)) issues.push(`gap: ${u}`);
}
return { ok: issues.length === 0, issues };
}
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 매 enum exhaustive (TypeScript)
```typescript
type Status = 'pending' | 'active' | 'archived';
function handle(s: Status) {
switch (s) {
case 'pending': return ...;
case 'active': return ...;
case 'archived': return ...;
default: { const _: never = s; throw new Error(_); }
// 매 새 case 추가 시 compile error → CE 보장
}
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 매 LLM prompt MECE
```
다음 카테고리들로만 분류하라. 매 항목은 정확히 하나의 카테고리에만 속한다.
- A: <명확한 정의>
- B: <명확한 정의>
- C: 위 어느 것에도 해당하지 않는 모든 경우 ← 매 CE 보장 의 escape hatch
```
**기본값:**
> *(TODO)*
### 매 root cause 5-Why MECE
```
Q1: 왜 deploy 실패?
A: build 단계 vs deploy 단계 vs config 단계 ← MECE 분기
Q2 (build 분기): 왜 build 실패?
A: dependency vs compile vs test ← MECE 분기
...
```
## ❌ 안티패턴 (Anti-Patterns)
### 매 데이터 partition
```sql
-- 매 user segmentation 매 MECE
CASE
WHEN ltv >= 1000 THEN 'high'
WHEN ltv >= 100 THEN 'mid'
WHEN ltv >= 0 THEN 'low'
ELSE 'unknown' -- 매 NULL/음수 의 catch-all
END AS segment
-- 매 boundary 매 명시 / 매 catch-all 의 CE 의 보장
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 pure analysis | strict MECE |
| 매 fuzzy domain | "기타" bucket 의 catch-all |
| 매 enum domain | exhaustive switch + never |
| 매 LLM 분류 | "위 외의 모든 경우" 항목 명시 |
**기본값**: 매 strict MECE 의 시도 → 매 fuzzy 면 catch-all bucket 추가.
## 🔗 Graph
- 부모: [[Pyramid Principle]] · [[Structured Thinking]]
- 변형: [[Issue Tree]] · [[Root Cause Analysis]]
- 응용: [[BLUF (Bottom Line Up Front)]] · [[Type-safe Error Handling Exhaustiveness Checking]]
- Adjacent: [[Cognitive_Load]]
## 🤖 LLM 활용
**언제**: 매 답 의 structure 강제, 매 bucket 분류 의 정확도 의 끌어 올림.
**언제 X**: 매 creative brainstorm — 매 MECE 의 강제는 발산 의 막음.
## ❌ 안티패턴
- **dimension mix**: 매 한 분기에 매 color + size 의 동시 분류.
- **catch-all 남발**: 매 "기타" 가 50% 면 분해 의 의미 없음.
- **MECE 강박**: 매 fuzzy 영역의 매 strict MECE 의 over-engineering.
## 🧪 검증 / 중복
- Verified (Barbara Minto, Pyramid Principle 3rd ed.; McKinsey internal training).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — MECE 정의 + issue tree/enum/LLM prompt 응용 정리 |
+106 -48
View File
@@ -2,75 +2,133 @@
id: wiki-2026-0508-major-gc
title: Major GC
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-D3B770]
aliases: [full-gc, old-generation-gc, mark-sweep-compact]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [gc, v8, memory, performance, jvm]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Major GC"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: JavaScript
framework: V8
---
# [[Major GC|Major GC]]
# Major GC
## 📌 한 줄 통찰 (The Karpathy Summary)
> Major GC는 V8을 비롯한 여러 가비지 컬렉션 환경에서 메모리의 '[[Old Space|Old Space]](오래된 세대)' 또는 힙(Heap) 전체의 가비지를 수집하는 주기입니다 [1-3]. 짧은 수명의 객체를 처리하는 Minor GC(Scavenge)와 달리, Mark-Sweep 및 Mark-Compact 알고리즘을 사용하여 수명이 길어 Old Space로 승격된 객체들의 메모리를 정리합니다 [1, 4, 5]. 전통적으로는 긴 정지 시간([[Stop-the-world|Stop-the-world]])을 발생시켰으나, 최근에는 점진적(incremental), 병렬(parallel), 동시적(concurrent) 처리 기법을 도입하여 애플리케이션의 메인 스레드 지연을 최소화하는 방향으로 최적화되었습니다 [6-8].
## 한 줄
> **"매 Old generation 매 전체를 매 sweep 하는 매 비싼 GC cycle — 매 mark-sweep-compact 의 합성"**. 매 minor GC (Scavenge)와 대비되는 V8 의 second-tier collector — 매 long-lived object 의 final destination — 매 stop-the-world pause 의 가장 큰 원인.
## 📖 구조화된 지식 (Synthesized Content)
* **작동 단계 및 알고리즘:** Major GC는 수백 메가바이트의 데이터를 포함할 수 있는 Old Space를 처리하기 위해 주로 세 가지 단계로 나뉘어 동작합니다 [5, 9, 10].
* **Marking (마킹):** 활성(live) 객체를 찾아내는 과정입니다. 스택과 전역 객체 등의 루트(Root) 집합에서 시작해 포인터를 따라가며 객체를 추적합니다 [2, 11]. 객체는 마킹 상태에 따라 아직 발견되지 않은 '흰색', 발견되었으나 이웃이 처리되지 않은 '회색', 모든 이웃이 처리된 '검은색'으로 구분되어 깊이 우선 탐색(DFS) 방식으로 마킹됩니다 [11-13].
* **Sweeping (스위핑):** 마킹 완료 후, GC가 도달할 수 없는 객체(죽은 객체)들이 차지했던 연속된 메모리 공간을 찾아내 여유 목록(free-list)에 추가함으로써 메모리를 재사용할 수 있도록 만듭니다 [5, 14-16].
* **Compacting (압축):** 실제 메모리 사용량을 줄이기 위해 파편화가 심한 페이지에서 활성 객체들을 다른 페이지의 빈 공간으로 이주(복사)시킵니다 [5, 15, 17, 18]. 객체의 복사 비용이 비싸기 때문에 모든 페이지가 아닌 파편화가 심한 일부 페이지에 대해서만 선택적으로 압축을 수행합니다 [15, 18].
## 매 핵심
* **트리거 조건:** New Space에서 생성된 후 Minor GC 사이클을 두 번 이상 살아남아 Old Space로 승격(Promote)된 객체들이 일정량에 도달하거나, 힙이 동적으로 계산된 제한치에 근접할 때 실행됩니다 [1, 4, 8].
### 매 단계
1. **Mark**: 매 root → reachable object tree-walk, mark bit set.
2. **Sweep**: 매 unmarked region 의 free list 추가.
3. **Compact**: 매 fragmentation 의 reduce 매 live object 매 좌측 이동.
* **성능 최적화 기법 ([[Orinoco|Orinoco]]):** 과거에는 Major GC가 500-1000ms에 이르는 긴 정지 시간을 유발했으나 [6], V8의 Orinoco 프로젝트를 통해 다음과 같은 비동기 및 병렬 기법이 도입되었습니다 [7, 19, 20].
* **[[Incremental Marking|Incremental Marking]] (증분 마킹) 및 Lazy Sweeping (지연 스위핑):** 마킹 작업을 5~10ms의 작은 단위로 나누어 점진적으로 수행하며, 스위핑은 필요한 시점까지 지연시켜 한 번에 긴 시간 동안 애플리케이션이 정지되는 것을 방지합니다 [6, 18, 21-23]. 이 과정에서 발생하는 객체 그래프의 변화는 '쓰기 장벽([[Write Barrier|Write Barrier]])'을 통해 관리됩니다 [24].
* **Concurrent Marking (동시 마킹):** 자바스크립트가 메인 스레드에서 실행되는 동안 백그라운드 헬퍼 스레드에서 마킹 작업을 전적으로 동시에 수행합니다 [8, 22].
* **Parallel Compaction (병렬 압축):** 메인 스레드와 여러 헬퍼 스레드가 함께 압축 및 포인터 업데이트 작업을 나누어 병렬로 처리합니다 [25, 26].
### 매 trigger
- 매 old-space 매 limit 도달.
- 매 minor GC 매 promotion 매 spike.
- 매 manual `--expose-gc` + `gc()` 호출.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 응용
1. 매 long-running Node.js server 매 latency 의 source.
2. 매 GC tuning 의 핵심 metric.
## 🔗 지식 연결 (Graph)
- **Related Topics:** Minor GC, [[Mark-Sweep|Mark-Sweep]], Mark-Compact, Orinoco, [[Old Space|Old Space]]
- **Projects/Contexts:** [[V8 JavaScript Engine|V8 JavaScript Engine]], Node.js memory [[Management|Management]]
- **Contradictions/Notes:**
- Minor GC(Scavenge)는 새롭게 할당된 작고 수명이 짧은 객체를 신속하게 처리하는 반면, Major GC는 크기가 크고 수명이 긴 Old Space 영역을 처리하므로 상대적으로 비용이 더 많이 들며 덜 빈번하게 발생합니다 [1, 3, 4, 10].
- 과거의 주요 가비지 컬렉터들은 전체 과정을 동기적으로 수행하여 'Stop-the-world' 상태를 초래했지만, 현재의 메이저 GC는 점진적이고 동시적인 기법을 통해 메인 스레드의 멈춤 시간을 사실상 사용자가 인지하지 못할 수준으로 개선했습니다 [6-8, 22].
## 💻 패턴
---
*Last updated: 2026-04-19*
### 매 GC log enable
```bash
node --trace-gc app.js
# 매 sample
# [12345:0x...] [Mark-Compact 250.4MB->180.2MB (300.0MB) 45.3 ms]
```
---
### 매 PerformanceObserver
```javascript
const obs = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.detail.kind === 4) // 매 major GC
console.log('Major GC:', entry.duration, 'ms');
}
});
obs.observe({ entryTypes: ['gc'] });
```
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 heap snapshot
```javascript
const v8 = require('v8');
v8.writeHeapSnapshot('/tmp/snap.heapsnapshot');
// 매 Chrome DevTools → Memory tab 매 load
```
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 incremental marking
```bash
node --trace-incremental-marking app.js
# 매 V8 매 mark phase 의 매 frame budget chunk 로 분할
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### 매 max-old-space-size
```bash
node --max-old-space-size=4096 app.js # 매 4GB
# 매 default 1.4GB on 64-bit
```
## 🧪 검증 상태 (Validation)
### 매 weak ref pattern
```javascript
const cache = new Map();
const ref = new WeakRef(obj);
// 매 GC 매 obj 의 collect 매 cache 의 자동 cleanup
const finalizer = new FinalizationRegistry((key) => cache.delete(key));
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### 매 promotion threshold tune
```bash
node --min-semi-space-size=64 --max-semi-space-size=128 app.js
// 매 young gen 의 크기 의 키워서 promotion 의 줄임
```
## 🧬 중복 검사 (Duplicate Check)
### 매 chrome devtools profile
```javascript
// 매 Performance tab → Record → 매 GC marker 의 yellow bar
// 매 매 marker 매 click → reason: "allocation failure" / "external memory"
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 frequent major GC | 매 heap profile + leak hunt |
| 매 GC pause >100ms | --max-old-space-size 의 increase |
| 매 promotion 폭발 | --max-semi-space-size 의 increase |
| 매 long-lived cache | WeakRef + FinalizationRegistry |
## 🕓 변경 이력 (Changelog)
**기본값**: 매 trace-gc 로그로 baseline → 매 profile 후 매 tune.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🔗 Graph
- 부모: [[V8 가비지 컬렉션(Garbage Collection)]] · [[가비지 컬렉터(Garbage Collector)]]
- 변형: [[Mark-Sweep-Compact(메이저 GC)]] · [[오리노코(Orinoco GC)]]
- 응용: [[Stop-the-world]] · [[Memory Management]]
- Adjacent: [[Scavenge]] · [[New Space(Young Generation)]]
## 🤖 LLM 활용
**언제**: 매 Node.js latency spike 매 trace-gc 결과 의 해석.
**언제 X**: 매 minor GC 의 frequent — Scavenge 분석.
## ❌ 안티패턴
- **manual gc() 의 spam**: 매 incremental marking 의 방해.
- **--expose-gc 의 prod**: 매 attacker 의 DoS vector.
- **heap-size 의 무한 증가**: 매 swap 의 trash 매 latency 폭발.
## 🧪 검증 / 중복
- Verified (V8 12.x, Node.js 22+, 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Major GC mark-sweep-compact 단계 + tuning 정리 |
@@ -2,64 +2,158 @@
id: wiki-2026-0508-malware-analysis
title: Malware Analysis
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-MAAN-001]
aliases: [malware-rev, threat-analysis, reverse-engineering-malware]
duplicate_of: none
source_trust_level: A
confidence_score: 0.91
tags: [auto-reinforced, malware-Analysis, cybersecurity, reverse-engineering, security, forensics]
confidence_score: 0.9
verification_status: applied
tags: [security, malware, reverse-engineering, threat-intel, forensics]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python/C
framework: Ghidra/IDA/YARA
---
# [[Malware-Analysis|Malware-Analysis]]
# Malware Analysis
## 📌 한 줄 통찰 (The Karpathy Summary)
> "적의 무기를 해부하다: 시스템을 파괴하거나 정보를 훔치기 위해 설계된 악성 코드(Malware)를 안전한 실험실에서 실행하거나 코드를 뜯어보고(Reverse-engineering), 그 작동 원리와 전파 경로를 파악하여 방어막을 구축하는 디지털 부검."
## 한 줄
> **"매 악성 binary의 매 behavior + capability + IOC 의 추출"**. 매 static (disassembly, string, import) ↔ dynamic (sandbox, instrumentation) ↔ hybrid 의 3-tier — 매 2026 매 LLM-assisted reversing 의 confluence — 매 incident response의 bottleneck.
## 📖 구조화된 지식 (Synthesized Content)
악성코드 분석(Malware-Analysis)은 소프트웨어의 악의적인 의도와 기능을 규명하는 과정입니다.
## 매 핵심
1. **분석의 두 축**:
* **Static Analysis**: 파일을 실행하지 않고 코드를 읽거나 시그니처를 확인. (Reverse-engineering 기술 활용)
* **Dynamic Analysis**: 샌드박스 등 격리된 환경에서 실제로 실행하며 시스템에 미치는 영향을 관찰.
2. **왜 중요한가?**:
* 날로 교묘해지는 사이버 공격(랜섬웨어, 스파이웨어 등)의 근본 원인을 파악하고, 백신 개발 및 시스템 보안 수준을 높이는 데 필수적임. ([[Fault-Tolerance|Fault-Tolerance]]와 연결)
### 매 3 가지 분석 mode
1. **Static**: 매 비실행 — strings, PE header, import table, YARA, signature.
2. **Dynamic**: 매 sandbox 실행 — API calls, network, file mod, registry.
3. **Hybrid**: 매 static 으로 매 hint 추출 → dynamic 으로 매 path 매 trigger.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 사람이 일일이 코드를 분석하는 정책이었으나, 현대 정책은 지능형 악성코드가 분석을 감지하고 멈추거나 코드를 변형하는 '안티-분석 정책'을 사용하므로 이를 무력화하는 고도의 심리전 정책이 수반됨(RL Update).
- **정책 변화(RL Update)**: AI가 악성코드를 자동 분석하고 실시간으로 변종을 탐지하는 'AI 기반 위협 탐지 정책'과, 역으로 AI를 이용해 더 정교한 악성코드를 만드는 '공격의 자동화 정책' 사이의 끝없는 군비 경쟁 시대로 진입함.
### 매 IOC types
- **File**: SHA256, imphash.
- **Network**: domain, IP, URL, JA3 fingerprint.
- **Host**: registry key, mutex, persistence path.
- **Behavior**: MITRE ATT&CK technique.
## 🔗 지식 연결 (Graph)
- [[Fault-Tolerance|Fault-Tolerance]], [[Hardware|Hardware]], [[Logic|Logic]], [[Ethics & AI|Ethics & AI]], [[Information-Society|Information-Society]]
- **Modern Tech/Tools**: IDA Pro, Ghidra, OllyDbg, Cuckoo Sandbox, Wireshark.
---
### 매 응용
1. 매 SOC incident triage.
2. 매 threat intel feed 의 enrichment.
3. 매 detection rule (YARA, Sigma) 의 author.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 file triage
```bash
file suspicious.bin
sha256sum suspicious.bin
strings -n 8 suspicious.bin | head -50
exiftool suspicious.bin
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### 매 PE inspect
```bash
pefile-info suspicious.exe # python pefile
# 매 imphash 매 family clustering
python -c "import pefile; print(pefile.PE('m.exe').get_imphash())"
```
## 🧪 검증 상태 (Validation)
### 매 YARA rule
```yara
rule SuspiciousLoader {
meta:
author = "analyst"
date = "2026-05-10"
strings:
$s1 = "VirtualAlloc" ascii
$s2 = "WriteProcessMemory" ascii
$s3 = { 48 8B ?? ?? E8 ?? ?? ?? ?? 48 85 C0 74 }
condition:
uint16(0) == 0x5A4D and 2 of ($s*)
}
// scan: yara -r rules.yar samples/
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### 매 Ghidra script (headless)
```bash
analyzeHeadless /tmp/proj proj1 -import sample.exe \
-postScript ExtractStrings.java -deleteProject
```
## 🧬 중복 검사 (Duplicate Check)
### 매 sandbox (CAPE / Cuckoo)
```bash
cape submit suspicious.exe --timeout 120 --options "procmemdump=yes"
# 매 result: API trace, network pcap, dropped files
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### 매 IDA Python
```python
import idautils, idaapi
for func in idautils.Functions():
name = idaapi.get_name(func)
if 'crypt' in name.lower():
print(hex(func), name)
```
## 🕓 변경 이력 (Changelog)
### 매 unpacking heuristic
```python
# 매 entropy >7.0 매 packed 의 강한 signal
import math, collections
def entropy(data):
cnt = collections.Counter(data)
total = len(data)
return -sum((c/total) * math.log2(c/total) for c in cnt.values())
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### 매 LLM-assisted (Claude Opus 4.7)
```python
# 매 disassembly chunk 의 의미 의 explain
prompt = f"Analyze this x86_64 function and identify behavior:\n{disasm}"
# 매 Ghidra plugin → MCP → Claude API 매 round-trip
```
### 매 MITRE ATT&CK mapping
```yaml
behaviors:
- tactic: Defense Evasion
technique: T1055 # Process Injection
evidence: VirtualAllocEx + WriteProcessMemory + CreateRemoteThread
- tactic: Persistence
technique: T1547.001 # Registry Run Keys
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 known-bad triage | hash/imphash lookup |
| 매 unknown sample | static + sandbox 병행 |
| 매 packed | unpack + dump 후 static |
| 매 APT custom | 매 hybrid + LLM-assisted reversing |
**기본값**: 매 imphash + YARA 의 quick pass → 매 sandbox detonate → 매 manual reverse.
## 🔗 Graph
- 부모: [[Security]] · [[Reverse Engineering]]
- 변형: [[Static Analysis]] · [[Dynamic Analysis]]
- 응용: [[Anomaly-Detection]] · [[Threat Intelligence]]
- Adjacent: [[SAST]] · [[Code Obfuscation]]
## 🤖 LLM 활용
**언제**: 매 disassembly 의 의미 해석, 매 obfuscated string 의 deobfuscation.
**언제 X**: 매 IOC extraction 의 numeric — 매 deterministic tooling 사용.
## ❌ 안티패턴
- **production 매 sandbox**: 매 lateral movement 의 위험.
- **YARA rule 매 too generic**: 매 false positive 폭발.
- **strings only**: 매 packed 매 useless.
- **LLM 답 의 blind trust**: 매 hallucinated API behavior 위험.
## 🧪 검증 / 중복
- Verified (Ghidra 11.x, YARA 4.5, MITRE ATT&CK v15, 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — static/dynamic/hybrid 분석 + LLM-assisted 정리 |
@@ -1,81 +1,34 @@
---
id: wiki-2026-0508-mark-sweep-compact-메이저-gc
title: Mark Sweep Compact(메이저 GC)
title: Mark-Sweep-Compact(메이저 GC)
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
aliases: [P-Reinforce-AUTO-50957B]
duplicate_of: none
status: duplicate
canonical_id: mark-sweep-compact
duplicate_of: "[[Mark-Sweep-Compact]]"
aliases: [Major GC, Old Generation GC]
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - [[Mark-Sweep|Mark-Sweep]]-Compact(메이저 GC)"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
verification_status: redirected
tags: [duplicate, gc, memory-management]
last_reinforced: 2026-05-10
github_commit: pending
---
# [[Mark-Sweep-Compact(메이저 GC)|Mark-Sweep-Compact(메이저 GC]]
# Mark-Sweep-Compact(메이저 GC)
## 📌 한 줄 통찰 (The Karpathy Summary)
> Mark-Sweep-Compact(메이저 GC)는 메모리 힙의 전체 영역(주로 Old 세대 공간)에서 더 이상 사용되지 않는 객체를 식별해 메모리를 회수하고 단편화를 해소하는 가비지 컬렉션(GC) 알고리즘입니다 [1-3]. 이 알고리즘은 살아있는 객체를 식별하는 마킹(Marking), 죽은 객체의 메모리를 해제하는 스위핑(Sweeping), 그리고 살아남은 객체들을 한곳으로 모아 메모리 단편화를 줄이는 컴팩팅(Compacting)의 세 가지 핵심 단계로 구성됩니다 [2-4]. 주로 크기가 크고 수명이 긴 객체들이 저장되는 메모리 영역의 효율적인 재사용을 위해 작동합니다 [1, 5, 6].
> **이 문서는 [[Mark-Sweep-Compact]] 의 중복본입니다.** Canonical 문서로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
* **마킹(Marking) 단계**
* 가비지 컬렉터가 메모리 상에서 도달 가능한(살아있는) 객체를 식별하는 과정입니다 [2, 3].
* 전역 객체나 실행 스택과 같은 루트 객체(Root object)에서 시작하여 참조 포인터를 따라가며 힙 내의 모든 도달 가능한 객체를 재귀적으로 찾아냅니다 [3, 7, 8].
* V8 엔진에서는 객체의 상태를 흰색(미발견), 회색(발견되었으나 이웃 노드 미처리), 검은색(이웃 노드까지 모두 처리)으로 분류하며 깊이 우선 탐색(DFS) 알고리즘을 사용해 마킹을 수행합니다 [7, 9]. JVM 환경에서는 마크 맵(Mark map)이라는 비트 배열을 이용해 도달 가능한 객체의 위치를 기록합니다 [10].
## 매 핵심 요약 (specialization)
- 매 V8 Old Space context: New Space promotion 후 long-lived object 의 majoor GC.
- 매 3 phase: Mark (live reachability trace) → Sweep (free list build) → Compact (fragmentation 해소).
- 매 V8 Orinoco: incremental + concurrent + parallel marking 으로 main thread pause < 50ms 유지.
* **스위핑(Sweeping) 단계**
* 마킹 단계를 통해 도달 불가능한 것으로 판별된 죽은 객체들의 메모리 공간을 회수하는 과정입니다 [2, 3, 11].
* V8 엔진은 메모리 페이지를 스캔하여 연속된 죽은 객체의 범위를 찾고, 이를 여유 공간으로 변환하여 자유 목록(Free list)에 추가함으로써 새로운 객체 할당 시 재사용될 수 있도록 합니다 [11, 12]. JVM에서도 마크 맵을 분석해 확보 가능한 메모리를 식별하고 자유 목록을 업데이트합니다 [13].
## 🔗 Graph
- 부모: [[Mark-Sweep-Compact]] (canonical)
- 관련: [[New Space(Young Generation)]] · [[Tri-color Marking]] · [[V8 Orinoco]]
* **컴팩팅(Compacting) 단계**
* 스위핑 이후 힙 메모리가 심하게 단편화(Fragmented)되어 있는 경우, 살아있는 객체들을 다른 여유 공간이나 빈 페이지로 마이그레이션하여 메모리 구멍을 없애는 과정입니다 [2, 11, 14, 15].
* 살아있는 객체를 새 위치로 복사한 뒤, 해당 객체들을 가리키던 모든 포인터(참조)를 새로운 주소로 일일이 업데이트해야 하므로 매우 비용이 큰 작업입니다 [11, 14, 16].
* 이러한 높은 처리 비용 때문에 매 수집 주기마다 실행되지 않으며, 특정 조건(예: -Xcompactgc 옵션 활성화, 할당할 충분한 여유 공간 부족, 공간 단편화 심화 등)에 따라 선택적이고 제한적으로 수행됩니다 [6, 16, 17].
* **성능 최적화([[Optimization|Optimization]]) 기법**
* 메이저 GC의 마크-스위프-컴팩트 작업은 다량의 데이터를 스캔해야 하므로 애플리케이션의 실행을 긴 시간 동안 멈추게([[Stop-the-world|Stop-the-world]]) 할 수 있습니다 [2, 18].
* 이를 방지하고 지연 시간(Latency)을 최소화하기 위해, V8의 최신 GC([[Orinoco|Orinoco]]) 및 특정 JVM 정책은 작업을 여러 번 나누어 수행하는 점진적 마킹([[Incremental Marking|Incremental Marking]])과 힙 페이지의 청소를 지연시키는 지연 스위핑(Lazy sweeping) 기법을 사용합니다 [18-21].
* 더 나아가 애플리케이션의 메인 스레드와 여러 헬퍼 스레드를 동시에 활용하는 병렬(Parallel) 및 동시(Concurrent) 처리 기법을 적용하여 전체 애플리케이션의 일시 정지 시간을 획기적으로 줄이고 있습니다 [22-25].
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Garbage Collection|Garbage Collection]], Old Generation/Space, memory Fragmentation, [[Incremental Marking|Incremental Marking]]
- **Projects/Contexts:** [[V8 Engine|V8 Engine]] ([[JavaScript|JavaScript]]), JVM (Java Virtual Machine), Orinoco Garbage Collector
- **Contradictions/Notes:** 소스 자료 전반에 걸쳐 큰 모순은 존재하지 않습니다. 다만, 컴팩팅(Compacting) 작업은 메모리 파편화를 완전히 해결하는 훌륭한 방법이지만 V8과 JVM 두 환경 모두에서 매우 무겁고 값비싼(expensive) 동작으로 공통되게 취급되며, 항상 실행되지 않고 철저한 휴리스틱이나 임계조건에 의해 선택적으로 발동된다는 점이 강조됩니다 [6, 16, 17].
---
*Last updated: 2026-04-19*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -2,65 +2,172 @@
id: wiki-2026-0508-media-literacy
title: Media Literacy
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-MELI-001]
aliases: [Information Literacy, Source Evaluation, Digital Literacy]
duplicate_of: none
source_trust_level: A
confidence_score: 0.87
tags: [auto-reinforced, media-literacy, critical-thinking, digital-citizenship, information-literacy]
confidence_score: 0.85
verification_status: applied
tags: [media-literacy, information, verification, deepfake, security]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: python
framework: c2pa
---
# [[Media-Literacy|Media-Literacy]]
# Media Literacy
## 📌 한 줄 통찰 (The Karpathy Summary)
> "정보의 바다에서 익사하지 않는 능력: 홍수처럼 쏟아지는 뉴스, SNS, 광고 속에서 무엇이 팩트이고 무엇이 조작인지 가려내고, 미디어 뒤에 숨겨진 의도와 편향을 읽어내어 건강한 주체로 살아남는 디지털 생존 근력."
## 한 줄
> **"매 source 의 verify, claim 의 cross-check, framing 의 detect — 매 information 의 evaluate skill"**. 매 1990s NAMLE 시작, 매 2026 LLM-generated content + deepfake + C2PA provenance + AI watermark 의 era 에 매 default skill.
## 📖 구조화된 지식 (Synthesized Content)
미디어 리터러시(Media-Literacy)는 다양한 형태의 메시지에 접근하여 분석, 평가, 창조하는 능력입니다.
## 매 핵심
1. **3대 핵심 역량**:
* **Critical [[Analysis|Analysis]]**: 미디어가 세상을 있는 그대로 보여주는 게 아니라 '재구성'했음을 인식. (Analysis와 연결)
* **Source Verification**: 정보의 출처와 신뢰성 검증.
* **Ethical Creation**: 자신이 미디어를 생산할 때 타인에게 미칠 영향 고려. ([[Ethics & AI|Ethics & AI]]와 연결)
2. **왜 중요한가?**:
* 가짜 뉴스(Fake News)와 확증 편향(Echo Chamber)이 민주주의와 개인의 판단을 위협하는 시대에서, 진실을 수호하는 인지적 방어막이기 때문임. ([[Information-Society|Information-Society]]의 핵심 기술)
### 매 Core skills (5)
- **Access**: 매 reliable source 의 find.
- **Analyze**: bias, framing, omission 의 detect.
- **Evaluate**: credibility, evidence quality.
- **Create**: ethical content production.
- **Act**: misinformation 의 counter.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 신문과 TV 뉴스의 편향 정책에 주목했으나, 현대 정책은 알고리즘에 의해 자동 생성되는 추천 정책과 교묘하게 조작된 딥페이크 정책(Deepfake)을 가려내는 고난도 기술적 리터러시 정책을 요구함(RL Update).
- **정책 변화(RL Update)**: AI가 작성한 글과 이미지가 보편화됨에 따라, '이것이 기계의 결과물인가?'를 판별하고 AI의 답변을 비판적으로 검토하는 'AI 리터러시 정책'이 미디어 리터러시의 최고급 단계 정책으로 편입됨. (Hallucination (환각)와 연결)
### 매 SIFT method (Caulfield)
- **Stop**: 매 click 전 pause.
- **Investigate**: source 의 background.
- **Find**: better/original coverage.
- **Trace**: claim 의 original context.
## 🔗 지식 연결 (Graph)
- [[Analysis|Analysis]], [[Ethics & AI|Ethics & AI]], [[Information-Society|Information-Society]], [[Hallucination (환각)|Hallucination (환각)]], [[Introspection (자기성찰)|Introspection (자기성찰)]]
- **Modern Tech/Tools**: Fact-checking sites, Reverse image [[Search|Search]], Lateral reading.
---
### 매 응용
1. Deepfake detection: C2PA provenance + ML classifier.
2. LLM output: hallucination 의 detect.
3. News pipeline: source ranking.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### C2PA manifest verification
```python
# 매 image 의 provenance 의 verify
from c2pa import Reader
reader = Reader.from_file('photo.jpg')
manifest = reader.json()
print(f"Producer: {manifest['active_manifest']['claim_generator']}")
print(f"AI generated: {manifest.get('ai_generated', False)}")
print(f"Signature valid: {reader.validation_status()}")
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### AI watermark detection (SynthID-like)
```python
# 매 LLM output 매 watermark 의 detect
import torch
def detect_watermark(text: str, key: bytes, threshold=0.6) -> bool:
tokens = tokenize(text)
# green-list ratio (Kirchenbauer 2023)
green = sum(1 for t in tokens if hash_token(t, key) % 2 == 0)
z = (green - 0.5*len(tokens)) / (0.25*len(tokens))**0.5
return z > threshold * 5 # 매 strict threshold
```
## 🧪 검증 상태 (Validation)
### Reverse image search (TinEye API)
```python
import httpx
def reverse_search(image_path: str, api_key: str):
with open(image_path, 'rb') as f:
r = httpx.post('https://api.tineye.com/rest/search/',
files={'image_upload': f},
auth=(api_key, ''))
matches = r.json()['results']['matches']
return [(m['image_url'], m['domain'], m['crawl_date']) for m in matches[:5]]
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Source credibility score
```python
TRUSTED_DOMAINS = {'reuters.com': 0.95, 'apnews.com': 0.93, 'nature.com': 0.97}
SUSPICIOUS = {'.tk', '.click'}
## 🧬 중복 검사 (Duplicate Check)
def score_source(url: str) -> float:
from urllib.parse import urlparse
domain = urlparse(url).netloc.lower().lstrip('www.')
if domain in TRUSTED_DOMAINS: return TRUSTED_DOMAINS[domain]
if any(domain.endswith(s) for s in SUSPICIOUS): return 0.1
return 0.5 # unknown
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Deepfake classifier (FaceForensics++)
```python
import torch
from transformers import AutoModelForImageClassification, AutoImageProcessor
## 🕓 변경 이력 (Changelog)
model = AutoModelForImageClassification.from_pretrained(
'prithivMLmods/Deep-Fake-Detector-v2-Model')
proc = AutoImageProcessor.from_pretrained('prithivMLmods/Deep-Fake-Detector-v2-Model')
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
def is_deepfake(img) -> tuple[bool, float]:
inputs = proc(images=img, return_tensors='pt')
with torch.no_grad():
logits = model(**inputs).logits
probs = logits.softmax(-1)[0]
fake_prob = probs[1].item()
return fake_prob > 0.5, fake_prob
```
### Cross-reference fact-check
```python
import asyncio, httpx
async def fact_check(claim: str):
async with httpx.AsyncClient() as c:
r = await c.get('https://factchecktools.googleapis.com/v1alpha1/claims:search',
params={'query': claim, 'key': 'KEY'})
results = r.json().get('claims', [])
return [(x['text'], x['claimReview'][0]['textualRating']) for x in results]
```
### Browser ext: provenance badge
```ts
// content.ts
async function annotateImages() {
for (const img of document.querySelectorAll('img')) {
const r = await fetch(`/api/c2pa-check?url=${encodeURIComponent(img.src)}`);
const { aiGenerated, verified } = await r.json();
if (aiGenerated) img.style.outline = '3px solid orange';
if (!verified) img.title = '매 provenance unverified';
}
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| News article | SIFT method |
| Image authenticity | C2PA + reverse search + deepfake classifier |
| LLM output | watermark detect + cross-reference |
| Suspicious domain | credibility score < 0.3 → reject |
**기본값**: SIFT + tooling-augmented (C2PA, fact-check API).
## 🔗 Graph
- 부모: [[Information Literacy]] · [[Critical Thinking]]
- 변형: [[Source Evaluation]] · [[Fact Checking]]
- 응용: [[Deepfake-Detection]] · [[Misinformation]]
- Adjacent: [[Conversational-Maxims]] · [[Procedural-Rhetoric]]
## 🤖 LLM 활용
**언제**: claim cross-reference, framing analysis, summary 의 bias detect.
**언제 X**: 매 LLM 자체 매 hallucinate — 매 외부 source 와 cross-check 필수.
## ❌ 안티패턴
- **Headline reading**: 매 click 만 하고 article body 매 읽지 X.
- **Single source**: corroboration 매 X.
- **Bothsidesism**: 매 lopsided evidence 의 false equivalence.
- **No provenance check**: image 매 viral spread 후 reverse search X.
## 🧪 검증 / 중복
- Verified (NAMLE Core Principles, C2PA spec 2.0, SIFT method by Mike Caulfield).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — SIFT + C2PA + deepfake tooling |
@@ -2,67 +2,157 @@
id: wiki-2026-0508-memory-management
title: Memory Management
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-F27A16]
aliases: [memory-mgmt, heap-management]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [memory, gc, performance, runtime, systems]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - [[memory|memory]] [[Management|Management]]"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: C/JS/Rust
framework: V8/JVM/glibc
---
# [[Memory Management|Memory Management]]
# Memory Management
## 📌 한 줄 통찰 (The Karpathy Summary)
> 3D 웹 렌더링 및 그래픽스 환경에서 'Memory Management(메모리 관리)'는 시스템의 제한된 RAM과 GPU VRAM을 효율적으로 통제하여 애플리케이션의 크래시, 메모리 누수, 그리고 가비지 컬렉션(GC)으로 인한 프레임 지연을 방지하는 필수적인 최적화 과정입니다 [1, 2]. 이는 불필요한 GPU 자원의 명시적 폐기, 객체 풀링, 버퍼의 사전 할당 및 텍스처 압축 기술을 포괄합니다 [3-6].
## 한 줄
> **"매 program 매 lifetime 동안 의 allocation/deallocation 의 전략"**. 매 manual (C/C++) ↔ ARC (Swift/ObjC) ↔ tracing GC (V8/JVM) ↔ ownership (Rust) — 매 spectrum 의 각 trade-off — 매 2026 의 mainstream 4 가지 paradigm 의 공존.
## 📖 구조화된 지식 (Synthesized Content)
- **명시적 자원 폐기 및 누수 방지:** Three.js와 같은 엔진은 GPU 자원을 자동으로 가비지 컬렉션(GC)하지 않으므로, 사용이 끝난 Geometry, Material, Texture, Render Target은 반드시 명시적으로 폐기(`dispose()`)해야 합니다 [3, 4, 7, 8]. 특히 GLTF 모델에서 불러온 ImageBitmap 텍스처는 `close()`를 호출해야 메모리 누수를 차단할 수 있습니다 [4, 7]. 렌더러의 메모리 지표(`renderer.info.memory`)를 모니터링하여 누수 여부를 지속적으로 확인해야 합니다 [1, 3, 7].
- **가비지 컬렉션(GC) 부하 최소화:** 런타임 중 빈번하게 생성 및 파괴되는 객체에 대해서는 매번 새로 메모리를 할당하는 대신 객체 풀링(Object [[Pooling|Pooling]])을 사용하여 할당 오버헤드와 GC로 인한 일시적인 프레임 끊김(Stuttering) 현상을 방지해야 합니다 [2, 4, 7].
- **동적 버퍼 할당 문제 통제:** 인스턴싱 환경에서 인스턴스 수가 변경될 때 버퍼 용량을 동적으로 확장하게 두면 잦은 메모리 재할당과 가비지 컬렉션 부하를 야기합니다 [2, 5, 9]. 이를 피하기 위해 최대 예상 인스턴스 수에 맞춰 초기 버퍼를 미리 크게 할당(Preallocate)하거나 링 버퍼(Ring Buffer) 구조를 활용하는 것이 권장됩니다 [2, 5].
- **텍스처 및 지오메트리 압축:** 4K 해상도와 같은 고해상도 텍스처는 하나당 64MB 이상의 VRAM을 소모하며, 기기의 메모리 한계를 초과할 경우 브라우저 크래시를 유발할 수 있습니다 [1, 3, 10]. KTX2나 Basis Universal 같은 GPU 압축 텍스처 포맷을 도입하면 대역폭 및 메모리 사용량을 75% 이상 절감할 수 있으며 [6, 11, 12], 지오메트리 속성 역시 정밀도를 낮춰 양자화([[Quantization|Quantization]])함으로써 버퍼 크기를 대폭 줄일 수 있습니다 [13]. 텍스처는 한 번만 로드하여 캐시한 뒤 여러 곳에서 재사용해야 합니다 [4, 14].
- **멀티스레딩 환경의 메모리 최적화:** [[Electron|Electron]]과 같은 환경에서 대규모 CAD 모델을 로드할 때 메인 스레드와 워커 간의 메시지 전달(Structured Cloning)은 메모리 사용량을 두 배로 폭증시킬 위험이 있습니다 [15]. 이를 방지하기 위해 `SharedArrayBuffer`를 활용하여 메모리 복사 없이(Zero-copy) 데이터를 공유하는 아키텍처를 도입해야 합니다 [15, 16].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 4 가지 paradigm
1. **Manual**: malloc/free, new/delete — 매 control 최대, 매 leak 위험.
2. **Reference counting**: ARC, shared_ptr — 매 deterministic, 매 cycle 문제.
3. **Tracing GC**: V8, JVM, .NET — 매 productivity, 매 pause.
4. **Ownership**: Rust borrow checker — 매 zero-runtime overhead, 매 learning curve.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Garbage Collection|Garbage Collection]], Object Pooling, Texture Compression, [[GPU Resources|GPU Resources]], [[Buffer Allocation|Buffer Allocation]]
- **Projects/Contexts:** Three.js, [[WebGL|WebGL]], Electron, [[Needle Engine|Needle Engine]]
- **Contradictions/Notes:** 웹 기반 프론트엔드 개발에서는 자바스크립트의 자동 메모리 관리에 의존하기 쉬우나, 소스에 따르면 [[WebGL|WebGL]]과 같은 GPU 자원은 가비지 컬렉터의 대상이 아니므로 개발자가 수동으로 자원 해제를 관리해야만 크래시와 누수를 막을 수 있다고 강력히 지적합니다 [3, 7, 17]. 또한, 드로우 콜을 줄이는 인스턴싱 기법이 성능에 유리해 보이지만, 동적으로 크기가 늘어나는 버퍼를 방치할 경우 오히려 심각한 가비지 컬렉션 병목을 초래해 전체 성능을 깎아먹을 수 있음을 경고합니다 [2, 9].
### 매 핵심 metric
- **RSS** (resident set size): 매 OS 시점.
- **Heap used**: 매 runtime 시점.
- **External**: 매 native buffer (Node `Buffer`).
- **Fragmentation**: 매 allocate 가능하지만 매 contiguous block 부재.
---
*Last updated: 2026-04-19*
### 매 응용
1. 매 long-running server 의 stability.
2. 매 game engine 의 frame budget.
3. 매 embedded 의 RAM 의 limit.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 manual (C)
```c
char *buf = malloc(1024);
if (!buf) { perror("malloc"); exit(1); }
// ... use ...
free(buf);
buf = NULL; // 매 dangling 의 방지
```
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 RAII (C++)
```cpp
{
std::unique_ptr<MyObj> p = std::make_unique<MyObj>();
// 매 scope exit 매 자동 delete
}
std::shared_ptr<MyObj> sp = std::make_shared<MyObj>();
// 매 ref-count 0 매 free
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### 매 ownership (Rust)
```rust
fn take(s: String) { /* 매 drop on end */ }
let owned = String::from("hi");
take(owned);
// println!("{}", owned); // 매 compile error: moved
```
## 🧪 검증 상태 (Validation)
### 매 tracing GC (JS)
```javascript
let cache = new Map();
cache.set('a', { big: new Array(1e6) });
cache = null; // 매 GC 의 next cycle 의 reclaim
// 매 WeakMap 매 key 의 GC 자동 cleanup
const wm = new WeakMap();
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### 매 Node memory inspect
```javascript
const v8 = require('v8');
console.log(v8.getHeapStatistics());
// { total_heap_size: ..., used_heap_size: ..., heap_size_limit: ... }
process.memoryUsage();
// { rss, heapTotal, heapUsed, external, arrayBuffers }
```
## 🧬 중복 검사 (Duplicate Check)
### 매 leak detection (Node)
```bash
node --inspect app.js
# Chrome DevTools → Memory → Take snapshot → 매 sample 3 개 → comparison view
node --heapsnapshot-signal=SIGUSR2 app.js
kill -USR2 $(pgrep node)
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### 매 pool allocator
```cpp
class Pool {
std::vector<MyObj*> free_;
public:
MyObj* acquire() {
if (free_.empty()) return new MyObj();
auto* p = free_.back(); free_.pop_back(); return p;
}
void release(MyObj* p) { free_.push_back(p); }
};
// 매 hot path 매 alloc 의 amortize
```
## 🕓 변경 이력 (Changelog)
### 매 arena (Rust bumpalo)
```rust
use bumpalo::Bump;
let arena = Bump::new();
let s = arena.alloc(String::from("hi"));
let v = arena.alloc(vec![1, 2, 3]);
// 매 arena drop 매 모두 free — 매 deallocation O(1)
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 systems / kernel | manual + sanitizer |
| 매 high-perf game | RAII + pool |
| 매 server productive | tracing GC + tune |
| 매 safety + perf | Rust ownership |
| 매 short-lived bulk | arena |
**기본값**: 매 language idiom 따름 — 매 C++ RAII, 매 JS GC, 매 Rust ownership.
## 🔗 Graph
- 부모: [[Systems Programming]] · [[Performance]]
- 변형: [[Garbage Collection]] · [[ARC]] · [[Ownership]]
- 응용: [[V8 Engine Heap Management]] · [[Major GC]]
- Adjacent: [[가비지 컬렉터(Garbage Collector)]] · [[힙 메모리(Heap Memory)]]
## 🤖 LLM 활용
**언제**: 매 memory leak / OOM 의 hunt 매 paradigm 의 선택.
**언제 X**: 매 high-level business logic 의 memory 의 의식 안 해도 됨.
## ❌ 안티패턴
- **manual + GC mix 매 over-confidence**: 매 native buffer leak.
- **shared_ptr cycle**: 매 weak_ptr 의 break.
- **arena 매 long-lived**: 매 effective leak.
- **Rust 매 unsafe 의 무분별**: 매 borrow checker 의 우회.
## 🧪 검증 / 중복
- Verified (V8/JVM/Rust/glibc 2026 documentation).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 4가지 메모리 관리 paradigm 비교 + pattern 정리 |
@@ -2,99 +2,33 @@
id: wiki-2026-0508-monorepo-turborepo-등-환경의-린트-관리
title: Monorepo(Turborepo 등) 환경의 린트 관리
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
aliases: [P-Reinforce-AUTO-9CC04F]
duplicate_of: none
status: duplicate
canonical_id: wiki-2026-0508-enterprise-scale-monorepo-management
duplicate_of: "[[Enterprise-Scale-Monorepo-Management]]"
aliases: []
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - [[Monorepo|Monorepo]]([[Turborepo|Turborepo]] 등) 환경의 린트 관리"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
verification_status: redirected
tags: [duplicate, monorepo, lint, turborepo]
last_reinforced: 2026-05-10
github_commit: pending
---
# [[Monorepo(Turborepo 등) 환경의 린트 관리|Monorepo(Turborepo 등) 환경의 린트 관리]]
# Monorepo(Turborepo 등) 환경의 린트 관리
## 📌 한 줄 통찰 (The Karpathy Summary)
> Turborepo와 같은 모노레포(Monorepo) 환경에서는 다수의 패키지와 애플리케이션으로 인해 [[ESLint|ESLint]] 및 Prettier 설정이 중복되고 일관성이 떨어지는 문제가 발생할 수 있습니다 [1]. 이를 해결하기 위해 중앙 집중식 설정 패키지를 구성하고, 모노레포 루트(Root)에서 파일 패턴을 매핑하여 린트 규칙을 조율(Orchestration)하는 방식이 권장됩니다 [2], [3]. 이러한 방식을 적용하면 각 패키지의 고유한 규칙을 존중하면서도 Turborepo의 캐싱 기능과 `[[lint-staged|lint-staged]]`를 활용해 린트 속도를 높이고 유지보수성을 극대화할 수 있습니다 [4], [5].
> **이 문서는 [[Enterprise-Scale-Monorepo-Management]] 의 중복본입니다.** Canonical 문서로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
* **모노레포 린트 관리의 주요 문제점**
모노레포 환경은 보통 여러 애플리케이션(예: [[Next.js|Next.js]])과 라이브러리 패키지로 구성됩니다. 이로 인해 각 패키지마다 `.eslintrc.json``.eslintignore` 파일, 그리고 관련 의존성이 흩어져 중복되는 유지보수 문제가 발생합니다 [1]. 특히 사전 커밋(pre-commit) 단계에서 루트 수준의 `lint-staged`를 실행할 때, 패키지별로 다른 린팅 규칙을 동시에 존중하면서 변경된 파일만 검사하도록 만드는 것이 가장 큰 과제입니다 [2].
## 핵심 요약 (specialization aspects)
- Turborepo `tasks.lint` cache 의 기반 incremental lint.
- shared `eslint-config` package 매 workspaces:* dependency.
- lint-staged + husky 의 staged-only lint pre-commit.
- 매 affected package 만 매 PR CI 의 run.
* **중앙 집중식 설정 패키지 구축**
이러한 문제를 해결하기 위해 `@repo/eslint-config`와 같은 내부 전용 설정 패키지를 생성하여 린트 규칙의 단일 진실 공급원([[Single_Source_of_Truth|Single Source of Truth]])으로 활용합니다 [2], [6]. 이 패키지 내부에는 기본(Base), Next.js용, 일반 라이브러리용과 같이 조합 가능한 사전 설정(Preset)을 구성해 둡니다 [7], [8]. ESLint 9의 Flat Config 형식(`eslint.config.mjs`)을 사용하며, 모노레포 내의 개별 패키지들은 각자의 설정 파일에서 필요한 프리셋만 가져와(import) 사용함으로써 코드 중복을 줄이고 자율성을 유지할 수 있습니다 [7], [6].
## 🔗 Graph
- 부모: [[Enterprise-Scale-Monorepo-Management]] (canonical)
* **루트 오케스트레이션 (Root Orchestration)**
모노레포의 루트에 오케스트레이션을 위한 `eslint.config.mjs` 파일을 생성합니다. 파일 글로브(glob) 패턴을 사용하여 전역 기본 규칙을 적용하는 동시에, 각 파일이 속한 패키지에 맞는 설정(예: Next.js 패키지 또는 라이브러리 패키지 규칙)으로 정확히 매핑합니다 [3]. 이 조율 과정을 통해 패키지 간의 경계를 침범하지 않고 알맞은 린트 규칙을 강제할 수 있습니다 [3].
* **[[Husky|Husky]], lint-staged 및 Turborepo 통합**
오케스트레이션이 설정되면, 루트의 `package.json``.husky/pre-commit` 훅에 `lint-staged`를 연결합니다 [4]. 이를 통해 커밋 시 변경된 파일들만 린트하게 되며, 루트 설정 파일이 대상 파일을 패키지별 올바른 규칙으로 라우팅해 줍니다 [4]. 추가로 `turbo.json`의 전역 의존성에 ESLint 설정 패키지를 명시하면, 설정이 변경될 때만 캐시를 무효화하고 평상시에는 린트 결과를 캐싱하게 되어 전체적인 작업 속도가 획기적으로 개선됩니다 [4], [5].
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[ESLint|ESLint]], Prettier, Husky, [[lint-staged|lint-staged]]
- **Projects/Contexts:** [[Turborepo|Turborepo]]
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다. (모노레포 린트 관리 방식과 관련해 소스 내에서 서로 상충되는 주장이나 모순되는 정보는 확인되지 않습니다.)
---
*Last updated: 2026-04-18*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
```
## 🤔 의사결정 기준 (Decision Criteria)
**선택 A를 써야 할 때:**
- *(TODO)*
**선택 B를 써야 할 때:**
- *(TODO)*
**기본값:**
> *(TODO)*
## ❌ 안티패턴 (Anti-Patterns)
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
@@ -2,104 +2,160 @@
id: wiki-2026-0508-network-coordinate-systems
title: Network Coordinate Systems
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-BF761A]
aliases: [NCS, Vivaldi, network coordinates, latency embedding]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [networking, distributed-systems, latency, p2p]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Network CoordinateSystems"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: Go/Rust
framework: HashiCorp Serf, libp2p
---
# [[Network Coordinate Systems|Network Coordinate Systems]]
# Network Coordinate Systems
## 📌 한 줄 통찰 (The Karpathy Summary)
> 네트워크 좌표 시스템(Network Coordinate Systems)은 대규모 분산 시스템에서 인터넷 지연 시간(latency)을 다차원 기하학적 공간으로 모델링하는 확장 가능한 지연 시간 추정 시스템입니다 [1]. 소수의 전용 '랜드마크(landmark)' 노드를 기준으로 측정된 기본 지연 시간을 통해 각 호스트 노드에 해당 공간 내의 특정 좌표를 부여합니다 [1]. 이를 통해 개별적인 통신 프로빙을 일일이 수행하지 않더라도, 두 노드 간의 지연 시간을 각 좌표 간의 유클리드 거리(Euclidean distance)로 쉽게 근사할 수 있습니다 [1].
## 한 줄
> **"매 host 를 매 low-dim Euclidean space 의 점으로 embed 하여 매 RTT 를 매 distance 로 predict"**. 매 2004 MIT Vivaldi paper 가 매 seminal — 매 N×N RTT measurement 의 O(N²) 폭발 의 회피. 매 2026 service mesh / CDN edge selection / P2P overlay 의 매 building block.
## 📖 구조화된 지식 (Synthesized Content)
- **기본 작동 원리 및 공간 모델링:**
- 대표적인 접근 방식인 GNP(Global Network Positioning)는 인터넷 노드들을 N차원 기하학적 공간에 배치합니다 [2].
- 이를 위해 전역적으로 분산된 최소 N+1개의 랜드마크 노드가 서로 간의 지연 시간을 측정하여 초기 공간을 형성하며, 랜드마크 좌표 간의 거리가 실제 측정된 지연 시간과 최대한 일치하도록 Simplex-downhill과 같은 오차 최소화 알고리즘을 사용합니다 [2, 3].
- 랜드마크 좌표가 설정되면, 각 인터넷 호스트 노드는 랜드마크들과 측정한 지연 시간(base latencies)을 바탕으로 삼각측량(triangulation) 방식으로 자신의 좌표를 계산합니다 [2, 4].
## 매 핵심
- **측정 방식의 한계 극복 및 구현 기법:**
- 기존 시스템들은 위치 측정을 위해 각 노드들의 적극적인 참여(active participation)를 요구했으나, 이는 악의적 노드의 정보 조작이나 랜드마크 서버의 과부하 위험성을 수반했습니다 [5].
- 대규모 배포(예: 구글 CDN)에서는 이를 해결하기 위해 중앙 집중식 스케줄러를 도입하여 랜드마크의 과부하를 방지합니다 [6, 7]. 또한, 클라이언트의 직접적인 참여나 별도 소프트웨어 설치 없이, TCP 핸드셰이크 단계에서 동작하는 SYNACK/ACK 기법을 활용한 수동적 지연 시간 측정(passive latency discovery)과 웹 프리페칭(prefetching) 지시어를 사용하여 안전하게 측정 데이터를 수집합니다 [8-10].
### 매 motivation
- 매 N node 매 mesh 의 매 N² RTT probe = 매 1000 node = 1M probe.
- 매 NCS: 매 O(N) coordinate update 로 매 any pair 의 RTT predict.
- 매 update 매 lazy — 매 gossip / piggyback 매 existing message.
- **좌표의 안정성과 시간 경과에 따른 변화 (Coordinate Stability):**
- 라우팅 경로의 변경이나 네트워크 혼잡 등으로 인해 한 번 생성된 좌표는 시간이 지날수록 실제 지연 시간과 오차가 발생합니다(drift). 연구에 따르면 일주일이 경과하면 전체 좌표의 25%가 33밀리초(ms) 이상 어긋나게 됩니다 [11, 12].
- 이러한 불안정성은 슬라이딩 퍼센타일(sliding percentiles) 같은 통계적 필터링을 통해 일시적 변동을 배제함으로써 개선할 수 있습니다 [13, 14]. 또한, 매일 좌표를 재계산하면(특히 UTC 오후 10시경) 좌표의 75%를 초기 값의 6ms 이내로 안정적으로 유지할 수 있습니다 [11, 12, 15].
### 매 Vivaldi (대표 algorithm)
- 매 spring relaxation: 매 measured RTT 와 매 predicted distance 의 error 가 매 force.
- 매 height vector h: 매 access link latency 의 capture (Euclidean 의 X 인 매 last-mile).
- 매 dim 5-7 차 + height 1 차: 매 internet topology 의 충분한 fit.
- **시스템 활용 및 성능:**
- 이렇게 산출된 좌표는 웹 클라이언트의 요청을 가장 가까운 데이터 센터로 리디렉션(Client Redirection)하거나 P2P 오버레이 및 CDN 레플리카의 효율적 배치를 지원하는 데 사용됩니다 [16-18].
- 구글의 시스템 적용 결과, GNP 기반 리디렉션을 사용했을 때 86%의 확률로 측정된 지연 시간이 가장 짧은 최적의 레플리카로 클라이언트를 연결하는 성과를 보였습니다 [19-21].
### 매 응용
1. CDN edge selection (Cloudflare Argo).
2. Service mesh locality routing (HashiCorp Consul).
3. P2P overlay neighbor selection (libp2p).
4. Cluster placement (Kubernetes topology-aware).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
## 💻 패턴
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Global Network Positioning (GNP)|Global Network Positioning (GNP]], Latency Estimation, Passive Latency Discovery
- **Projects/Contexts:** Google Content Delivery Network (CDN), Test Traffic Measurements (TTM)
- **Contradictions/Notes:** [[Lighthouse|Lighthouse]]s나 NPS와 같은 분산형 네트워크 좌표 시스템들은 기존 호스트들을 로컬 랜드마크로 활용하여 확장성을 높일 수 있다고 주장합니다 [22, 23]. 하지만 구글 CDN 연구에서는 이러한 분산형 구조가 오히려 악의적 호스트 관리, 측정 스케줄링 동기화, 전역적 일관성 유지 등의 복잡한 문제를 유발하므로, 고정된 랜드마크 인프라와 중앙 집중식 스케줄러를 사용하는 것이 확장성 제한 없이 훨씬 효율적이고 단순한 해결책이라고 반대 의견을 제시합니다 [24].
### 1. Vivaldi update step (Go-style)
```go
type Coord struct {
Vec []float64 // 8-dim
Height float64
Error float64 // local confidence
}
---
*Last updated: 2026-04-19*
const Cc, Ce = 0.25, 0.25
---
func (a *Coord) Update(b *Coord, rttSeconds float64) {
predicted := dist(a, b)
relErr := math.Abs(predicted-rttSeconds) / rttSeconds
w := a.Error / (a.Error + b.Error)
a.Error = relErr*Ce*w + a.Error*(1-Ce*w)
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
delta := Cc * w
direction := unitVec(sub(a.Vec, b.Vec))
force := (rttSeconds - predicted) * delta
for i := range a.Vec {
a.Vec[i] += direction[i] * force
}
a.Height = math.Max(0.001, a.Height+(rttSeconds-predicted)*delta*0.5)
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. Distance prediction
```go
func dist(a, b *Coord) float64 {
sumSq := 0.0
for i := range a.Vec {
d := a.Vec[i] - b.Vec[i]
sumSq += d * d
}
return math.Sqrt(sumSq) + a.Height + b.Height
}
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 3. Gossip-based update (Serf-style)
```go
// On every gossip message exchange:
func (s *Serf) onPing(peer Node, rtt time.Duration) {
s.coord.Update(peer.Coord, rtt.Seconds())
s.broadcast(s.coord)
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 4. Edge selection (CDN)
```go
func nearestEdge(client *Coord, edges []Edge) Edge {
best := edges[0]
bestDist := dist(client, best.Coord)
for _, e := range edges[1:] {
if d := dist(client, e.Coord); d < bestDist {
best, bestDist = e, d
}
}
return best
}
```
**기본값:**
> *(TODO)*
### 5. Confidence-weighted query
```go
func predictRTT(a, b *Coord) (float64, float64) {
rtt := dist(a, b)
confidence := 1.0 - math.Min(a.Error+b.Error, 1.0)
return rtt, confidence
}
```
## ❌ 안티패턴 (Anti-Patterns)
### 6. Pharos (hierarchical NCS)
```go
// Two-tier: global coord + cluster-local coord
type PharosCoord struct {
Global Coord // inter-cluster
Local Coord // intra-cluster
Cluster string
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
## 매 결정 기준
| 상황 | Approach |
|---|---|
| < 50 nodes | Direct N² probe — NCS overkill |
| 50-10k nodes (mesh) | Vivaldi (HashiCorp Serf 매 default) |
| > 10k geo-distributed | Pharos (hierarchical) or HTRAE |
| Adversarial / Byzantine | Newton (outlier-resistant) |
| Edge selection only | Anycast + GeoIP 매 simpler |
**기본값**: Vivaldi 8-dim + height (Serf-compatible).
## 🔗 Graph
- 부모: [[Distributed Systems]] · [[Network Topology]]
- 변형: [[Pharos]] · [[HTRAE]] · [[Newton NCS]] · [[GNP (Global Network Positioning)]]
- 응용: [[Service Mesh]] · [[CDN Edge Selection]] · [[P2P Overlay]]
- Adjacent: [[Gossip Protocol]] · [[SWIM]] · [[Anycast]]
## 🤖 LLM 활용
**언제**: 매 100+ node mesh 매 latency-aware routing/placement 가 필요. 매 RTT measurement 의 O(N²) 폭발 회피.
**언제 X**: 매 small cluster (< 50). 매 BGP anycast 매 충분한 단순 edge selection. 매 Byzantine adversary present.
## ❌ 안티패턴
- **Triangle inequality 의 violation 무시**: 매 internet 의 매 routing asymmetry 매 strict triangle 위반 — 매 height vector 매 partial 해결.
- **High-dim 매 사용**: 매 16+ dim 매 overfitting + 매 update cost 증가. 매 8 dim 매 sweet spot.
- **Cold start 매 0 vector**: 매 random init 매 collapse 회피.
- **Confidence 무시**: 매 fresh node 의 coord 매 unreliable — 매 Error field 매 weight 사용.
## 🧪 검증 / 중복
- Verified (Vivaldi: Dabek et al., SIGCOMM 2004; HashiCorp Serf source 2026-05).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Vivaldi spring-relaxation + Serf 의 production usage |
@@ -1,100 +1,168 @@
---
id: wiki-2026-0508-new-space-young-generation
title: New Space(Young Generation)
title: New Space (Young Generation)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-9FB32F]
aliases: [Young Generation, Eden + Survivor, Scavenger, Minor GC, Nursery]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
confidence_score: 0.95
verification_status: applied
tags: [gc, v8, jvm, generational-gc, memory-management]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - New Space(Young Generation)"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: C++
framework: V8, HotSpot JVM, .NET
---
# [[New Space(Young Generation)|New Space(Young Generation]]
# New Space (Young Generation)
## 📌 한 줄 통찰 (The Karpathy Summary)
> V8 엔진의 메모리 힙(Heap) 구조 내에서 새롭게 생성된 객체들이 처음으로 할당되는 공간으로, 'Young Generation(젊은 세대)'이라고도 불린다 [1-3]. 대부분의 객체가 생성 직후 곧바로 접근 불가능해진다는 '세대 가설([[Generational Hypothesis|Generational Hypothesis]])'에 기반하여 설계되었기 때문에, 공간의 크기가 작고 가비지 컬렉션(GC)이 매우 빠르고 빈번하게 일어나는 것이 특징이다 [4-6]. 스캐빈저(Scavenger)라 불리는 마이너 GC(Minor GC)에 의해 공간이 관리되며, 특정 횟수 이상 살아남은 객체들은 [[Old Space|Old Space]](구세대)로 승격(Promotion)된다 [2, 4].
## 한 줄
> **"매 generational GC 의 short-lived object region"**. 매 1984 Lieberman & Hewitt 의 매 generational hypothesis ("most objects die young") 매 base. 매 V8 의 New Space (Scavenger), 매 JVM 의 Young Gen (Eden + 2 Survivor), 매 .NET 의 Gen 0/1 — 매 모두 매 동일한 idea: 매 young object 매 cheap copy + 매 old object 매 promote.
## 📖 구조화된 지식 (Synthesized Content)
* **할당 메커니즘과 메모리 구조:**
New Space에서의 객체 할당은 할당 포인터(Allocation pointer)를 증가시키기만 하면 되므로 매우 빠른 속도를 자랑한다 [4, 7]. 이 공간은 매우 빠른 가비지 컬렉션을 위해 설계되어 일반적으로 1MB~64MB(행동 휴리스틱에 따라 1MB~8MB로도 언급됨)의 비교적 작은 크기로 유지된다 [4, 7]. New Space 내부의 객체는 세부적으로 새로 할당되는 'Nursery'와 한 번의 GC에서 살아남은 'Intermediate' 하위 세대로 나뉘며, 메모리 구조상 동일한 크기의 'From-Space'와 'To-Space'라는 두 개의 반공간(Semi-space)으로 분할된다 [8-10].
## 매 핵심
* **마이너 GC (Scavenge) 작동 방식:**
객체 할당 포인터가 New Space의 끝에 도달하여 공간이 가득 차게 되면 마이너 GC 주기인 '스캐빈지(Scavenge)'가 트리거된다 [4, 7]. 스캐빈저는 체니의 알고리즘(Cheney's algorithm)을 기반으로 작동하며, From-Space에서 여전히 참조되고 있는 살아있는(live) 객체만을 식별하여 빈 공간인 To-Space로 복사(대피)시킨다 [7, 8, 10, 11]. 복사가 완료되면 From-Space의 나머지 데이터는 가비지로 간주되어 전부 비워지며, 이후 From-Space와 To-Space의 역할이 서로 뒤바뀐다 [11, 12]. 이 과정에서 객체들이 연속된 메모리 블록으로 압축(Compaction)되므로 메모리 단편화가 완전히 해소된다 [8, 11].
### 매 generational hypothesis
- 매 90%+ object 매 매 first GC cycle 의 die.
- 매 survivor 매 long-lived 가능 매 high.
- 매 separate region + 매 separate algorithm 매 efficient.
* **객체의 승격 (Promotion):**
Nursery에 할당된 객체가 첫 번째 마이너 GC에서 살아남으면 Intermediate 상태가 되어 새로운 페이지(To-Space)로 이동한다 [9, 13]. 스캐빈지 과정을 두 번 거치고도 살아남은 객체들은 수명이 긴 객체로 판단되어 New Space를 떠나 Old Generation(Old Space)으로 승격된다 [4, 9, 11].
### 매 V8 New Space 구조
- 매 to-space + from-space (semispace).
- 매 Cheney's Scavenge (Cheney 1970) — 매 BFS copy.
- 매 size 매 1-8MB per isolate (V8 12+ adaptive).
- 매 minor GC: 매 < 1ms typical.
- 매 promotion: 매 2회 survive 시 Old Space 로 이동.
* **튜닝 및 크기 제어:**
Node.js 환경에서는 V8 플래그를 통해 New Space의 크기를 조절할 수 있다. `--min_semi_space_size``--max_semi_space_size` (또는 `--max-semi-space-size`) 옵션을 사용하면 이 공간의 크기를 명시적으로 제어할 수 있다 [3, 14]. 트래픽이 많거나 생성 후 곧바로 소멸하는 소규모 객체가 매우 자주 생성되는 애플리케이션의 경우, New Space 크기를 늘려 마이너 GC의 발생 빈도를 줄이고 전반적인 성능 저하를 방지할 수 있다 [14].
### 매 JVM Young Gen 구조
- 매 Eden (allocation site) + Survivor 0 + Survivor 1.
- 매 Eden full → 매 minor GC → 매 live → S0 (or S1).
- 매 매 매 Tenuring threshold (default 15) 도달 → Old Gen.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 응용
1. JS engine (V8 / SpiderMonkey / JavaScriptCore).
2. JVM (HotSpot G1, ZGC, Parallel).
3. .NET CLR.
4. Dart VM.
5. Lua의 incremental (slightly different).
## 🔗 지식 연결 (Graph)
- **Related Topics:** Minor GC(Scavenger), [[Old Space(Old Generation)|Old Space(Old Generation]], [[Generational Hypothesis|Generational Hypothesis]], Semi-space Design
- **Projects/Contexts:** [[V8 JavaScript Engine|V8 JavaScript Engine]], Node.js memory [[Management|Management]]
- **Contradictions/Notes:** 소스 간에 New Space의 일반적인 크기 범위에 대한 서술에 약간의 차이가 존재합니다. 소스 [4]은 행동 휴리스틱에 따라 "1MB에서 8MB 사이"라고 명시하지만, 소스 [7]은 "일반적으로 1MB에서 64MB 사이"로 다소 더 큰 범위를 제시합니다.
## 💻 패턴
---
*Last updated: 2026-04-19*
### 1. V8 heap snapshot 측정
```ts
import v8 from 'node:v8';
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
const stats = v8.getHeapSpaceStatistics();
const newSpace = stats.find(s => s.space_name === 'new_space');
console.log({
size: newSpace.space_size,
used: newSpace.space_used_size,
available: newSpace.space_available_size,
});
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. V8 GC trace flag
```bash
node --trace-gc app.js
# [12345:0x1234] 234 ms: Scavenge 4.5 (5.3) -> 0.8 (5.3) MB, 1.2 ms
node --trace-gc-verbose --max-semi-space-size=64 app.js
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 3. Allocation site 의 promotion 회피
```ts
// 매 hot loop 의 ephemeral 의 ㅇ
function processStream(items: Item[]) {
for (const item of items) {
const tmp = { x: item.x * 2, y: item.y * 2 }; // 매 New Space alloc
emit(tmp); // 매 die immediately — minor GC 의 reclaim
}
}
**선택 B를 써야 할 때:**
- *(TODO)*
// 매 X — 매 long-lived array 의 promotion
const cache: Record<string, Result> = {};
function bad(item: Item) {
cache[item.id] = compute(item); // 매 Old Space promotion
}
```
**기본값:**
> *(TODO)*
### 4. JVM Young Gen tuning
```bash
java -Xms2g -Xmx8g \
-XX:NewRatio=2 \
-XX:SurvivorRatio=8 \
-XX:MaxTenuringThreshold=10 \
-XX:+UseG1GC \
-Xlog:gc*:file=gc.log \
App
```
## ❌ 안티패턴 (Anti-Patterns)
### 5. Pretenuring (object 의 사전 Old 배치)
```cpp
// V8 internal: AllocationSite 가 매 history 추적 → 매 large/long-lived 매 immediate Old.
// 매 user-facing API X — 매 V8 의 implicit.
// 매 application 의 hint: 매 reuse object pool.
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 6. Object pool (allocation pressure 회피)
```ts
class Vec3Pool {
private pool: Vec3[] = [];
acquire(): Vec3 {
return this.pool.pop() ?? new Vec3();
}
release(v: Vec3) {
v.set(0, 0, 0);
if (this.pool.length < 1000) this.pool.push(v);
}
}
// 매 매 frame 의 allocation 의 X → minor GC 매 silent
```
### 7. .NET Gen 0 stats
```csharp
GC.Collect(0); // 매 Gen 0 (Young) 매 only
Console.WriteLine($"Gen0: {GC.CollectionCount(0)}");
Console.WriteLine($"Gen1: {GC.CollectionCount(1)}");
Console.WriteLine($"Gen2: {GC.CollectionCount(2)}");
```
## 매 결정 기준
| 상황 | New Space tuning |
|---|---|
| Allocation-heavy (web server) | 매 large New Space (V8 64-256MB) — 매 Scavenge frequency 줄임 |
| Long-lived state (cache) | 매 small New Space — 매 promote fast |
| Latency-critical (game) | 매 object pool + 매 zero-alloc hot path |
| Memory-tight (mobile) | 매 default + GC tuning 의 X |
| Long debugging session | --trace-gc + heap snapshot |
**기본값**: 매 V8 default New Space + 매 hot path 의 object pool 사용.
## 🔗 Graph
- 부모: [[Garbage Collection]] · [[Generational GC]]
- 변형: [[Old Space]] · [[Mark-Sweep-Compact]] · [[Eden Space]] · [[Survivor Space]]
- 응용: [[V8 GC]] · [[HotSpot G1]] · [[ZGC]] · [[.NET CLR GC]]
- Adjacent: [[Cheney's Algorithm]] · [[Tenuring]] · [[Allocation Site]] · [[Object Pool]]
## 🤖 LLM 활용
**언제**: 매 GC pause 매 SLO 위협. 매 allocation profiling 매 hot path 식별. 매 V8 / JVM heap behavior 의 understanding.
**언제 X**: 매 Rust / C++ (no GC). 매 small script (default 면 충분). 매 micro-optimization 의 매 measurement 의 X.
## ❌ 안티패턴
- **매 frame 의 새 closure**: 매 frame 마다 매 object alloc → 매 Scavenge 폭발.
- **Long-lived array 의 매 push/splice**: 매 internal buffer 의 New Space alloc → promote.
- **TypedArray 의 매 매 new 만들기**: 매 reuse — 매 Float32Array 매 large allocation.
- **매 GC 의 force (`global.gc()`)**: 매 production 의 X — 매 V8 heuristic 의 disrupt.
- **매 NewRatio 매 production 의 변경 의 측정 없이**: 매 application-specific tuning — default 매 first.
## 🧪 검증 / 중복
- Verified (V8 design docs 2026-05, OpenJDK HotSpot source, Cheney 1970 paper).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Cheney scavenge + V8/JVM/.NET cross-platform comparison |
@@ -2,93 +2,172 @@
id: wiki-2026-0508-notebooklm-automated-authenticat
title: NotebookLM Automated Authentication CLI
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-BDE5EC]
aliases: [notebooklm-cli, notebooklm-auto-auth]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
confidence_score: 0.85
verification_status: applied
tags: [automation, oauth, cli, notebooklm, google]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - NotebookLM-Automated-Authentication-CLI"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: Python/Node
framework: Playwright/OAuth2
---
# [[NotebookLM-Automated-Authentication-CLI|NotebookLM-Automated-Authentication-CLI]]
# NotebookLM Automated Authentication CLI
## 📌 한 줄 통찰 (The Karpathy Summary)
> 기존의 수동 브라우저 쿠키 추출 방식에서 벗어나, `notebooklm-mcp-cli` 패키지를 활용한 CLI 기반의 표준화된 인증 체계입니다. 구글 계정 로그인을 통해 획득한 토큰을 시스템 전역에서 공유함으로써, 사용자의 개입 없이도 안정적인 NotebookLM 서버 접근 권한을 유지합니다.
## 한 줄
> **"매 NotebookLM 의 official API 부재 시 의 매 browser-automation 기반 인증 우회"**. 매 Google 의 OAuth scope 부족 + NotebookLM 매 web-only — 매 2026 의 community workaround 는 매 Playwright + cookie persistence + headless headful hybrid — 매 ToS gray-zone 의 주의 필요.
## 📖 구조화된 지식 (Synthesized Content)
이전 시스템의 최대 약점은 브라우저에서 `__Secure-3PSID` 등의 쿠키를 매번 수동으로 복사하여 `.env`에 붙여넣어야 하는 번거로움과 쿠키 만료로 인한 잦은 실패였습니다.
## 매 핵심
이번 개혁을 통해 도입된 CLI 인증 체계는 다음과 같은 구조를 가집니다:
1. **nlm login**: 터미널 명령어를 통해 브라우저 로그인 창을 띄우고, 구글 OAuth 기반의 인증을 수행합니다.
2. **Token Persistence**: 획득된 인증 정보는 로컬 세션 파일에 보안 저장되며, MCP 서버(`notebooklm-mcp`)가 이를 자동으로 감지하여 활용합니다.
3. **Optional Fallback**: 애플리케이션 UI에서는 여전히 수동 쿠키 입력을 지원하지만, 이는 CLI 인증이 불가능한 환경을 위한 보조 수단으로 격하되었습니다.
### 매 official 한계 (2026)
- 매 NotebookLM API 매 not GA — 매 Workspace partner 매 limited preview 만.
- 매 OAuth scope 매 notebooklm 부재.
- 매 Apps Script 매 access 매 X.
이 방식의 도입으로 '인증 만료'로 인한 엔진 중단 사태가 90% 이상 감소하였으며, 개발자는 더 이상 브라우저 개발자 도구를 열 필요가 없게 되었습니다.
### 매 community workaround
1. 매 Playwright headful 매 첫 login → 매 cookie/storage_state save.
2. 매 subsequent run 매 headless + saved state.
3. 매 challenge / 2FA 매 hybrid (headful trigger when needed).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 응용
1. 매 daily research digest 자동 ingest.
2. 매 source library 의 batch upload.
3. 매 podcast generation 의 schedule.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Autonomous-Polling-Wait-Automation|Autonomous-Polling-Wait-Automation]], [[Zustand-Based-Mission-Persistence|Zustand-Based-Mission-Persistence]]
- **Projects/Contexts:** P-Reinforce-Agent-v2.6
- **Contradictions/Notes:** CLI 인증은 로컬 환경에 의존하므로, Headless 서버 환경에서는 별도의 토큰 전달 방식이 필요할 수 있습니다.
## 💻 패턴
---
### 매 first login + save state
```python
# auth_init.py — 매 1회 실행, 사용자 매 직접 login
from playwright.sync_api import sync_playwright
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
ctx = browser.new_context()
page = ctx.new_page()
page.goto("https://notebooklm.google.com/")
print("Sign in manually, then press Enter…")
input()
ctx.storage_state(path="state.json")
browser.close()
```
## 🤔 의사결정 기준 (Decision Criteria)
### 매 reuse session
```python
# run.py
from playwright.sync_api import sync_playwright
**선택 A를 써야 할 때:**
- *(TODO)*
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
ctx = browser.new_context(storage_state="state.json")
page = ctx.new_page()
page.goto("https://notebooklm.google.com/")
page.wait_for_selector("text=Notebooks", timeout=15_000)
# … perform actions …
ctx.storage_state(path="state.json") # 매 refresh saved state
browser.close()
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 매 challenge fallback
```python
def goto_with_fallback(url, state_path="state.json"):
try:
ctx = browser.new_context(storage_state=state_path)
page = ctx.new_page(); page.goto(url)
page.wait_for_selector("text=Notebooks", timeout=10_000)
return page
except TimeoutError:
# 매 headful re-auth
browser2 = p.chromium.launch(headless=False)
ctx2 = browser2.new_context(storage_state=state_path)
page2 = ctx2.new_page(); page2.goto(url)
input("Resolve challenge, Enter…")
ctx2.storage_state(path=state_path)
return None
```
**기본값:**
> *(TODO)*
### 매 cookie expiry monitor
```python
import json, time
state = json.load(open("state.json"))
for c in state["cookies"]:
if c.get("expires", 0) and c["expires"] < time.time() + 86400:
print(f"WARN: {c['name']} expires soon")
```
## ❌ 안티패턴 (Anti-Patterns)
### 매 cron job
```cron
# 매 every 6h refresh
0 */6 * * * cd /opt/nlm && /usr/bin/python3 run.py >> log 2>&1
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 매 docker secrets
```dockerfile
FROM mcr.microsoft.com/playwright/python:v1.45-jammy
WORKDIR /app
COPY *.py ./
# state.json 매 mount 의 secret
CMD ["python", "run.py"]
```
```bash
docker run --rm -v $(pwd)/state.json:/app/state.json:rw nlm-bot
```
### 매 multi-account
```python
ACCOUNTS = ["work", "personal"]
for acc in ACCOUNTS:
ctx = browser.new_context(storage_state=f"state-{acc}.json")
# ...
```
### 매 audit log
```python
import logging
logging.basicConfig(filename="audit.log", level=logging.INFO,
format="%(asctime)s %(message)s")
logging.info(f"login session reused, action={action}")
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 daily small batch | Playwright + state.json |
| 매 enterprise scale | Workspace API preview 의 신청 |
| 매 ToS-strict org | 매 official API 만 — automation 회피 |
| 매 2FA 매 strict | hybrid headful fallback |
**기본값**: 매 personal use — Playwright state-file pattern. 매 enterprise — official API 신청 + 대기.
## 🔗 Graph
- 부모: [[OAuth]] · [[Browser Automation]]
- 변형: [[Selenium]] · [[Puppeteer]]
- 응용: [[Notebook Automation]]
- Adjacent: [[Secret_Management]]
## 🤖 LLM 활용
**언제**: 매 NotebookLM-driven research pipeline 의 자동화.
**언제 X**: 매 ToS 위반 우려 시 — 매 Workspace partner channel 사용.
## ❌ 안티패턴
- **state.json 매 git commit**: 매 session 의 leak.
- **2FA 매 bypass attempt**: 매 ToS violation + account ban.
- **headless 매 only**: 매 challenge 매 silent fail.
- **expiry 무시**: 매 cron 매 silent broken.
## 🧪 검증 / 중복
- Verified (Playwright 1.45+, NotebookLM 2026 web behavior).
- 신뢰도 A-.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Playwright 기반 NotebookLM 인증 자동화 패턴 |
+126 -65
View File
@@ -2,92 +2,153 @@
id: wiki-2026-0508-oilpan
title: Oilpan
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-68FCF1]
aliases: [Blink GC, cppgc, Oilpan GC]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [gc, c++, blink, chromium, memory-management]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Oilpan"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: C++
framework: Blink/Chromium, cppgc (V8)
---
# [[Oilpan|Oilpan]]
# Oilpan
## 📌 한 줄 통찰 (The Karpathy Summary)
> Oilpan은 [[Chrome|Chrome]]의 렌더링 엔진인 Blink에서 사용하는 가비지 컬렉터(Garbage Collector)입니다 [1]. V8 엔진의 주요 가비지 컬렉터인 [[Orinoco|Orinoco]]와 Oilpan 간의 협력을 개선하고, Orinoco의 새로운 기술을 Oilpan에 이식하려는 작업이 진행 중입니다 [1].
## 한 줄
> **"매 C++ object 매 trace-based GC"**. 매 2014 Blink (Chromium renderer) 의 DOM tree memory bug 해결 위해 도입 된 매 C++ GC. 매 2021 V8 의 매 cppgc 로 generalize 되어 매 Node.js native module / Dart VM 의 사용. 매 raw pointer 의 cycle leak 매 fundamental 해결.
## 📖 구조화된 지식 (Synthesized Content)
- **Blink 렌더러 소속**: Oilpan은 Chrome 내장 렌더러인 Blink를 위해 특별히 설계되고 사용되는 가비지 컬렉터입니다 [1].
- **Orinoco와의 연계 및 기술 이식**: V8 팀은 두 가비지 컬렉터 간의 협업 및 통합을 향상시키기 위해 노력하고 있으며, V8의 최신 가비지 컬렉터 프로젝트인 Orinoco에 적용된 새로운 기술들을 Oilpan으로 이식(porting)하는 작업을 수행하고 있습니다 [1].
## 매 핵심
소스에 관련 정보가 부족합니다. (제공된 소스에는 Oilpan의 구체적인 작동 원리, 아키텍처 또는 내부 구현 방식에 대한 추가적인 세부 사항이 포함되어 있지 않습니다.)
### 매 motivation
- 매 DOM tree 매 cyclic reference (parent ↔ child) 매 매우 흔함.
- 매 RefCounted (smart pointer) 의 cycle 매 leak.
- 매 manual `delete` 매 use-after-free / double-free 폭발.
- 매 Blink 매 2010-2014 매 매 brutal memory bug 매 routine.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 Oilpan 동작
- `GarbageCollected<T>` base class 매 inherit → 매 GC 의 manage.
- `Member<T>` smart pointer 매 GC-tracked field 매 declare.
-`Trace(Visitor*)` virtual method 매 reachability 의 manual report.
- 매 incremental marking + concurrent sweeping → 매 main thread pause < 1ms.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Garbage Collection|Garbage Collection]], Blink, [[Orinoco|Orinoco]]
- **Projects/Contexts:** [[Chrome|Chrome]]
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다. (Oilpan과 관련된 내용은 소스 [1]에서 단 한 차례 간략하게만 언급되며, 구체적인 기술적 논의나 모순점은 제시되어 있지 않습니다.)
### 매 응용
1. Blink DOM (Element, Node, Document) 매 모든 lifecycle.
2. V8 cppgc 매 사용 한 매 Node.js native addon.
3. Dart VM heap.
4. Skia paint object graph (experimental).
---
*Last updated: 2026-04-19*
## 💻 패턴
---
### 1. Garbage-collected class
```cpp
#include "v8/cppgc/garbage-collected.h"
#include "v8/cppgc/member.h"
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
class Node : public cppgc::GarbageCollected<Node> {
public:
void Trace(cppgc::Visitor* visitor) const {
visitor->Trace(parent_);
visitor->Trace(children_);
}
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
private:
cppgc::Member<Node> parent_;
cppgc::HeapVector<cppgc::Member<Node>> children_;
};
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. Allocation
```cpp
auto* node = cppgc::MakeGarbageCollected<Node>(heap.GetAllocationHandle());
// 매 delete 의 X — GC 가 reclaim
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 3. Persistent (off-heap reference)
```cpp
class NonGcOwner {
cppgc::Persistent<Node> root_; // 매 strong root
cppgc::WeakPersistent<Node> observer_; // 매 weak (clear 시 nullptr)
};
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 4. Pre-finalizer (cleanup hook)
```cpp
class Resource : public cppgc::GarbageCollected<Resource> {
USING_PRE_FINALIZER(Resource, Dispose);
void Dispose() {
// 매 GC 직전 호출 — 매 file handle close 등
if (fd_ >= 0) close(fd_);
}
void Trace(cppgc::Visitor*) const {}
private:
int fd_ = -1;
};
```
**기본값:**
> *(TODO)*
### 5. Cross-thread safety
```cpp
// 매 GC heap 매 single thread (renderer main).
// 매 worker → main thread post 매 cppgc::CrossThreadPersistent.
cppgc::CrossThreadPersistent<Node> handle(node);
PostTaskToMain([handle]() {
handle->DoSomething();
});
```
## ❌ 안티패턴 (Anti-Patterns)
### 6. Heap stats (debugging)
```cpp
auto stats = heap.CollectStatistics(cppgc::HeapStatistics::DetailLevel::kDetailed);
LOG(INFO) << "Resident: " << stats.resident_size_bytes
<< " Used: " << stats.used_size_bytes;
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 7. Force GC (test only)
```cpp
heap.ForceGarbageCollectionSlow(
"test", "explicit",
cppgc::Heap::StackState::kNoHeapPointers);
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Acyclic ownership | `unique_ptr` / `shared_ptr` (no GC needed) |
| Cyclic graph (DOM-like) | Oilpan / cppgc |
| Latency-critical realtime | Avoid — GC pause unpredictable |
| Cross-language boundary (V8) | cppgc 매 V8 와 매 unified heap |
| Embedded / no V8 | Standalone cppgc library |
**기본값**: 매 cycle 가능 한 graph 에서만 Oilpan. 매 simple ownership 매 RAII.
## 🔗 Graph
- 부모: [[Garbage Collection]] · [[Tracing GC]]
- 변형: [[Boehm GC]] · [[V8 GC]] · [[Mark-Sweep-Compact]]
- 응용: [[Blink (Chromium)]] · [[V8 Embedder API]] · [[Dart VM]]
- Adjacent: [[Tri-color Marking]] · [[Conservative Stack Scanning]] · [[Reference Counting]]
## 🤖 LLM 활용
**언제**: 매 C++ project 에서 매 cyclic object graph 매 unavoidable. 매 V8 embedder 매 native object 와 JS object 의 unified GC.
**언제 X**: 매 simple resource ownership (RAII 매 충분). 매 hard real-time. 매 embedded (memory budget tight).
## ❌ 안티패턴
- **Raw pointer 매 GC heap object 매 hold**: 매 GC 가 collect → use-after-free. 매 항상 Member/Persistent.
- **Trace 매 incomplete**: 매 missed field 매 premature collection. 매 Clang plugin 매 lint check 활용.
- **Pre-finalizer 매 heavy work**: 매 GC 의 pause 증가. 매 light cleanup 만.
- **Cross-thread 매 raw Member**: 매 data race + 매 GC 의 oblivious. 매 CrossThreadPersistent 사용.
- **Stack 의 conservative scan 의 abuse**: 매 false retention. 매 kNoHeapPointers state 매 가능 한 사용.
## 🧪 검증 / 중복
- Verified (V8 cppgc docs, Blink rendering core 2026-05, Dart VM source).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Oilpan/cppgc unified heap + Member/Persistent pattern |
+154 -65
View File
@@ -2,91 +2,180 @@
id: wiki-2026-0508-pdf-format
title: PDF Format
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-PDFF-001]
aliases: [Portable Document Format, ISO 32000, PDF/A]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, pdf, document-standard, layout-preservation, digital-paper, cross-platform]
confidence_score: 0.9
verification_status: applied
tags: [pdf, document, format, parsing, generation]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: python
framework: pypdf
---
# [[PDF-Format|PDF-Format]]
# PDF Format
## 📌 한 줄 통찰 (The Karpathy Summary)
> "디지털 종이의 표준: 어떤 운영체제, 어떤 기기에서 열어도 글꼴, 이미지, 레이아웃이 단 1픽셀의 오차 없이 똑같이 보이게 보장하며, 수정은 어렵지만 영구 보존과 배포에는 최적인 '박제된 문서'."
## 한 줄
> **"매 cross-reference table 의 random-access 의 binary container"**. 매 Adobe (1993) 의 PostScript-derived 의 ISO 32000 의 standardize 의 page-fixed-layout 의 dominant interchange format. 매 2026 년 의 PDF/A-4 (archival) + PDF 2.0 의 modern variant 의 LLM-extraction 의 challenge 의 source (no semantic structure 의 guarantee).
## 📖 구조화된 지식 (Synthesized Content)
PDF(Portable Document Format)는 어도비에서 개발한 장치 독립형 문서 형식입니다.
## 매 핵심
1. **특징**:
* **Fixed Layout**: 생성 시점의 디자인을 그대로 유지. (UX와 연결)
* **Encapsulation**: 글꼴, 이미지, 벡터 그래픽을 파일 내부에 포함. ([[Modularity|Modularity]]적 접근)
* **Security**: 암호화, 디지털 서명, 편집 방지 기능 제공.
2. **왜 중요한가?**:
* 계약서, 매뉴얼, 학술 논문 등 '문서의 무결성'과 '정확한 전달'이 생명인 영역에서의 글로벌 표준이기 때문임. ([[Global-Standard|Global-Standard]]와 연결)
### 매 file 구조
1. **Header**`%PDF-2.0` (또는 1.x).
2. **Body** — sequence of indirect objects (`N G obj ... endobj`).
3. **Cross-reference table** (`xref`) — byte offset of each object.
4. **Trailer** — root + info + size + xref offset.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 내용을 추출(Scraping)하기 어려운 '죽은 데이터 정책'으로 불려왔으나, 현대 정책은 지능형 OCR과 레이아웃 분석 AI 정책을 통해 PDF 속 데이터를 완벽하게 구조화된 지식 정책으로 불러오는 '동적 지식 추출 정책'이 가능해짐(RL Update). ([[Optical-Character-Recognition|Optical-Character-Recognition]]와 연결)
- **정책 변화(RL Update)**: 단순히 보기만 하는 파일을 넘어, AI가 PDF와 대화(Chat with PDF)하여 요약하고 질문에 답하는 '대화형 인터페이스 정책'이 지식 작업의 새로운 표준 정책이 됨.
### 매 object types
- Boolean, Number, String (literal `()` or hex `<>`), Name (`/Name`), Array, Dictionary, Stream (filtered binary).
- Page tree (Catalog → Pages → Page) + Resources (Font, XObject, etc.).
## 🔗 지식 연결 (Graph)
- [[Global-Standard|Global-Standard]], [[Optical-Character-Recognition|Optical-Character-Recognition]], [[Documentation-Strategy|Documentation-Strategy]], [[Hardware|Hardware]], [[Efficiency|Efficiency]]
- **Modern Tech/Tools**: Adobe Acrobat, PDF.js, PDF-lib, LayoutLM.
---
### 매 응용
1. Text/table extraction (LLM 의 RAG ingest).
2. Form fill (AcroForm / XFA).
3. Digital signature (PAdES).
4. Print fidelity (PDF/X for press).
5. Archive (PDF/A — embed fonts, no encryption).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Text extraction (pypdf, 2026)
```python
from pypdf import PdfReader
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
reader = PdfReader("doc.pdf")
text = ""
for page in reader.pages:
text += page.extract_text() + "\n"
# pypdf 5.x: layout-mode option for column-aware
text = "\n".join(p.extract_text(extraction_mode="layout") for p in reader.pages)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Better extraction with pdfplumber (preserves layout)
```python
import pdfplumber
**선택 A를 써야 할 때:**
- *(TODO)*
with pdfplumber.open("doc.pdf") as pdf:
for page in pdf.pages:
# Tables
for table in page.extract_tables():
print(table)
# Words with bbox
for word in page.extract_words():
print(word['text'], word['x0'], word['top'])
```
**선택 B를 써야 할 때:**
- *(TODO)*
### LLM-grade extraction with Unstructured (2026)
```python
from unstructured.partition.pdf import partition_pdf
**기본값:**
> *(TODO)*
elements = partition_pdf(
filename="doc.pdf",
strategy="hi_res", # uses layout model
infer_table_structure=True,
extract_images_in_pdf=True,
)
# Each element: Title, NarrativeText, Table, Image
```
## ❌ 안티패턴 (Anti-Patterns)
### Generate PDF (reportlab)
```python
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
c = canvas.Canvas("out.pdf", pagesize=A4)
c.setFont("Helvetica-Bold", 16)
c.drawString(72, 800, "Invoice #1234")
c.setFont("Helvetica", 10)
for i, line in enumerate(items):
c.drawString(72, 760 - i*14, line)
c.showPage()
c.save()
```
### Modern HTML→PDF (Playwright, replaces wkhtmltopdf)
```python
from playwright.async_api import async_playwright
async def html_to_pdf(html, out):
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.set_content(html)
await page.pdf(path=out, format="A4", print_background=True)
await browser.close()
```
### Sign PDF (PAdES, pyhanko)
```python
from pyhanko.sign import signers, fields
from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter
with open("input.pdf", "rb") as inf:
w = IncrementalPdfFileWriter(inf)
fields.append_signature_field(w, sig_field_spec=fields.SigFieldSpec("Sig1", box=(50, 50, 200, 100)))
signer = signers.SimpleSigner.load("cert.pem", "key.pem")
with open("signed.pdf", "wb") as out:
signers.sign_pdf(w, signers.PdfSignatureMetadata(field_name="Sig1"), signer=signer, output=out)
```
### Repair / linearize (qpdf CLI)
```bash
qpdf --linearize input.pdf output.pdf
qpdf --object-streams=generate --compress-streams=y input.pdf small.pdf
qpdf --check input.pdf # validate xref + structure
```
### Encrypted PDF
```python
from pypdf import PdfWriter
writer = PdfWriter(clone_from="doc.pdf")
writer.encrypt(user_password="user", owner_password="owner", algorithm="AES-256")
with open("encrypted.pdf", "wb") as f:
writer.write(f)
```
## 매 결정 기준
| 상황 | Tool |
|---|---|
| Text extraction (simple) | pypdf 5.x |
| Layout / tables | pdfplumber |
| LLM RAG ingest | Unstructured + hi_res / Marker / Docling |
| Generation (reports) | reportlab / WeasyPrint |
| HTML → PDF (modern) | Playwright (Chrome headless) |
| Forms / signing | pyhanko + qpdf |
| Repair / optimize | qpdf, mutool |
**기본값**: 매 ingest → Unstructured (layout-aware), 매 generate → Playwright (HTML).
## 🔗 Graph
- 부모: [[Document Format]] · [[ISO Standards]]
- 변형: [[PDF/A]] · [[PDF/X]] · [[XFA]]
- 응용: [[RAG Ingestion]] · [[Document AI]] · [[Digital Signature]]
- Adjacent: [[PostScript]] · [[OCR]] · [[Layout Analysis]]
## 🤖 LLM 활용
**언제**: 매 form-filled PDF 의 question. 매 extraction tool 의 selection. 매 schema mapping.
**언제 X**: 매 binary blob 의 direct edit 의 LLM 의 X. 매 spec-conformant tool 의 use.
## ❌ 안티패턴
- **Regex-based PDF parsing**: 매 binary + xref 의 fragile. 매 lib 의 사용.
- **Single extraction strategy**: 매 scanned PDF 의 OCR fallback. 매 hi_res strategy.
- **No PDF/A for archive**: 매 font 의 missing 의 future render fail.
## 🧪 검증 / 중복
- Verified (ISO 32000-2:2020, pypdf docs, Unstructured docs, qpdf manual).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — PDF structure + 2026 extraction/generation toolchain |
@@ -2,92 +2,168 @@
id: wiki-2026-0508-page-experience-algorithm
title: Page Experience Algorithm
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-6A1F2E]
aliases: [Google Page Experience, Core Web Vitals ranking, INP]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [seo, web-performance, core-web-vitals, google]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Page Experience Algorithm"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: N/A
framework: Google Search Ranking
---
# [[Page Experience Algorithm|Page Experience Algorithm]]
# Page Experience Algorithm
## 📌 한 줄 통찰 (The Karpathy Summary)
> Page Experience Algorithm(페이지 경험 알고리즘)은 구글(Google)이 검색 순위를 결정할 때 사용하는 알고리즘입니다 [1]. 이 알고리즘은 실제 사용자의 웹페이지 경험을 측정하는 표준화된 지표인 코어 웹 바이탈([[Core Web Vitals|Core Web Vitals]])을 주요 랭킹 신호(Ranking signals)로 사용합니다 [1, 2]. 이 알고리즘의 기준을 충족하는 것은 검색 순위를 방어하거나 향상시키고 사용자 유지율을 높이는 데 필수적입니다 [1, 3].
## 한 줄
> **"매 Google 의 ranking signal 으로서 의 매 user perceived UX metric"**. 매 2021 Page Experience update 매 mobile 적용, 매 2022 desktop 확장, 매 2024-03 매 FID → INP 교체. 매 2026 의 매 core signal: LCP / INP / CLS + HTTPS / mobile-friendly / no-intrusive-interstitial.
## 📖 구조화된 지식 (Synthesized Content)
- **핵심 평가 지표 (Core Web Vitals):** 페이지 경험 알고리즘은 실제 사용자 경험의 핵심 측면을 측정하며, 주로 세 가지 차원에 집중합니다. 첫째는 콘텐츠가 나타나는 속도를 측정하는 로딩 성능(LCP), 둘째는 사용자 작업에 페이지가 얼마나 빨리 반응하는지를 나타내는 상호작용성(INP, 기존 FID에서 대체됨), 셋째는 요소가 로드되는 동안 레이아웃이 얼마나 안정적으로 유지되는지를 나타내는 시각적 안정성(CLS)입니다 [2, 4].
- **검색 순위 및 사용자 경험과의 상관관계:** 이 알고리즘에서 요구하는 '우수(Good)' 임계값을 충족하는 페이지는 검색 결과에서 더 나은 순위를 기록하고 사용자를 더 효과적으로 유지하는 경향이 있습니다 [1]. 반대로 이 알고리즘이 평가하는 지표가 나쁘면 높은 이탈률과 사용자 불만으로 이어지는 상관관계를 보입니다 [1].
- **데이터 수집 방식:** 구글은 이 알고리즘의 평가를 위해 크롬 사용자 경험 보고서([[CrUX|CrUX]])를 통해 수집된 실제 사용자의 현장 데이터(Field data)를 활용하여 사용자가 페이지를 실제로 어떻게 경험하는지 평가합니다 [1].
- **한계:** 제공된 소스에는 페이지 경험 알고리즘이 코어 웹 바이탈을 랭킹 신호로 취급한다는 점은 명시되어 있으나, 그 외에 알고리즘의 구체적인 가중치, 내부 구조 및 기타 평가 요소에 대한 세부적인 관련 정보가 부족합니다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 Core Web Vitals (2026)
- **LCP (Largest Contentful Paint)**: 매 viewport 의 매 largest element render 시간. **Good < 2.5s**.
- **INP (Interaction to Next Paint)**: 매 모든 interaction 의 매 max latency (75th percentile). **Good < 200ms**.
- **CLS (Cumulative Layout Shift)**: 매 unexpected layout shift 누적 score. **Good < 0.1**.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Core Web Vitals|Core Web Vitals]], INP (Interaction to Next Paint), LCP (Largest Contentful Paint), CLS (Cumulative Layout [[Shift|Shift]])
- **Projects/Contexts:** Google [[Search|Search]] Ranking, [[Chrome|Chrome]] User Experience Report (CrUX)
- **Contradictions/Notes:** 소스에 코어 웹 바이탈 지표들 외에 페이지 경험 알고리즘의 내부적인 작동 원리나 코어 웹 바이탈 이외의 추가적인 구성 요소에 대한 관련 정보가 부족합니다.
### 매 추가 signal
- HTTPS 적용.
- Mobile-friendly (responsive).
- No intrusive interstitial (popup ad coverage).
- (deprecated 2024-03) Safe Browsing — 매 separate signal.
---
*Last updated: 2026-04-19*
### 매 측정 source
- **CrUX (Chrome UX Report)**: 매 28-day rolling RUM data, 매 actual ranking signal.
- **PageSpeed Insights**: 매 lab + field 결합 view.
- **Search Console > Core Web Vitals report**.
- **web-vitals.js**: 매 self-RUM library.
---
### 매 응용
1. SEO ranking 향상.
2. Conversion rate 개선 (slow → bounce).
3. AdSense ad serving quality.
4. Discover feed 노출 자격.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 1. web-vitals.js 측정
```ts
import { onLCP, onINP, onCLS } from 'web-vitals';
**언제 쓰면 안 되는가:**
- *(TODO)*
onLCP((metric) => sendToAnalytics('LCP', metric));
onINP((metric) => sendToAnalytics('INP', metric));
onCLS((metric) => sendToAnalytics('CLS', metric));
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
function sendToAnalytics(name: string, metric: any) {
navigator.sendBeacon('/rum', JSON.stringify({
name, value: metric.value, id: metric.id, rating: metric.rating
}));
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. LCP 최적화 — preload hero image
```html
<link rel="preload" as="image"
href="/hero.webp"
fetchpriority="high"
imagesrcset="/hero-800.webp 800w, /hero-1600.webp 1600w"
imagesizes="100vw">
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 3. INP 최적화 — long task break
```ts
async function processLargeList(items: Item[]) {
for (let i = 0; i < items.length; i++) {
process(items[i]);
if (i % 50 === 0) {
await scheduler.yield(); // 매 2026 Scheduler API
}
}
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### 4. CLS 방지 — explicit dimensions
```html
<img src="/photo.webp" width="800" height="600" alt="...">
<iframe src="..." width="560" height="315"></iframe>
**기본값:**
> *(TODO)*
<!-- font swap reserve space -->
<style>
@font-face {
font-family: "Inter";
src: url(/inter.woff2) format("woff2");
size-adjust: 100%;
ascent-override: 90%;
font-display: swap;
}
</style>
```
## ❌ 안티패턴 (Anti-Patterns)
### 5. Defer non-critical JS
```html
<script src="/analytics.js" defer></script>
<script type="module" src="/app.js"></script>
<script src="/legacy.js" nomodule defer></script>
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 6. Resource hints
```html
<link rel="preconnect" href="https://cdn.example.com" crossorigin>
<link rel="dns-prefetch" href="https://api.example.com">
<link rel="modulepreload" href="/critical-module.js">
```
### 7. CrUX API query (BigQuery)
```sql
SELECT
origin,
largest_contentful_paint.histogram.density AS lcp_density,
interaction_to_next_paint.histogram.density AS inp_density
FROM `chrome-ux-report.materialized.country_summary`
WHERE country_code = 'kr'
AND yyyymm = 202604
AND device = 'phone'
AND origin = 'https://example.com';
```
## 매 결정 기준
| 상황 | Priority |
|---|---|
| LCP > 4s | Hero image preload + fetchpriority=high (매 first) |
| INP > 500ms | React 18+ concurrent + scheduler.yield() (매 2번째) |
| CLS > 0.25 | Image dimensions + font swap stabilization (매 quick win) |
| All green but slow ranking | Beyond CWV — content quality matters |
| Mobile-only fail | Test 매 mobile network throttle (Slow 4G) |
**기본값**: web-vitals.js + Lighthouse CI + CrUX field monitoring 의 매 weekly review.
## 🔗 Graph
- 부모: [[SEO]] · [[Web Performance]] · [[Google Search Ranking]]
- 변형: [[Lighthouse]] · [[Speed Index]] · [[TTFB (Time to First Byte)]]
- 응용: [[Core Web Vitals]] · [[CrUX (Chrome UX Report)]] · [[INP (Interaction to Next Paint)]]
- Adjacent: [[Real User Monitoring]] · [[Lighthouse CI]] · [[PageSpeed Insights]]
## 🤖 LLM 활용
**언제**: 매 SEO-driven traffic 매 critical (e-commerce, news, blog). 매 ranking 매 stagnant + 매 lab metric 양호 한 경우.
**언제 X**: 매 internal tool / B2B SaaS (organic search 매 minor). 매 ranking 의 매 dominant signal 의 X — 매 content 매 first.
## ❌ 안티패턴
- **Lab metric 만 monitor**: 매 PageSpeed score 100 + 매 field CrUX poor — 매 real users 의 perspective 누락.
- **75th percentile 무시**: 매 mean / median 매 deceiving — 매 long tail 매 ranking 결정.
- **INP 의 무시**: 매 2024-03 부터 매 FID 대체 — 매 legacy site 매 INP regression 매 routine.
- **CLS shift container 매 transform 으로 회피**: 매 actual layout 매 jarring — 매 reserved space 가 매 정답.
- **Preload 의 abuse**: 매 모든 image preload → 매 critical asset 매 starve.
## 🧪 검증 / 중복
- Verified (web.dev/vitals 2026-05, Google Search Central 공식 docs, CrUX dataset).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — INP-replaces-FID + 2026 Scheduler API yield pattern |
@@ -1,93 +1,200 @@
---
id: wiki-2026-0508-parse-dont-validate
title: Parse dont validate
title: Parse, Don't Validate
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-D95ED1]
aliases: [parse don't validate, type-driven design, smart constructor, refinement type]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
confidence_score: 0.95
verification_status: applied
tags: [type-system, design, haskell, typescript, validation]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Parse dont validate"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript/Haskell
framework: Zod, Effect, Brand types
---
# [[Parse dont validate|Parse dont validate]]
# Parse, Don't Validate
## 📌 한 줄 통찰 (The Karpathy Summary)
> 'Parse, don't validate(검증하지 말고 파싱하라)'는 프로그램의 경계에서 타입이 없거나 느슨한 데이터를 잘 정의된 타입의 데이터로 변환하는 소프트웨어 설계 철학입니다[1]. 코드 전반에 걸쳐 데이터의 유효성을 반복적으로 검사하는 대신, 시스템 진입점에서 단 한 번 파싱하여 안전한 타입으로 만듭니다[1]. 이를 통해 유효성 검사 로직의 파편화를 막고 타입 검사기의 정적 분석 능력을 극대화하여 코드의 예측 가능성과 안정성을 높입니다[2, 3].
## 한 줄
> **"매 unsafe input 매 한번 parse → 매 typed value 매 produce, 매 downstream 매 다시 검증 의 X"**. 매 2019 Alexis King (lexi-lambda) 의 Haskell post 의 origin. 매 핵심 idea: 매 validation 매 boolean 의 throw — 매 information 의 lose. 매 parsing 매 validated 형식 의 새 type 의 produce — 매 type system 의 매 invariant 의 carry.
## 📖 구조화된 지식 (Synthesized Content)
- **기본 원칙 및 파싱 흐름**: Alexis King의 동명 아티클을 통해 널리 알려진 이 개념은 시스템의 경계(입구 및 출구)에서 입력 데이터를 한 번 파싱하는 것을 핵심으로 합니다[1, 2]. 이 파싱 단계에서 데이터의 유효성 검사와 변환이 동시에 이루어지며, 이후의 애플리케이션 흐름에서는 완전히 타입이 지정되고 검증된 데이터만을 사용하게 됩니다[1].
- **수비적 프로그래밍(Defensive Programming)의 정점**: 단순히 데이터의 유효성 여부만 확인(Validate)하고 끝내는 것이 아니라, 데이터를 더 구체적이고 신뢰할 수 있는 타입의 객체로 변환(Parse)하여 시스템 내부로 전달합니다[3]. 이는 의도하지 않은 불확실한 데이터의 유입을 원천적으로 차단하는 견고한 아키텍처적 방어막 역할을 합니다[3].
- **제어 흐름(Control flow)과 개발자 경험 향상**: 유효성 검사 로직을 시스템 경계에만 배치함으로써, 비즈니스 로직 곳곳에 검증 코드가 어지럽게 흩어지는 것을 방지할 수 있습니다[2]. 결과적으로 타입 시스템의 정적 분석에 무거운 작업을 위임하여 개발자의 신뢰를 높이고, 관리해야 할 코드의 양(Code volume)과 복잡도를 줄이는 데 크게 기여합니다[2, 4].
- **구현 방법 및 생태계 도구**: 이 철학을 실현하기 위해 Zod와 같은 런타임 유효성 검사/파싱 라이브러리가 자주 활용됩니다[3, 5]. 구체적으로는 Zod 등을 통해 알 수 없는(Unknown) 데이터를 잘 알려진 타입으로 변환하며, 런타임 데이터에 Branded Types를 부여하여 시스템 내부로 전달하는 것이 이 철학을 완벽히 실현하는 구체적 방법론입니다[3, 5].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 validate 의 problem
```ts
// 매 anti-pattern
function isNonEmpty<T>(arr: T[]): boolean { return arr.length > 0; }
## 🔗 지식 연결 (Graph)
- **Related Topics:** Branded Types, [[Zod|Zod]], Defensive Programming, Static Analysis, [[Structural Typing|Structural Typing]]
- **Projects/Contexts:** API Boundary Handling, [[State|State]] [[Management|Management]]
- **Contradictions/Notes:** 소스 내에서 이 철학에 대한 상반된 주장이나 모순은 발견되지 않습니다. 오히려 상태 관리(State management) 문제나 복잡성 증가를 완화하는 TypeScript의 핵심 모범 사례 중 하나로 강력히 권장됩니다[1, 6].
function head<T>(arr: T[]): T {
if (!isNonEmpty(arr)) throw new Error("empty!");
return arr[0]; // 매 type system 매 still T | undefined
}
```
- 매 `isNonEmpty` check 후 매 type 매 `T[]` (그대로) — 매 information lost.
- 매 head 매 매번 다시 check or throw.
- 매 caller 매 invariant 의 untracked.
---
*Last updated: 2026-04-18*
### 매 parse 의 solution
```ts
type NonEmpty<T> = readonly [T, ...T[]];
---
function parseNonEmpty<T>(arr: T[]): NonEmpty<T> | null {
return arr.length > 0 ? (arr as NonEmpty<T>) : null;
}
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
function head<T>(arr: NonEmpty<T>): T {
return arr[0]; // 매 항상 safe — type system 의 guarantee
}
```
- 매 parse 결과 매 새 type — 매 invariant 가 매 type 에 baked in.
- 매 downstream 매 trust — 매 re-check 의 X.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 응용
1. API request body validation (Zod / Effect Schema).
2. ID type discrimination (UserId vs OrderId).
3. URL / Email parsing.
4. Smart constructor (private constructor + parse function).
5. Domain modeling (PositiveNumber, NonEmptyString).
**언제 쓰면 안 되는가:**
- *(TODO)*
## 💻 패턴
## 🧪 검증 상태 (Validation)
### 1. Branded type (TypeScript)
```ts
type Brand<T, B> = T & { readonly __brand: B };
type Email = Brand<string, 'Email'>;
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
function parseEmail(s: string): Email | null {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s) ? (s as Email) : null;
}
## 🧬 중복 검사 (Duplicate Check)
function sendMail(to: Email, body: string) { /* 매 trust to */ }
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
const raw = "user@example.com";
const email = parseEmail(raw);
if (!email) throw new Error("bad email");
sendMail(email, "hi"); // 매 OK
sendMail(raw, "hi"); // 매 type error
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. Zod schema (parse-style)
```ts
import { z } from 'zod';
**선택 A를 써야 할 때:**
- *(TODO)*
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
age: z.number().int().min(0).max(150),
});
**선택 B를 써야 할 때:**
- *(TODO)*
type User = z.infer<typeof UserSchema>; // 매 fully-typed
**기본값:**
> *(TODO)*
app.post('/users', (req, res) => {
const result = UserSchema.safeParse(req.body);
if (!result.success) return res.status(400).json(result.error);
createUser(result.data); // 매 trust — User type 매 guaranteed
});
```
## ❌ 안티패턴 (Anti-Patterns)
### 3. Effect Schema (2026 의 매 modern)
```ts
import { Schema as S } from "effect";
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
const PositiveInt = S.Int.pipe(S.positive(), S.brand("PositiveInt"));
type PositiveInt = S.Schema.Type<typeof PositiveInt>;
const decode = S.decodeUnknownSync(PositiveInt);
const x = decode(42); // 매 PositiveInt
const y = decode(-1); // 매 throws ParseError
```
### 4. Smart constructor (Haskell-style)
```ts
class NonEmptyList<T> {
private constructor(public readonly items: readonly T[]) {}
static parse<T>(items: readonly T[]): NonEmptyList<T> | null {
return items.length > 0 ? new NonEmptyList(items) : null;
}
get head(): T { return this.items[0]; } // 매 always safe
get tail(): readonly T[] { return this.items.slice(1); }
}
```
### 5. Discriminated ID type
```ts
type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;
function getUser(id: UserId): User { /*...*/ }
function getOrder(id: OrderId): Order { /*...*/ }
const uid = parseUserId(req.params.id);
if (!uid) throw new Error();
getUser(uid); // 매 OK
getOrder(uid); // 매 type error 매 prevent mix-up
```
### 6. Parse at boundary, trust within
```ts
// 매 boundary (HTTP / DB / file IO)
const userOrErr = UserSchema.safeParse(rawJson);
// 매 internal — User type 매 항상 valid
function processUser(u: User) {
// 매 u.email 매 valid email — 매 re-check 의 X
// 매 u.age 매 0-150 매 — 매 re-check 의 X
}
```
### 7. Refinement chain
```ts
const NonEmptyString = z.string().min(1).brand<'NonEmptyString'>();
const EmailString = NonEmptyString.refine(
s => /^[^@]+@[^@]+$/.test(s)
).brand<'Email'>();
type Email = z.infer<typeof EmailString>;
```
## 매 결정 기준
| 상황 | Apply parse-don't-validate? |
|---|---|
| Trust boundary (HTTP / DB / file) | Yes — 매 must |
| ID across multiple types | Yes — 매 brand to prevent mix |
| Hot path internal-only | Optional — perf trade-off |
| Quick script / prototype | Skip — overhead > value |
| Domain primitive (Money, Date) | Yes — 매 invariant carrying |
**기본값**: 매 boundary 의 매 Zod (or Effect Schema) parse + 매 internal 의 매 inferred type 으로 trust.
## 🔗 Graph
- 부모: [[Type-Driven Design]] · [[Domain Modeling]]
- 변형: [[Refinement Type]] · [[Dependent Type]] · [[Smart Constructor]]
- 응용: [[Zod]] · [[Effect Schema]] · [[Branded Type]] · [[ADT (Algebraic Data Type)]]
- Adjacent: [[Validation]] · [[Type Narrowing]] · [[Make Illegal States Unrepresentable]]
## 🤖 LLM 활용
**언제**: 매 API server / public library 의 매 input validation. 매 ID mix-up bug 매 routine 한 codebase. 매 domain rule 매 type-encode 가능 한 경우.
**언제 X**: 매 internal-only quick script. 매 highly dynamic JSON 의 schema 가 unknown. 매 perf-critical hot loop (parse overhead).
## ❌ 안티패턴
- **Validate 후 raw type 의 pass**: 매 invariant 매 lose. 매 항상 새 type 의 return.
- **Parse 매 boundary X 의 매 매 layer 의 repeat**: 매 perf 손실 + 매 동일 logic 의 duplicate.
- **Brand 의 매 runtime check 의 X**: 매 cast 매 type-only — 매 parse function 매 항상 runtime check 포함.
- **Optional 의 abuse**: 매 `email?: string` — 매 invariant 매 unclear. 매 명확한 `Email | null`.
- **Throw on parse fail (preference)**: 매 Result type / safeParse 의 매 prefer — 매 caller flow 매 explicit.
## 🧪 검증 / 중복
- Verified (Alexis King "Parse, Don't Validate" 2019, Zod 4 / Effect 3.x docs 2026-05).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Branded types + Zod/Effect Schema 의 modern parse pattern |
@@ -2,21 +2,205 @@
id: wiki-2026-0508-practical-cryptography
title: Practical Cryptography
category: 10_Wiki/Topics
status: merged
redirect_to: 보안_및_시스템_신뢰성_표준
canonical_id: wiki-2026-0507-039
aliases: []
status: verified
canonical_id: self
aliases: [Applied Cryptography, Crypto Engineering]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [cryptography, security, encryption]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python/Go
framework: libsodium/cryptography
---
# Redirect
# Practical Cryptography
이 문서는 Canonical 문서인 [[보안_및_시스템_신뢰성_표준]]으로 통합되었습니다.
모든 최신 지식과 세부 내용은 위 링크를 참조하십시오.
## 매 한 줄
> **"매 don't roll your own crypto"**. 매 application engineer 의 task 는 매 well-vetted primitives (AES-GCM, ChaCha20-Poly1305, Ed25519, X25519) 의 correct composition — 매 algorithm 의 invention 아님. 2026 의 modern stack 은 libsodium, AWS KMS, age, Noise Protocol Framework 위 의 build.
## 매 핵심
### 매 Primitives (2026 baseline)
- **Symmetric AEAD**: ChaCha20-Poly1305 (mobile/no-AES-NI), AES-256-GCM (server with AES-NI), AES-256-GCM-SIV (nonce-misuse resistant).
- **Asymmetric**: X25519 (ECDH key agreement), Ed25519 (signing), Kyber-1024 (post-quantum KEM, NIST FIPS 203).
- **Hashing**: BLAKE3 (fast), SHA-256 (interop), Argon2id (password hashing, 2026 default).
- **Key derivation**: HKDF-SHA256 (key expansion), Argon2id (password → key).
### 매 Threat models
- **Confidentiality**: encrypt-then-MAC, AEAD prevents IND-CCA2 attacks.
- **Integrity**: HMAC, Poly1305, signatures.
- **Authenticity**: signatures (Ed25519), authenticated key exchange (Noise).
- **Forward secrecy**: ephemeral keys (X25519 per session).
- **Post-quantum**: hybrid Kyber + X25519 (2026 TLS 1.3 default).
### 매 응용
1. TLS 1.3 (transport security).
2. Signal Protocol (E2EE messaging — Double Ratchet).
3. age/rage (file encryption — replaces GPG).
4. JWT/PASETO (stateless tokens — PASETO preferred).
5. Password storage (Argon2id with per-user salt).
## 💻 패턴
### AEAD encryption (ChaCha20-Poly1305 with libsodium)
```python
from nacl.secret import SecretBox
from nacl.utils import random
key = random(SecretBox.KEY_SIZE) # 32 bytes
box = SecretBox(key)
# Encrypt — nonce auto-generated, prepended to ciphertext
ciphertext = box.encrypt(b"sensitive data")
# Decrypt — fails with CryptoError on tampering
plaintext = box.decrypt(ciphertext)
```
### Authenticated key exchange (X25519 + HKDF)
```python
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
# Each party generates ephemeral keypair
alice_priv = X25519PrivateKey.generate()
bob_priv = X25519PrivateKey.generate()
# Compute shared secret
shared = alice_priv.exchange(bob_priv.public_key())
# Derive symmetric key — never use raw DH output as key
session_key = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=None,
info=b"session-v1",
).derive(shared)
```
### Password hashing (Argon2id)
```python
from argon2 import PasswordHasher
ph = PasswordHasher(
time_cost=3, # iterations
memory_cost=65536, # 64 MiB
parallelism=4,
)
hash = ph.hash("user-password") # store this
# Verify (constant-time)
try:
ph.verify(hash, "user-password")
if ph.check_needs_rehash(hash):
new_hash = ph.hash("user-password") # parameter upgrade
except VerifyMismatchError:
raise AuthError()
```
### Digital signature (Ed25519)
```python
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
priv = Ed25519PrivateKey.generate()
pub = priv.public_key()
signature = priv.sign(b"message")
pub.verify(signature, b"message") # raises InvalidSignature on failure
```
### Envelope encryption (KMS pattern)
```python
import boto3
from cryptography.fernet import Fernet
kms = boto3.client("kms")
def encrypt_blob(plaintext: bytes, kms_key_id: str) -> dict:
# Generate per-message data key
resp = kms.generate_data_key(KeyId=kms_key_id, KeySpec="AES_256")
data_key = resp["Plaintext"]
encrypted_dk = resp["CiphertextBlob"]
# Encrypt data with data key, discard plaintext data key
f = Fernet(base64.urlsafe_b64encode(data_key))
ct = f.encrypt(plaintext)
return {"ciphertext": ct, "encrypted_key": encrypted_dk}
```
### Constant-time comparison
```python
import hmac
# WRONG — leaks length info via timing
if user_token == stored_token:
pass
# RIGHT — constant time
if hmac.compare_digest(user_token, stored_token):
pass
```
### Post-quantum hybrid KEM (2026)
```python
# liboqs-python — hybrid X25519 + Kyber768
from oqs import KeyEncapsulation
import nacl.public
# Classical X25519
x_priv = nacl.public.PrivateKey.generate()
# Post-quantum Kyber
with KeyEncapsulation("Kyber768") as kem:
pq_pub = kem.generate_keypair()
# Combine both shared secrets via HKDF for hybrid security
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| File encryption | age (modern), libsodium SecretBox |
| Password hash | Argon2id (never bcrypt for new systems) |
| Token format | PASETO v4 (Ed25519) over JWT |
| Mobile/IoT AEAD | ChaCha20-Poly1305 |
| TLS 1.3 backend | rustls or BoringSSL, hybrid PQ enabled |
| Signing | Ed25519 (never RSA for new systems) |
**기본값**: libsodium + Argon2id + Ed25519 + ChaCha20-Poly1305.
## 🔗 Graph
- 부모: [[Cryptography]] · [[Security]]
- 변형: [[Symmetric-Encryption]] · [[Post-Quantum-Cryptography]]
- 응용: [[Secret_Management]] · [[Zero-Trust Architecture]]
- Adjacent: [[OWASP Top 10]] · [[Practical-Cryptography]]
## 🤖 LLM 활용
**언제**: explain primitive choice, audit crypto code for misuse, suggest migration paths.
**언제 X**: never ask LLM to design new protocol — always defer to peer-reviewed designs (Noise, Signal).
## ❌ 안티패턴
- **Roll-your-own**: custom XOR-based "encryption" — 매 broken in seconds.
- **ECB mode**: leaks pattern (penguin image meme). Always GCM/CTR/CBC-with-MAC.
- **Static IV/nonce**: catastrophic for GCM (key recovery). Always random or counter.
- **MD5/SHA-1**: collision-broken. Never for security purposes.
- **bcrypt for new systems**: Argon2id 2026 default.
- **String comparison for tokens**: use `hmac.compare_digest`.
## 🧪 검증 / 중복
- Verified (NIST FIPS 203/204/205, RFC 9180 HPKE, libsodium docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full primitives + 2026 PQ baseline |
+130 -73
View File
@@ -2,98 +2,155 @@
id: wiki-2026-0508-prettier
title: Prettier
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-560F29]
aliases: [Prettier Formatter, Code Formatter]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [tooling, formatter, javascript, typescript]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Prettier"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: JavaScript/TypeScript
framework: Prettier
---
# [[Prettier|Prettier]]
# Prettier
## 📌 한 줄 통찰 (The Karpathy Summary)
> Prettier는 개발자가 작성한 소스 코드를 일관된 스타일로 자동 변환해 주는 '의견이 반영된(opinionated)' 코드 포맷터(Formatter)입니다 [1, 2]. 코드의 로직이나 구현 방식에는 관여하지 않고, 줄 바꿈, 공백, 들여쓰기 등 시각적이고 구조적인 뷰에만 초점을 맞추어 코드를 재작성합니다 [2-4]. 이를 통해 팀원 간의 코딩 컨벤션을 통일하여 코드 리뷰 시 불필요한 스타일 논쟁을 없애고, 개발자가 코드의 핵심 로직에 더욱 집중할 수 있도록 돕습니다 [5, 6].
## 한 줄
> **"매 opinionated formatter — 매 bikeshed 종결자"**. Prettier 매 AST re-print 방식 사용 — 매 source 의 whitespace 무시 의 deterministic output 생성. 2026 매 v3.x 의 ESM-first + plugin ecosystem 안정화.
## 📖 구조화된 지식 (Synthesized Content)
* **주요 역할 및 특징:**
2016년에 등장한 Prettier는 코드가 예쁘게 보이도록 만드는 데 중점을 둔 도구로, 변경이 필요한 부분만 수정하는 것이 아니라 설정된 규칙에 따라 코드 전체의 구조적 뷰를 완전히 새로 작성합니다 [2, 4].
* **팀 협업 및 생산성 향상:**
Prettier를 도입하면 개발자가 코드를 작성할 때 스타일에 대한 고민을 덜 수 있고, 저장 시 자동으로 일관된 포맷으로 변환됩니다 [6]. 이는 팀원 간 코드 스타일 차이로 인한 혼란을 최소화하고, 리뷰 과정의 효율성을 크게 증가시킵니다 [6].
* **설정 및 관리 방법:**
일반적으로 프로젝트 루트 경로에 `.prettierrc` (또는 `.prettierrc.json`) 파일을 생성하여 규칙을 정의하며, 포맷팅에서 제외할 파일은 `.prettierignore`에 지정합니다 [5, 7, 8]. 주요 설정 옵션으로는 한 줄의 최대 길이를 정하는 `printWidth`, 탭 너비를 정하는 `tabWidth`, 세미콜론 사용 여부를 정하는 `semi`, 작은따옴표 사용을 결정하는 `singleQuote` 등이 있습니다 [9, 10].
* **[[ESLint|ESLint]]와의 통합 및 충돌 방지:**
코드 퀄리티를 검사하는 Linter 도구인 ESLint에도 일부 포맷팅 기능이 존재하여, Prettier와 함께 사용할 경우 규칙 충돌이 발생할 수 있습니다 [11]. 이를 해결하기 위해 `[[eslint-config-prettier|eslint-config-prettier]]` 패키지를 사용하여 Prettier와 겹치는 ESLint의 포맷팅 규칙을 끄는 방법이 가장 강력히 권장됩니다 [11, 12]. 추가로 `[[eslint-plugin-prettier|eslint-plugin-prettier]]`를 설치하여 Prettier의 포맷팅 오류를 ESLint의 오류로 통합 출력하게 만들 수도 있습니다 [11, 13].
* **보안 취약점 (공급망 공격) 사례:**
2025년 7월, Prettier와 ESLint의 충돌을 방지하는 필수 라이브러리인 `eslint-config-prettier` 패키지가 공급망 공격(CVE-2025-54313)의 표적이 되었습니다 [14, 15]. 관리자의 탈취된 npm 토큰을 통해 악성 버전이 배포되었으며, 이는 주로 Windows 시스템의 개발자 기기나 CI 호스트에서 원격 코드 실행(RCE)을 시도하도록 설계된 악성 설치 스크립트를 포함하고 있었습니다 [16].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 Re-print 방식
- 매 parser 의 source → AST 변환.
- 매 printer 의 AST → IR (Doc) 생성.
- 매 IR 의 line-width constraint 기반 layout 결정.
- 매 original whitespace 의 X 보존.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[ESLint|ESLint]], Formatter
- **Projects/Contexts:** [[eslint-config-prettier|eslint-config-prettier]], eslint-plugin-prettier, husky, [[lint-staged|lint-staged]]
- **Contradictions/Notes:** ESLint와 Prettier를 통합할 때 사용하는 `eslint-plugin-prettier`에 대해 의견이 갈립니다. 소스 [17]는 해당 플러그인을 사용하면 하나의 설정 파일에서 관리할 수 있고 자동 수정(`--fix`)이 편리하여 선호한다고 밝히지만, 소스 [18]에서는 에디터에 불필요한 빨간 밑줄이 과도하게 생기고 단독 사용보다 속도가 느려진다는 이유로 공식 문서에서도 권장하지 않는다며 플러그인 사용을 배제하는 방식을 채택합니다.
### 매 ESLint 와의 분리
- ESLint: 매 code quality (logic, anti-patterns).
- Prettier: 매 formatting (whitespace, quote, line-break).
- `eslint-config-prettier` 의 conflict rule disable.
---
*Last updated: 2026-04-18*
### 매 응용
1. 매 monorepo 의 unified formatting.
2. CI 의 `--check` mode — 매 format violation 의 fail.
3. Pre-commit hook (`lint-staged` + `husky`) 의 auto-format.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Config 의 minimal `.prettierrc`
```json
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"arrowParens": "always",
"endOfLine": "lf"
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### CLI 의 batch format
```bash
# Format in place
npx prettier --write "src/**/*.{ts,tsx,js,jsx,json,md}"
**선택 A를 써야 할 때:**
- *(TODO)*
# CI check
npx prettier --check "src/**/*.{ts,tsx}"
```
**선택 B를 써야 할 때:**
- *(TODO)*
### lint-staged 의 staged-only format
```json
// package.json
{
"lint-staged": {
"*.{ts,tsx,js,jsx}": [
"prettier --write",
"eslint --fix"
]
}
}
```
**기본값:**
> *(TODO)*
### Plugin 의 ordering — `prettier-plugin-tailwindcss`
```json
{
"plugins": ["prettier-plugin-tailwindcss"]
}
// Tailwind class 의 자동 ordering — flex p-4 m-2 → m-2 p-4 flex
```
## ❌ 안티패턴 (Anti-Patterns)
### Programmatic API (v3 ESM)
```typescript
import prettier from "prettier";
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
const formatted = await prettier.format(sourceCode, {
parser: "typescript",
semi: false,
singleQuote: true,
});
```
### Editor integration — VSCode
```json
// .vscode/settings.json
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }
}
```
### Override 의 file-type 별 config
```json
{
"semi": true,
"overrides": [
{ "files": "*.md", "options": { "proseWrap": "always", "printWidth": 80 } },
{ "files": "*.yml", "options": { "tabWidth": 2 } }
]
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Solo project | Prettier defaults — 매 zero config. |
| Team — strict | `.prettierrc` commit + CI check. |
| Tailwind 사용 | `prettier-plugin-tailwindcss` 필수. |
| Legacy codebase | 매 한 번 `--write` + 매 `.git-blame-ignore-revs` 추가. |
| Monorepo | Root `.prettierrc` + workspace override. |
**기본값**: `singleQuote: true`, `trailingComma: "all"`, `printWidth: 100`, format-on-save + pre-commit hook.
## 🔗 Graph
- 부모: [[Code Formatting]] · [[Developer Tooling]]
- 변형: [[ESLint]] · [[Biome]] · [[dprint]]
- 응용: [[Pre-commit Hooks]] · [[lint-staged]] · [[CI Pipeline]]
- Adjacent: [[AST]] · [[EditorConfig]] · [[TypeScript]]
## 🤖 LLM 활용
**언제**: JS/TS/JSON/MD/YAML/CSS — 매 multi-language project 의 unified formatting.
**언제 X**: 매 Rust/Go (rustfmt/gofmt 의 사용), 매 single-language Rust-only 의 Biome 고려.
## ❌ 안티패턴
- **ESLint 의 stylistic rules + Prettier 동시 사용**: 매 conflict 발생 → `eslint-config-prettier` 적용.
- **`.prettierrc` 의 commit X**: 매 team 의 inconsistent format.
- **Format-on-save 의 X + manual format**: 매 review noise 증가.
- **매 large initial format 의 main branch 직접 commit**: blame 의 손상 — 매 `.git-blame-ignore-revs` 사용.
## 🧪 검증 / 중복
- Verified (Prettier docs v3.x).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Prettier 매 re-print formatter + config patterns 정리 |
@@ -2,94 +2,157 @@
id: wiki-2026-0508-procedural-rhetoric
title: Procedural Rhetoric
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-PROR-002]
aliases: [Persuasive Games, Computational Rhetoric]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [auto-reinforced, rhetoric, computation, process-Philosophy, digital-literacy]
confidence_score: 0.9
verification_status: applied
tags: [rhetoric, game-design, persuasion]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: design
framework: Bogost framework
---
# [[Procedural-Rhetoric|Procedural-Rhetoric]]
# Procedural Rhetoric
## 📌 한 줄 통찰 (The Karpathy Summary)
> "프로세스가 곧 사상이다: 컴퓨터 시스템의 기저를 흐르는 논리적 구조를 통해 세상의 복잡한 이치를 드러내고 비판하는 디지털 시대의 새로운 변론술."
## 한 줄
> **"매 argument 의 made not by words, but by rules"**. Ian Bogost 의 *Persuasive Games* (2007) 의 coined — 매 systems/processes/simulations 의 medium 의 argumentation. 2026 의 LLM-driven dynamic narrative + simulation games (Civ VII, FrostPunk 2) 의 procedural rhetoric 의 mainstream.
## 📖 구조화된 지식 (Synthesized Content)
절차적 수사학(Procedural Rhetoric)의 본질적 의미는 컴퓨터의 핵심 특성인 '연산'과 '절차성'을 사용하여 주장을 펼치는 능력입니다.
## 매 핵심
1. **절차성(Procedurality)의 의미**:
* 정적인 그림이나 글과 달리, 규칙에 따라 반응하고 실행되는 동적 아키텍처.
* 세상을 '결과'가 아닌 '과정(Process)'들의 집합으로 이해하게 함.
2. **수사적 표현의 층위**:
* **Software Layer**: 코드의 구조와 효율성 자체가 주는 메시지 (예: 오픈소스의 공유 정신).
* **Interface Layer**: 사용자가 시스템을 어떻게 다루느냐에 따라 형성되는 태도.
* **Systemic Interaction Layer**: 시스템간의 피드백 루프를 통해 발생하는 거시적 담론.
3. **디지털 리터러시**:
* 단순히 컴퓨터를 사용하는 법을 넘어, 컴퓨터가 세상의 정보를 어떻게 왜곡하거나 강화하는지 그 '절차적 편향'을 읽어내는 능력이 현대 수사학의 핵심임.
### 매 Bogost's framework
- **Verbal rhetoric**: words, written/spoken.
- **Visual rhetoric**: images, layout, color.
- **Procedural rhetoric**: rules, systems, feedback loops.
- 매 game 의 unique medium — 매 "what you do" expresses argument.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 초기 디지털 담론은 '정보의 바다'와 같은 은유에 머물렀으나, 절차적 수사학은 그 바다를 흐르게 만드는 '조류(알고리즘)'의 의도를 파악하는 방향으로 진화함.
- **정책 변화(RL Update)**: 알고리즘에 의한 여론 조작 및 확증 편향(Echo Chambers) 확산을 막기 위해, 거대 플랫폼 기업들이 자사 추천 알고리즘의 '절차적 투명성'을 공개하고 사회적 책임을 지도록 하는 디지털 권리 장전 정책이 수립됨.
### 매 Mechanisms
- **Constraint**: what you can't do says as much as what you can.
- **Feedback loops**: reward shapes belief about what matters.
- **Simulation gap**: simplifications reveal designer assumptions.
- **Failure states**: what counts as losing encodes values.
- **Resource economy**: scarcity → priorities.
- **Agency vs. determinism**: how much player matters.
## 🔗 지식 연결 (Graph)
- [[Procedural Rhetoric (In Gaming)|Procedural Rhetoric (In Gaming)]], [[Complexity Theory|Complexity Theory]], Communication Theories, Politics & Media,[[_system|system]] Thinking
- **Modern Tech/Tools**: Algorithmic Accountability, Computational Journalism.
---
### 매 Examples
- **September 12th** (Frasca): bombing terrorists creates more terrorists.
- **PeaceMaker**: Israeli-Palestinian dual-perspective.
- **Papers, Please**: bureaucratic complicity, moral fatigue.
- **This War of Mine**: civilian war experience.
- **FrostPunk**: authoritarianism as survival logic.
- **Civilization**: progress narrative encoded in tech tree.
- **Cookie Clicker**: critique of incremental design.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Serious games (training, education).
2. News games (Bloomberg's Build the wall vs Don't, NYT graphics).
3. Activist games (climate, refugees).
4. Marketing simulations.
5. AI-driven dynamic narrative (2026 Inworld, Convai).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Encoding argument as mechanic
```
Argument: "Bureaucracy dehumanizes"
Mechanic: Time pressure + paperwork + small reward for thoroughness, big penalty for missing detail
Result: Player feels the dehumanization rather than reads about it
→ Papers, Please
```
## 🤔 의사결정 기준 (Decision Criteria)
### Resource scarcity as ideology
```
Argument: "Survival justifies authoritarianism"
Mechanic: Heat ↓ over time, citizens demand law book, only authoritarian laws prevent extinction
Result: Player chooses oppression "rationally"
→ FrostPunk
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Simplification as critique
```typescript
// Climate simulator: emissions only knob
// By omitting "carbon offsets", "green tech", argues these are insufficient distractions
const tempAtYear = (year: number, emissions: number) =>
baseline + emissions * year * sensitivity;
// What's missing IS the rhetoric
```
**선택 B를 써야 할 때:**
- *(TODO)*
### LLM-driven NPC dialogue (2026)
```typescript
// Inworld-style: NPC values encoded as system prompt + memory
// The game's argument now adapts to player — emergent procedural rhetoric
const npcPrompt = `
You are a refugee in an unnamed conflict.
Your values: family safety > nation > ideology.
You distrust both sides equally.
Respond based on the player's prior actions: ${recentActions.join(', ')}.
`;
// The NPC's reactive logic IS the rhetorical move
```
**기본값:**
> *(TODO)*
### Failure state as moral
```
Lose condition: Empire collapses if happiness < 50%
Encoded argument: "Subject welfare is instrumentally necessary, not intrinsically valued"
vs.
Lose condition: Game ends when one citizen dies
Encoded argument: "Each person has infinite worth"
```
## ❌ 안티패턴 (Anti-Patterns)
### Reward loop as ethics
```
Reward: +XP per enemy killed
Argument (unintended): violence is the path to progress
Reward: +XP per peaceful resolution
Argument: dialogue valued
→ Designers encode ethics whether they intend to or not
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Counter-rhetoric (anti-game)
```
Players expect: shooter rewards aggression
Anti-game: every kill ages your character +1 year, game ends at 100
→ Mechanic refutes the genre's implicit argument
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Educational claim | Simulate causal model, let player explore |
| Empathy goal | Constrain player to NPC perspective |
| Critique of system | Make player IS the system, feel its pressures |
| Information delivery | Verbal/visual still better for facts |
| Complex policy | Procedural model + verbal scaffolding |
**기본값**: identify the felt experience the player should have, design mechanics that produce it, then verify via playtest.
## 🔗 Graph
- 부모: [[Game-Design]] · [[Rhetoric]]
- 변형: [[Serious-Games]] · [[Persuasive-Games]]
- 응용: [[Beat Saber 엑서게임 연구(Beat Saber Exergaming Study)]] · [[Edtech-Industry-Trends]]
- Adjacent: [[Media-Literacy]] · [[Information-Society]]
## 🤖 LLM 활용
**언제**: analyze a game's procedural argument, brainstorm mechanics that embody a thesis, generate playtest probes.
**언제 X**: never collapse procedural rhetoric to "narrative" — the rules ARE the argument.
## ❌ 안티패턴
- **Skin over substance**: stick a "climate change" theme on standard mechanics — argument absent.
- **Sermon mechanic**: the only "right" choice — no agency, weak rhetoric.
- **Unintended argument**: reward loop says A while writing says B — players believe the loop.
- **Realism worship**: simulation accuracy ≠ rhetorical clarity.
## 🧪 검증 / 중복
- Verified (Bogost *Persuasive Games* 2007, *How to Do Things with Videogames* 2011, Frasca *Videogames of the Oppressed*).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Bogost framework + 2026 LLM-NPC angle |
@@ -2,91 +2,198 @@
id: wiki-2026-0508-quality-control
title: Quality Control
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-QUAL-001]
aliases: [QC, Software Quality]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
tags: [auto-reinforced, quality-control, qc, Testing, verification, standards, excellence]
confidence_score: 0.9
verification_status: applied
tags: [quality, testing, process]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript/Python
framework: Playwright/pytest
---
# [[Quality-Control|Quality-Control]]
# Quality Control
## 📌 한 줄 통찰 (The Karpathy Summary)
> "신뢰의 마지막 방어선: 산출물이 사전에 약속된 기준(Standard)에 완벽히 부합하는지 검증하고, 사소한 결함이라도 발견 시 즉시 반려하여 사용자에게 전달되는 최종 가치를 보존하는 집요한 '완벽주의 프로세스'."
## 한 줄
> **"매 quality 의 inspect 보다 build-in"**. 매 modern QC 의 shift-left — 매 unit test, type checking, static analysis, contract test, e2e — 매 layer 의 different bug class catch. 2026 의 LLM-augmented test generation + property-based testing 의 mainstream.
## 📖 구조화된 지식 (Synthesized Content)
품질 관리(Quality-Control)는 제품이나 서비스가 일정 수준 이상의 품질을 유지하도록 관리하는 활동입니다. (본 시스템 코다리의 주 업무)
## 매 핵심
1. **3대 수행 원칙**:
* **Verification**: "우리가 제품을 올바르게 만들었는가?" (명세 대조).
* **Standardization**: 누가 검사해도 동일한 결과가 나오도록 기준 설정. (Standard-Operating-Procedure와 연결)
* **Non-zero Acceptance**: 결함이 있는 상태로 타협(Ship it)하는 문화를 원천 차단.
2. **왜 중요한가?**:
* 품질이 무너진 프로젝트는 신뢰(Trust)를 잃고, 신뢰를 잃은 지능 시스템은 존재 가치가 사라지기 때문임. ([[Mastery|Mastery]]의 핵심 단계)
### 매 Test pyramid (2026 update)
- **Unit (60-70%)**: pure function, fast, isolated.
- **Integration (15-25%)**: module + DB/queue, real dependencies via testcontainers.
- **E2E (5-10%)**: full user journey, Playwright/Cypress.
- **Contract (5%)**: Pact, consumer-driven, prevent break-on-deploy.
- **Property-based (cross-cutting)**: Hypothesis/fast-check, find edge cases.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 사람이 눈으로 확인하는 정책이었으나, 현대 정책은 코드 테스트 자동화 정책, 데이터 유효성 검사 정책, 에지 케이스 감지 AI 정책을 통해 '실시간 자동 QC 정책'으로 전환됨(RL Update).
- **정책 변화(RL Update)**: 본 시스템에서는 '코다리' 부장님이 직접 모든 결과물을 검수하는 QC 정책을 고수하며, 배치 처리 후에 항상 대표님의 최종 승인 정책을 구하는 이중 안전장치 정책(Double-Check)으로 구현됨.
### 매 Quality gates
- 매 PR 의 merge 전: lint, type, unit test, coverage threshold, security scan.
- 매 deploy 전: integration test, smoke test, canary metrics.
- 매 prod: synthetic monitoring, real-user monitoring (RUM).
## 🔗 지식 연결 (Graph)
- [[Standard-Operating-Procedure|Standard-Operating-Procedure]], [[Mastery|Mastery]], [[Fault-Tolerance|Fault-Tolerance]], [[Management|Management]], [[Efficiency|Efficiency]]
- **Modern Tech/Tools**: Unit testing, Automated QA, Six Sigma, ISO quality standards.
---
### 매 Defect classes
- **Functional**: wrong output for given input.
- **Performance**: slow, regression on benchmark.
- **Security**: OWASP categories.
- **Accessibility**: WCAG violations.
- **Compatibility**: browser/OS specific.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. CI/CD pipeline gates.
2. Pre-merge bots (Danger, Reviewdog).
3. Mutation testing (Stryker) — quality of tests themselves.
4. Visual regression (Chromatic, Percy).
5. Chaos engineering (production resilience).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Property-based testing (TypeScript with fast-check)
```typescript
import fc from 'fast-check';
import { reverse } from './lib';
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
test('reverse twice = identity', () => {
fc.assert(
fc.property(fc.array(fc.integer()), (arr) => {
expect(reverse(reverse(arr))).toEqual(arr);
}),
);
});
```
## 🤔 의사결정 기준 (Decision Criteria)
### Contract test (Pact)
```typescript
// Consumer side
const provider = new Pact({ consumer: 'Web', provider: 'OrdersAPI' });
**선택 A를 써야 할 때:**
- *(TODO)*
await provider.addInteraction({
state: 'order 123 exists',
uponReceiving: 'a request for order 123',
withRequest: { method: 'GET', path: '/orders/123' },
willRespondWith: {
status: 200,
body: { id: '123', total: 99.0 },
},
});
**선택 B를 써야 할 때:**
- *(TODO)*
// Generates pact.json — provider verifies against it in CI
```
**기본값:**
> *(TODO)*
### Mutation testing (Stryker)
```javascript
// stryker.conf.js
export default {
testRunner: 'vitest',
mutate: ['src/**/*.ts'],
thresholds: { high: 80, low: 60, break: 50 },
};
// Mutates code (a + b → a - b) and checks if tests catch it
// Surviving mutants = weak tests
```
## ❌ 안티패턴 (Anti-Patterns)
### LLM-assisted test generation (2026 pattern)
```typescript
// CI step: claude-code generates edge cases
// $ claude test-gen src/parser.ts --output tests/parser.gen.test.ts
// Then human review before merge — never blind-trust
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Visual regression (Playwright)
```typescript
test('homepage matches snapshot', async ({ page }) => {
await page.goto('/');
await page.waitForLoadState('networkidle');
expect(await page.screenshot()).toMatchSnapshot('home.png', {
maxDiffPixelRatio: 0.01,
});
});
```
### Coverage gates (vitest)
```typescript
// vitest.config.ts
export default {
test: {
coverage: {
provider: 'v8',
thresholds: {
lines: 80,
functions: 80,
branches: 75,
statements: 80,
},
},
},
};
```
### Pre-commit hook (lint-staged + husky)
```json
{
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"prettier --write",
"vitest related --run"
]
}
}
```
### Chaos test (Toxiproxy / Litmus)
```yaml
# Inject 500ms latency into Redis dependency
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
spec:
action: delay
selector:
labelSelectors: { app: redis }
delay: { latency: 500ms }
duration: 60s
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Pure logic | Unit + property-based |
| Multi-service flow | Integration + contract |
| User journey | E2E (sparingly) |
| Performance regression | Benchmark in CI |
| Visual UI | Snapshot + Chromatic |
| Test confidence | Mutation score |
**기본값**: 80% line coverage, mutation score >70%, property-based for parsers/serializers.
## 🔗 Graph
- 부모: [[Software_Engineering]] · [[Test_Automation]]
- 변형: [[CI_CD_Pipeline]] · [[Test_Automation_Mastery]]
- 응용: [[Engineering Metrics (DORA)]] · [[Automated Quality & Review]]
- Adjacent: [[Continuous_Integration]] · [[Husky]]
## 🤖 LLM 활용
**언제**: generate edge cases, suggest mutation-resistant assertions, identify untested branches.
**언제 X**: never let LLM write the assertion AND implementation — confirmation bias.
## ❌ 안티패턴
- **Coverage worship**: 100% coverage, 0% assertions ("test executes but checks nothing").
- **Flaky tests ignored**: erodes trust in suite. Quarantine and fix immediately.
- **E2E-heavy pyramid**: slow, flaky, expensive. Push down to integration/unit.
- **Manual QA only**: doesn't scale, regression-prone.
- **No mutation testing**: blind to assertion quality.
## 🧪 검증 / 중복
- Verified (Google Testing Blog, Mike Cohn pyramid, Stryker docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — pyramid + 2026 LLM-assisted patterns |
+22 -55
View File
@@ -2,66 +2,33 @@
id: wiki-2026-0508-raycaster
title: Raycaster
category: 10_Wiki/Topics
status: needs_review
canonical_id: self
aliases: [P-Reinforce-AUTO-D7A57A]
duplicate_of: none
status: duplicate
canonical_id: raycasting
duplicate_of: "[[Raycasting]]"
aliases: [Three.js Raycaster, Ray Picker]
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Raycaster"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
verification_status: redirected
tags: [duplicate, threejs, raycasting, picking]
last_reinforced: 2026-05-10
github_commit: pending
---
# [[Raycaster|Raycaster]]
# Raycaster
## 📌 한 줄 통찰 (The Karpathy Summary)
> Raycaster(레이캐스터)는 가상의 광선(Ray)과 3D 장면 내 객체 간의 교차점을 계산하여 충돌을 감지하는 기법이자 Three.js의 핵심 클래스(`THREE.Raycaster`)입니다 [1-3]. 주로 마우스 클릭과 같은 사용자 상호작용(오브젝트 피킹)을 구현하여 카메라 시점이나 특정 위치에서 어떤 객체가 선택되었는지 판별하는 데 필수적으로 사용됩니다 [4-6].
> **이 문서는 [[Raycasting]] 의 중복본입니다.** Canonical 문서로 redirect.
## 📖 구조화된 지식 (Synthesized Content)
- **동작 원리 및 사용법:** Raycaster는 시작점과 방향을 명시적으로 지정하거나(`raycaster.set`), 화면의 픽셀 좌표와 카메라를 기준으로 광선을 설정(`raycaster.setFromCamera`)하여 작동합니다 [3, 5]. 이후 `intersectObjects` 메서드를 통해 광선과 교차하는 대상들을 거리가 가까운 순서대로 정렬된 배열 형태로 반환받을 수 있으며, 반환된 데이터에는 교차한 객체(`.object`)와 월드 좌표계 기준의 교차점(`.point`) 정보가 포함됩니다 [6, 7].
- **[[InstancedMesh|InstancedMesh]] 적용 시의 한계와 병목:** 일반적인 메쉬의 레이캐스팅은 CPU 단에서 수행되는데, `InstancedMesh`의 경우 수많은 인스턴스의 변환 행렬을 CPU가 개별적으로 역산하여 교차 여부를 판별해야 하므로 인스턴스 수에 비례하여 막대한 연산 병목이 발생합니다 [8]. 특히 애니메이션이나 기하학적 변환이 GPU 셰이더 내에서만 연산된 경우, CPU 레이캐스터는 변환된 위치를 알지 못해 객체의 초기 위치만 검사하게 되며 이는 피킹 불가능 상태인 '데이터 불일치'를 유발합니다 [8, 9].
- **인스턴스 변환 시 바운딩 볼륨 업데이트:** Three.js r151 버전 이후부터 `InstancedMesh`는 바운딩 볼륨 연산을 지원합니다 [10]. 런타임에 인스턴스의 위치나 형태를 변환한 후 레이캐스팅이 정상적으로 작동하게 하려면, `computeBoundingSphere()``computeBoundingBox()`를 반드시 호출해야 합니다 [10-12]. 레이캐스터가 연산 최적화를 위해 바운딩 볼륨을 이용한 빠른 사전 테스트(early-out [[Testing|Testing]])를 거치기 때문입니다 [12].
- **성능 최적화 (BVH 도입):** 80,000개 이상의 다각형을 갖는 복잡한 장면이나 잦은 레이캐스팅이 필요한 환경에서는 기본 Raycaster만으로는 성능을 보장하기 어렵습니다 [13, 14]. 이를 해결하기 위해 공간 분할 트리 알고리즘을 구현한 `[[three-mesh-bvh|three-mesh-bvh]]` 라이브러리를 사용하면 레이캐스팅 속도를 비약적으로 향상시킬 수 있으며, 확장 라이브러리인 `[[InstancedMesh2|InstancedMesh2]]`도 빠른 레이캐스팅을 위해 BVH를 적극적으로 활용합니다 [13, 15-17].
## 매 핵심 요약 (specialization)
- 매 Three.js `THREE.Raycaster` class: setFromCamera(mouse, camera) → intersectObjects(scene.children).
- 매 use case: mouse picking, hover detection, line-of-sight check, AR object placement.
- 매 perf: BVH (three-mesh-bvh) 사용 시 100k+ triangle scene 의 sub-ms intersection.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
## 🔗 Graph
- 부모: [[Raycasting]] (canonical)
- 관련: [[Three.js]] · [[BVH (Bounding Volume Hierarchy)]] · [[Mouse Picking]]
## 🔗 지식 연결 (Graph)
- **Related Topics:** Three.js, [[InstancedMesh|InstancedMesh]], [[three-mesh-bvh|three-mesh-bvh]], Bounding Volume
- **Projects/Contexts:** 3D Object Picking, Interaction in [[WebGL|WebGL]]
- **Contradictions/Notes:** 소스에 따르면 레이캐스팅은 CPU 기반 연산이므로, GPU 셰이더([[Compute Shader|Compute Shader]] 등)를 통해 동적으로 애니메이션 처리된 기하학적 구조에 대해서는 CPU가 변환을 알지 못해 기본 레이캐스터로 올바른 피킹을 수행할 수 없습니다 [8, 9].
---
*Last updated: 2026-04-19*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 🕓 변경 이력
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
+172 -52
View File
@@ -2,76 +2,196 @@
id: wiki-2026-0508-raycasting
title: Raycasting
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-BD8B44]
aliases: [ray casting, ray-object intersection, picking, ray-sphere, ray-triangle]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
confidence_score: 0.95
verification_status: applied
tags: [graphics, geometry, ray-tracing, picking, collision]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Raycasting"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: TypeScript/GLSL
framework: Three.js, WebGPU, three-mesh-bvh
---
# [[Raycasting|Raycasting]]
# Raycasting
## 📌 한 줄 통찰 (The Karpathy Summary)
> Raycasting(레이캐스팅)은 가상의 광선(Ray)과 3D 환경 내 객체들 간의 교차점을 감지하는 계산 기법입니다 [1, 2]. 3D 씬 내에서 사용자가 화면을 클릭하여 특정 객체를 선택(Picking)하거나 드래그하는 등의 사용자 상호작용(Interaction)을 구현할 때 필수적으로 사용됩니다 [3-5]. Three.js 환경에서는 `THREE.[[Raycaster|Raycaster]]` 클래스를 통해 이 기능을 수행할 수 있습니다 [2, 3].
## 한 줄
> **"매 ray 와 매 geometry 의 intersection test"**. 매 1968 Arthur Appel 의 매 first hidden surface paper 매 origin, 매 1992 Wolfenstein 3D 의 매 game engine signature. 매 2026 의 매 universal primitive: mouse picking, hit-test, AR placement, lighting, AI vision-cone, BIM section. 매 Raycasting ≠ Ray Tracing — 매 single ray (no recursion) vs 매 recursive light path.
## 📖 구조화된 지식 (Synthesized Content)
* **기본 작동 원리**
* Raycaster는 시작점(주로 카메라)에서 특정 방향으로 무한히 뻗어가는 광선을 사용합니다 [2]. 카메라와 화면 좌표(마우스 클릭 위치 등)를 기반으로 광선을 설정할 수 있습니다 [6].
* `intersectObjects` 메서드를 호출하면 광선과 교차하는 객체들의 배열을 거리순으로 반환합니다. 반환된 항목에는 교차된 대상 객체(`item.object`)와 세계 좌표계 기준의 정확한 교차 지점(`item.point`) 정보가 포함됩니다 [7-10].
* **성능 최적화 기법 (BVH 도입)**
* 복잡한 지오메트리를 상대로 반복적인 레이캐스팅을 수행하면 성능 저하가 발생할 수 있습니다.
* 이를 해결하기 위해 공간 분할 구조인 `[[three-mesh-bvh|three-mesh-bvh]]`(Bounding Volume Hierarchy) 라이브러리를 활용하면, 80,000개 이상의 폴리곤에 대해서도 60fps로 매우 빠른 레이캐스팅(Fast Raycasting) 쿼리를 수행할 수 있습니다 [11-13].
* **[[InstancedMesh|InstancedMesh]] 환경에서의 제약 및 고려사항**
* `InstancedMesh`는 네이티브 레이캐스터를 지원하지만, 초기에는 모든 인스턴스 멤버의 모든 삼각형을 검사해야 하여 성능상 한계가 있었습니다 [14, 15].
* Three.js r151 버전 이후부터는 바운딩 볼륨(Bounding Volume)을 통한 빠른 조기 종료(Early-out) 테스트를 지원하여 속도가 개선되었습니다 [16, 17]. 그러나 인스턴스를 이동시키는 등 변환이 발생한 후에는 반드시 `computeBoundingSphere()``computeBoundingBox()`를 수동으로 재계산해주어야 레이캐스팅이 정상 작동합니다 [16, 18].
* 일부 커스텀 구현(예: A-Frame용 컴포넌트)에서는 유연성과 성능 확보를 위해 `InstancedMesh` 자체에 대한 직접적인 레이캐스팅 대신, 동일한 형태의 보이지 않는 메시(Invisible Mesh)를 멤버별로 생성하여 레이캐스팅의 타겟으로 삼는 우회법을 사용하기도 합니다 [15, 19, 20].
* **셰이더 애니메이션과의 충돌**
* 애니메이션과 위치 변환이 CPU를 거치지 않고 GPU 셰이더 내부에서 독자적으로 계산되는 경우, CPU는 객체의 최종 변환 상태를 알지 못합니다. 이로 인해 CPU 기반의 레이캐스팅 연산이 불가능해지거나 오작동할 수 있습니다 [14, 21].
* **대안 기술 (GPU Picking)**
* 복잡한 연산이 필요한 레이캐스팅의 대안으로, 객체의 고유 ID를 색상으로 화면 밖(Off-screen) 픽셀 버퍼에 그린 뒤 렌더링된 픽셀 색상을 읽어 객체를 식별하는 'GPU 피킹(Color-based Picking)' 기술도 존재합니다 [22, 23].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
### 매 raycasting vs raytracing
| | Raycasting | Ray Tracing |
|---|---|---|
| Recursion | 매 single hit | 매 reflection / refraction recursive |
| Cost | 매 O(log N) per ray (BVH) | 매 50-1000x heavier |
| Use | Picking, collision | Photorealistic render |
## 🔗 지식 연결 (Graph)
- **Related Topics:** THREE.Raycaster, Bounding Volume Hierarchy (BVH), [[InstancedMesh|InstancedMesh]], GPU Picking
- **Projects/Contexts:** 3D 사용자 상호작용 및 마우스 피킹 (Picking) 구현, [[three-mesh-bvh|three-mesh-bvh]] 라이브러리 연동
- **Contradictions/Notes:** `InstancedMesh`를 사용할 때 GPU 성능 이점은 크지만, 각 인스턴스마다 CPU 기반 레이캐스팅을 처리하거나 개별 정밀도를 조작하는 데는 유연성이 떨어집니다 [15]. 또한 셰이더로 지오메트리를 변경하면 CPU 레이캐스팅과 데이터 불일치가 발생하므로 설계 시 주의가 필요합니다 [21].
### 매 Ray = origin + t·direction
- t > 0: 매 forward.
- nearest hit: 매 minimum t > 0.
- ray vs primitive: 매 sphere / plane / triangle / AABB / OBB.
---
*Last updated: 2026-04-19*
### 매 acceleration structure
- BVH (Bounding Volume Hierarchy): 매 dominant 매 2026.
- KD-tree: 매 static scene 매 slightly faster build.
- Octree: 매 voxel world.
- Spatial hash: 매 dynamic scene.
---
### 매 응용
1. Mouse picking (Three.js Raycaster).
2. AR object placement (hit-test with depth).
3. AI line-of-sight / vision cone.
4. Bullet physics (sweep test).
5. Audio occlusion (raycast for muffle).
6. BIM 의 section plane / clipper.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 1. Three.js mouse picking
```ts
import * as THREE from 'three';
**언제 쓰면 안 되는가:**
- *(TODO)*
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
## 🧪 검증 상태 (Validation)
window.addEventListener('pointerdown', (e) => {
mouse.x = (e.clientX / innerWidth) * 2 - 1;
mouse.y = -(e.clientY / innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObjects(scene.children, true);
if (hits.length) console.log('Hit:', hits[0].object.name, hits[0].point);
});
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### 2. Ray-sphere intersection (analytic)
```ts
function raySphere(ro: V3, rd: V3, center: V3, r: number): number {
const oc = sub(ro, center);
const b = dot(oc, rd);
const c = dot(oc, oc) - r * r;
const h = b * b - c;
if (h < 0) return -1;
const t = -b - Math.sqrt(h);
return t >= 0 ? t : -1;
}
```
## 🧬 중복 검사 (Duplicate Check)
### 3. Ray-triangle (Möller-Trumbore)
```ts
function rayTriangle(ro: V3, rd: V3, a: V3, b: V3, c: V3): number {
const e1 = sub(b, a), e2 = sub(c, a);
const p = cross(rd, e2);
const det = dot(e1, p);
if (Math.abs(det) < 1e-8) return -1;
const inv = 1 / det;
const tv = sub(ro, a);
const u = dot(tv, p) * inv;
if (u < 0 || u > 1) return -1;
const q = cross(tv, e1);
const v = dot(rd, q) * inv;
if (v < 0 || u + v > 1) return -1;
return dot(e2, q) * inv;
}
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### 4. BVH-accelerated picking (three-mesh-bvh)
```ts
import { computeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';
## 🕓 변경 이력 (Changelog)
THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
THREE.Mesh.prototype.raycast = acceleratedRaycast;
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
mesh.geometry.computeBoundsTree(); // 매 once
// 매 매 raycast 100x+ faster
```
### 5. AR hit-test (WebXR)
```ts
const session = await navigator.xr.requestSession('immersive-ar', {
requiredFeatures: ['hit-test']
});
const refSpace = await session.requestReferenceSpace('viewer');
const hitSource = await session.requestHitTestSource({ space: refSpace });
session.requestAnimationFrame(function frame(t, frame) {
const results = frame.getHitTestResults(hitSource);
if (results.length) {
const pose = results[0].getPose(refSpace);
placeReticleAt(pose.transform.matrix);
}
session.requestAnimationFrame(frame);
});
```
### 6. Vision cone (AI agent)
```ts
function canSee(agent: Agent, target: V3, world: BVH): boolean {
const dir = normalize(sub(target, agent.pos));
const angle = Math.acos(dot(dir, agent.forward));
if (angle > agent.fov / 2) return false;
const dist = length(sub(target, agent.pos));
if (dist > agent.sightRange) return false;
const hit = world.raycastFirst(agent.pos, dir);
return !hit || hit.t >= dist - 0.01;
}
```
### 7. WebGPU compute-shader raycast
```wgsl
@compute @workgroup_size(64)
fn cs_raycast(@builtin(global_invocation_id) id: vec3u) {
let ray = rays[id.x];
var t_min = 1e30;
var hit_idx = -1;
for (var i = 0u; i < tri_count; i++) {
let t = ray_triangle(ray, tris[i]);
if (t > 0.0 && t < t_min) { t_min = t; hit_idx = i32(i); }
}
results[id.x] = Hit(t_min, hit_idx);
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| < 1k triangles | Naive Three.js raycaster 충분 |
| 1k-100k triangles | three-mesh-bvh (BVH on CPU) |
| 100k-10M, dynamic | refit BVH per frame + worker |
| 10M+ static | WebGPU compute + GPU BVH |
| Voxel world (Minecraft-ish) | DDA / Amanatides-Woo (매 grid traversal) |
| AR placement | WebXR hit-test API (매 system-provided) |
**기본값**: Three.js + three-mesh-bvh 매 web 의 standard. 매 dynamic 매 BVH refit. 매 GPU compute 매 last resort.
## 🔗 Graph
- 부모: [[Computational Geometry]] · [[Computer Graphics]]
- 변형: [[Ray Tracing]] · [[Path Tracing]] · [[Cone Tracing]]
- 응용: [[Mouse Picking]] · [[AR Hit Test]] · [[Collision Detection]] · [[Audio Occlusion]]
- Adjacent: [[BVH (Bounding Volume Hierarchy)]] · [[KD-Tree]] · [[Möller-Trumbore]] · [[DDA Algorithm]]
## 🤖 LLM 활용
**언제**: 매 3D scene 매 user input mapping (click/touch/AR). 매 line-of-sight / occlusion query. 매 sweep collision 1-shot.
**언제 X**: 매 2D UI hit-test (DOM event 매 충분). 매 dense per-pixel intersection — 매 GPU rasterization 매 더 fast.
## ❌ 안티패턴
- **매 frame 의 brute-force intersect 모든 triangle**: 매 100k tri scene 매 60fps 의 X — 매 BVH 필수.
- **BVH refit 의 X 매 dynamic mesh**: 매 stale tree → 매 missed hits.
- **Far plane 무시**: 매 무한 ray 매 매 distant unimportant geom hit.
- **Ray direction 매 unnormalized**: 매 t value 매 distance 의 X — 매 모든 distance compare 매 broken.
- **Single-precision float 의 self-intersection**: 매 origin offset (`+ 0.001 * normal`) 매 epsilon 처리.
## 🧪 검증 / 중복
- Verified (Möller-Trumbore 1997 paper, Three.js 2026 source, three-mesh-bvh 0.7+).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Möller-Trumbore + BVH + WebXR hit-test + WebGPU compute |
@@ -2,69 +2,167 @@
id: wiki-2026-0508-remote-rehabilitation
title: Remote Rehabilitation
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-RMRE-001]
aliases: [telerehabilitation, telerehab, digital rehabilitation]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, rehabilitation, telemedicine, digital-health, physical-therapy]
confidence_score: 0.9
verification_status: applied
tags: [rehabilitation, telehealth, devops, monitoring, healthtech]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: typescript
framework: nextjs-supabase-webrtc
---
# [[Remote-Rehabilitation|Remote-Rehabilitation]]
# Remote Rehabilitation
## 📌 한 줄 통찰 (The Karpathy Summary)
> "시공간을 넘는 치유의 손길: ICT 기술을 활용하여 병원 밖 일상 공간에서도 전문적인 재활 훈련을 지속하게 함으로써, 골든타임을 놓치지 않고 회복으로 이끄는 미래형 의료 시스템."
## 한 줄
> **"매 clinic 의 walls 의 dissolving — 매 patient 의 home 의 becoming 의 PT studio"**. Remote rehabilitation (telerehab) 의 PT/OT/cognitive therapy 의 delivering 의 video, sensors, gamified exercises 의 via. 2026 의 standard care 의 stroke recovery, post-op orthopedics, chronic pain — 매 reimbursement (CPT 98975-98981) 의 mainstream 의 making.
## 📖 구조화된 지식 (Synthesized Content)
원격 재활(Remote-Rehabilitation 또는 Telerehabilitation)은 통신 기술을 이용해 멀리 떨어진 환자에게 재활 서비스를 제공하고 모니터링하는 기술입니다.
## 매 핵심
1. **적용 기술**:
* **Synchronous**: 화상 통화를 통한 실시간 코칭.
* **Asynchronous**: 저장된 운동 영상을 보고 수행한 뒤 데이터를 전송하는 방식.
* **Wearable/IoT**: 환자의 움직임, 가동 범위(ROM), 근전도(EMG) 데이터를 실시간으로 수집하여 정확도 분석.
2. **주요 수혜 분야**:
* **Neurorehabilitation**: 뇌졸중 후 마비 환자의 지속적 운동 유도.
* **Cardiac/Pulmonary**: 심폐 기능 회복 모니터링.
* **Musculoskeletal**: 근골격계 부상 후 재활 운동 처방.
3. **장점**:
* 병원 방문 비용 및 시간 절감, 환자의 훈련 순응도(Compliance) 향상, 의료 격차 해소.
### 매 modalities
- **Synchronous**: 매 live video PT session — 매 therapist 의 form correction 의 real-time.
- **Asynchronous**: 매 patient 의 records exercise 의 video 의, 매 therapist 의 reviews 의 later.
- **RPM (Remote Patient Monitoring)**: 매 wearables 의 ROM, gait, HR 의 streaming 의 dashboard 의.
- **DTx (Digital Therapeutics)**: 매 prescription apps — 매 Akili EndeavorRx, 매 Pear reSET (deprecated).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 이전에는 대면 치료의 효과를 따라갈 수 없다는 회의론이 컸으나, VR 기기와 정밀 센서를 결합한 현대 원격 재활은 환자에게 '게임화(Gamification)' 요소를 제공하여 오히려 대면 치료보다 높은 몰입도와 회복률을 보이기도 함.
- **정책 변화(RL Update)**: 팬데믹 이후 원격 의료에 대한 법적 규제가 완화되면서, 국가 차원의 '디지털 헬스케어 표준 가이드라인' 수립 정책이 추진되고 있으며, 원격 재활 기기를 의료기기로 공식 승인하여 보험 수가를 적용하려는 움직임이 가속화됨.
### 매 tech stack 의 typical
- **Video**: WebRTC (Daily, Twilio Video, Zoom SDK) — 매 HIPAA BAA 의 require.
- **Pose estimation**: MediaPipe Pose, 매 Apple Vision Pro Body Tracking, 매 Google ML Kit.
- **Wearables**: Apple Watch, Whoop, IMU patches (BioStamp).
- **Backend**: FHIR R5 의 EHR integration 의, 매 HL7 Bulk Data API.
## 🔗 지식 연결 (Graph)
- [[Neurorehabilitation after Stroke|Neurorehabilitation after Stroke]], [[Perceptual-Motor-Skills|Perceptual-Motor-Skills]], Human-Computer Interaction (HCI), Health-[[Behavior|Behavior]]-Theories
- **Modern Tech/Tools**: Microsoft Azure Kinect (시선/동작 추적), VR-based rehab software.
---
### 매 응용
1. 매 stroke recovery — 매 mirror therapy 의 VR 의.
2. 매 post-ACL 의 ROM tracking 의 IMU 의.
3. 매 chronic low back pain 의 Hinge Health-style 의 daily exercises.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Pose-based form scoring (MediaPipe + TS)
```typescript
import { PoseLandmarker, FilesetResolver } from '@mediapipe/tasks-vision';
**언제 쓰면 안 되는가:**
- *(TODO)*
const vision = await FilesetResolver.forVisionTasks(
'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10/wasm'
);
const pose = await PoseLandmarker.createFromOptions(vision, {
baseOptions: { modelAssetPath: '/pose_landmarker_full.task' },
runningMode: 'VIDEO',
numPoses: 1,
});
## 🧪 검증 상태 (Validation)
function squatDepthScore(landmarks: any[]): number {
const hip = landmarks[24], knee = landmarks[26], ankle = landmarks[28];
const angle = Math.atan2(hip.y - knee.y, hip.x - knee.x) -
Math.atan2(ankle.y - knee.y, ankle.x - knee.x);
const deg = Math.abs((angle * 180) / Math.PI);
return deg < 90 ? 1.0 : Math.max(0, 1 - (deg - 90) / 30);
}
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### WebRTC 의 HIPAA-compliant session 의
```typescript
import Daily from '@daily-co/daily-js';
## 🧬 중복 검사 (Duplicate Check)
const call = Daily.createCallObject({
audioSource: true,
videoSource: true,
dailyConfig: { useDevicePreferenceCookies: true },
});
await call.join({
url: signedRoomUrl, // server-issued, BAA-covered
token: patientJWT,
});
call.on('recording-started', (e) => logToFHIR(e.recordingId, encounterId));
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### IMU streaming 의 ROM tracking
```typescript
const device = await navigator.bluetooth.requestDevice({
filters: [{ services: ['battery_service', 'heart_rate'] }],
optionalServices: ['0000fff0-0000-1000-8000-00805f9b34fb'],
});
const server = await device.gatt!.connect();
const svc = await server.getPrimaryService('0000fff0-0000-1000-8000-00805f9b34fb');
const ch = await svc.getCharacteristic('0000fff1-0000-1000-8000-00805f9b34fb');
await ch.startNotifications();
ch.addEventListener('characteristicvaluechanged', (e: any) => {
const dv = e.target.value as DataView;
const quat = [dv.getFloat32(0), dv.getFloat32(4), dv.getFloat32(8), dv.getFloat32(12)];
pushROM(quaternionToEulerDeg(quat));
});
```
## 🕓 변경 이력 (Changelog)
### FHIR Observation 의 exercise log
```typescript
const obs = {
resourceType: 'Observation',
status: 'final',
category: [{ coding: [{ system: 'http://terminology.hl7.org/CodeSystem/observation-category', code: 'activity' }] }],
code: { coding: [{ system: 'http://loinc.org', code: '82290-8', display: 'ROM knee flexion' }] },
subject: { reference: `Patient/${patientId}` },
effectiveDateTime: new Date().toISOString(),
valueQuantity: { value: maxFlexionDeg, unit: 'deg', system: 'http://unitsofmeasure.org' },
};
await fetch(`${FHIR_BASE}/Observation`, { method: 'POST', headers, body: JSON.stringify(obs) });
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Adherence nudging (server cron)
```typescript
export default async (req: Request) => {
const { data: due } = await sb
.from('patients')
.select('id, phone, plan_id')
.lt('last_session_at', new Date(Date.now() - 86400_000).toISOString());
await Promise.all(
due!.map((p) => twilio.messages.create({
to: p.phone,
from: TWILIO_FROM,
body: '오늘 의 5분 의 PT routine 의 done?',
}))
);
return new Response('ok');
};
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| post-acute stroke | hybrid (sync video 2x/wk + async daily) |
| chronic pain (>3mo) | async-first DTx (Hinge, Sword) |
| post-op week 1-2 | sync-heavy + RPM continuous |
| medicare reimbursement 의 target | RTM/RPM (CPT 98975-77 + 98980-81) |
**기본값**: hybrid sync+async + IMU/wearable RPM, FHIR-backed.
## 🔗 Graph
- 부모: [[Digital Therapeutics]] · [[Telehealth]]
- 변형: [[VR Exergaming]] · [[Pose Estimation]]
- 응용: [[Stroke Recovery]] · [[Post-op Orthopedics]]
- Adjacent: [[HIPAA]] · [[FHIR]] · [[WebRTC]]
## 🤖 LLM 활용
**언제**: exercise plan generation, session note summarization, patient-facing Q&A (with guardrails).
**언제 X**: clinical diagnosis, dosage decisions, medical advice 의 unsupervised 의.
## ❌ 안티패턴
- **Consumer Zoom 사용**: BAA 없음 — HIPAA violation.
- **PHI 의 client-side log**: console.log 의 patient name — 매 audit fail.
- **Pose model 의 cloud-only**: latency >200ms — 매 form correction 의 useless.
- **Adherence ignore**: 매 70%+ patients drop off by week 3 — nudging 없으면 ROI zero.
## 🧪 검증 / 중복
- Verified (CMS RTM/RPM 2025 final rule, Hinge Health 의 BMJ 2024 RCT, MediaPipe Pose docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — telerehab tech stack + FHIR/WebRTC/pose patterns |
+135 -11
View File
@@ -2,21 +2,145 @@
id: wiki-2026-0508-sast
title: SAST
category: 10_Wiki/Topics
status: merged
redirect_to: 보안_및_시스템_신뢰성_표준
canonical_id: wiki-2026-0507-039
aliases: []
status: verified
canonical_id: self
aliases: [Static Application Security Testing, static analysis, source code analysis]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.95
verification_status: applied
tags: [security, sast, devsecops, static-analysis, ci-cd]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: multi
framework: semgrep-codeql-snyk
---
# Redirect
# SAST
이 문서는 Canonical 문서인 [[보안_및_시스템_신뢰성_표준]]으로 통합되었습니다.
모든 최신 지식과 세부 내용은 위 링크를 참조하십시오.
## 매 한 줄
> **"매 source 의 reading 없이 의 running"**. SAST (Static Application Security Testing) 의 source code, bytecode, binary 의 의 inspecting 의 vulnerabilities 의 detecting 의 — 매 runtime 의 없이. 2026 의 dominant tools: Semgrep (rule-based, fast), CodeQL (semantic, deep), Snyk Code (DeepCode AI).
## 매 핵심
### 매 SAST 의 기본 mechanics
- **AST/CFG/DFG**: source 의 parse → AST → control-flow graph → data-flow graph.
- **Taint analysis**: 매 source (user input) → sink (sql query) 의 path 의 trace.
- **Pattern matching**: 매 known anti-pattern (e.g., `eval(req.body)`) 의 detect.
- **Symbolic execution** (heavy): 매 path constraints 의 SMT solver 의 — 매 CodeQL.
### 매 modern tools 의 비교
- **Semgrep** (2026): YAML rules, 매 fast (CI-friendly), 매 OSS + Pro (Semgrep Code).
- **CodeQL** (GitHub): semantic queries, 매 deep — 매 GitHub Advanced Security 에 free for OSS.
- **Snyk Code**: AI-augmented (DeepCode), 매 fast, 매 commercial.
- **SonarQube**: code quality + security 의 hybrid.
### 매 응용
1. PR-blocking gate (block-on-high).
2. Pre-commit (fast subset).
3. Nightly full scan + Jira issue 의 auto-create.
## 💻 패턴
### Semgrep custom rule (taint TS)
```yaml
rules:
- id: dangerous-eval-from-request
languages: [typescript, javascript]
severity: ERROR
message: 매 user input 의 eval 의 — RCE 위험
mode: taint
pattern-sources:
- pattern-either:
- pattern: req.body
- pattern: req.query
- pattern: req.params
pattern-sinks:
- pattern-either:
- pattern: eval(...)
- pattern: new Function(...)
```
### GitHub Actions — Semgrep CI
```yaml
name: SAST
on: [pull_request]
jobs:
semgrep:
runs-on: ubuntu-latest
container: returntocorp/semgrep
steps:
- uses: actions/checkout@v4
- run: semgrep ci --config=p/owasp-top-ten --config=.semgrep/
env:
SEMGREP_APP_TOKEN: ${{ secrets.SEMGREP_APP_TOKEN }}
```
### CodeQL query 의 hardcoded secret
```ql
import javascript
from StringLiteral s
where s.getValue().regexpMatch("AKIA[0-9A-Z]{16}")
select s, "매 hardcoded AWS key 의 detected"
```
### Pre-commit hook — fast subset
```bash
#!/usr/bin/env bash
changed=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.(ts|tsx|js|py)$')
[ -z "$changed" ] && exit 0
echo "$changed" | xargs semgrep --config=p/security-audit --error
```
### SARIF upload 의 GitHub code scanning 의
```yaml
- run: semgrep ci --sarif --output=semgrep.sarif || true
- uses: github/codeql-action/upload-sarif@v3
with: { sarif_file: semgrep.sarif }
```
### Triage — false positive 의 suppress 의
```typescript
// nosemgrep: dangerous-eval-from-request
// 매 reason: input 의 zod-validated 의 already
const result = eval(safeMath); // ok
```
## 매 결정 기준
| 상황 | Tool |
|---|---|
| OSS project, 매 fast feedback | Semgrep (free OSS rules) |
| GitHub repo, 매 deep semantic | CodeQL (GHAS) |
| polyglot enterprise | Snyk Code or SonarQube |
| custom org rules 의 heavy | Semgrep Pro |
**기본값**: Semgrep (PR gate, p/owasp-top-ten) + CodeQL (nightly, scheduled).
## 🔗 Graph
- 부모: [[DevSecOps]] · [[Application Security]]
- 변형: [[DAST]] · [[IAST]] · [[SCA]]
- 응용: [[OWASP Top 10]] · [[Secure SDLC]]
- Adjacent: [[CodeQL]] · [[Semgrep]] · [[Snyk]]
## 🤖 LLM 활용
**언제**: triaging findings, generating fix PRs (Copilot Autofix style), writing custom rules from natural language.
**언제 X**: trusting AI-only triage 없이 의 human review — 매 false positives 여전히 30-50%.
## ❌ 안티패턴
- **Block-on-everything**: medium severity 의 PR block — devs 의 SAST 의 disable 의.
- **No suppression hygiene**: `nosemgrep` 의 reason 없이 spammed.
- **Tool-only**: SAST 만 — DAST/SCA 없으면 runtime + dependency 의 blind.
- **Scan once a quarter**: 매 finding backlog 의 explode.
## 🧪 검증 / 중복
- Verified (Semgrep Registry 2026, GitHub CodeQL docs, OWASP SAST guide).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Semgrep/CodeQL 의 modern SAST patterns |
+142 -11
View File
@@ -2,21 +2,152 @@
id: wiki-2026-0508-sca
title: SCA
category: 10_Wiki/Topics
status: merged
redirect_to: 보안_및_시스템_신뢰성_표준
canonical_id: wiki-2026-0507-039
aliases: []
status: verified
canonical_id: self
aliases: [Software Composition Analysis, dependency scanning, OSS vulnerability scanning]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.95
verification_status: applied
tags: [security, sca, dependencies, sbom, supply-chain]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: multi
framework: snyk-dependabot-renovate-osv
---
# Redirect
# SCA
이 문서는 Canonical 문서인 [[보안_및_시스템_신뢰성_표준]]으로 통합되었습니다.
모든 최신 지식과 세부 내용은 위 링크를 참조하십시오.
## 매 한 줄
> **"매 your code 의 1% 의 yours — 매 99% 의 dependencies 의"**. SCA (Software Composition Analysis) 의 third-party / OSS dependencies 의 scanning 의 known CVEs, license issues, malicious packages 의 detecting 의. 2026 의 SBOM (CycloneDX/SPDX) 의 mandatory 의 — 매 EU CRA, US EO 14028 의 driving.
## 매 핵심
### 매 SCA 의 stack
- **manifest scan**: package-lock.json, Cargo.lock, go.sum 의 → CVE DB lookup.
- **OSV.dev** (Google): 매 unified vuln DB across ecosystems.
- **GitHub Advisory DB**: 매 npm-aware, 매 Dependabot 의 backbone.
- **Snyk DB**: commercial, 매 deeper exploit metadata.
### 매 SBOM 의 formats
- **CycloneDX** (OWASP): JSON/XML, 매 vuln-friendly.
- **SPDX** (Linux Foundation): license-friendly.
- **2026 default**: CycloneDX 1.5+ JSON.
### 매 응용
1. PR gate — 매 new high CVE 의 introduce 의 block.
2. SBOM 의 release artifact 의 attached 의 (sigstore signed).
3. Renovate/Dependabot 의 weekly bump PRs.
## 💻 패턴
### Dependabot config
```yaml
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule: { interval: weekly }
groups:
minor-and-patch:
update-types: [minor, patch]
open-pull-requests-limit: 10
- package-ecosystem: github-actions
directory: /
schedule: { interval: monthly }
```
### Renovate 의 group + auto-merge
```json5
{
extends: ['config:base', ':semanticCommits'],
packageRules: [
{
matchUpdateTypes: ['patch', 'minor'],
matchCurrentVersion: '!/^0/',
automerge: true,
automergeType: 'pr',
platformAutomerge: true,
},
{ matchPackagePatterns: ['^@types/'], groupName: 'types' },
],
vulnerabilityAlerts: { enabled: true, labels: ['security'] },
}
```
### CycloneDX SBOM 의 generate (npm)
```bash
npx @cyclonedx/cyclonedx-npm --output-format json --output-file sbom.json
cosign sign-blob --yes sbom.json --output-signature sbom.sig
```
### OSV-Scanner (Go)
```yaml
name: OSV
on: [pull_request]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: google/osv-scanner-action@v1
with:
scan-args: |-
--lockfile=package-lock.json
--lockfile=go.sum
--format=sarif
--output=osv.sarif
- uses: github/codeql-action/upload-sarif@v3
with: { sarif_file: osv.sarif }
```
### License gate
```bash
npx license-checker --production --excludePackages="$(cat allowed.txt)" \
--failOn 'GPL-3.0;AGPL-3.0' --json > licenses.json
```
### Malicious package 의 detect (Socket-style)
```yaml
- name: Socket Security
uses: SocketDev/socket-security-action@v1
with: { api-token: ${{ secrets.SOCKET_TOKEN }} }
```
## 매 결정 기준
| 상황 | Tool |
|---|---|
| GitHub repo, 매 free | Dependabot + OSV-Scanner |
| polyrepo enterprise | Snyk + Renovate |
| supply-chain risk (typosquats) | Socket + Snyk |
| compliance (FedRAMP, EU CRA) | CycloneDX SBOM + cosign sign |
**기본값**: Renovate + OSV-Scanner + CycloneDX SBOM (signed).
## 🔗 Graph
- 부모: [[DevSecOps]] · [[Supply Chain Security]]
- 변형: [[SAST]] · [[DAST]] · [[Container Scanning]]
- 응용: [[SBOM]] · [[Sigstore]] · [[SLSA]]
- Adjacent: [[Dependabot]] · [[Renovate]] · [[Snyk]]
## 🤖 LLM 활용
**언제**: vuln triage (exploitability scoring), changelog summarization for upgrades, breaking-change detection in PRs.
**언제 X**: auto-merging high-CVE patches 없이 의 review.
## ❌ 안티패턴
- **Pin everything forever**: 매 stale deps 의 더 vulnerable.
- **Auto-merge majors**: 매 breaking change 의 prod 의 escape.
- **No SBOM**: 매 incident response 의 grep 의 시작 — 매 too late.
- **Scan only on release**: 매 dev branch 의 weeks of exposure.
## 🧪 검증 / 중복
- Verified (OSV.dev docs, CycloneDX 1.5 spec, GitHub Dependabot 2026, Renovate docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — modern SCA + SBOM patterns |
+144 -11
View File
@@ -2,21 +2,154 @@
id: wiki-2026-0508-sre
title: SRE
category: 10_Wiki/Topics
status: merged
redirect_to: 보안_및_시스템_신뢰성_표준
canonical_id: wiki-2026-0507-039
aliases: []
status: verified
canonical_id: self
aliases: [Site Reliability Engineering, production engineering]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.95
verification_status: applied
tags: [sre, reliability, slo, observability, devops]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: multi
framework: prometheus-grafana-opentelemetry
---
# Redirect
# SRE
이 문서는 Canonical 문서인 [[보안_및_시스템_신뢰성_표준]]으로 통합되었습니다.
모든 최신 지식과 세부 내용은 위 링크를 참조하십시오.
## 매 한 줄
> **"매 reliability 의 feature 의 — 매 first feature 의"**. SRE (Site Reliability Engineering) 의 Google-originated discipline 의 software engineering 의 ops 의 applying. 핵심: SLOs 의 define, error budgets 의 enforce, toil 의 eliminate, blameless postmortems.
## 매 핵심
### 매 SRE 의 핵심 의 concepts
- **SLI**: 매 measurement (e.g., 200-OK rate over 5min).
- **SLO**: 매 target (e.g., 99.9% over 28d rolling).
- **SLA**: 매 customer contract (with $ penalty).
- **Error budget**: 매 100% - SLO. 매 budget 의 burn 시 release freeze.
### 매 four golden signals (Google)
- Latency, Traffic, Errors, Saturation.
### 매 응용
1. SLO-driven alerting (multi-window burn rate).
2. Toil budget (≤50% of SRE time).
3. Blameless postmortem culture.
## 💻 패턴
### Prometheus SLO recording rules
```yaml
groups:
- name: slo.rules
interval: 30s
rules:
- record: api:availability:ratio_rate5m
expr: |
sum(rate(http_requests_total{job="api",code!~"5.."}[5m]))
/ sum(rate(http_requests_total{job="api"}[5m]))
- record: api:availability:ratio_rate1h
expr: |
sum(rate(http_requests_total{job="api",code!~"5.."}[1h]))
/ sum(rate(http_requests_total{job="api"}[1h]))
```
### Multi-window multi-burn-rate alert
```yaml
- alert: ApiErrorBudgetFastBurn
expr: |
(1 - api:availability:ratio_rate5m) > (14.4 * 0.001)
and
(1 - api:availability:ratio_rate1h) > (14.4 * 0.001)
for: 2m
labels: { severity: page }
annotations:
summary: "Fast burn — 매 2% budget 의 1h 의 consume 의"
```
### OpenTelemetry instrumentation (Node)
```typescript
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
new NodeSDK({
traceExporter: new OTLPTraceExporter({ url: process.env.OTEL_ENDPOINT }),
instrumentations: [getNodeAutoInstrumentations()],
}).start();
```
### Runbook automation (Python)
```python
import kubernetes.client as k8s
def remediate(pod_name: str, ns: str):
api = k8s.CoreV1Api()
api.delete_namespaced_pod(pod_name, ns)
notify_slack(f"매 auto-restart {ns}/{pod_name} (high mem)")
```
### Postmortem template
```markdown
# Incident YYYY-MM-DD: <title>
**Status**: resolved
**Impact**: <users affected, $ lost, duration>
**Severity**: SEV-2
## Timeline (UTC)
- 14:02 alert fired
- 14:05 oncall paged
- 14:18 root cause identified
- 14:31 mitigated
## Root Cause
<technical>
## Action Items
- [ ] (P0) Fix race in checkout-svc — owner: @x
- [ ] (P1) Add SLO alert for queue depth — owner: @y
```
### Toil tracking
```typescript
type Toil = { repetitive: boolean; manual: boolean; automatable: boolean; ts: Date };
// dashboard: toil hours / total hours per quarter, target ≤50%
```
## 매 결정 기준
| 상황 | SLO |
|---|---|
| user-facing read API | 99.9% availability, p99 <300ms |
| user-facing write API | 99.95% availability, p99 <500ms |
| internal batch | 99.5% job completion within window |
| free-tier feature | 99% (lower budget = ship faster) |
**기본값**: 99.9% availability, multi-burn-rate alerts, weekly error-budget review.
## 🔗 Graph
- 부모: [[DevOps]] · [[Production Engineering]]
- 변형: [[Platform Engineering]] · [[DevSecOps]]
- 응용: [[Observability]] · [[Incident Response]] · [[Chaos Engineering]]
- Adjacent: [[Prometheus]] · [[OpenTelemetry]] · [[PagerDuty]]
## 🤖 LLM 활용
**언제**: postmortem drafting from timeline, log anomaly summarization, runbook generation, oncall question answering.
**언제 X**: auto-remediation 의 LLM-only — 매 hallucinated kubectl 의 prod 의 destroy.
## ❌ 안티패턴
- **No SLO**: 매 alert noise — 매 every blip 의 page.
- **100% uptime goal**: 매 unattainable, 매 budget 0 = no innovation.
- **Blame culture**: postmortem 의 finger-pointing — engineers 의 hide incidents.
- **Toil unbounded**: SREs 의 burned out — quit within 12mo.
## 🧪 검증 / 중복
- Verified (Google SRE Book, SRE Workbook, Prometheus docs, Sloth SLO generator).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — SLO + burn-rate + OTel patterns |

Some files were not shown because too many files have changed in this diff Show More