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

# Delete Cluster

> Permanently delete GPU clusters with data backup and billing finalization options

## Overview

The Delete Cluster endpoint permanently removes GPU clusters and all associated resources. This operation is irreversible and includes options for data backup, billing finalization, and cleanup of related resources like snapshots and network configurations.

## Endpoint

```bash curl
DELETE https://api.tensorone.ai/v1/clusters/{cluster_id}
```

## Path Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `cluster_id` | string | Yes | Unique cluster identifier |

## Request Body

| Parameter | Type | Required | Description |
| - | - | - | - |
| `force` | boolean | No | Force delete without graceful shutdown (default: false) |
| `create_final_snapshot` | boolean | No | Create final snapshot before deletion (default: false) |
| `snapshot_name` | string | No | Custom name for final snapshot |
| `preserve_snapshots` | boolean | No | Keep existing snapshots after cluster deletion (default: true) |
| `delete_snapshots` | boolean | No | Delete all associated snapshots (default: false) |
| `finalize_billing` | boolean | No | Finalize billing and generate final invoice (default: true) |
| `cleanup_network_resources` | boolean | No | Remove security groups and network configs (default: true) |
| `wait_for_completion` | boolean | No | Wait for complete deletion (default: false) |
| `timeout_minutes` | integer | No | Maximum wait time for completion (default: 10, max: 30) |
| `deletion_reason` | string | No | Reason for deletion (for audit logs) |
| `confirm_deletion` | string | No | Must be "DELETE" to confirm permanent deletion |

## Request Examples

```bash curl
# Basic cluster deletion
curl -X DELETE "https://api.tensorone.ai/v1/clusters/cluster_abc123" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "confirm_deletion": "DELETE",
    "deletion_reason": "Project completed"
  }'

# Delete with final backup
curl -X DELETE "https://api.tensorone.ai/v1/clusters/cluster_abc123" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "confirm_deletion": "DELETE",
    "create_final_snapshot": true,
    "snapshot_name": "final_backup_training_model",
    "preserve_snapshots": true,
    "wait_for_completion": true,
    "deletion_reason": "Training completed - archiving results"
  }'

# Force delete with complete cleanup
curl -X DELETE "https://api.tensorone.ai/v1/clusters/cluster_abc123" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "confirm_deletion": "DELETE",
    "force": true,
    "delete_snapshots": true,
    "cleanup_network_resources": true,
    "deletion_reason": "Emergency cleanup - security incident"
  }'
```

```python Python
import requests
import time

def delete_cluster_safe(cluster_id, reason=None, create_backup=True):
    """Safely delete cluster with optional backup"""
    
    payload = {
        "confirm_deletion": "DELETE",
        "create_final_snapshot": create_backup,
        "preserve_snapshots": True,
        "finalize_billing": True,
        "cleanup_network_resources": True,
        "wait_for_completion": True,
        "timeout_minutes": 15
    }
    
    if reason:
        payload["deletion_reason"] = reason
    
    if create_backup:
        # Generate snapshot name with timestamp
        from datetime import datetime
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        payload["snapshot_name"] = f"final_backup_{cluster_id}_{timestamp}"
    
    response = requests.delete(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=payload
    )
    
    result = response.json()
    
    if result["success"]:
        print(f"Cluster {cluster_id} deleted successfully")
        if create_backup and "final_snapshot_id" in result.get("data", {}):
            print(f"Final backup created: {result['data']['final_snapshot_id']}")
        if "billing_summary" in result.get("data", {}):
            billing = result["data"]["billing_summary"]
            print(f"Final cost: ${billing['total_cost']:.2f}")
    
    return result

def delete_training_cluster_with_archive(cluster_id, model_name, experiment_id):
    """Delete training cluster with comprehensive archival"""
    
    # First, get cluster information for archival metadata
    cluster_info = requests.get(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}",
        headers={"Authorization": f"Bearer {API_KEY}"}
    ).json()
    
    if not cluster_info["success"]:
        return {"success": False, "error": "Failed to get cluster info for archival"}
    
    cluster = cluster_info["data"]
    
    # Create comprehensive snapshot name
    snapshot_name = f"archive_{model_name}_{experiment_id}_{int(time.time())}"
    
    deletion_payload = {
        "confirm_deletion": "DELETE",
        "create_final_snapshot": True,
        "snapshot_name": snapshot_name,
        "preserve_snapshots": True,  # Keep all training checkpoints
        "finalize_billing": True,
        "wait_for_completion": True,
        "timeout_minutes": 20,
        "deletion_reason": f"Training completed - {model_name} experiment {experiment_id}"
    }
    
    response = requests.delete(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json=deletion_payload
    )
    
    result = response.json()
    
    if result["success"]:
        archive_info = {
            "cluster_id": cluster_id,
            "model_name": model_name,
            "experiment_id": experiment_id,
            "final_snapshot_id": result["data"]["final_snapshot_id"],
            "training_duration_hours": result["data"]["billing_summary"]["session_duration_hours"],
            "total_cost": result["data"]["billing_summary"]["total_cost"],
            "gpu_hours": result["data"]["resource_usage"]["total_gpu_hours"],
            "deleted_at": result["data"]["deleted_at"],
            "snapshots_preserved": len(result["data"]["snapshots_preserved"])
        }
        
        print(f"Training cluster archived successfully:")
        print(f"  Model: {model_name}")
        print(f"  Experiment: {experiment_id}")
        print(f"  Final snapshot: {archive_info['final_snapshot_id']}")
        print(f"  Total cost: ${archive_info['total_cost']:.2f}")
        print(f"  GPU hours: {archive_info['gpu_hours']:.1f}")
        
        return {"success": True, "archive_info": archive_info}
    
    return result

def batch_delete_clusters(cluster_ids, deletion_strategy="safe"):
    """Delete multiple clusters with specified strategy"""
    
    results = []
    
    for cluster_id in cluster_ids:
        try:
            if deletion_strategy == "safe":
                result = delete_cluster_safe(
                    cluster_id, 
                    reason="Batch cleanup - safe deletion",
                    create_backup=True
                )
            elif deletion_strategy == "force":
                result = requests.delete(
                    f"https://api.tensorone.ai/v1/clusters/{cluster_id}",
                    headers={"Authorization": f"Bearer {API_KEY}"},
                    json={
                        "confirm_deletion": "DELETE",
                        "force": True,
                        "delete_snapshots": True,
                        "deletion_reason": "Batch cleanup - force deletion"
                    }
                ).json()
            else:  # minimal
                result = requests.delete(
                    f"https://api.tensorone.ai/v1/clusters/{cluster_id}",
                    headers={"Authorization": f"Bearer {API_KEY}"},
                    json={
                        "confirm_deletion": "DELETE",
                        "deletion_reason": "Batch cleanup - minimal deletion"
                    }
                ).json()
            
            results.append({
                "cluster_id": cluster_id,
                "success": result["success"],
                "strategy": deletion_strategy,
                "final_cost": result.get("data", {}).get("billing_summary", {}).get("total_cost"),
                "snapshots_created": 1 if result.get("data", {}).get("final_snapshot_id") else 0
            })
            
        except Exception as e:
            results.append({
                "cluster_id": cluster_id,
                "success": False,
                "error": str(e)
            })
        
        # Brief delay between deletions to avoid rate limits
        time.sleep(2)
    
    return {
        "deletion_strategy": deletion_strategy,
        "total_clusters": len(cluster_ids),
        "successful_deletions": len([r for r in results if r["success"]]),
        "total_cost_recovered": sum(r.get("final_cost", 0) for r in results if r.get("final_cost")),
        "results": results
    }
```

```javascript JavaScript
// Safe cluster deletion with backup
async function deleteClusterSafely(clusterId, options = {}) {
  const deletionConfig = {
    confirm_deletion: 'DELETE',
    create_final_snapshot: options.createBackup !== false, // default true
    preserve_snapshots: options.preserveSnapshots !== false, // default true
    finalize_billing: options.finalizeBilling !== false, // default true
    cleanup_network_resources: options.cleanupNetwork !== false, // default true
    wait_for_completion: options.waitForCompletion || false,
    deletion_reason: options.reason || 'Manual deletion request'
  };
  
  if (deletionConfig.create_final_snapshot) {
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    deletionConfig.snapshot_name = options.snapshotName || `final_backup_${clusterId}_${timestamp}`;
  }
  
  if (options.force) {
    deletionConfig.force = true;
  }
  
  try {
    const response = await fetch(`https://api.tensorone.ai/v1/clusters/${clusterId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(deletionConfig)
    });
    
    const result = await response.json();
    
    if (!result.success) {
      throw new Error(`Failed to delete cluster: ${result.error.message}`);
    }
    
    console.log(`Cluster ${clusterId} deleted successfully`);
    
    if (result.data.final_snapshot_id) {
      console.log(`Final backup created: ${result.data.final_snapshot_id}`);
    }
    
    return {
      clusterId: clusterId,
      deleted: true,
      finalSnapshotId: result.data.final_snapshot_id,
      totalCost: result.data.billing_summary?.total_cost,
      deletedAt: result.data.deleted_at,
      resourcesCleanedUp: result.data.resources_cleaned_up || []
    };
    
  } catch (error) {
    console.error(`Error deleting cluster ${clusterId}:`, error);
    throw error;
  }
}

// Project cleanup - delete all clusters in a project
async function cleanupProject(projectId, cleanupOptions = {}) {
  console.log(`Starting cleanup for project: ${projectId}`);
  
  try {
    // Get all clusters in the project
    const clustersResponse = await fetch(`https://api.tensorone.ai/v1/clusters?project_id=${projectId}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    });
    
    const clustersData = await clustersResponse.json();
    
    if (!clustersData.success) {
      throw new Error(`Failed to get project clusters: ${clustersData.error.message}`);
    }
    
    const clusters = clustersData.data.clusters;
    
    if (clusters.length === 0) {
      return {
        projectId: projectId,
        message: 'No clusters found in project',
        totalCost: 0,
        clustersDeleted: 0
      };
    }
    
    console.log(`Found ${clusters.length} clusters to delete`);
    
    // Categorize clusters by type for appropriate deletion strategy
    const productionClusters = clusters.filter(c => 
      c.name.includes('prod') || c.tags?.environment === 'production'
    );
    const developmentClusters = clusters.filter(c => 
      c.name.includes('dev') || c.tags?.environment === 'development'
    );
    const trainingClusters = clusters.filter(c =>
      c.name.includes('train') || c.tags?.purpose === 'training'
    );
    const otherClusters = clusters.filter(c =>
      !productionClusters.includes(c) && 
      !developmentClusters.includes(c) && 
      !trainingClusters.includes(c)
    );
    
    const deletionResults = [];
    
    // Delete production clusters with maximum safety
    for (const cluster of productionClusters) {
      console.log(`Deleting production cluster: ${cluster.name}`);
      try {
        const result = await deleteClusterSafely(cluster.id, {
          createBackup: true,
          preserveSnapshots: true,
          reason: `Project cleanup - production cluster: ${cluster.name}`,
          waitForCompletion: true
        });
        deletionResults.push(result);
      } catch (error) {
        deletionResults.push({
          clusterId: cluster.id,
          deleted: false,
          error: error.message
        });
      }
      
      // Longer delay for production clusters
      await new Promise(resolve => setTimeout(resolve, 5000));
    }
    
    // Delete training clusters with backup
    for (const cluster of trainingClusters) {
      console.log(`Deleting training cluster: ${cluster.name}`);
      try {
        const result = await deleteClusterSafely(cluster.id, {
          createBackup: true,
          preserveSnapshots: true,
          reason: `Project cleanup - training cluster: ${cluster.name}`,
          waitForCompletion: false
        });
        deletionResults.push(result);
      } catch (error) {
        deletionResults.push({
          clusterId: cluster.id,
          deleted: false,
          error: error.message
        });
      }
      
      await new Promise(resolve => setTimeout(resolve, 2000));
    }
    
    // Delete development clusters with minimal backup
    for (const cluster of developmentClusters) {
      console.log(`Deleting development cluster: ${cluster.name}`);
      try {
        const result = await deleteClusterSafely(cluster.id, {
          createBackup: cleanupOptions.backupDevClusters || false,
          preserveSnapshots: false,
          reason: `Project cleanup - development cluster: ${cluster.name}`,
          waitForCompletion: false
        });
        deletionResults.push(result);
      } catch (error) {
        deletionResults.push({
          clusterId: cluster.id,
          deleted: false,
          error: error.message
        });
      }
      
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
    
    // Delete other clusters
    for (const cluster of otherClusters) {
      console.log(`Deleting cluster: ${cluster.name}`);
      try {
        const result = await deleteClusterSafely(cluster.id, {
          createBackup: cleanupOptions.backupOtherClusters !== false,
          reason: `Project cleanup - ${cluster.name}`,
          waitForCompletion: false
        });
        deletionResults.push(result);
      } catch (error) {
        deletionResults.push({
          clusterId: cluster.id,
          deleted: false,
          error: error.message
        });
      }
      
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
    
    const successfulDeletions = deletionResults.filter(r => r.deleted);
    const totalCost = successfulDeletions.reduce((sum, r) => sum + (r.totalCost || 0), 0);
    
    return {
      projectId: projectId,
      totalClusters: clusters.length,
      clustersDeleted: successfulDeletions.length,
      clustersFailed: deletionResults.length - successfulDeletions.length,
      totalCostRecovered: totalCost,
      categorization: {
        production: productionClusters.length,
        training: trainingClusters.length,
        development: developmentClusters.length,
        other: otherClusters.length
      },
      results: deletionResults
    };
    
  } catch (error) {
    console.error(`Project cleanup failed for ${projectId}:`, error);
    throw error;
  }
}

// Emergency deletion with force
async function emergencyDeleteCluster(clusterId, emergencyReason) {
  console.warn(`EMERGENCY DELETION of cluster ${clusterId}: ${emergencyReason}`);
  
  const deletionConfig = {
    confirm_deletion: 'DELETE',
    force: true,
    create_final_snapshot: false, // Skip backup for emergency
    delete_snapshots: false, // Preserve snapshots unless specified
    cleanup_network_resources: true,
    wait_for_completion: true,
    timeout_minutes: 5, // Short timeout for emergency
    deletion_reason: `EMERGENCY: ${emergencyReason}`
  };
  
  try {
    const response = await fetch(`https://api.tensorone.ai/v1/clusters/${clusterId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(deletionConfig)
    });
    
    const result = await response.json();
    
    if (!result.success) {
      throw new Error(`Emergency deletion failed: ${result.error.message}`);
    }
    
    console.log(`Emergency deletion completed for cluster ${clusterId}`);
    
    return {
      clusterId: clusterId,
      emergencyDeleted: true,
      deletedAt: result.data.deleted_at,
      reason: emergencyReason,
      resourcesCleaned: result.data.resources_cleaned_up || []
    };
    
  } catch (error) {
    console.error(`Emergency deletion failed for cluster ${clusterId}:`, error);
    throw error;
  }
}
```

## Response Schema

```json Success Response (Immediate)
{
  "success": true,
  "data": {
    "id": "cluster_abc123",
    "name": "ml-training-cluster",
    "status": "deleting",
    "deletion_initiated_at": "2024-01-15T18:00:00Z",
    "estimated_completion_time": "2024-01-15T18:05:00Z",
    "deletion_progress": {
      "phase": "creating_final_snapshot",
      "percentage": 30,
      "current_step": "Creating final data snapshot",
      "steps_completed": 3,
      "total_steps": 8
    },
    "final_snapshot": {
      "creating": true,
      "snapshot_name": "final_backup_training_model",
      "estimated_size_gb": 456.8,
      "estimated_completion": "2024-01-15T18:03:00Z"
    },
    "billing_preview": {
      "session_duration_hours": 8.5,
      "estimated_final_cost": 102.50,
      "currency": "USD",
      "billing_cutoff": "2024-01-15T18:00:00Z"
    }
  },
  "meta": {
    "request_id": "req_delete_123",
    "wait_for_completion": false
  }
}
```

```json Success Response (Wait for Completion)
{
  "success": true,
  "data": {
    "id": "cluster_abc123",
    "name": "ml-training-cluster",
    "status": "deleted",
    "deletion_initiated_at": "2024-01-15T18:00:00Z",
    "deleted_at": "2024-01-15T18:04:32Z",
    "deletion_duration_seconds": 272,
    "final_snapshot_id": "snap_final_xyz789",
    "final_snapshot": {
      "id": "snap_final_xyz789",
      "name": "final_backup_training_model",
      "size_gb": 456.8,
      "created_at": "2024-01-15T18:03:15Z",
      "retention_days": 30
    },
    "snapshots_preserved": [
      {
        "id": "snap_checkpoint_001",
        "name": "epoch_100_checkpoint",
        "size_gb": 234.5,
        "created_at": "2024-01-14T10:30:00Z"
      },
      {
        "id": "snap_checkpoint_002", 
        "name": "epoch_200_checkpoint",
        "size_gb": 245.2,
        "created_at": "2024-01-15T02:15:00Z"
      }
    ],
    "billing_summary": {
      "session_start": "2024-01-15T09:30:00Z",
      "session_end": "2024-01-15T18:00:00Z",
      "session_duration_hours": 8.5,
      "total_cost": 102.50,
      "currency": "USD",
      "cost_breakdown": {
        "gpu_cost": 85.00,
        "cpu_cost": 10.20,
        "memory_cost": 4.25,
        "storage_cost": 2.55,
        "network_cost": 0.50
      },
      "invoice_id": "inv_cluster_abc123_final"
    },
    "resource_usage": {
      "total_gpu_hours": 34.0,
      "peak_gpu_utilization": 94.3,
      "avg_gpu_utilization": 87.2,
      "total_data_processed_gb": 1250.5,
      "network_data_transfer_gb": 45.8
    },
    "resources_cleaned_up": [
      "compute_instance",
      "gpu_allocation",
      "storage_volumes",
      "network_interfaces",
      "security_groups",
      "dns_records"
    ],
    "data_retention": {
      "snapshots_retained": 3,
      "snapshot_retention_days": 30,
      "snapshot_storage_cost_per_day": 1.25,
      "automatic_cleanup_date": "2024-02-14T18:04:32Z"
    }
  },
  "meta": {
    "request_id": "req_delete_123",
    "wait_for_completion": true,
    "total_wait_time_seconds": 272
  }
}
```

## Deletion Progress Phases

| Phase | Description | Typical Duration |
| - | - | - |
| `stopping_cluster` | Gracefully stopping all running processes | 1-5 minutes |
| `creating_final_snapshot` | Creating final backup snapshot (if requested) | 2-10 minutes |
| `finalizing_billing` | Processing final billing and generating invoice | 30-60 seconds |
| `cleaning_storage` | Removing storage volumes and data (except preserved) | 1-3 minutes |
| `cleaning_network` | Removing network resources and security groups | 30-60 seconds |
| `cleaning_compute` | Releasing GPU and compute resources | 30-60 seconds |
| `updating_records` | Updating database records and audit logs | 10-30 seconds |
| `completed` | Deletion process finished | - |

## Use Cases

### Project Completion Cleanup

Clean up all resources when a project is completed.

```python
def cleanup_completed_project(project_id, project_name):
    """Clean up all resources for a completed project"""
    
    print(f"Starting cleanup for completed project: {project_name}")
    
    # Get all clusters in the project
    clusters_response = requests.get(
        "https://api.tensorone.ai/v1/clusters",
        headers={"Authorization": f"Bearer {API_KEY}"},
        params={"project_id": project_id}
    )
    
    clusters = clusters_response.json()["data"]["clusters"]
    
    cleanup_summary = {
        "project_id": project_id,
        "project_name": project_name,
        "total_clusters": len(clusters),
        "clusters_deleted": 0,
        "total_cost_recovered": 0,
        "snapshots_preserved": 0,
        "cleanup_details": []
    }
    
    for cluster in clusters:
        cluster_type = "unknown"
        
        # Determine cluster type and appropriate cleanup strategy
        if "prod" in cluster["name"].lower():
            cluster_type = "production"
            create_backup = True
            preserve_snapshots = True
        elif "train" in cluster["name"].lower():
            cluster_type = "training"
            create_backup = True
            preserve_snapshots = True
        elif "dev" in cluster["name"].lower():
            cluster_type = "development"
            create_backup = False
            preserve_snapshots = False
        else:
            cluster_type = "other"
            create_backup = True
            preserve_snapshots = True
        
        try:
            result = delete_cluster_safe(
                cluster["id"],
                reason=f"Project completion cleanup - {project_name}",
                create_backup=create_backup
            )
            
            if result["success"]:
                cleanup_summary["clusters_deleted"] += 1
                cleanup_summary["total_cost_recovered"] += result.get("data", {}).get("billing_summary", {}).get("total_cost", 0)
                cleanup_summary["snapshots_preserved"] += len(result.get("data", {}).get("snapshots_preserved", []))
                
                cleanup_summary["cleanup_details"].append({
                    "cluster_id": cluster["id"],
                    "cluster_name": cluster["name"],
                    "cluster_type": cluster_type,
                    "success": True,
                    "final_cost": result.get("data", {}).get("billing_summary", {}).get("total_cost"),
                    "final_snapshot_id": result.get("data", {}).get("final_snapshot_id")
                })
            
        except Exception as e:
            cleanup_summary["cleanup_details"].append({
                "cluster_id": cluster["id"],
                "cluster_name": cluster["name"],
                "cluster_type": cluster_type,
                "success": False,
                "error": str(e)
            })
    
    print(f"Project cleanup completed:")
    print(f"  Clusters deleted: {cleanup_summary['clusters_deleted']}/{cleanup_summary['total_clusters']}")
    print(f"  Total cost recovered: ${cleanup_summary['total_cost_recovered']:.2f}")
    print(f"  Snapshots preserved: {cleanup_summary['snapshots_preserved']}")
    
    return cleanup_summary
```

### Cost Optimization Cleanup

Delete expensive idle clusters to reduce costs.

```javascript
async function cleanupExpensiveIdleClusters(costThreshold = 10.0, idleHours = 24) {
  console.log(`Cleaning up idle clusters costing more than $${costThreshold}/hour idle for ${idleHours}+ hours`);
  
  try {
    // Get all running clusters
    const response = await fetch('https://api.tensorone.ai/v1/clusters?status=running&include_metrics=true', {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    });
    
    const clustersData = await response.json();
    const clusters = clustersData.data.clusters;
    
    const expensiveIdleClusters = clusters.filter(cluster => {
      const hourlyRate = cluster.cost.hourly_rate;
      const gpuUtilization = cluster.metrics.current.gpu_utilization;
      const lastAccessed = new Date(cluster.last_accessed);
      const hoursIdle = (Date.now() - lastAccessed.getTime()) / (1000 * 60 * 60);
      
      return hourlyRate >= costThreshold && 
             gpuUtilization < 5 && // Very low utilization
             hoursIdle >= idleHours;
    });
    
    console.log(`Found ${expensiveIdleClusters.length} expensive idle clusters`);
    
    const deletionResults = [];
    let totalSavings = 0;
    
    for (const cluster of expensiveIdleClusters) {
      try {
        console.log(`Deleting idle cluster: ${cluster.name} ($${cluster.cost.hourly_rate}/hr)`);
        
        const result = await deleteClusterSafely(cluster.id, {
          createBackup: true, // Always backup expensive clusters
          preserveSnapshots: true,
          reason: `Cost optimization - idle cluster cleanup (${cluster.cost.hourly_rate}/hr for ${Math.round((Date.now() - new Date(cluster.last_accessed).getTime()) / (1000 * 60 * 60))} hours)`,
          waitForCompletion: false
        });
        
        totalSavings += cluster.cost.hourly_rate;
        
        deletionResults.push({
          clusterId: cluster.id,
          name: cluster.name,
          hourlyRate: cluster.cost.hourly_rate,
          hoursIdle: Math.round((Date.now() - new Date(cluster.last_accessed).getTime()) / (1000 * 60 * 60)),
          success: true,
          finalSnapshotId: result.finalSnapshotId
        });
        
      } catch (error) {
        deletionResults.push({
          clusterId: cluster.id,
          name: cluster.name,
          hourlyRate: cluster.cost.hourly_rate,
          success: false,
          error: error.message
        });
      }
      
      // Brief delay between deletions
      await new Promise(resolve => setTimeout(resolve, 2000));
    }
    
    const successfulDeletions = deletionResults.filter(r => r.success);
    
    return {
      totalCandidates: expensiveIdleClusters.length,
      successfulDeletions: successfulDeletions.length,
      hourlySavings: totalSavings,
      estimatedMonthlySavings: totalSavings * 24 * 30,
      results: deletionResults
    };
    
  } catch (error) {
    console.error('Cost optimization cleanup failed:', error);
    throw error;
  }
}
```

### Emergency Security Cleanup

Quickly delete clusters in response to security incidents.

```python
def emergency_security_cleanup(incident_id, affected_cluster_ids, security_reason):
    """Emergency deletion of clusters due to security incident"""
    
    print(f"EMERGENCY SECURITY CLEANUP - Incident: {incident_id}")
    print(f"Reason: {security_reason}")
    print(f"Affected clusters: {len(affected_cluster_ids)}")
    
    cleanup_results = {
        "incident_id": incident_id,
        "security_reason": security_reason,
        "total_clusters": len(affected_cluster_ids),
        "clusters_deleted": 0,
        "clusters_failed": 0,
        "emergency_actions": [],
        "cleanup_timestamp": datetime.now().isoformat()
    }
    
    for cluster_id in affected_cluster_ids:
        try:
            print(f"Emergency deleting cluster: {cluster_id}")
            
            # Force delete with minimal delay
            emergency_payload = {
                "confirm_deletion": "DELETE",
                "force": True,
                "create_final_snapshot": False,  # Skip backup for speed
                "delete_snapshots": True,        # Remove all data for security
                "cleanup_network_resources": True,
                "wait_for_completion": True,
                "timeout_minutes": 5,            # Short timeout
                "deletion_reason": f"SECURITY INCIDENT {incident_id}: {security_reason}"
            }
            
            response = requests.delete(
                f"https://api.tensorone.ai/v1/clusters/{cluster_id}",
                headers={"Authorization": f"Bearer {API_KEY}"},
                json=emergency_payload
            )
            
            result = response.json()
            
            if result["success"]:
                cleanup_results["clusters_deleted"] += 1
                cleanup_results["emergency_actions"].append({
                    "cluster_id": cluster_id,
                    "action": "force_deleted",
                    "deleted_at": result["data"]["deleted_at"],
                    "resources_cleaned": result["data"]["resources_cleaned_up"]
                })
                print(f"✅ Emergency deleted: {cluster_id}")
            else:
                cleanup_results["clusters_failed"] += 1
                cleanup_results["emergency_actions"].append({
                    "cluster_id": cluster_id,
                    "action": "delete_failed",
                    "error": result["error"]["message"]
                })
                print(f"❌ Failed to delete: {cluster_id} - {result['error']['message']}")
                
        except Exception as e:
            cleanup_results["clusters_failed"] += 1
            cleanup_results["emergency_actions"].append({
                "cluster_id": cluster_id,
                "action": "delete_error",
                "error": str(e)
            })
            print(f"❌ Error deleting {cluster_id}: {str(e)}")
    
    print(f"\nEmergency cleanup completed:")
    print(f"  Successfully deleted: {cleanup_results['clusters_deleted']}")
    print(f"  Failed deletions: {cleanup_results['clusters_failed']}")
    
    # Log security incident for audit
    security_log = {
        "incident_id": incident_id,
        "timestamp": cleanup_results["cleanup_timestamp"],
        "action": "emergency_cluster_cleanup",
        "affected_resources": len(affected_cluster_ids),
        "successful_cleanup": cleanup_results["clusters_deleted"],
        "reason": security_reason
    }
    
    return cleanup_results, security_log
```

## Error Handling

```json Confirmation Required
{
  "success": false,
  "error": {
    "code": "CONFIRMATION_REQUIRED",
    "message": "Deletion confirmation required for permanent operation",
    "details": {
      "required_field": "confirm_deletion",
      "required_value": "DELETE",
      "cluster_id": "cluster_abc123",
      "cluster_name": "ml-training-cluster",
      "warning": "This operation is permanent and cannot be undone"
    }
  }
}
```

```json Cluster Has Dependencies
{
  "success": false,
  "error": {
    "code": "CLUSTER_HAS_DEPENDENCIES",
    "message": "Cluster cannot be deleted due to active dependencies",
    "details": {
      "dependencies": [
        {
          "type": "snapshot",
          "id": "snap_123",
          "name": "critical_checkpoint",
          "dependent_resources": ["cluster_def456"]
        },
        {
          "type": "network_config",
          "id": "vpc_789",
          "shared_with": ["cluster_ghi789"]
        }
      ],
      "suggestions": [
        "Delete or move dependent snapshots first",
        "Update network configuration sharing"
      ]
    }
  }
}
```

```json Billing Not Finalized
{
  "success": false,
  "error": {
    "code": "BILLING_NOT_FINALIZED",
    "message": "Cannot delete cluster with pending billing processes",
    "details": {
      "pending_charges": 45.75,
      "billing_period_end": "2024-01-15T23:59:59Z",
      "estimated_finalization": "2024-01-16T01:00:00Z",
      "suggestion": "Wait for billing period to end or force delete with finalize_billing=true"
    }
  }
}
```

```json Snapshot Creation Failed
{
  "success": false,
  "error": {
    "code": "SNAPSHOT_CREATION_FAILED",
    "message": "Failed to create final snapshot before deletion",
    "details": {
      "error_reason": "Insufficient storage quota",
      "required_storage_gb": 456.8,
      "available_storage_gb": 200.0,
      "suggestion": "Either increase storage quota or proceed without final snapshot using create_final_snapshot=false"
    }
  }
}
```

## Security Considerations

* **Permanent Operation**: Cluster deletion is irreversible - ensure proper confirmation
* **Data Security**: Consider data sensitivity when choosing snapshot preservation options
* **Access Control**: Verify deletion permissions, especially for shared clusters
* **Audit Logging**: All deletions are logged for compliance and security auditing
* **Emergency Procedures**: Have emergency deletion procedures for security incidents

## Best Practices

1. **Backup Important Data**: Always create final snapshots for critical workloads
2. **Staged Deletion**: Delete development clusters first, then production
3. **Cost Tracking**: Monitor deletion savings and optimize deletion strategies
4. **Security Compliance**: Follow data retention policies and regulatory requirements
5. **Documentation**: Document deletion reasons for audit trails
6. **Automation**: Implement automated cleanup for idle or completed workloads


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.