Files
2nd/10_Wiki/Topics/AI_and_ML/Debugging Methods.md
T
2026-05-10 22:08:15 +09:00

8.8 KiB
Raw Blame History

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-debugging-methods Debugging Methods 10_Wiki/Topics verified self
debugging
frontend debugging
observability
Sentry
LogRocket
time-travel debug
session replay
none A 0.93 applied
debugging
observability
sentry
logrocket
devtools
error-boundary
time-travel
profiling
2026-05-10 pending
language framework
JS / Python / Go 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)

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)

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)

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)

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)

import { configureStore } from '@reduxjs/toolkit';

const store = configureStore({
  reducer: rootReducer,
  devTools: process.env.NODE_ENV !== 'production',
});

// 매 매 action 의 record + 매 replay 가능.

Memory leak detection

// 매 [[Chrome DevTools 메모리 프로파일링]] 참조

// 매 3-snapshot technique
// 1. Heap snapshot baseline.
// 2. 매 suspect action × 5.
// 3. Heap snapshot.
// 4. Compare → detached DOM, growing objects.

Performance profiling

// 매 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

## 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)

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)

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)
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

// 매 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

🤖 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.

🧪 검증 / 중복

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — process + tools + 매 Sentry / OTel / git bisect / LLM debug code