Files
2nd/10_Wiki/Topics/AI_and_ML/Debugging Methods.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

356 lines
8.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
id: wiki-2026-0508-debugging-methods
title: Debugging Methods
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [debugging, frontend debugging, observability, Sentry, LogRocket, time-travel debug, session replay]
duplicate_of: none
source_trust_level: A
confidence_score: 0.93
verification_status: applied
tags: [debugging, observability, sentry, logrocket, devtools, error-boundary, time-travel, profiling]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: JS / Python / Go
framework: Sentry / Datadog / Chrome DevTools / Redux DevTools
---
# Debugging Methods
## 매 한 줄
> **"매 hypothesis-driven 의 systematic"**. 매 reproduce → 매 narrow → 매 hypothesize → 매 test → 매 fix → 매 prevent. 매 modern: 매 observability (Sentry, Datadog) + 매 session replay + 매 distributed trace + 매 LLM-aided.
## 매 핵심 process
### Scientific debugging
1. **Reproduce**: 매 minimum reproducer.
2. **Observe**: 매 relevant signal.
3. **Hypothesize**: 매 specific cause.
4. **Test**: 매 verify hypothesis.
5. **Fix**: 매 root cause.
6. **Prevent**: 매 test + 매 doc + 매 monitor.
### 매 method
#### Print / Log debugging
- 매 simplest.
- 매 strategic placement.
#### Debugger (breakpoint)
- 매 step-through.
- 매 inspect state.
- 매 conditional breakpoint.
#### Logging + observability
- 매 structured log.
- 매 distributed trace.
- 매 metric.
#### Time-travel
- 매 Redux DevTools, Reduxify.
- 매 action replay.
#### Differential
- 매 git bisect.
- 매 binary search of commits.
#### Rubber duck
- 매 explain to inanimate.
- 매 self-clarification.
#### Profiling
- 매 CPU / memory / GPU.
### 매 modern stack
#### Frontend
- **Sentry**: error tracking + session replay.
- **LogRocket**: session replay focus.
- **Datadog RUM**.
- **PostHog**.
- **Chrome DevTools** (Performance + Memory).
- **React DevTools**.
- **Redux DevTools**.
#### Backend
- **Sentry**: error tracking.
- **Datadog APM** / **New Relic**.
- **OpenTelemetry**: standard.
- **Honeycomb**: 매 observability 의 best.
- **Jaeger / Zipkin**: tracing.
#### Logs / metrics
- **Grafana + Loki + Prometheus**.
- **ELK / OpenSearch**.
### LLM-aided debugging
- **Cursor / Copilot**: 매 inline suggestion.
- **Cody / Continue**: 매 codebase-aware.
- **Sentry AI**: 매 root cause suggest.
- **Stack trace → 매 LLM 의 fix proposal**.
### 매 prevention
- **Type check** (TypeScript).
- **Linter** (ESLint).
- **Test** (unit / integration / e2e).
- **Property-based test**.
- **Sanitizer** (UBSan, ASan, TSan).
- **Fuzz test**.
## 💻 패턴
### Sentry (frontend)
```ts
import * as Sentry from '@sentry/react';
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations: [
Sentry.browserTracingIntegration(),
Sentry.replayIntegration({
maskAllText: true, // 매 PII protection
blockAllMedia: true,
}),
],
tracesSampleRate: 0.1, // 매 10%
replaysSessionSampleRate: 0.05,
replaysOnErrorSampleRate: 1.0, // 매 100% on error
release: process.env.RELEASE,
environment: process.env.NODE_ENV,
});
// 매 manual breadcrumb
Sentry.addBreadcrumb({
category: 'auth',
message: 'User logged in',
level: 'info',
});
// 매 manual capture
try {
riskyOperation();
} catch (e) {
Sentry.captureException(e, {
tags: { feature: 'checkout' },
extra: { orderId: '...' },
});
}
```
### Error Boundary (React)
```tsx
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
Sentry.captureException(error, { extra: info });
}
render() {
if (this.state.hasError) return <Fallback />;
return this.props.children;
}
}
<ErrorBoundary>
<App />
</ErrorBoundary>
```
### Distributed tracing (OpenTelemetry)
```python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
@tracer.start_as_current_span('handle_request')
def handle(req):
span = trace.get_current_span()
span.set_attribute('user.id', req.user.id)
with tracer.start_as_current_span('db_query') as db_span:
db_span.set_attribute('db.statement', 'SELECT * FROM users WHERE id = ?')
result = db.query(...)
return result
```
### git bisect (commit-level)
```bash
git bisect start
git bisect bad HEAD # 매 broken now
git bisect good v1.0 # 매 known good
# 매 매 step:
# Run test → 'good' or 'bad'
git bisect good
# 매 끝나면
git bisect reset
```
### Time-travel (Redux DevTools)
```ts
import { configureStore } from '@reduxjs/toolkit';
const store = configureStore({
reducer: rootReducer,
devTools: process.env.NODE_ENV !== 'production',
});
// 매 매 action 의 record + 매 replay 가능.
```
### Memory leak detection
```js
// 매 [[Chrome DevTools 메모리 프로파일링]] 참조
// 매 3-snapshot technique
// 1. Heap snapshot baseline.
// 2. 매 suspect action × 5.
// 3. Heap snapshot.
// 4. Compare → detached DOM, growing objects.
```
### Performance profiling
```js
// 매 Chrome DevTools Performance tab
performance.mark('start_search');
const results = expensiveSearch(query);
performance.mark('end_search');
performance.measure('search', 'start_search', 'end_search');
// 매 prod: web-vitals + measurement
import { onINP } from 'web-vitals';
onINP(metric => sendToAnalytics(metric));
```
### Reproducible bug report
```markdown
## Repro
1. ...
2. ...
## Expected
...
## Actual
...
## Environment
- Browser: Chrome 130
- OS: macOS 15
- Build: abc123 (commit: SHA)
- User: id 42 (test account)
## Logs / screenshots
[Sentry link, console output, screenshot]
```
### Property-based test (Hypothesis / fast-check)
```python
from hypothesis import given, strategies as st
@given(st.integers(), st.integers())
def test_addition_commutative(a, b):
assert add(a, b) == add(b, a)
```
### LLM-aided debug (stack trace)
```python
def llm_suggest_fix(error_message, traceback, code_context):
prompt = f"""Bug report:
Error: {error_message}
Traceback:
{traceback}
Code context:
{code_context}
Suggest:
1. Most likely root cause (1-2 sentences).
2. Specific fix (code diff).
3. How to prevent recurrence (test, type, validation).
Be specific, no generic advice."""
return llm.generate(prompt)
```
### Bisection (manual binary search)
```python
def bisect_failing_input(test_fn, inputs):
"""매 매 input 의 specific 의 fail 하는 case 의 narrow."""
lo, hi = 0, len(inputs) - 1
while lo < hi:
mid = (lo + hi) // 2
if test_fn(inputs[:mid + 1]).failed:
hi = mid
else:
lo = mid + 1
return inputs[lo]
```
### Conditional breakpoint
```js
// 매 Chrome DevTools: 매 매 breakpoint 의 right-click → "Edit breakpoint" → condition
// 매 example: user.id === 42 && retryCount > 5
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Reproducible | Debugger + breakpoint |
| Production | Sentry + session replay |
| Performance | DevTools Performance + APM |
| Memory leak | Heap snapshot 3-shot |
| Distributed | OpenTelemetry trace |
| Bisection | git bisect |
| Cannot reproduce | Session replay + log search |
| Heisenbug | Differential debug + logging |
**기본값**: Sentry + DevTools + git bisect + LLM assist.
## 🔗 Graph
- 부모: [[Debugging]] · [[Observability]]
- 변형: [[Sentry]] · [[OpenTelemetry]] · [[LogRocket]]
- 응용: [[Chrome DevTools 메모리 프로파일링]] · [[Bottlenecks]] · [[CI_CD 파이프라인 및 IDE 통합 보안]]
- Adjacent: [[Concept-Drift]] · [[Quality_Code_Review_Modern]] · [[Bottlenecks]] · [[Code_Smells]]
## 🤖 LLM 활용
**언제**: 매 stack trace analysis. 매 root cause hypothesis. 매 test design.
**언제 X**: 매 sensitive data (no upload to LLM).
## ❌ 안티패턴
- **No reproducer**: 매 hard to fix.
- **No observability**: 매 prod 의 silent.
- **Print all the things** (no structure): 매 noise.
- **No sample / batch**: 매 cost ↑.
- **Skip prevention** (no test for fix): 매 regression.
- **Privacy 의 ignore** (session replay): 매 PII leak.
## 🧪 검증 / 중복
- Verified (Sentry / Datadog docs, OpenTelemetry standard, Chrome DevTools).
- 신뢰도 A.
- Related: [[Chrome DevTools 메모리 프로파일링]] · [[Bottlenecks]] · [[CI_CD 파이프라인 및 IDE 통합 보안]] · [[Quality_Code_Review_Modern]] · [[Concept-Drift]].
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — process + tools + 매 Sentry / OTel / git bisect / LLM debug code |