AI Debug — 5 Error Types, Precise Templates
Chapter 10: AI Debug — 5 Error Types, Precise Templates
Effective AI debugging starts with feeding the right information. This chapter categorizes 5 common error types and provides the best prompt template for each, plus log analysis and performance profiling workflows. After this chapter, you'll be able to turn any error into a precise AI question in under 2 minutes.
Why AI Debugging Sometimes Fails
The single most common reason AI debugging fails: you didn't give it enough specific information.
Ineffective:
"This function has a bug, help me find it"
Effective:
Error type + full stack trace + trigger conditions + expected behavior + what you've already ruled out
Think of debugging prompts like describing symptoms to a doctor. "I feel bad" can't be diagnosed. "Sharp intermittent pain in the lower right abdomen that started after eating, worse when pressed" gives the doctor what they need. AI has seen vast numbers of error patterns, but it has zero knowledge of your runtime state — you need to translate that into text.
Most common mistake: truncating the stack trace. Every line in a stack trace carries information, especially the middle frames. Giving AI only the final error line is like showing a doctor only the symptom without the history. Always paste the complete stack trace.
5 Error Types and Their Debug Templates
Type 1: Runtime Exceptions (TypeError / AttributeError / NullPointerException)
The critical context for this type: the trigger path + data state + what null checks you've already verified.
Cursor Chat Prompt Template
@src/services/order.ts
Error (complete stack trace):
TypeError: Cannot read properties of undefined (reading 'id')
at OrderService.processOrder (/src/services/order.ts:45:23)
at POST /api/orders (/src/routes/orders.ts:12:18)
Trigger condition:
This error fires when a user places an order with an empty cart
Data context:
user object structure: { id: 1, cartId: null }
No null check is performed when cart is null
Expected behavior:
Should return 400 { error: "Cart is empty" } — should not crash
Already investigated:
- Confirmed cartId=null triggers this
- processOrder does not check whether cart exists before accessing it
Type 2: Async Issues (Race condition / Unhandled Promise / async/await misuse)
Async bugs are hard to reproduce consistently. Give AI the reproduction rate, timing correlation, and the suspected concurrent code section.
Cursor Chat Prompt Template
@src/hooks/useCartSync.ts @src/api/cart.ts
Problem:
Sometimes users see stale data that only updates after a refresh
Reproduces ~20% of the time, more frequently under high load
Suspected area:
[paste the concurrent/async code section here]
I suspect a race condition but cannot pinpoint it
Please analyze the code for possible race conditions,
explain which async sequences are not ordered correctly,
and suggest fixes using locks or queuing
Type 3: Performance Issues (Slow query / Memory leak / High CPU)
Performance debugging requires measured data, not impressions. Give AI EXPLAIN ANALYZE output, profile results, and data scale — it will give precise optimization directions.
Cursor Chat Prompt Template
Page load time degraded from 200ms to 3s starting last Friday after deploy
@src/db/queries/orderQuery.ts
EXPLAIN ANALYZE output:
Seq Scan on orders (cost=0.00..45231.00 rows=892 width=284)
(actual time=0.043..2847.123 rows=892 loops=1)
Filter: ((status = 'PENDING') AND (created_at >= '2024-01-01'))
Rows Removed by Filter: 498108
Data scale: users 500k rows, orders 2M rows
Analyze the query performance issue, identify missing indexes,
provide CREATE INDEX DDL, and estimate the performance improvement
AI reads Seq Scan and Rows Removed by Filter: 498108 directly from the EXPLAIN output, immediately diagnoses the missing composite index on (status, created_at DESC), and explains why it will reduce the query from 3s to 10-50ms.
Type 4: Environment Differences (Works locally, fails in production)
The core of environment diff debugging is systematically enumerating every known difference. Node version, database type, environment variables — any could be the root cause.
Cursor Chat Prompt Template
Works locally, fails in production
Production error log:
[paste production error here]
Local: runs without errors
Known environment differences:
- Node version: local 20.x, production 18.x (possible culprit?)
- Database: local SQLite, production PostgreSQL (JSON field handling differs)
- Environment variables: confirmed .env.production values match local
- File permissions: production container may have restricted write access
List the most likely root causes in descending probability order,
with a verification method for each
Type 5: Logic Errors (Output doesn't match expectations)
The most effective way to ask about logic errors is with specific input-output pairs, not descriptions of "something feels wrong."
Cursor Chat Prompt Template
@src/utils/shipping.ts
Function: calculateShippingCost
Test cases (expected vs actual):
- Input: weight=2, distance=100, memberLevel="gold"
Expected: $5.00 (gold member gets 50% off)
Actual: $10.00 (discount not applied)
- Input: weight=5, distance=500, memberLevel="basic"
Expected: $25.00
Actual: $25.00 (correct)
- Input: weight=2, distance=100, memberLevel="silver"
Expected: $7.00 (silver gets 30% off)
Actual: $10.00 (discount not applied)
Pattern: basic tier is correct, gold and silver discounts are both ignored
Find the bug in the discount logic
Advanced: AI Log Pattern Analysis
Production bugs often can only be diagnosed through logs. Feeding logs to AI for pattern recognition is 10x faster than manual reading.
Log Analysis Prompt
The following is 1 hour of sanitized application error logs.
Users report intermittent payment failures:
[2024-03-15 14:23:11] ERROR payment_service: Stripe API timeout after 30000ms
[2024-03-15 14:23:45] INFO payment_service: Payment completed successfully
[2024-03-15 14:31:22] ERROR payment_service: Stripe API timeout after 30000ms
[2024-03-15 14:31:58] ERROR payment_service: Duplicate payment detected, idempotency key already used
[2024-03-15 14:45:03] ERROR payment_service: Stripe API timeout after 30000ms
[2024-03-15 14:45:38] ERROR payment_service: Duplicate payment detected, idempotency key already used
... (pattern repeats 12 times)
Analyze:
1. What is the pattern of the errors?
2. What is the root cause?
3. Why are duplicate charges occurring?
4. How to fix it?
AI identifies the pattern: every Stripe timeout is immediately followed by a "Duplicate payment detected." The root cause is that the retry logic generates a new idempotency key instead of reusing the original, so Stripe sees two distinct payment requests and flags the second as a duplicate — but the charge may still go through. Fix: always reuse the same idempotency key on retry.
Performance Debug: Feed Profile Data to AI
Python cProfile
import cProfile
import pstats
profiler = cProfile.Profile()
profiler.enable()
generate_monthly_report() # your slow function
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(20) # top 20 time consumers
Paste the pstats output into Cursor Chat along with the relevant file. When AI sees get_order_by_id called 8,934 times taking 67% of runtime, it immediately identifies the N+1 query pattern and gives you the batch query fix.
Node.js Heap Snapshot
Steps
1. Start with --inspect: node --inspect src/server.js
2. Open chrome://inspect in Chrome, go to Memory tab
3. Take a Heap Snapshot before and after memory grows
4. Compare snapshots — find the object type with the largest Delta
5. Give AI the growing object name and its retainer path:
"Heap snapshot comparison (10 minutes apart):
- EventEmitter instances: grew from 142 to 4,891
- WebSocketConnection objects: grew by 4,749
- Retainer path: WebSocketManager → Map(connections) → WebSocketConnection[]
@src/services/websocket.ts
Analyze the likely memory leak cause. Focus on whether
connections are properly cleaned up on disconnect."
Chapter Key Takeaways
| Takeaway | Core Principle |
|---|---|
| 1. Information completeness | Always include full stack trace + trigger condition + what you've ruled out — never just the error message |
| 2. Match context to error type | Async bugs need timing info; performance bugs need profile data; logic bugs need input/output pairs |
| 3. Data over intuition | For performance bugs, attach measured data (EXPLAIN, profile output) — "feels slow" has no diagnostic value |
| 4. Log pattern recognition | Feed 100 lines of error logs to AI and ask for patterns — 10x faster than reading manually |
| 5. Systematic env diff | List every known difference between local and production — Node version, DB type, env vars, file permissions |