Serverless debugging

From abcnuts/manus-skills · View interactive version

Serverless debugging is an AI agent skill from the GitHub repository abcnuts/manus-skills. Debug serverless and edge functions where traditional logging is limited. Use when features are deployed but not triggering, logs are missing, or runtime behavior differs from expectations in Supabase Edge Functions, AWS Lambda, Cloudflare Workers, or similar platforms.

How to use this skill

Skill file

Serverless Debugging

Systematic debugging methodology for serverless/edge functions where console.log may not appear in logs and traditional debugging tools are unavailable.

When to Use This Skill

Core Methodology: 4-Phase Approach

Phase 1: Evidence Gathering

Collect evidence from ALL layers before forming hypotheses. Avoid jumping to conclusions.

Database Layer:

Code Layer:

Runtime Layer:

Environment Layer:

Evidence Checklist: See references/evidence-checklist.md for comprehensive list

Phase 2: Pattern Analysis

Compare working vs. broken behavior to identify differences.

Key Questions:

Common Patterns:

Phase 3: Hypothesis Formation

Form specific, testable hypotheses based on evidence.

Good Hypothesis Characteristics:

Example Hypotheses:

Testing Without Logs:

Phase 4: Implementation & Verification

Fix the root cause and verify across all layers.

Fix Implementation:

Verification:

Common Serverless Bugs

See references/common-serverless-bugs.md for detailed catalog. Quick reference:

Type Coercion Issues:

Async/Timing Issues:

Environment Differences:

Database Issues:

Alternative Debugging Strategies

When console.log doesn't work, use these alternatives:

Database-Driven Debugging:

-- Create debug log table
CREATE TABLE debug_logs (
  id SERIAL PRIMARY KEY,
  timestamp TIMESTAMPTZ DEFAULT NOW(),
  function_name TEXT,
  checkpoint TEXT,
  data JSONB
);

-- Write debug info from code
INSERT INTO debug_logs (function_name, checkpoint, data)
VALUES ('my-function', 'before-extraction', jsonb_build_object('count', message_count));

Error Response Debugging:

// Return diagnostic info in error response
return new Response(JSON.stringify({
  debug: {
    messageCount: messageCount,
    lastExtraction: lastExtraction,
    shouldExtract: shouldExtractMemories(messageCount, lastExtraction)
  }
}), { status: 200 });

Code Analysis:

See references/logging-alternatives.md for more strategies.

Practical Tools

Deployment Verification:

# Use scripts/check_deployment.py
python scripts/check_deployment.py <function-name> <local-path>

Database State Analysis:

# Use scripts/database_debugger.py
python scripts/database_debugger.py <table-name> <condition>

Type Analysis:

# Use scripts/type_analyzer.py
python scripts/type_analyzer.py <file-path> <function-name>

Real-World Example: Wade Memory Extraction Bug

Symptom: Proactive memory extraction never triggered despite code being deployed.

Phase 1 Evidence:

Phase 2 Pattern:

Phase 3 Hypothesis:

Phase 4 Fix:

// Before: Only checked null
if (lastExtractionAt === null) {
  return messageCount >= 4;
}

// After: Check both null AND 0
if (lastExtractionAt === null || lastExtractionAt === 0) {
  return messageCount >= 4;
}

Result: Feature now works correctly, triggers after 4 messages.

Best Practices

  1. Gather evidence before hypothesizing - Resist the urge to guess
  2. Use database as debugging tool - When logs fail, database writes work
  3. Check type coercion carefully - 0, null, undefined are all different
  4. Verify deployed code - Don't assume local matches production
  5. Test in isolation - Minimal reproduction cases reveal root cause
  6. Document the process - Future debugging benefits from past patterns

Quick Start

  1. Read references/evidence-checklist.md and gather evidence from all layers
  2. Identify patterns using Phase 2 questions
  3. Form testable hypothesis
  4. Use scripts/ tools to verify hypothesis
  5. Implement fix and verify across all layers
  6. Document bug and fix for future reference

When 3+ Fixes Fail: Question the Architecture

Red flag pattern: Multiple fix attempts, each revealing new problems in different layers.

Symptoms

Pattern: Not converging on a solution. Each fix reveals a NEW problem.

What This Means

Per systematic-debugging Phase 4.5:

If 3+ fixes failed: STOP and question the architecture

This is NOT a bug. This is an ARCHITECTURAL PROBLEM.

Root Cause Analysis

The real issues:

  1. Generic error messages - Can't see actual problem
  2. No direct code access - Can't iterate quickly
  3. Complex deployment pipeline - Adds failure points
  4. No local testing - Can't reproduce issue
  5. Limited observability - Can't see runtime state

What to Do

STOP attempting more fixes. Instead:

  1. Get better error visibility
  1. Simplify the workflow
  1. Question the fundamentals

Real-World Example: Stripe Integration

Attempts:

  1. Added Stripe keys to Vercel → Still failing
  2. Force redeployed → Still failing
  3. Added keys to all environments → Still failing
  4. Created lazy initialization fix → Deployment failed
  5. Tried Google Drive transfer → Downloaded 0 bytes

Root cause: Generic error message hid the actual Stripe error

Solution: Add comprehensive error logging to see real error, then fix that

Lesson: After 3 failed fixes, we should have stopped and added better logging FIRST

Key Takeaways

See also: systematic-debugging skill Phase 4.5

Lazy Initialization for External Services

Problem: Module-level initialization fails in serverless environments.

// ❌ DON'T: Initialize at module load
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

Why it fails:

Solution: Lazy initialization pattern

// ✅ DO: Initialize on first use
let stripeInstance = null;

function getStripe() {
  if (!stripeInstance) {
    const key = process.env.STRIPE_SECRET_KEY;
    if (!key) throw new Error('STRIPE_SECRET_KEY not set');
    stripeInstance = require('stripe')(key);
  }
  return stripeInstance;
}

Benefits:

See references/lazy-initialization-patterns.md for complete examples.

Enhanced Error Logging

Problem: Generic error messages hide root cause.

// ❌ DON'T: Hide error details
catch (error) {
  res.status(500).json({ error: 'An error occurred' });
}

Solution: Log full error details

// ✅ DO: Log comprehensive error info
catch (error) {
  console.error('Operation failed:', {
    message: error.message,
    type: error.type,
    code: error.code,
    stack: error.stack,
    context: { priceId, userId }
  });
  res.status(500).json({ 
    error: error.message,
    type: error.type,
    code: error.code
  });
}

See references/enhanced-error-logging.md for patterns.

Diagnostic Health Endpoints

Add health check endpoints to verify configuration:

app.get('/api/health', (req, res) => {
  const config = {
    stripe: !!process.env.STRIPE_SECRET_KEY,
    supabase: !!process.env.SUPABASE_URL
  };
  
  const keyPrefixes = {
    stripe: config.stripe ? process.env.STRIPE_SECRET_KEY.substring(0, 7) : 'none'
  };
  
  res.json({ 
    status: 'ok',
    configured: config,
    keyPrefixes: keyPrefixes
  });
});

Usage:

curl https://your-api.vercel.app/api/health

This immediately shows:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.