[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -4,113 +4,169 @@ title: Call Stack Analysis
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-REINFORCE-WIKI-DEV-CALL-STACK-ANALYSIS, 호출 스택, Call Stack, 스택 트레이스, 런타임 추적, 디버깅 흐름]
|
||||
aliases: [Call Stack, Stack Trace Analysis, Flame Graph, Profiling Stack]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [Debugging, Runtime, Analysis, Architecture, Onboarding]
|
||||
raw_sources: [Datacollector_Export_2026-05-02]
|
||||
last_reinforced: 2026-05-02
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [profiling, performance, flame-graph, debugging, observability]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: Polyglot
|
||||
framework: perf/eBPF/pprof
|
||||
---
|
||||
|
||||
# [[호출 스택 분석과 런타임 흐름 추적 (Call Stack Analysis)]]
|
||||
# Call Stack Analysis
|
||||
|
||||
## 1. 개요
|
||||
호출 스택(Call Stack)은 프로그램 실행 중 현재 활성화된 서브루틴(함수, 메서드 등)의 정보를 저장하는 스택 구조의 메모리 영역이다. 개발자에게 호출 스택은 코드가 실제로 실행되는 런타임의 동적인 흐름을 이해하고, 특정 지점에 도달하기까지의 인과 관계를 추적하는 가장 강력한 디버깅 및 분석 도구로 기능한다.
|
||||
## 매 한 줄
|
||||
> **"매 performance bug 의 95% 는 'where is CPU time spent?' — 매 call stack sampling 이 답한다."**. 매 stack trace 를 statistical 하게 sampling → flame graph 로 visualize 하면 hot path 가 즉시 보임. 매 2026 표준 stack 은 Linux perf + eBPF, 매 inferno / pyroscope / Datadog Continuous Profiler.
|
||||
|
||||
## 2. 분석 전략 및 기법
|
||||
- **하향식 추적 (Top-down Trace)**: 애플리케이션의 최상위 진입점(Entry Point)에서 시작하여 호출 스택을 따라 깊숙한 내부 구현체로 진입하며 시스템의 오케스트레이션 로직 파악.
|
||||
- **상향식 분석 (Bottom-up Analysis)**: 에러가 발생한 최종 지점에서 시작하여 호출 스택을 거슬러 올라가며, 어떤 상위 계층의 데이터가 문제를 유발했는지 근본 원인(Root Cause) 식별.
|
||||
- **실시간 관찰 (Live Debugging)**: 디버거의 중단점(Breakpoints)을 활용하여 특정 시점의 호출 스택과 메모리 상태, 변수 값을 직접 확인하며 정적 코드 독해의 한계 극복.
|
||||
- **타임박싱 (Timeboxing)**: 대규모 시스템에서 스택의 깊이가 너무 깊어질 경우 길을 잃을 위험이 크므로, 추적 시간을 제한하고 필요시 동료의 도움을 받는 효율적인 탐색 전략 병행.
|
||||
## 매 핵심
|
||||
|
||||
## 3. 엔지니어링 가치
|
||||
- **복잡성 해독**: 정적으로는 파악하기 어려운 비동기 호출, 콜백 구조, 다형성을 통한 동적 바인딩 등의 실제 실행 경로를 명확히 가시화.
|
||||
- **온보딩 가속화**: 낯선 코드베이스에서 작은 버그를 재현하고 스택을 추적해 보는 과정을 통해, 시스템의 전반적인 레이어 구조와 책임 분산 방식 실전 학습.
|
||||
- **성능 및 안정성 진단**: 불필요하게 깊은 재귀 호출이나 비효율적인 호출 연쇄를 발견하여 아키텍처적 개선 지점 도출.
|
||||
### 매 sampling vs instrumentation
|
||||
- **Sampling profiler**: 매 N Hz (보통 99/999Hz) 마다 stack capture → low overhead, statistical.
|
||||
- **Instrumented profiler**: 매 every entry/exit hook → exact, but 10-100x overhead.
|
||||
- **현대 default**: 매 sampling — 매 production-safe.
|
||||
|
||||
## 4. 트레이드오프 및 주의사항
|
||||
- **비동기 흐름의 단절**: 이벤트 루프나 비동기 프라미스 구조에서는 전통적인 호출 스택이 끊어질 수 있다. 이 경우 비동기 스택 추적(Async Stack Traces) 기능을 지원하는 도구 활용 필요.
|
||||
- **성능 오버헤드**: 상세한 스택 트레이스를 지속적으로 생성하고 로깅하는 것은 런타임 성능에 영향을 줄 수 있으므로, 운영 환경에서는 임계치 조절 필요.
|
||||
- **인지 부하**: 너무 방대한 호출 스택은 오히려 개발자를 혼란에 빠뜨릴 수 있다. 비즈니스 로직과 무관한 프레임워크 내부 스택은 필터링하여 핵심 흐름에 집중.
|
||||
### 매 stack source
|
||||
- **Frame pointer (RBP) walk**: 매 fastest, requires `-fno-omit-frame-pointer`.
|
||||
- **DWARF unwind**: 매 .eh_frame 사용 — frame pointer 불필요하나 expensive.
|
||||
- **ORC unwinder**: 매 Linux kernel 의 lightweight DWARF subset.
|
||||
- **eBPF stackmap**: 매 user+kernel stack 통합.
|
||||
|
||||
## 5. 지식 연결 (Related)
|
||||
- [[Intentional_Failure_Induction]]: 호출 스택을 얻기 위해 고의로 에러를 유발하는 기법.
|
||||
- [[Testability_Architecture]]: 호출 스택 추적이 용이하도록 명확한 계층 구조를 설계하는 원칙.
|
||||
- [[Logs_and_Error_Messages]]: 스택 트레이스가 기록되는 주요 매체 및 분석 단서.
|
||||
### 매 visualization
|
||||
- **Flame graph (Brendan Gregg)**: 매 x=share of samples, y=stack depth, width=hot.
|
||||
- **Icicle graph**: 매 flipped flame — root at top.
|
||||
- **Differential flame graph**: 매 두 profile diff — perf regression 사냥.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
- **정보 상태**: 검증 완료 (Verified)
|
||||
- **출처 신뢰도**: A
|
||||
- **검토 이유**: 시스템의 실행 흐름을 정밀하게 분석하고 런타임 결함을 신속하게 진단하기 위한 기술적 분석 표준 정립.
|
||||
### 매 응용
|
||||
1. **CPU bottleneck 진단**: 매 hot function 식별.
|
||||
2. **Lock contention**: 매 off-CPU profile + futex stack.
|
||||
3. **GC pressure**: 매 alloc-stack profile.
|
||||
4. **Cold start**: 매 startup phase flame graph.
|
||||
5. **Continuous profiling**: 매 prod 24/7 sample → regression alerting.
|
||||
|
||||
## 📌 한 줄 통찰 (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
|
||||
### Linux perf — basic
|
||||
```bash
|
||||
# 30s sample at 99Hz
|
||||
perf record -F 99 -a -g --call-graph dwarf -- sleep 30
|
||||
perf script > out.stack
|
||||
# render
|
||||
git clone https://github.com/brendangregg/FlameGraph
|
||||
./FlameGraph/stackcollapse-perf.pl out.stack | \
|
||||
./FlameGraph/flamegraph.pl > flame.svg
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### eBPF profile (BCC)
|
||||
```bash
|
||||
profile-bpfcc -F 99 -f 30 > out.folded
|
||||
flamegraph.pl out.folded > flame.svg
|
||||
# advantages: lower overhead, kernel+user merged
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Go pprof
|
||||
```go
|
||||
import _ "net/http/pprof"
|
||||
func main() {
|
||||
go http.ListenAndServe(":6060", nil)
|
||||
// ... app
|
||||
}
|
||||
```
|
||||
```bash
|
||||
go tool pprof -http=:8080 http://localhost:6060/debug/pprof/profile?seconds=30
|
||||
# interactive flame graph in browser
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Python py-spy (no code change)
|
||||
```bash
|
||||
py-spy record -o flame.svg -d 30 --pid $(pgrep -f myapp.py)
|
||||
# zero instrumentation, samples a running process
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Node.js / V8
|
||||
```bash
|
||||
node --prof app.js
|
||||
# ... run workload ...
|
||||
node --prof-process isolate-0xNNN-v8.log > profile.txt
|
||||
# or 0x: npx 0x -- node app.js
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### JVM async-profiler
|
||||
```bash
|
||||
# attach to running JVM, 60s flame graph
|
||||
asprof -d 60 -f flame.html $PID
|
||||
# also captures lock contention, alloc, wall-clock
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Rust — pprof crate
|
||||
```rust
|
||||
use pprof::ProtoBuf;
|
||||
let guard = pprof::ProfilerGuardBuilder::default()
|
||||
.frequency(999)
|
||||
.blocklist(&["libc", "libgcc", "pthread"])
|
||||
.build()?;
|
||||
// ... workload ...
|
||||
let report = guard.report().build()?;
|
||||
let mut file = std::fs::File::create("profile.pb")?;
|
||||
report.pprof()?.encode(&mut file)?;
|
||||
```
|
||||
|
||||
### Continuous profiling (Pyroscope / Grafana)
|
||||
```yaml
|
||||
# pyroscope agent — runs alongside app
|
||||
pyroscope:
|
||||
server: http://pyroscope:4040
|
||||
app_name: api-prod
|
||||
spy_name: ebpfspy # auto-detect language
|
||||
sample_rate: 100
|
||||
```
|
||||
|
||||
### Differential flame graph
|
||||
```bash
|
||||
./FlameGraph/difffolded.pl before.folded after.folded | \
|
||||
./FlameGraph/flamegraph.pl > diff.svg
|
||||
# red = got slower, blue = got faster
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Tool |
|
||||
|---|---|
|
||||
| Linux native (C/C++/Rust/Go) | perf + FlameGraph |
|
||||
| Container / k8s (no SYS_ADMIN) | pprof endpoint |
|
||||
| Python prod | py-spy |
|
||||
| JVM prod | async-profiler |
|
||||
| Continuous 24/7 | Pyroscope / Datadog |
|
||||
| Off-CPU (lock/IO) | offcputime-bpfcc |
|
||||
|
||||
**기본값**: 99Hz sampling → folded → flamegraph.pl. 매 첫 5분 안에 hot path 보임.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Performance_Engineering]] · [[Observability]]
|
||||
- 변형: [[Flame_Graph]] · [[Off_CPU_Profile]] · [[Differential_Flame_Graph]]
|
||||
- 응용: [[Continuous_Profiling]] · [[Performance_Regression_Detection]]
|
||||
- Adjacent: [[eBPF]] · [[perf]] · [[pprof]] · [[Brendan_Gregg]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: hot function 분석, regression diff, profile 결과 해석.
|
||||
**언제 X**: tail latency / distributed trace (분산 환경은 OpenTelemetry).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Time.time printf 로그 profiling**: 매 statistical 안 되고 hot loop 망침.
|
||||
- **Frame pointer 없는 build**: 매 unwind 망가짐 — `-fno-omit-frame-pointer` 필수.
|
||||
- **너무 낮은 sample rate (10Hz)**: 매 30초 = 300 samples — noise dominate.
|
||||
- **너무 높은 rate (10kHz)**: 매 self-overhead 가 측정 결과 왜곡.
|
||||
- **Single-run profile 만 보기**: 매 variance — minimum 5 runs 권장.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Brendan Gregg "Systems Performance" 2nd ed 2020, Linux perf docs, async-profiler README 2024).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — sampling profilers, flame graphs, multi-language tooling |
|
||||
|
||||
Reference in New Issue
Block a user