> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zenable.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Finding & Fixing Bugs

> AI-powered analysis identifies subtle bugs and suggests fixes before production

## Overview

Bugs slip through reviews and automated testing misses edge cases. Zenable provides AI-powered analysis that identifies subtle bugs and suggests fixes before production, resulting in fewer production incidents.

## Out-of-the-Box Bug Detection

Zenable automatically identifies these common bug patterns:

<Card title="Standard Bug Detection" icon="bug">
  * **Race Conditions** - Unsafe concurrent access, thread safety issues
  * **Null/Undefined** - Missing null checks, potential NPEs
  * **Resource Leaks** - Unclosed files, database connections, memory leaks
  * **Logic Errors** - Off-by-one errors, incorrect conditionals
  * **Type Mismatches** - Implicit conversions, type confusion
  * **Edge Cases** - Boundary conditions, empty collections
</Card>

## Custom Bug Detection Rules

Define your organization's specific bug patterns:

> "All database operations must use our retry wrapper, all API calls must include correlation IDs, all monetary calculations must use our Money class with 4 decimal precision, and all user inputs must be sanitized with our custom sanitizer."

## In Action

```bash theme={null}
# Comprehensive bug scan with both standard and custom checks
zenable check '**/*.{py,js,ts,go}'

# Focus on critical code paths, excluding test files
zenable check 'src/api/**/*' 'src/payments/**/*' \
  --exclude '**/test_*.py' \
  --exclude '**/*.test.{js,ts}' \
  --exclude '**/*_test.go'
```

## Custom Bug Examples

### Example: Business Logic Validation

**Your Policy:** "All financial calculations must account for currency conversion and rounding rules"

```python expandable theme={null}
# ❌ Common bug: incorrect money handling
def calculate_total(items):
    return sum(item.price for item in items)

# ✅ Zenable enforces your money handling rules
def calculate_total(items):
    total = Money(0, currency="USD")
    for item in items:
        converted = currency_service.convert(
            item.price,
            from_currency=item.currency,
            to_currency="USD",
            rate_date=datetime.now()
        )
        total = total.add(converted, rounding=ROUND_HALF_EVEN)
    return total
```

### Example: API Contract Enforcement

**Your Policy:** "All API responses must include request ID, timestamp, and rate limit headers"

```javascript expandable theme={null}
// ❌ Missing required response structure
app.get('/api/users', async (req, res) => {
    const users = await db.getUsers();
    res.json(users);
});

// ✅ Zenable enforces API contract
app.get('/api/users', async (req, res) => {
    const users = await db.getUsers();
    res.set({
        'X-Request-ID': req.id,
        'X-Timestamp': Date.now(),
        'X-RateLimit-Remaining': req.rateLimit.remaining
    });
    res.json({
        data: users,
        meta: {
            request_id: req.id,
            timestamp: Date.now(),
            count: users.length
        }
    });
});
```

### Example: Data Consistency Rules

**Your Policy:** "All database writes must use transactions with retry logic and audit logging"

```python expandable theme={null}
# ❌ Bug: no transaction or retry
def update_user_balance(user_id, amount):
    user = get_user(user_id)
    user.balance += amount
    save_user(user)

# ✅ Zenable enforces consistency requirements
@with_retry(max_attempts=3, backoff=exponential)
@with_transaction
@audit_log
def update_user_balance(user_id, amount, reason):
    with db.transaction() as tx:
        user = tx.query(User).with_for_update().get(user_id)
        old_balance = user.balance
        user.balance += amount

        tx.add(BalanceHistory(
            user_id=user_id,
            old_balance=old_balance,
            new_balance=user.balance,
            change_amount=amount,
            reason=reason
        ))

        tx.commit()
```

## Benefits

* **Fewer Production Incidents** - Catch bugs before they reach users
* **Custom Rule Enforcement** - Ensure your specific patterns are followed
* **Reduced Debugging Time** - Find root causes faster
* **Improved Code Quality** - Systematic bug prevention

## Related Use Cases

* [Preventing AI Mistakes](/use-cases/preventing-ai-mistakes) - Stop bugs at the source
* [Security Assessment](/use-cases/security-assessment) - Deep vulnerability analysis
* [Policy as Code](/use-cases/policy-as-code) - Define bug prevention rules
