chain-rdeveloper portal
build

Debug Procedures

Overview

This guide provides systematic debugging procedures for diagnosing issues in the Chainr platform.

Initial Assessment

1. Gather Context

# Get current system status
date
whoami
pwd
echo $PATH

# Check service status
docker ps -a
docker stats

# System resource usage
df -h
free -h
top -b -n1 | head -20

2. Review Logs

# Recent application logs
docker logs --tail 100 svc-core
docker logs --tail 100 svc-auth
docker logs --tail 100 svc-ai

# System logs
journalctl -u docker --since "1 hour ago"
dmesg | tail -50

# Nginx access/error logs
docker exec nginx tail -100 /var/log/nginx/access.log
docker exec nginx tail -100 /var/log/nginx/error.log

3. Check Health Endpoints

# Service health checks
curl -s http://localhost:8000/health | jq .
curl -s http://localhost:8001/health | jq .
curl -s http://localhost:8002/health | jq .

# Database connectivity
docker exec svc-core python -c "
import asyncpg
async def test():
    conn = await asyncpg.connect('postgresql://...')
    await conn.close()
    print('DB OK')
import asyncio
asyncio.run(test())
"

Application Debugging

API Request Debugging

1. Enable Debug Logging

# Temporarily enable debug logging
import logging
logging.basicConfig(level=logging.DEBUG)

# Or update settings
settings.monitoring.log_level = "DEBUG"

2. Trace Request Flow

# Add request tracing middleware
@app.middleware("http")
async def trace_requests(request, call_next):
    request_id = str(uuid.uuid4())
    logger.info(f"Request {request_id}: {request.method} {request.url}")

    start_time = time.time()
    response = await call_next(request)
    duration = time.time() - start_time

    logger.info(f"Response {request_id}: {response.status_code} in {duration:.2f}s")
    return response

3. Debug Authentication

# Test JWT token decoding
import jwt
from app.core.security import get_password_hash, verify_password

# Test password verification
hashed = get_password_hash("testpassword")
assert verify_password("testpassword", hashed)

# Test token creation/decoding
token = create_access_token({"sub": "user123"})
decoded = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
print(decoded)

Database Debugging

1. Query Analysis

-- Enable query logging
SET log_statement = 'all';
SET log_duration = 'on';

-- Check active connections
SELECT * FROM pg_stat_activity;

-- Find slow queries
SELECT
    query,
    total_time,
    mean_time,
    calls
FROM pg_stat_statements
ORDER BY total_time DESC
LIMIT 10;

-- Check table sizes
SELECT
    schemaname,
    tablename,
    pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size
FROM pg_tables
ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;

2. Connection Pool Monitoring

# SQLAlchemy engine status
from app.db.session import engine

# Check pool status
print(f"Pool size: {engine.pool.size()}")
print(f"Checked out: {engine.pool.checkedout()}")
print(f"Invalid: {engine.pool.invalid()}")
print(f"Recycled: {engine.pool._recycles}")

3. Migration Debugging

# Check migration status
alembic current
alembic history --verbose

# Debug migration script
alembic upgrade --sql head  # Show SQL without executing

# Manual migration execution
alembic upgrade +1  # Step by step

Cache Debugging

1. Redis Analysis

# Connect to Redis
redis-cli

# Check cache status
INFO
KEYS *
TTL chainr:*

# Monitor cache operations
MONITOR

# Check memory usage
INFO memory

2. Cache Hit/Miss Analysis

# Add cache debugging
class DebugCache:
    def __init__(self, redis_client):
        self.redis = redis_client
        self.hits = 0
        self.misses = 0

    async def get(self, key):
        value = await self.redis.get(key)
        if value:
            self.hits += 1
            print(f"CACHE HIT: {key}")
        else:
            self.misses += 1
            print(f"CACHE MISS: {key}")
        return value

    def get_stats(self):
        total = self.hits + self.misses
        hit_rate = self.hits / total if total > 0 else 0
        return {"hits": self.hits, "misses": self.misses, "hit_rate": hit_rate}

Performance Debugging

1. Profiling Application Code

# Use py-spy for production profiling
py-spy top --pid $(pgrep uvicorn)

# Memory profiling
from memory_profiler import profile

@profile
def slow_function():
    # Code to profile
    pass

# CPU profiling
import cProfile
cProfile.run('slow_function()', 'profile_output.prof')

# Analyze profile
import pstats
p = pstats.Stats('profile_output.prof')
p.sort_stats('cumulative').print_stats(20)

2. Database Performance Analysis

# SQLAlchemy query profiling
from sqlalchemy import event
from sqlalchemy.engine import Engine

@event.listens_for(Engine, "before_cursor_execute")
def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
    context._query_start_time = time.time()
    logger.debug(f"SQL: {statement}")
    logger.debug(f"Params: {parameters}")

@event.listens_for(Engine, "after_cursor_execute")
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
    total_time = time.time() - context._query_start_time
    if total_time > 0.1:  # Log slow queries
        logger.warning(f"SLOW QUERY ({total_time:.2f}s): {statement}")

3. Network Performance

# Test inter-service latency
time curl http://svc-auth:3000/health
time curl http://svc-ai:5000/health

# Network diagnostics
ping svc-core
traceroute svc-core

# Check network interfaces
ip addr show
netstat -tlnp

Frontend Debugging

1. Browser Developer Tools

// Console debugging
console.log("Debug info:", data);
console.table(arrayData);
console.time("operation");
// ... code ...
console.timeEnd("operation");

// Network tab analysis
// Check API calls, response times, status codes

// Application tab
// Local storage, session storage, cookies
// Service worker status

2. React DevTools

// Component debugging
const DebugComponent = ({ data }) => {
  console.log("Component props:", data);
  return <div>{/* component JSX */}</div>;
};

// Performance profiling
React.Profiler;

3. API Debugging

// Debug API calls
const debugFetch = async (url, options = {}) => {
  console.log("API Call:", url, options);
  const start = Date.now();

  try {
    const response = await fetch(url, options);
    const duration = Date.now() - start;

    console.log(`API Response (${duration}ms):`, {
      status: response.status,
      headers: Object.fromEntries(response.headers),
      url: response.url,
    });

    const data = await response.json();
    console.log("Response data:", data);
    return data;
  } catch (error) {
    console.error("API Error:", error);
    throw error;
  }
};

Container Debugging

1. Container Inspection

# Inspect running container
docker inspect svc-core

# Check container logs with timestamps
docker logs --timestamps svc-core

# Execute commands in running container
docker exec -it svc-core /bin/bash

# Check container resource usage
docker stats svc-core

2. Image Debugging

# Build with no cache for debugging
docker build --no-cache -t debug-image .

# Run container with debug options
docker run -it --entrypoint /bin/bash debug-image

# Check image layers
docker history debug-image

3. Multi-Container Debugging

# Check network connectivity
docker exec svc-core ping svc-auth

# Inspect network
docker network inspect chainr_default

# Test service discovery
docker exec svc-core nslookup svc-auth

External Service Debugging

1. AI Service Debugging

# Test OpenAI API directly
import openai

client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
try:
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": "Hello"}]
    )
    print("OpenAI API working:", response)
except Exception as e:
    print("OpenAI API error:", e)

2. Database Connection Debugging

# Test database connection
import asyncpg

async def debug_db():
    try:
        conn = await asyncpg.connect(
            user=os.getenv("DB_USER"),
            password=os.getenv("DB_PASSWORD"),
            database=os.getenv("DB_NAME"),
            host=os.getenv("DB_HOST")
        )

        # Test basic query
        result = await conn.fetchval("SELECT version()")
        print("DB version:", result)

        # Test application tables
        tables = await conn.fetchval("SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public'")
        print("Tables count:", tables)

        await conn.close()
        print("Database connection successful")

    except Exception as e:
        print("Database connection failed:", e)
        import traceback
        traceback.print_exc()

asyncio.run(debug_db())

Advanced Debugging Techniques

1. Remote Debugging

# Enable remote debugging
import debugpy

debugpy.listen(("0.0.0.0", 5678))
debugpy.wait_for_client()  # Wait for debugger to attach

# In VS Code launch.json
{
    "name": "Python: Remote Attach",
    "type": "python",
    "request": "attach",
    "connect": {
        "host": "localhost",
        "port": 5678
    }
}

2. Memory Leak Detection

# Use tracemalloc for memory debugging
import tracemalloc

tracemalloc.start()

# Take initial snapshot
snapshot1 = tracemalloc.take_snapshot()

# Run code that may leak
# ... application code ...

# Take second snapshot
snapshot2 = tracemalloc.take_snapshot()

# Compare snapshots
top_stats = snapshot2.compare_to(snapshot1, 'lineno')
for stat in top_stats[:10]:
    print(stat)

3. Race Condition Debugging

# Add logging for concurrent operations
import asyncio
import logging

logger = logging.getLogger(__name__)

async def concurrent_operation(lock: asyncio.Lock, operation_id: int):
    logger.info(f"Operation {operation_id}: Waiting for lock")
    async with lock:
        logger.info(f"Operation {operation_id}: Acquired lock")
        # Critical section
        await asyncio.sleep(0.1)
        logger.info(f"Operation {operation_id}: Released lock")

4. Load Testing for Debugging

# Use artillery for load testing
npm install -g artillery

# Create test script
echo '
config:
  target: "http://localhost:8000"
  phases:
    - duration: 60
      arrivalRate: 10
scenarios:
  - name: "API load test"
    requests:
      - get:
          url: "/api/projects"
' > load-test.yml

# Run load test
artillery run load-test.yml

Debug Data Collection

1. System Information

# Collect comprehensive system info
{
    echo "=== System Information ==="
    uname -a
    echo
    echo "=== Docker Version ==="
    docker --version
    echo
    echo "=== Running Containers ==="
    docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
    echo
    echo "=== Resource Usage ==="
    docker stats --no-stream
    echo
    echo "=== Recent Logs ==="
    docker logs --tail 50 svc-core
} > debug_info_$(date +%Y%m%d_%H%M%S).txt

2. Application State Dump

# Create application state snapshot
@app.get("/debug/state")
async def debug_state(db: Session = Depends(get_db)):
    return {
        "timestamp": datetime.utcnow(),
        "database": {
            "connection_count": len(db.get_bind().pool._pool),
            "active_connections": db.get_bind().pool.checkedout(),
        },
        "cache": {
            "redis_info": redis_client.info(),
        },
        "system": {
            "cpu_percent": psutil.cpu_percent(),
            "memory_percent": psutil.virtual_memory().percent,
            "disk_usage": psutil.disk_usage('/').percent,
        }
    }

Post-Debug Procedures

1. Clean Up Debug Code

  • Remove debug logging statements

  • Disable debug endpoints in production

  • Remove temporary debugging middleware

  • Revert configuration changes

2. Document Findings

## Debug Report: [Issue Title]

### Problem

[Description of the issue]

### Root Cause

[What was found to be causing the issue]

### Solution

[How the issue was resolved]

### Prevention

[Steps to prevent similar issues in the future]

### Files Changed

- [List of modified files]
- [Configuration changes]

3. Implement Monitoring

  • Add alerts for similar issues

  • Create dashboards for key metrics

  • Implement automated health checks

  • Set up log aggregation rules

4. Knowledge Base Updates

  • Update troubleshooting guides

  • Add to common issues documentation

  • Create runbooks for similar problems

  • Share findings with the team

Following these systematic debugging procedures will help quickly identify and resolve issues while building institutional knowledge for future problem-solving.