Back to list
gtakairo

systematic-debugging

by gtakairo

Personal dotfiles and development environment configurations with comprehensive Claude Code setup

0🍴 0📅 Jan 17, 2026

SKILL.md


name: systematic-debugging description: "Four-phase systematic debugging methodology for efficient problem resolution. Use when investigating bugs, errors, or unexpected behavior." enabled: true visibility: default allowedTools: ["bash", "read", "grep", "glob"]

Systematic Debugging Skill

Apply structured debugging methodology to identify and resolve issues efficiently.

Four-Phase Debugging Process

Phase 1: Reproduction

Goal: Reliably reproduce the bug

Steps:

  1. Gather Information

    • Error messages and stack traces
    • User reports and steps to reproduce
    • Environment details (OS, versions)
    • Recent changes (commits, deployments)
  2. Create Minimal Reproduction

    • Reduce to smallest failing case
    • Isolate from unrelated code
    • Document exact steps
    • Verify consistency
  3. Document Observations

    • What happens vs. what should happen
    • Frequency (always, sometimes, rare)
    • Conditions that trigger the bug
    • Related symptoms

Output:

## Bug Reproduction

**Environment**:
- OS: Linux 6.14.0
- Language: Python 3.9
- Framework: Django 4.2

**Steps to Reproduce**:
1. Navigate to /api/users
2. Submit POST with empty body
3. Observe 500 error

**Expected**: 400 error with validation message
**Actual**: 500 internal server error
**Frequency**: 100% reproducible

Phase 2: Diagnosis

Goal: Identify root cause

Investigation Techniques:

  1. Binary Search Method

    • Comment out half the code
    • Narrow down the problematic section
    • Repeat until isolated
  2. Add Logging

    print(f"DEBUG: variable = {variable}")
    logging.debug(f"Function called with {args}")
    
  3. Use Debugger

    • Set breakpoints
    • Inspect variable values
    • Step through execution
    • Watch expressions
  4. Check Assumptions

    • Verify input values
    • Confirm function behavior
    • Validate external dependencies
    • Test edge cases
  5. Read Stack Traces

    File "app.py", line 42, in process_data
        result = transform(data)
    File "utils.py", line 15, in transform
        return data.strip()  # <- Error here
    AttributeError: 'NoneType' object has no attribute 'strip'
    
    • Start from bottom (actual error)
    • Trace upward through calls
    • Identify where None was introduced

Common Bug Patterns:

Null/Undefined:

// Bug: Accessing property of null
const name = user.profile.name;  // Error if profile is null

// Fix: Optional chaining
const name = user?.profile?.name ?? 'Unknown';

Off-by-One:

# Bug: Missing last element
for i in range(len(items) - 1):  # Wrong!
    process(items[i])

# Fix: Correct range
for i in range(len(items)):
    process(items[i])

Race Conditions:

// Bug: Async race condition
let data = null;
fetchData().then(result => { data = result; });
console.log(data);  // null - async not complete

// Fix: Await
const data = await fetchData();
console.log(data);  // Correct value

Type Confusion:

# Bug: String used as number
total = "5" + 3  # Result: "53" not 8

# Fix: Convert types
total = int("5") + 3  # Result: 8

Phase 3: Fix

Goal: Implement correct solution

Fix Guidelines:

  1. Understand Before Fixing

    • Don't guess and check
    • Know why the bug occurs
    • Consider side effects
  2. Minimal Changes

    • Fix only the bug
    • Avoid refactoring during fix
    • Keep changes reviewable
  3. Fix Root Cause, Not Symptoms

    # Bad: Hiding symptom
    try:
        process(data)
    except:
        pass  # Bug still exists!
    
    # Good: Fix root cause
    if data is not None and validate(data):
        process(data)
    else:
        handle_invalid_data(data)
    
  4. Add Defensive Code

    // Add validation
    function divide(a, b) {
      if (b === 0) {
        throw new Error('Division by zero');
      }
      return a / b;
    }
    
  5. Document the Fix

    # Fix: Handle None values from API
    # Bug: API returns None when user not found, causing AttributeError
    def get_user_name(user_id):
        user = api.get_user(user_id)
        return user.name if user else "Unknown User"
    

Phase 4: Verification

Goal: Ensure fix works and doesn't break anything

Verification Steps:

  1. Test the Fix

    • Run original reproduction steps
    • Verify bug no longer occurs
    • Test edge cases
  2. Add Regression Test

    def test_handle_none_user():
        """Regression test for user None bug"""
        user_id = 99999  # Non-existent
        name = get_user_name(user_id)
        assert name == "Unknown User"
    
  3. Run Full Test Suite

    • Unit tests
    • Integration tests
    • Ensure no regressions
  4. Manual Testing

    • Test related features
    • Check user workflows
    • Verify in staging environment
  5. Monitor After Deploy

    • Watch error logs
    • Check metrics
    • Get user feedback

Debugging Tools

Command-Line Tools

# Search for error patterns
grep -r "ERROR" logs/

# Find recent changes
git log --since="1 week ago" --oneline

# Check process/resources
ps aux | grep process_name
top -p PID

# Network debugging
curl -v http://api.example.com
netstat -an | grep PORT

Language-Specific Debuggers

Python:

import pdb; pdb.set_trace()  # Breakpoint
# or
breakpoint()  # Python 3.7+

JavaScript:

debugger;  // Breakpoint in browser/Node
console.log('Debug:', variable);
console.table(array);  // Formatted output

Bash:

set -x  # Print commands as executed
bash -x script.sh  # Debug mode

Debugging Strategies

When Stuck

  1. Take a Break

    • Fresh perspective helps
    • Avoid tunnel vision
  2. Explain to Someone

    • Rubber duck debugging
    • Clarifies thinking
  3. Simplify

    • Remove complexity
    • Test components separately
  4. Check Documentation

    • API documentation
    • Language specs
    • Framework guides
  5. Search for Similar Issues

    • Stack Overflow
    • GitHub issues
    • Error message search

Prevention

  • Write tests first (TDD)
  • Add logging early
  • Use type checking
  • Code reviews
  • Linting and static analysis

Debugging Checklist

  • Bug reliably reproduced
  • Minimal reproduction created
  • Root cause identified (not just symptom)
  • Fix implemented and tested
  • Regression test added
  • Full test suite passes
  • Documentation updated
  • Related code reviewed
  • Fix deployed and monitored

Common Debugging Mistakes

Guessing randomly → Use systematic approach ❌ Changing multiple things → Change one thing at a time ❌ Not reproducing first → Always reproduce reliably ❌ Fixing symptoms → Find and fix root cause ❌ No regression test → Add test to prevent recurrence ❌ Assuming cause → Verify with evidence ❌ Skipping verification → Always verify fix works


Example: Complete Debugging Session

## Bug: User Profile Page 500 Error

### Phase 1: Reproduction
- Error: 500 Internal Server Error on /profile/123
- Steps: Navigate to any user profile page
- Frequency: Intermittent (30% of requests)
- Stack trace: AttributeError in profile_view.py:45

### Phase 2: Diagnosis
- Added logging: Sometimes user.preferences is None
- Found: New users don't have preferences created
- Root cause: profile_view assumes preferences exist

### Phase 3: Fix
```python
# Before (buggy)
def get_user_profile(user_id):
    user = User.objects.get(id=user_id)
    theme = user.preferences.theme  # Crashes if None

# After (fixed)
def get_user_profile(user_id):
    user = User.objects.get(id=user_id)
    theme = user.preferences.theme if user.preferences else 'default'

Phase 4: Verification

  • ✓ Tested with new users (no preferences)
  • ✓ Tested with existing users (with preferences)
  • ✓ Added regression test
  • ✓ All tests pass
  • ✓ Deployed to staging
  • ✓ Monitoring - no errors after 24h

---

## Remember

> "Debugging is twice as hard as writing the code in the first place." - Brian Kernighan

- Be patient and systematic
- Document your findings
- Learn from each bug
- Prevent future occurrences

Score

Total Score

50/100

Based on repository quality metrics

SKILL.md

SKILL.mdファイルが含まれている

+20
LICENSE

ライセンスが設定されている

0/10
説明文

100文字以上の説明がある

0/10
人気

GitHub Stars 100以上

0/15
最近の活動

3ヶ月以内に更新がある

0/10
フォーク

10回以上フォークされている

0/5
Issue管理

オープンIssueが50未満

+5
言語

プログラミング言語が設定されている

+5
タグ

1つ以上のタグが設定されている

0/5

Reviews

💬

Reviews coming soon