debugging について
エラー、ログ、パフォーマンス、分散システムの問題を調べる開発者向けデバッグスキルです。仮説に基づく調査手順や分析テンプレートに加え、Python と JavaScript/Node.js の例を扱います。
主な機能
- 01仮説に基づくトラブルシューティング
- 02複雑なバグ向け拡張思考の指針
- 03MECE・5 Whys・タイムラインのテンプレート
- 04Python のデバッグとログの例
- 05JavaScript/Node.js のデバッグ例
- 06コンテナのデバッグ手順
活用シーン
- 01断続的なエラーの原因を特定
- 02分散サービスにまたがる障害を分析
- 03性能低下やリソース問題を調査
- 04ログやデバッガーで仮説を検証
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ thelobbi/ claude --skill debuggingインストール後、Claude Code で/debuggingを入力して読み込まれたか確認します。
詳細
デバッグスキル
複雑なシナリオに対応する、拡張思考を統合した包括的なデバッグ機能を提供します。
このスキルを使用するタイミング
次の作業を行うときに、このスキルを有効にしてください。
- エラーのトラブルシューティング
- ログ分析
- パフォーマンスのデバッグ
- 分散システムのデバッグ
- メモリやリソースの問題への対処
- 深い推論を要する、複雑で多層的なバグへの対処
複雑なデバッグにおける拡張思考
拡張思考を有効にするタイミング
デバッグ時には、次のような場合に拡張思考(Claude のより深い推論モード)を使用してください。
- 根本原因が不明:考えられる原因が複数あり、障害のパターンが明確でない場合
- 断続的な問題:競合状態、タイミングの問題、非決定的な障害がある場合
- 複数システムにまたがる障害:複数のサービスに及ぶ分散システムのバグがある場合
- 原因不明のパフォーマンス問題:明らかなボトルネックがないのに、予想外に遅くなる場合
- 複雑な状態の問題:複雑な状態遷移や副作用が関係するバグがある場合
- セキュリティ脆弱性:慎重な分析を要する、見つけにくいセキュリティ上の問題がある場合
拡張思考を有効にする方法
# In your debugging prompt
Claude, please use extended thinking to help debug this issue:
[Describe the problem with symptoms, context, and what you've tried]
拡張思考では、次のことが可能になります。
- 仮説を体系的に生成する
- 複数の調査経路を立てる
- より深くパターンを認識する
- 分野を横断した洞察を得る(例:ネットワーク+アプリケーション+インフラストラクチャ)
仮説駆動型デバッグのフレームワーク
複雑なバグには、次の構造化されたアプローチを使用してください。
1. 観察フェーズ
What happened?
- Error message/stack trace
- Frequency (always/intermittent)
- When it started
- Environmental context
- Recent changes
2. 仮説の生成
Generate 3-5 plausible hypotheses:
H1: [Most likely cause based on symptoms]
Evidence for: [...]
Evidence against: [...]
Test: [How to validate/invalidate]
H2: [Alternative explanation]
Evidence for: [...]
Evidence against: [...]
Test: [How to validate/invalidate]
H3: [Edge case or rare scenario]
Evidence for: [...]
Evidence against: [...]
Test: [How to validate/invalidate]
3. 体系的なテスト
Priority order (high to low confidence):
1. Test H1 → Result: [Pass/Fail/Inconclusive]
2. Test H2 → Result: [Pass/Fail/Inconclusive]
3. Test H3 → Result: [Pass/Fail/Inconclusive]
New evidence discovered:
- [Finding 1]
- [Finding 2]
Revised hypotheses if needed:
- [...]
4. 根本原因の特定
Confirmed root cause: [...]
Contributing factors: [...]
Why it wasn't caught earlier: [...]
5. 修正と検証
Fix implemented: [...]
Tests added: [...]
Validation: [...]
Prevention: [...]
構造化されたデバッグテンプレート
テンプレート 1:MECE によるバグ分析(相互排他的かつ全体網羅的)
## Bug: [Title]
### Problem Statement
- **What**: [Precise description]
- **Where**: [System/component]
- **When**: [Conditions/triggers]
- **Impact**: [Severity/scope]
### MECE Hypothesis Tree
**Layer 1: System Boundaries**
- [ ] Frontend issue
- [ ] Backend API issue
- [ ] Database issue
- [ ] Infrastructure/network issue
- [ ] External dependency issue
**Layer 2: Component-Specific** (based on Layer 1 finding)
- [ ] [Sub-component A]
- [ ] [Sub-component B]
- [ ] [Sub-component C]
**Layer 3: Code-Level** (based on Layer 2 finding)
- [ ] Logic error
- [ ] State management
- [ ] Resource handling
- [ ] Configuration
### Investigation Log
| Time | Action | Result | Next Step |
|------|--------|--------|-----------|
| [HH:MM] | [What you tested] | [Finding] | [Decision] |
### Root Cause
[Final determination with evidence]
### Fix
[Solution with rationale]
テンプレート 2:5 Whys 分析
## Issue: [Brief description]
**Symptom**: [Observable problem]
**Why 1**: Why did this happen?
→ [Answer]
**Why 2**: Why did [answer from Why 1] occur?
→ [Answer]
**Why 3**: Why did [answer from Why 2] occur?
→ [Answer]
**Why 4**: Why did [answer from Why 3] occur?
→ [Answer]
**Why 5**: Why did [answer from Why 4] occur?
→ [Root cause]
**Fix**: [Addresses root cause]
**Prevention**: [Process/check to prevent recurrence]
テンプレート 3:タイムラインの再構築
## Incident Timeline: [Event]
**Goal**: Reconstruct exact sequence leading to failure
| Time | Event | System State | Evidence |
|------|-------|--------------|----------|
| T-5min | [Normal operation] | [State] | [Logs] |
| T-2min | [Trigger event] | [State change] | [Logs/metrics] |
| T-30s | [Cascade starts] | [Degraded] | [Alerts] |
| T-0 | [Failure] | [Failed state] | [Error logs] |
| T+5min | [Recovery action] | [Recovering] | [Actions taken] |
**Critical Path**: [Sequence of events that led to failure]
**Alternative Scenarios**: [What could have prevented it at each step]
Python のデバッグパターン
仮説駆動型 Python デバッグの例
```python """ バグ:API エンドポイントが断続的に 500 エラーを返す 症状:10 件に 1 件のリクエストが失敗し、毎回同じユーザー ID で発生する 仮説:ユーザーデータのキャッシュで競合状態が発生している """
H1:ユーザー間でキャッシュキーが衝突している
テスト:キャッシュ操作の前後に詳細なログを追加する
import logging logging.basicConfig(level=logging.DEBUG)
def get_user(user_id): cache_key = f"user:{user_id}" logging.debug(f"キャッシュキーを取得:{cache_key}、ユーザー {user_id}")
cached = cache.get(cache_key)
if cached:
logging.debug(f"キャッシュヒット:{cache_key} -> {cached}")
return cached
user = db.query(User).filter_by(id=user_id).first()
logging.debug(f"ユーザー {user_id} の DB 取得:{user}")
cache.set(cache_key, user, timeout=300)
logging.debug(f"キャッシュを設定:{cache_key} -> {user}")
return user
結果:コードパスによって cache_key の形式が異なることを発見
根本原因:文字列フォーマットの不整合(f"user:{id}" と f"user_{id}")
```
コンテキストマネージャーを使った高度なデバッグ
```python import time from contextlib import contextmanager
@contextmanager def debug_timer(operation_name): """処理時間を計測し、遅い場合にログを記録する""" start = time.perf_counter() try: yield finally: duration = time.perf_counter() - start if duration > 1.0: # 遅い処理のしきい値 logging.warning( f"{operation_name} の処理に {duration:.2f} 秒かかりました", extra={'operation': operation_name, 'duration': duration} )
使用例
with debug_timer("database_query"): results = db.query(User).filter(...).all()
@contextmanager def hypothesis_test(hypothesis_name, expected_outcome): """デバッグ仮説をテストして検証する""" print(f"\n=== テスト中:{hypothesis_name} ===") print(f"予想される結果:{expected_outcome}") start_state = capture_state() try: yield finally: end_state = capture_state() outcome = compare_states(start_state, end_state) print(f"実際の結果:{outcome}") print(f"仮説 {'CONFIRMED' if outcome == expected_outcome else 'REJECTED'}")
使用方法
with hypothesis_test( "H1: データベース接続プールの枯渇", expected_outcome="負荷中にpool_sizeが増加する" ): # 負荷テストを実行 for i in range(100): api_call() ```
高度なテクニックを使ったpdbデバッガー
```python
基本的なブレークポイント
import pdb; pdb.set_trace()
Python 3.7+
breakpoint()
条件付きブレークポイント
if user_id == 12345: breakpoint()
事後デバッグ(クラッシュ後にデバッグ)
import pdb try: risky_function() except Exception: pdb.post_mortem()
よく使うpdbコマンド
n(ext) - 次の行を実行
s(tep) - 関数の中に入る
c(ontinue) - 実行を続ける
p expr - 式を出力
pp expr - 整形して出力
l(ist) - ソースコードを表示
w(here) - スタックトレースを表示
u(p) - スタックフレームを上に移動
d(own) - スタックフレームを下に移動
b(reak) - ブレークポイントを設定
cl(ear) - ブレークポイントをクリア
q(uit) - デバッガーを終了
高度な方法:プログラムからのデバッグ
import pdb pdb.run('my_function()', globals(), locals()) ```
ロギング
```python import logging
logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler('debug.log'), logging.StreamHandler() ] )
logger = logging.getLogger(name)
logger.debug("デバッグメッセージ") logger.info("情報メッセージ") logger.warning("警告メッセージ") logger.error("エラーメッセージ", exc_info=True) ```
例外処理
```python import traceback
try: result = risky_operation() except Exception as e: # トレースバック全体を記録 logger.error(f"操作に失敗しました: {e}") logger.error(traceback.format_exc())
# または、トレースバックを文字列として取得
tb = traceback.format_exception(type(e), e, e.__traceback__)
error_details = ''.join(tb)
```
JavaScript/Node.jsのデバッグ
仮説に基づくJavaScriptデバッグの例
```javascript /**
- バグ:WebSocket接続でのメモリリーク
- 症状:時間の経過とともにメモリが増加し、最終的にクラッシュする
- 仮説:切断時にイベントリスナーがクリーンアップされていない */
// H1:イベントリスナーが蓄積している // テスト:リスナー数を追跡 class WebSocketManager { constructor() { this.connections = new Map(); this.debugListenerCounts = true; }
addConnection(userId, socket) { console.debug(`[H1 Test] ユーザー ${userId} の接続を追加`);
if (this.debugListenerCounts) {
console.debug(\`[H1] 追加前のリスナー数:\${socket.listenerCount('message')}\`);
}
socket.on('message', (data) => this.handleMessage(userId, data));
socket.on('close', () => this.removeConnection(userId));
if (this.debugListenerCounts) {
console.debug(\`[H1] 追加後のリスナー数:\${socket.listenerCount('message')}\`);
}
this.connections.set(userId, socket);
}
removeConnection(userId) { console.debug(`[H1 Test] ユーザー ${userId} の接続を削除`);
const socket = this.connections.get(userId);
if (socket) {
const messageListenerCount = socket.listenerCount('message');
console.debug(\`[H1] まだアタッチされているリスナー:\${messageListenerCount}\`);
// 結果:同じイベントに3つ以上のリスナーがあることを発見!
// 根本原因:再接続時にリスナーを削除していない
socket.removeAllListeners();
this.connections.delete(userId);
}
} } ```
高度なコンソールデバッグ
```javascript // 基本的なログ出力 console.log('Basic log'); console.error('Error message'); console.warn('Warning');
// 深さを指定したオブジェクトの確認 console.dir(object, { depth: null, colors: true }); console.table(array);
// パフォーマンス計測 console.time('operation'); // ... code ... console.timeEnd('operation');
// メモリ使用量 console.memory; // Chrome only
// スタックトレース console.trace('Trace point');
// ログを整理するためのグループ化 console.group('User Authentication Flow'); console.log('Step 1: Validate credentials'); console.log('Step 2: Generate token'); console.groupEnd();
// 条件付きログ出力 const debug = (label, data) => { if (process.env.DEBUG) { console.log(`[DEBUG] ${label}:`, JSON.stringify(data, null, 2)); } };
// 仮説検証用ヘルパー function testHypothesis(name, test, expected) { console.group(`Testing: ${name}`); console.log(`Expected: ${expected}`); const actual = test(); console.log(`Actual: ${actual}`); console.log(`Result: ${actual === expected ? 'PASS' : 'FAIL'}`); console.groupEnd(); return actual === expected; }
// 使用例 testHypothesis( 'H1: Cache returns stale data', () => cache.get('key').timestamp, Date.now() ); ```
Async/Promise の問題のデバッグ
```javascript // Promise チェーンを追跡 const debugPromise = (label, promise) => { console.log(`[${label}] Started`); return promise .then(result => { console.log(`[${label}] Resolved:`, result); return result; }) .catch(error => { console.error(`[${label}] Rejected:`, error); throw error; }); };
// 使用例 await debugPromise('DB Query', db.users.findOne({ id: 123 }));
// 競合状態のデバッグ async function debugRaceCondition() { const operations = [ { name: 'Op1', fn: async () => { await delay(100); return 'A'; } }, { name: 'Op2', fn: async () => { await delay(50); return 'B'; } }, { name: 'Op3', fn: async () => { await delay(150); return 'C'; } } ];
const results = await Promise.allSettled( operations.map(async op => { const start = Date.now(); const result = await op.fn(); const duration = Date.now() - start; console.log(`${op.name} completed in ${duration}ms: ${result}`); return { op: op.name, result, duration }; }) );
console.table(results.map(r => r.value)); }
// 弱参照を使用したメモリリークのデバッグ class DebugMemoryLeaks { constructor() { this.weakMap = new WeakMap(); this.strongRefs = new Map(); }
trackObject(id, obj) { // 弱参照 - ほかに参照がなければ GC によって回収されます this.weakMap.set(obj, { id, created: Date.now() });
// 強参照 - GC を妨げます(リークの原因となる可能性があります)
this.strongRefs.set(id, obj);
console.log(\`Tracking \${id}: Strong refs=\${this.strongRefs.size}\`);
}
release(id) { this.strongRefs.delete(id); console.log(`Released ${id}: Strong refs=${this.strongRefs.size}`); }
checkLeaks() { console.log(`Potential leaks: ${this.strongRefs.size} strong references`); return Array.from(this.strongRefs.keys()); } } ```
Node.js Inspector
```bash
Inspector を有効にして起動
node --inspect app.js node --inspect-brk app.js # 最初の行で停止
Chrome DevTools でデバッグ
chrome://inspect を開く
```
VS Code デバッグ構成
```json { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Debug Agent", "program": "${workspaceFolder}/src/index.js", "env": { "NODE_ENV": "development" } } ] } ```
コンテナーのデバッグ
Docker
```bash
ログを表示
docker logs --tail=100 -f
シェルを実行
docker exec -it /bin/sh
コンテナーを調査
docker inspect
リソース使用量
docker stats
実行中のコンテナをデバッグする
docker run -it --rm
--network=container:
nicolaka/netshoot
```
Kubernetes
```bash
Pod のログ
kubectl logs -n agents -f kubectl logs -n agents --previous # 前回のクラッシュ
Pod 内でコマンドを実行
kubectl exec -it -n agents -- /bin/sh
エフェメラルコンテナでデバッグ
kubectl debug -n agents -it --image=busybox
ローカルデバッグ用のポートフォワード
kubectl port-forward 8080:8080 -n agents
イベント
kubectl get events -n agents --sort-by='.lastTimestamp'
リソース使用状況
kubectl top pods -n agents ```
ログ分析
パターンマッチング
```bash
ログからエラーを検索
grep -i "error|exception|failed" app.log
発生回数をカウント
grep -c "ERROR" app.log
該当箇所の前後のコンテキストを表示
grep -B 5 -A 5 "OutOfMemory" app.log
時間範囲で絞り込み
awk '/2024-01-15 10:00/,/2024-01-15 11:00/' app.log ```
JSON ログ
```bash
jq で JSON ログを解析
cat app.log | jq 'select(.level == "error")' cat app.log | jq 'select(.timestamp > "2024-01-15T10:00:00")'
特定のフィールドを抽出
cat app.log | jq -r '[.timestamp, .level, .message] | @tsv' ```
パフォーマンスのデバッグ
Python のプロファイリング
```python
cProfile
import cProfile cProfile.run('main()', 'output.prof')
行プロファイラー
@profile def slow_function(): pass
メモリプロファイラー
from memory_profiler import profile
@profile def memory_heavy(): pass ```
ネットワークのデバッグ
```bash
接続を確認
ping telnet nc -zv
DNS の名前解決
nslookup dig
HTTP のデバッグ
curl -v http://localhost:8080/health curl -X POST -d '{"test": true}' -H "Content-Type: application/json" http://localhost:8080/api ```
よくあるデバッグ項目のチェックリスト
- ログを確認する:アプリケーション、システム、コンテナのログ
- 設定を確認する:環境変数、設定ファイル
- 接続をテストする:ネットワーク、データベース、外部サービス
- リソースを確認する:CPU、メモリ、ディスク容量
- 最近の変更を確認する:Git ログ、デプロイ履歴
- ローカルで再現する:同じ環境、同じデータ
- 二分探索する:問題の範囲を特定する
デバッグの判断ツリー
この判断ツリーを使って、適切なデバッグ方法を判断します。
START: What kind of bug?
│
├─ Known error message/stack trace
│ └─ Use: Direct log analysis + Stack trace walkthrough
│
├─ Intermittent/Race condition
│ └─ Use: Extended thinking + Timeline reconstruction + Hypothesis-driven
│
├─ Performance degradation
│ └─ Use: Profiling + Hypothesis-driven + MECE analysis
│
├─ Distributed system failure
│ └─ Use: Extended thinking + Timeline reconstruction + Multi-system tracing
│
├─ Complex state bug
│ └─ Use: Extended thinking + Hypothesis-driven + pdb/debugger
│
├─ Memory leak
│ └─ Use: Memory profiling + Hypothesis-driven + Weak reference analysis
│
└─ Unknown root cause
└─ Use: Extended thinking + MECE analysis + 5 Whys
複雑なデバッグのベストプラクティス
1. 調査内容を記録する
デバッグログを常に記録してください。
## Bug Investigation: [Title]
**Start Time**: 2024-01-15 10:00
**Investigator**: [Name]
### Timeline
- 10:00 - Started investigation, checked logs
- 10:15 - Found error pattern in auth service
- 10:30 - Hypothesis: Cache expiration race condition
- 10:45 - Added debug logging, confirmed hypothesis
- 11:00 - Implemented fix, testing
### Hypotheses Tested
- [x] H1: Cache race condition (CONFIRMED)
- [ ] H2: Database connection pool (REJECTED)
- [ ] H3: Network timeout (NOT TESTED)
### Root Cause
[Final determination]
### Fix Applied
[Solution details]
### Prevention
[How to prevent recurrence]
2. 科学的手法を使う
- 観察する:症状、エラーメッセージ、ログを収集する
- 仮説を立てる:もっともらしい説明を3~5個考える
- 予測する:仮説が正しい場合、何が確認できるでしょうか。
- テストする:仮説を検証または否定する実験を設計する
- 分析する:予測と実際の結果を比較する
- 結論を出す:証拠に基づいて根本原因を確認する
3. 拡張思考を活用する
拡張思考を有効にするタイミング:
- 複雑さのしきい値:相互に作用するシステムが3つを超える場合
- 不確実性が高い:可能性が同程度にある原因が複数ある場合
- 影響が大きい:本番環境の停止、セキュリティ問題、データ損失
- パターンが不明瞭:明らかなエラーメッセージやログがない場合
- 時間的制約がある:プレッシャーの下で体系的なアプローチが必要な場合
4. よくある落とし穴を避ける
AVOID:
- ❌ Changing multiple things at once (can't isolate cause)
- ❌ Assuming first hypothesis is correct (confirmation bias)
- ❌ Debugging without logs/evidence (guessing)
- ❌ Not documenting what you tried (repeating failed attempts)
- ❌ Skipping reproduction step (fix might not work)
DO:
- ✅ Change one variable at a time
- ✅ Test multiple hypotheses systematically
- ✅ Add instrumentation before debugging
- ✅ Keep investigation log
- ✅ Write regression test after fix
5. デバッグ計測のパターン
# Python: Comprehensive debugging decorator
import functools
import time
import logging
def debug_trace(func):
"""Decorator to trace function execution with timing and state"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
func_name = func.__qualname__
logger.debug(f"→ Entering {func_name}")
logger.debug(f" Args: {args}")
logger.debug(f" Kwargs: {kwargs}")
start = time.perf_counter()
try:
result = func(*args, **kwargs)
duration = time.perf_counter() - start
logger.debug(f"← Exiting {func_name} ({duration:.3f}s)")
logger.debug(f" Result: {result}")
return result
except Exception as e:
duration = time.perf_counter() - start
logger.error(f"✗ Exception in {func_name} ({duration:.3f}s): {e}")
raise
return wrapper
# Usage
@debug_trace
def complex_operation(user_id, data):
# Your code here
pass
// JavaScript: Comprehensive debugging wrapper
function debugTrace(label) {
return function(target, propertyKey, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = async function(...args) {
console.log(\`→ Entering \${label || propertyKey}\`);
console.log(\` Args:\`, args);
const start = performance.now();
try {
const result = await originalMethod.apply(this, args);
const duration = performance.now() - start;
console.log(\`← Exiting \${label || propertyKey} (\${duration.toFixed(2)}ms)\`);
console.log(\` Result:\`, result);
return result;
} catch (error) {
const duration = performance.now() - start;
console.error(\`✗ Exception in \${label || propertyKey} (\${duration.toFixed(2)}ms):\`, error);
throw error;
}
};
return descriptor;
};
}
// Usage
class UserService {
@debugTrace('UserService.getUser')
async getUser(userId) {
// Your code here
}
}
相互参照と関連スキル
関連スキル
このデバッグスキルは、以下のスキルと連携します。
-
extended-thinking (
.claude/skills/extended-thinking/SKILL.md)- 使用場面:根本原因が不明な複雑なバグ
- 有効化方法:デバッグプロンプトに「use extended thinking」を追加します
- 利点:より深いパターン認識と、体系的な仮説の生成
-
complex-reasoning (
.claude/skills/complex-reasoning/SKILL.md)- 使用場面:論理的な連鎖を必要とする複数ステップのデバッグ
- パターン:バグ調査におけるChain-of-thought、tree-of-thought
- 利点:複雑なバグシナリオを構造的に推論できます
-
deep-analysis (
.claude/skills/deep-analysis/SKILL.md)- 使用場面:事後分析、根本原因の調査
- パターン:包括的なコードレビュー、アーキテクチャ分析
- 利点:表面的なバグにとどまらず、システム上の問題を特定します
-
testing (
.claude/skills/testing/SKILL.md)- 使用場面:バグ修正後の回帰テストの作成
- 連携:バグ → デバッグ → 修正 → テスト → 検証
- 利点:バグの再発を防ぎます
-
kubernetes (
.claude/skills/kubernetes/SKILL.md)- 使用場面:K8s における分散システムのデバッグ
- ツール:kubectl logs、exec、debug、events
- 連携:コンテナのデバッグパターン
スキルを組み合わせる場面
| シナリオ | 組み合わせるスキル | 理由 |
|---|---|---|
| 本番環境の停止 | debugging + extended-thinking + kubernetes | 複雑な分散システムには深い推論が必要です |
| 断続的なテスト失敗 | debugging + testing + complex-reasoning | 仮説を体系的に検証する必要があります |
| パフォーマンスの低下 | debugging + deep-analysis | 根本原因がアーキテクチャにある可能性があります |
| セキュリティ脆弱性 | debugging + extended-thinking + deep-analysis | 慎重かつ徹底した分析が必要です |
| メモリリーク | debugging + complex-reasoning | 複数ステップにわたる調査が必要です |
連携例
例 1:複雑な本番環境のバグ
# Prompt combining skills
Claude, I have a complex production bug affecting multiple services.
Please use extended thinking and the debugging skill to help investigate.
Symptoms:
- API requests timeout intermittently (1 in 50 requests)
- Only affects authenticated users
- Started after recent deployment
- No obvious errors in logs
Please use:
1. MECE analysis to categorize possible causes
2. Hypothesis-driven debugging framework
3. Timeline reconstruction of recent changes
例 2:メモリリークの調査
# Prompt combining skills
Claude, use complex reasoning and debugging skills to investigate a memory leak.
Context:
- Node.js service memory grows from 200MB to 2GB over 6 hours
- No errors logged
- Happens only in production, not staging
Apply:
1. Hypothesis-driven framework (generate 5 hypotheses)
2. Memory leak detection patterns (weak references)
3. Extended thinking for pattern recognition across codebase
クイックリファレンスカード
デバッグワークフローの概要
1. OBSERVE
- Collect error messages, logs, metrics
- Identify patterns (frequency, conditions, scope)
- Document symptoms
2. HYPOTHESIZE (use extended thinking if complex)
- Generate 3-5 plausible hypotheses
- Rank by likelihood
- Design tests for each
3. TEST
- Change one variable at a time
- Add instrumentation (logging, tracing)
- Collect evidence
4. ANALYZE
- Compare predictions vs results
- Eliminate invalidated hypotheses
- Refine remaining hypotheses
5. FIX
- Implement solution
- Add regression test
- Document root cause
6. VALIDATE
- Verify fix in affected environment
- Monitor metrics
- Update documentation
ツール選択ガイド
| 問題の種類 | 主なツール | 副次的なツール |
|---|---|---|
| ロジックエラー | pdb/debugger | ロギング、ユニットテスト |
| パフォーマンス | Profiler | 仮説検証、メトリクス |
| メモリリーク | Memory profiler | 弱参照、ヒープダンプ |
| 非同期処理/タイミング | タイムラインの再構築 | Extended thinking、ロギング |
| 分散システム | トレーシング(ログ) | Kubernetes ツール、MECE 分析 |
| 原因不明 | Extended thinking | MECE、5 Whys、仮説駆動型 |
スキルのバージョン:2.0(extended thinking との連携を強化) 最終更新日:2024-01-15 管理者:Golden Armada AI Agent Fleet