Debugging with AI

Practical Exercise 4

Hands-On

Use AI to identify, understand, and fix bugs efficiently

Practical Objectives

1

Use AI to analyze error messages and stack traces

2

Apply chain-of-thought debugging prompts

3

Debug logic errors with AI assistance

4

Write tests to prevent regression

Task 1: Analyze This Buggy Code

This shopping cart has bugs. Find and fix them:

class ShoppingCart:
    def __init__(self):
        self.items = []

    def add_item(self, name, price, quantity):
        self.items.append({"name": name, "price": price, "qty": quantity})

    def remove_item(self, name):
        for item in self.items:
            if item["name"] == name:
                self.items.remove(item)  # Bug 1: Modifying list while iterating

    def calculate_total(self):
        total = 0
        for item in self.items:
            total += item["price"] * item["quantity"]  # Bug 2: Wrong key name
        return total

    def apply_discount(self, percent):
        self.total = self.calculate_total()
        return self.total - (self.total * percent)  # Bug 3: percent should be /100

Task 2: Use AI to Debug

Use this chain-of-thought debugging prompt:

Debugging Prompt TemplateI have a bug in my code. Help me debug it step by step: 1. Code: [paste the buggy code] 2. Expected behavior: Shopping cart should correctly add/remove items and calculate totals with discounts. 3. Actual behavior: - remove_item doesn't remove all matching items - calculate_total throws KeyError - apply_discount gives wrong values 4. Debug step by step: - What is each function supposed to do? - Trace through with sample data - Identify where actual differs from expected - Propose fixes with explanations

Task 3: Stack Trace Analysis

Ask AI to analyze this error:

Traceback (most recent call last):
  File "cart.py", line 42, in <module>
    total = cart.calculate_total()
  File "cart.py", line 15, in calculate_total
    total += item["price"] * item["quantity"]
KeyError: 'quantity'
Error Analysis PromptAnalyze this Python error: [paste stack trace] 1. What does this error mean? 2. What line caused it? 3. What's the root cause? 4. How do I fix it? 5. How do I prevent similar errors?

Task 4: Debug Logic Errors

This function has a logic bug - no error, but wrong output:

def find_duplicates(lst):
    """Return list of duplicate values."""
    seen = []
    duplicates = []
    for item in lst:
        if item in seen:
            duplicates.append(item)  # Bug: adds multiple times
        seen.append(item)
    return duplicates

# find_duplicates([1, 2, 2, 2, 3]) returns [2, 2] instead of [2]

Debugging Strategy

Ask AI: "Trace through find_duplicates([1, 2, 2, 2, 3]) step by step. Show the state of 'seen' and 'duplicates' after each iteration."

Task 5: Write Regression Tests

After fixing bugs, write tests to prevent regression:

Test Generation PromptGenerate pytest tests for the ShoppingCart class: Test cases needed: 1. add_item adds items correctly 2. remove_item removes only the specified item 3. remove_item handles item not found 4. calculate_total returns correct sum 5. apply_discount with 10% reduces total by 10% 6. apply_discount with 0% returns original total 7. Empty cart has total of 0 Use descriptive test names and assertions.

Task 6: Async/Race Condition Bug

Debug this async code with AI:

async def fetch_user_data(user_ids):
    results = []
    for user_id in user_ids:
        data = await fetch_user(user_id)
        results.append(data)  # Potential: Order not guaranteed with concurrent calls
    return results

async def update_balance(user_id, amount):
    balance = await get_balance(user_id)
    new_balance = balance + amount  # Bug: Race condition between read and write
    await set_balance(user_id, new_balance)
Ask AI: "What race conditions exist in update_balance? How would concurrent calls with user_id=1 cause issues?"

Deliverables Checklist

Bug Fixes

  • Fixed remove_item iteration bug
  • Fixed KeyError in calculate_total
  • Fixed discount calculation

Understanding

  • Can explain each bug's root cause
  • Used chain-of-thought debugging
  • Traced execution step by step

Tests

  • Tests for all fixed bugs
  • Edge cases covered
  • All tests passing

Advanced

  • Identified race condition
  • Proposed fix with locking
  • Documented the solution

Debugging Complete!

You've mastered AI-assisted debugging

Next: Practical 5 - AI-Assisted Code Review

Slide Overview