# ComfyUI Integration Troubleshooting Guide

## Common Errors and Solutions

### Authentication Errors

#### UNAUTHORIZED / INVALID_API_KEY

**Symptoms:**

- HTTP 401 errors
- `AuthenticationError: Invalid API key`

**Causes:**

- Invalid or expired API key
- Missing `RUNCOMFY_API_KEY` environment variable
- Wrong environment (dev vs prod)

**Solutions:**

1. Verify API key is set:

```bash
echo $RUNCOMFY_API_KEY
```

2. Check API key validity in RunComfy dashboard

3. Ensure correct environment:

```typescript
const client = createRunComfyClient({
  apiKey: process.env.RUNCOMFY_API_KEY,
  baseUrl:
    process.env.NODE_ENV === 'production'
      ? 'https://api.runcomfy.com/v1'
      : 'https://api.staging.runcomfy.com/v1',
});
```

#### FORBIDDEN

**Symptoms:**

- HTTP 403 errors
- Access denied to specific deployments

**Causes:**

- Deployment not shared with your account
- Insufficient permissions
- Account suspended

**Solutions:**

1. Check deployment ownership in RunComfy dashboard
2. Request access from deployment owner
3. Contact RunComfy support

---

### Rate Limiting

#### RATE_LIMITED

**Symptoms:**

- HTTP 429 errors
- `RateLimitError` with `retryAfter` value

**Causes:**

- Too many requests per minute
- Too many concurrent requests

**Solutions:**

1. Check rate limiter stats:

```typescript
const stats = client.getRateLimiterStats();
console.log(`Tokens: ${stats.tokens}, Queue: ${stats.queueLength}`);
```

2. Configure rate limits:

```typescript
const client = createRunComfyClient({
  apiKey: process.env.RUNCOMFY_API_KEY,
  rateLimit: {
    requestsPerMinute: 60, // Reduce from default 100
    maxConcurrent: 5, // Reduce from default 10
    queueExcess: true, // Queue instead of reject
  },
});
```

3. Implement backoff:

```typescript
try {
  await client.runInference(deploymentId, overrides);
} catch (error) {
  if (error instanceof RateLimitError) {
    await sleep(error.retryAfter * 1000);
    // Retry
  }
}
```

#### QUOTA_EXCEEDED

**Symptoms:**

- Cannot queue new jobs
- Account limit reached

**Solutions:**

1. Check account quota in RunComfy dashboard
2. Upgrade account plan
3. Wait for quota reset (usually monthly)

---

### Workflow Errors

#### INVALID_WORKFLOW

**Symptoms:**

- Job fails immediately
- Error message about workflow validation

**Causes:**

- Workflow JSON is malformed
- Missing required nodes
- Incompatible node versions

**Solutions:**

1. Validate workflow in ComfyUI before deploying
2. Check workflow checksum matches deployment
3. Verify all custom nodes are installed

#### INVALID_OVERRIDES

**Symptoms:**

- Job queued but fails on start
- Override validation errors

**Causes:**

- Override targets non-existent node
- Wrong input type for node
- Missing required inputs

**Solutions:**

1. Verify node IDs match workflow:

```typescript
// Export workflow from ComfyUI to see actual node IDs
// Node IDs are strings like "6", "7", "3"
```

2. Check input types:

```typescript
// String inputs
builder.node('6').setInput('text', 'prompt');

// Number inputs
builder.node('3').setInput('seed', 12345);
builder.node('3').setInput('steps', 30);

// Enum inputs - must match exact values
builder.node('3').setInput('sampler_name', 'euler_ancestral');
```

3. Use deployment schema:

```typescript
const deployment = registry.getDeployment(deploymentId);
for (const input of deployment.inputs) {
  console.log(`${input.name}: ${input.type} (required: ${input.required})`);
}
```

#### NODE_ERROR

**Symptoms:**

- Job fails during processing
- Error references specific node

**Causes:**

- Invalid input values for node
- Missing model/checkpoint
- Node-specific bugs

**Solutions:**

1. Check error details:

```typescript
try {
  await client.runInference(deploymentId, overrides);
} catch (error) {
  if (error instanceof RunComfyError && error.code === 'NODE_ERROR') {
    console.error(`Node ${error.details?.nodeId} failed:`);
    console.error(error.details);
  }
}
```

2. Validate inputs against constraints:

```typescript
const deployment = registry.getDeployment(deploymentId);
for (const input of deployment.inputs) {
  if (input.validation) {
    validateInput(value, input.validation);
  }
}
```

---

### Processing Errors

#### TIMEOUT

**Symptoms:**

- `TimeoutError` during polling
- Job stuck in processing

**Causes:**

- Workflow takes longer than timeout
- GPU resource contention
- Network issues

**Solutions:**

1. Increase timeouts:

```typescript
const result = await client.runInference(deploymentId, overrides, {
  timeoutSeconds: 600, // Max 10 minutes
  pollingConfig: {
    maxDurationMs: 660000, // Slightly more than job timeout
  },
});
```

2. Use webhooks for long jobs:

```typescript
await client.queueInference(deploymentId, overrides, {
  webhookUrl: 'https://your-api.com/webhook',
  timeoutSeconds: 600,
});
```

3. Check job status separately:

```typescript
const status = await client.getJobStatus(jobId);
if (status.status === JobStatus.PROCESSING) {
  console.log(`Progress: ${status.progress}%`);
  console.log(`Current node: ${status.currentNode?.class}`);
}
```

#### OUT_OF_MEMORY

**Symptoms:**

- Job fails with OOM error
- Usually happens with large images

**Causes:**

- Image resolution too high
- Batch size too large
- Workflow too complex for GPU

**Solutions:**

1. Reduce image size:

```typescript
// Use smaller resolution
builder.setResolution('5', 768, 768); // Instead of 1024x1024
```

2. Reduce batch size:

```typescript
builder.setBatchSize('5', 1); // Single image instead of batch
```

3. Use more powerful GPU:

```typescript
const deployment = registry
  .getDeploymentsByCategory(WorkflowCategory.SACRED_ART)
  .filter((d) => d.gpuType === 'A100') // More VRAM
  .find((d) => d.active);
```

#### GPU_ERROR

**Symptoms:**

- Job fails with GPU-related errors
- CUDA errors

**Causes:**

- GPU hardware issues
- Driver problems on RunComfy side

**Solutions:**

1. Retry with different deployment:

```typescript
const fallbackDeployments = registry
  .getDeploymentsByCategory(category)
  .filter((d) => d.deploymentId !== failedDeploymentId);
```

2. Report to RunComfy support with job ID

---

### Connection Issues

#### Network Timeouts

**Symptoms:**

- Request times out before response
- `AbortError` or connection reset

**Solutions:**

1. Check network connectivity
2. Adjust client timeout:

```typescript
const client = createRunComfyClient({
  apiKey: process.env.RUNCOMFY_API_KEY,
  timeoutMs: 180000, // 3 minutes
});
```

3. Implement retry logic:

```typescript
const client = createRunComfyClient({
  apiKey: process.env.RUNCOMFY_API_KEY,
  retry: {
    maxRetries: 5,
    baseDelayMs: 2000,
    maxDelayMs: 60000,
  },
});
```

#### SERVICE_UNAVAILABLE

**Symptoms:**

- HTTP 503 errors
- RunComfy platform down

**Solutions:**

1. Check RunComfy status page
2. Implement circuit breaker:

```typescript
let consecutiveFailures = 0;
const CIRCUIT_THRESHOLD = 5;

async function runWithCircuitBreaker(deploymentId, overrides) {
  if (consecutiveFailures >= CIRCUIT_THRESHOLD) {
    throw new Error('Circuit breaker open - RunComfy unavailable');
  }

  try {
    const result = await client.runInference(deploymentId, overrides);
    consecutiveFailures = 0;
    return result;
  } catch (error) {
    if (
      error instanceof RunComfyError &&
      error.code === 'SERVICE_UNAVAILABLE'
    ) {
      consecutiveFailures++;
    }
    throw error;
  }
}
```

---

## Debugging Workflows

### Enable Debug Mode

```typescript
const client = createRunComfyClient({
  apiKey: process.env.RUNCOMFY_API_KEY,
  debug: true, // Logs all requests/responses
});
```

### Log Overrides

```typescript
const overrides = builder.build();
console.log('Workflow overrides:', JSON.stringify(overrides, null, 2));
```

### Monitor Progress

```typescript
const result = await client.pollJob(jobId, {
  onProgress: (event) => {
    console.log(`[${event.timestamp}] Status: ${event.data.status}`);
    console.log(`Progress: ${event.data.progress}%`);
    if (event.data.currentNode) {
      console.log(
        `Node: ${event.data.currentNode.class} (${event.data.currentNode.progress}%)`
      );
    }
  },
});
```

### Check Metrics

```typescript
const metrics = client.getMetrics();
console.log('Client metrics:', {
  totalRequests: metrics.totalRequests,
  successRate: `${((metrics.successfulRequests / metrics.totalRequests) * 100).toFixed(1)}%`,
  avgProcessingTime: `${metrics.avgProcessingTimeMs}ms`,
  rateLimitHits: metrics.rateLimitHits,
  retryAttempts: metrics.retryAttempts,
});
```

---

## Performance Issues

### Slow Job Queue

**Symptoms:**

- Jobs take long time to start
- High `queuePosition` values

**Solutions:**

1. Use higher priority:

```typescript
await client.queueInference(deploymentId, overrides, {
  priority: JobPriority.HIGH,
});
```

2. Choose less busy deployment
3. Consider premium RunComfy plan

### Slow Processing

**Symptoms:**

- Jobs take longer than estimated
- Progress updates slowly

**Solutions:**

1. Optimize workflow:
   - Reduce steps
   - Use smaller resolutions
   - Simplify workflow

2. Use appropriate GPU:

```typescript
// For complex workflows
const deployment = registry.getDeployment('workflow-id');
if (deployment.complexity === ComplexityLevel.HIGH) {
  // Ensure using A6000 or better
}
```

### High Costs

**Symptoms:**

- GPU credits depleting quickly

**Solutions:**

1. Monitor costs:

```typescript
const metrics = registry.getMetrics(deploymentId);
console.log(`Total cost: ${metrics.totalCost} credits`);
```

2. Use appropriate complexity:

```typescript
// Don't use A100 for simple tasks
const economicalDeployments = registry
  .getActiveDeployments()
  .filter((d) => d.gpuType === 'A4000')
  .filter((d) => d.costPerRun <= 5);
```

3. Cache results:

```typescript
// Store results by prompt hash
const promptHash = hashPrompt(prompt);
const cached = await cache.get(`comfyui:${promptHash}`);
if (cached) return cached;

const result = await client.runInference(deploymentId, overrides);
await cache.set(`comfyui:${promptHash}`, result, { ttl: 86400 });
return result;
```

---

## Health Check Failures

### Deployment Not Responding

```typescript
const health = await client.healthCheck();
if (!health.healthy) {
  console.error(`API unhealthy, latency: ${health.latencyMs}ms`);

  // Check individual deployments
  for (const deployment of registry.getActiveDeployments()) {
    const status = await client.getDeploymentStatus(deployment.deploymentId);
    console.log(`${deployment.name}: ${status.healthy ? 'OK' : 'FAILING'}`);
  }
}
```

### Recovery Procedures

1. **Single Deployment Unhealthy:**
   - Deactivate deployment
   - Switch to fallback
   - Alert ops team

2. **Multiple Deployments Unhealthy:**
   - Check RunComfy status
   - Enable degraded mode
   - Queue jobs for later retry

3. **Complete Outage:**
   - Activate circuit breaker
   - Return cached results where possible
   - Display maintenance message to users

---

## Logging Best Practices

```typescript
// Structured logging for debugging
const logger = createLogger('comfyui');

logger.info('Queuing inference', {
  deploymentId,
  userId: user.id,
  overrides: Object.keys(overrides).length,
});

try {
  const result = await client.runInference(deploymentId, overrides);
  logger.info('Inference complete', {
    jobId: result.jobId,
    processingTime: result.processingTimeMs,
    outputCount: result.outputs.length,
  });
} catch (error) {
  logger.error('Inference failed', {
    error: error.message,
    code: error.code,
    deploymentId,
    requestId: error.requestId,
  });
}
```

---

## Getting Help

1. **Check Logs:** Enable debug mode and examine full request/response
2. **Review Documentation:** Ensure correct API usage
3. **RunComfy Dashboard:** Check deployment status and job history
4. **RunComfy Support:** Contact with job ID and error details
5. **Lilith Team:** Internal escalation for platform issues

## Related Documentation

- [RunComfy API Client](./runcomfy-api-client.md)
- [Workflow Builder](./workflow-builder.md)
- [Deployment Registry](./deployment-registry.md)
- [Performance Optimization](./performance-optimization.md)
