> ## 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.

# Restart Cluster

> Restart GPU clusters with configuration updates and state preservation options

## Overview

The Restart Cluster endpoint allows you to restart running or stopped GPU clusters, optionally applying configuration updates during the restart process. This is useful for applying system updates, changing configurations, or recovering from errors while preserving data and work state.

## Endpoint

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

## Path Parameters

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

## Request Body

| Parameter | Type | Required | Description |
| - | - | - | - |
| `force` | boolean | No | Force restart without graceful shutdown (default: false) |
| `grace_period_minutes` | integer | No | Grace period for graceful shutdown (default: 5, max: 30) |
| `wait_for_ready` | boolean | No | Wait for cluster to be fully ready after restart (default: false) |
| `timeout_minutes` | integer | No | Maximum wait time for completion (default: 15, max: 60) |
| `preserve_state` | boolean | No | Preserve running processes and state (default: false) |
| `update_configuration` | object | No | Configuration updates to apply during restart |
| `environment_updates` | object | No | Environment variable updates |
| `port_mapping_updates` | array | No | Port mapping changes |
| `restart_reason` | string | No | Reason for restart (for audit logs) |
| `restore_from_snapshot` | string | No | Snapshot ID to restore from during restart |
| `update_docker_image` | string | No | New Docker image to use after restart |
| `apply_system_updates` | boolean | No | Apply pending system updates (default: false) |

### Configuration Updates

```json
{
  "update_configuration": {
    "cpu_cores": 64,              // Update CPU allocation
    "memory_gb": 512,             // Update memory allocation  
    "storage_gb": 2000,           // Expand storage (cannot shrink)
    "gpu_count": 8,               // Update GPU count (if available)
    "region": "us-west-2"         // Change region (requires data migration)
  }
}
```

## Request Examples

```bash curl
# Basic cluster restart
curl -X POST "https://api.tensorone.ai/v1/clusters/cluster_abc123/restart" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "wait_for_ready": true,
    "timeout_minutes": 20,
    "restart_reason": "Apply system updates"
  }'

# Restart with configuration updates
curl -X POST "https://api.tensorone.ai/v1/clusters/cluster_abc123/restart" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "wait_for_ready": true,
    "update_configuration": {
      "memory_gb": 512,
      "cpu_cores": 64
    },
    "update_docker_image": "tensorone/pytorch:2.2-cuda12.1",
    "environment_updates": {
      "MODEL_VERSION": "v2.0",
      "BATCH_SIZE": "128"
    },
    "apply_system_updates": true,
    "restart_reason": "Scale up for large model training"
  }'

# Force restart with snapshot restore
curl -X POST "https://api.tensorone.ai/v1/clusters/cluster_abc123/restart" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "force": true,
    "wait_for_ready": true,
    "restore_from_snapshot": "snap_xyz789",
    "port_mapping_updates": [
      {
        "internal_port": 8080,
        "external_port": 0,
        "protocol": "tcp",
        "description": "Web Interface"
      }
    ],
    "restart_reason": "Restore from backup after error"
  }'
```

```python Python
import requests
import time

def restart_cluster_basic(cluster_id, reason=None):
    """Basic cluster restart with optional reason"""
    
    payload = {
        "wait_for_ready": True,
        "timeout_minutes": 15,
        "apply_system_updates": True
    }
    
    if reason:
        payload["restart_reason"] = reason
    
    response = requests.post(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/restart",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=payload
    )
    
    result = response.json()
    
    if result["success"]:
        print(f"Cluster {cluster_id} restarted successfully")
        if "data" in result:
            print(f"New configuration applied: {result['data'].get('configuration_changes', 'None')}")
    
    return result

def restart_with_scaling(cluster_id, new_config):
    """Restart cluster with resource scaling"""
    
    payload = {
        "wait_for_ready": True,
        "timeout_minutes": 25,
        "update_configuration": {
            "cpu_cores": new_config.get("cpu_cores"),
            "memory_gb": new_config.get("memory_gb"),
            "gpu_count": new_config.get("gpu_count"),
            "storage_gb": new_config.get("storage_gb")
        },
        "environment_updates": new_config.get("environment", {}),
        "restart_reason": f"Resource scaling: {new_config.get('reason', 'Configuration update')}"
    }
    
    # Remove None values
    payload["update_configuration"] = {k: v for k, v in payload["update_configuration"].items() if v is not None}
    
    response = requests.post(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/restart",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=payload
    )
    
    result = response.json()
    
    if result["success"]:
        data = result["data"]
        print(f"Cluster {cluster_id} scaled and restarted")
        print(f"New hourly rate: ${data['cost']['new_hourly_rate']}")
        
        if "configuration_changes" in data:
            for change in data["configuration_changes"]:
                print(f"  {change}")
    
    return result

def restart_training_cluster_with_checkpoint(cluster_id, checkpoint_snapshot_id, model_config):
    """Restart training cluster from checkpoint with new model configuration"""
    
    payload = {
        "wait_for_ready": True,
        "timeout_minutes": 30,
        "restore_from_snapshot": checkpoint_snapshot_id,
        "update_docker_image": model_config.get("docker_image"),
        "environment_updates": {
            "RESUME_FROM_CHECKPOINT": "true",
            "CHECKPOINT_SNAPSHOT_ID": checkpoint_snapshot_id,
            "MODEL_CONFIG": model_config.get("model_name", "default"),
            "LEARNING_RATE": str(model_config.get("learning_rate", 0.001)),
            "BATCH_SIZE": str(model_config.get("batch_size", 32))
        },
        "update_configuration": {
            "memory_gb": model_config.get("memory_gb"),
            "gpu_count": model_config.get("gpu_count")
        },
        "restart_reason": f"Resume training from checkpoint: {checkpoint_snapshot_id}"
    }
    
    # Clean up None values
    for key in ["update_docker_image"]:
        if payload.get(key) is None:
            del payload[key]
    
    payload["update_configuration"] = {k: v for k, v in payload["update_configuration"].items() if v is not None}
    
    response = requests.post(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/restart",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=payload
    )
    
    return response.json()

def rolling_restart_for_maintenance(cluster_ids, maintenance_config):
    """Perform rolling restart of multiple clusters for maintenance"""
    
    results = []
    
    for i, cluster_id in enumerate(cluster_ids):
        print(f"Restarting cluster {i+1}/{len(cluster_ids)}: {cluster_id}")
        
        # Stagger restarts to avoid resource contention
        if i > 0:
            time.sleep(maintenance_config.get("stagger_delay_seconds", 60))
        
        restart_config = {
            "wait_for_ready": True,
            "timeout_minutes": 20,
            "apply_system_updates": True,
            "restart_reason": f"Scheduled maintenance: {maintenance_config.get('maintenance_id', 'unknown')}"
        }
        
        # Apply any cluster-specific configurations
        if cluster_id in maintenance_config.get("cluster_overrides", {}):
            overrides = maintenance_config["cluster_overrides"][cluster_id]
            if "docker_image" in overrides:
                restart_config["update_docker_image"] = overrides["docker_image"]
            if "environment" in overrides:
                restart_config["environment_updates"] = overrides["environment"]
        
        try:
            result = restart_cluster_basic(cluster_id, restart_config["restart_reason"])
            results.append({
                "cluster_id": cluster_id,
                "success": result["success"],
                "restart_duration": result.get("data", {}).get("restart_duration_seconds"),
                "error": result.get("error")
            })
        except Exception as e:
            results.append({
                "cluster_id": cluster_id,
                "success": False,
                "error": str(e)
            })
    
    return results
```

```javascript JavaScript
// Basic cluster restart with monitoring
async function restartCluster(clusterId, options = {}) {
  const restartConfig = {
    wait_for_ready: options.waitForReady !== false, // default true
    timeout_minutes: options.timeoutMinutes || 15,
    apply_system_updates: options.applyUpdates !== false, // default true
    restart_reason: options.reason || 'Manual restart request'
  };
  
  if (options.gracePeriod) {
    restartConfig.grace_period_minutes = options.gracePeriod;
  }
  
  if (options.force) {
    restartConfig.force = true;
  }
  
  const response = await fetch(`https://api.tensorone.ai/v1/clusters/${clusterId}/restart`, {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(restartConfig)
  });
  
  const result = await response.json();
  
  if (!result.success) {
    throw new Error(`Failed to restart cluster: ${result.error.message}`);
  }
  
  return result.data;
}

// Restart with comprehensive configuration updates
async function restartWithUpdates(clusterId, updates) {
  const restartConfig = {
    wait_for_ready: true,
    timeout_minutes: 25,
    restart_reason: updates.reason || 'Configuration update'
  };
  
  // Hardware configuration updates
  if (updates.hardware) {
    restartConfig.update_configuration = {};
    
    ['cpu_cores', 'memory_gb', 'gpu_count', 'storage_gb'].forEach(key => {
      if (updates.hardware[key] !== undefined) {
        restartConfig.update_configuration[key] = updates.hardware[key];
      }
    });
  }
  
  // Software updates
  if (updates.dockerImage) {
    restartConfig.update_docker_image = updates.dockerImage;
  }
  
  if (updates.environment) {
    restartConfig.environment_updates = updates.environment;
  }
  
  // Port mapping updates
  if (updates.portMappings) {
    restartConfig.port_mapping_updates = updates.portMappings;
  }
  
  // Snapshot restore
  if (updates.snapshotId) {
    restartConfig.restore_from_snapshot = updates.snapshotId;
  }
  
  try {
    const response = await fetch(`https://api.tensorone.ai/v1/clusters/${clusterId}/restart`, {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(restartConfig)
    });
    
    const result = await response.json();
    
    if (!result.success) {
      throw new Error(result.error.message);
    }
    
    return {
      clusterId: result.data.id,
      status: result.data.status,
      configurationChanges: result.data.configuration_changes || [],
      newHourlyRate: result.data.cost?.new_hourly_rate,
      restartDuration: result.data.restart_duration_seconds,
      proxyUrl: result.data.network?.proxy_url
    };
    
  } catch (error) {
    console.error(`Error restarting cluster ${clusterId}:`, error);
    throw error;
  }
}

// Blue-green deployment restart pattern
async function blueGreenRestart(primaryClusterId, backupClusterId, newConfig) {
  console.log('Starting blue-green restart pattern...');
  
  try {
    // Step 1: Start backup cluster with new configuration
    console.log('Starting backup cluster with new configuration...');
    const backupResult = await restartWithUpdates(backupClusterId, {
      ...newConfig,
      reason: 'Blue-green deployment - backup activation'
    });
    
    console.log(`Backup cluster ${backupClusterId} is ready`);
    
    // Step 2: Wait for backup to be fully operational
    await new Promise(resolve => setTimeout(resolve, 30000)); // 30 second settling time
    
    // Step 3: Health check backup cluster
    const healthCheck = await fetch(`https://api.tensorone.ai/v1/clusters/${backupClusterId}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    });
    
    const backupHealth = await healthCheck.json();
    
    if (backupHealth.data.status !== 'running') {
      throw new Error('Backup cluster failed health check');
    }
    
    // Step 4: Switch traffic (this would typically involve load balancer updates)
    console.log('Backup cluster healthy, switching traffic...');
    
    // Step 5: Restart primary cluster with new configuration
    console.log('Restarting primary cluster...');
    const primaryResult = await restartWithUpdates(primaryClusterId, {
      ...newConfig,
      reason: 'Blue-green deployment - primary update'
    });
    
    console.log(`Primary cluster ${primaryClusterId} restarted successfully`);
    
    return {
      success: true,
      primaryCluster: {
        id: primaryClusterId,
        status: primaryResult.status,
        proxyUrl: primaryResult.proxyUrl
      },
      backupCluster: {
        id: backupClusterId,
        status: backupResult.status,
        proxyUrl: backupResult.proxyUrl
      },
      deploymentDuration: Date.now() - startTime
    };
    
  } catch (error) {
    console.error('Blue-green restart failed:', error);
    
    // Attempt rollback - ensure primary is running
    try {
      await restartCluster(primaryClusterId, {
        reason: 'Blue-green deployment rollback',
        force: true
      });
    } catch (rollbackError) {
      console.error('Rollback failed:', rollbackError);
    }
    
    throw error;
  }
}

// Batch restart with dependency management
async function batchRestartWithDependencies(restartPlan) {
  const results = new Map();
  const completed = new Set();
  const failed = new Set();
  
  // Process clusters in dependency order
  for (const phase of restartPlan.phases) {
    console.log(`Starting restart phase: ${phase.name}`);
    
    const phasePromises = phase.clusters.map(async (clusterConfig) => {
      const clusterId = clusterConfig.clusterId;
      
      try {
        // Wait for dependencies to complete
        if (clusterConfig.dependencies) {
          for (const dep of clusterConfig.dependencies) {
            if (!completed.has(dep)) {
              throw new Error(`Dependency ${dep} not completed`);
            }
            if (failed.has(dep)) {
              throw new Error(`Dependency ${dep} failed`);
            }
          }
        }
        
        const result = await restartWithUpdates(clusterId, clusterConfig.updates);
        
        results.set(clusterId, {
          success: true,
          phase: phase.name,
          ...result
        });
        
        completed.add(clusterId);
        console.log(`✅ ${clusterId} restarted successfully`);
        
      } catch (error) {
        results.set(clusterId, {
          success: false,
          phase: phase.name,
          error: error.message
        });
        
        failed.add(clusterId);
        console.error(`❌ ${clusterId} restart failed:`, error.message);
      }
    });
    
    // Wait for all clusters in this phase to complete
    await Promise.allSettled(phasePromises);
    
    // Check if we should continue to next phase
    const phaseFailures = phase.clusters.filter(c => failed.has(c.clusterId));
    if (phaseFailures.length > 0 && phase.stopOnFailure) {
      console.error(`Phase ${phase.name} had failures, stopping batch restart`);
      break;
    }
  }
  
  return {
    totalClusters: restartPlan.phases.reduce((sum, phase) => sum + phase.clusters.length, 0),
    successful: completed.size,
    failed: failed.size,
    results: Object.fromEntries(results)
  };
}
```

## Response Schema

```json Success Response (Immediate)
{
  "success": true,
  "data": {
    "id": "cluster_abc123",
    "name": "ml-training-cluster",
    "status": "restarting",
    "restart_initiated_at": "2024-01-15T17:00:00Z",
    "estimated_completion_time": "2024-01-15T17:08:00Z",
    "restart_type": "graceful",
    "restart_progress": {
      "phase": "stopping_processes",
      "percentage": 25,
      "current_step": "Gracefully stopping running processes",
      "steps_completed": 2,
      "total_steps": 8
    },
    "configuration_updates": {
      "pending": [
        "memory_gb: 256 -> 512",
        "docker_image: pytorch:2.1 -> pytorch:2.2",
        "cpu_cores: 32 -> 64"
      ],
      "applied": []
    },
    "cost_impact": {
      "old_hourly_rate": 8.50,
      "new_hourly_rate": 12.50,
      "rate_change_reason": "Memory and CPU upgrade"
    }
  },
  "meta": {
    "request_id": "req_restart_789",
    "wait_for_ready": false
  }
}
```

```json Success Response (Wait for Ready)
{
  "success": true,
  "data": {
    "id": "cluster_abc123",
    "name": "ml-training-cluster",
    "status": "running",
    "restart_initiated_at": "2024-01-15T17:00:00Z",
    "restart_completed_at": "2024-01-15T17:07:45Z",
    "restart_duration_seconds": 465,
    "restart_type": "graceful",
    "downtime_seconds": 125,
    "configuration_changes": [
      "memory_gb: 256 -> 512",
      "docker_image: tensorone/pytorch:2.1-cuda11.8 -> tensorone/pytorch:2.2-cuda12.1",
      "cpu_cores: 32 -> 64",
      "system_updates: 12 packages updated"
    ],
    "configuration": {
      "gpu_type": "A100",
      "gpu_count": 4,
      "cpu_cores": 64,
      "memory_gb": 512,
      "storage_gb": 1000
    },
    "network": {
      "proxy_url": "https://cluster-abc123.tensorone.ai",
      "ssh_connection": {
        "host": "ssh-abc123.tensorone.ai",
        "port": 22,
        "username": "root",
        "connection_string": "ssh root@ssh-abc123.tensorone.ai",
        "status": "connected"
      },
      "port_mappings": [
        {
          "internal_port": 8080,
          "external_port": 32001,
          "protocol": "tcp",
          "description": "Web Interface",
          "url": "https://cluster-abc123.tensorone.ai:32001",
          "status": "active"
        }
      ]
    },
    "cost": {
      "old_hourly_rate": 8.50,
      "new_hourly_rate": 12.50,
      "rate_increase_percent": 47.1,
      "billing_updated_at": "2024-01-15T17:07:45Z"
    },
    "environment": {
      "variables_updated": ["MODEL_VERSION", "BATCH_SIZE"],
      "docker_image_updated": true,
      "system_packages_updated": 12
    },
    "health_checks": {
      "gpu_health": "healthy",
      "storage_health": "healthy", 
      "network_health": "healthy",
      "docker_health": "healthy",
      "application_health": "healthy"
    },
    "performance_impact": {
      "cpu_performance_increase": "~100%",
      "memory_bandwidth_increase": "~100%",
      "expected_training_speedup": "1.8x"
    }
  },
  "meta": {
    "request_id": "req_restart_789",
    "wait_for_ready": true,
    "total_wait_time_seconds": 465
  }
}
```

## Restart Progress Phases

| Phase | Description | Typical Duration |
| - | - | - |
| `stopping_processes` | Gracefully stopping running processes | 1-10 minutes |
| `creating_checkpoint` | Creating state checkpoint (if preserve\_state=true) | 30s-5 minutes |
| `updating_configuration` | Applying hardware/software updates | 1-3 minutes |
| `starting_services` | Starting system services and Docker containers | 30s-2 minutes |
| `health_checks` | Running health checks and validation | 30s-1 minute |
| `ready` | Cluster is fully operational | - |

## Use Cases

### System Updates and Maintenance

Apply system updates and security patches with minimal downtime.

```python
def apply_system_updates(cluster_ids, maintenance_window):
    """Apply system updates during maintenance window"""
    
    results = []
    
    for cluster_id in cluster_ids:
        # Get current cluster configuration
        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"]:
            results.append({"cluster_id": cluster_id, "success": False, "error": "Failed to get cluster info"})
            continue
        
        cluster = cluster_info["data"]
        
        # Determine restart strategy based on cluster type
        restart_config = {
            "wait_for_ready": True,
            "timeout_minutes": 20,
            "apply_system_updates": True,
            "restart_reason": f"Maintenance window: {maintenance_window['id']}"
        }
        
        # Production clusters get more graceful treatment
        if "prod" in cluster["name"].lower():
            restart_config["grace_period_minutes"] = 15
            restart_config["preserve_state"] = True
        else:
            restart_config["grace_period_minutes"] = 5
        
        # Apply any pending Docker image updates
        if maintenance_window.get("docker_updates", {}).get(cluster_id):
            restart_config["update_docker_image"] = maintenance_window["docker_updates"][cluster_id]
        
        try:
            result = restart_cluster_basic(cluster_id, restart_config["restart_reason"])
            
            results.append({
                "cluster_id": cluster_id,
                "name": cluster["name"],
                "success": result["success"],
                "downtime_seconds": result.get("data", {}).get("downtime_seconds"),
                "updates_applied": result.get("data", {}).get("configuration_changes", [])
            })
            
        except Exception as e:
            results.append({
                "cluster_id": cluster_id,
                "success": False,
                "error": str(e)
            })
    
    return {
        "maintenance_window": maintenance_window["id"],
        "total_clusters": len(cluster_ids),
        "successful_updates": len([r for r in results if r["success"]]),
        "results": results
    }
```

### Model Version Deployment

Deploy new model versions with configuration updates.

```javascript
async function deployModelVersion(clusterId, modelDeployment) {
  const deploymentConfig = {
    wait_for_ready: true,
    timeout_minutes: 30,
    update_docker_image: modelDeployment.dockerImage,
    environment_updates: {
      MODEL_VERSION: modelDeployment.version,
      MODEL_PATH: modelDeployment.modelPath,
      CONFIG_PATH: modelDeployment.configPath,
      DEPLOYMENT_ID: modelDeployment.deploymentId
    },
    restart_reason: `Model deployment: ${modelDeployment.name} v${modelDeployment.version}`
  };
  
  // Add hardware scaling if specified
  if (modelDeployment.scaling) {
    deploymentConfig.update_configuration = {
      gpu_count: modelDeployment.scaling.gpuCount,
      memory_gb: modelDeployment.scaling.memoryGb,
      cpu_cores: modelDeployment.scaling.cpuCores
    };
  }
  
  // Add port mappings for new services
  if (modelDeployment.services) {
    deploymentConfig.port_mapping_updates = modelDeployment.services.map(service => ({
      internal_port: service.port,
      external_port: 0, // Auto-assign
      protocol: 'tcp',
      description: service.description
    }));
  }
  
  try {
    console.log(`Deploying ${modelDeployment.name} v${modelDeployment.version} to cluster ${clusterId}`);
    
    const result = await restartWithUpdates(clusterId, deploymentConfig);
    
    // Validate deployment
    const healthCheck = await validateModelDeployment(clusterId, modelDeployment);
    
    if (!healthCheck.success) {
      throw new Error(`Model deployment validation failed: ${healthCheck.error}`);
    }
    
    return {
      success: true,
      clusterId: clusterId,
      deploymentId: modelDeployment.deploymentId,
      modelVersion: modelDeployment.version,
      proxyUrl: result.proxyUrl,
      services: result.portMappings || [],
      deploymentTime: result.restartDuration,
      healthCheck: healthCheck
    };
    
  } catch (error) {
    console.error(`Model deployment failed for cluster ${clusterId}:`, error);
    
    // Attempt rollback if previous version info is available
    if (modelDeployment.previousVersion) {
      console.log('Attempting rollback to previous version...');
      try {
        await deployModelVersion(clusterId, {
          ...modelDeployment,
          version: modelDeployment.previousVersion.version,
          dockerImage: modelDeployment.previousVersion.dockerImage,
          deploymentId: `rollback_${modelDeployment.deploymentId}`
        });
      } catch (rollbackError) {
        console.error('Rollback failed:', rollbackError);
      }
    }
    
    throw error;
  }
}

async function validateModelDeployment(clusterId, modelDeployment) {
  // Wait for services to be ready
  await new Promise(resolve => setTimeout(resolve, 30000));
  
  try {
    // Get cluster info to check services
    const response = await fetch(`https://api.tensorone.ai/v1/clusters/${clusterId}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    });
    
    const cluster = await response.json();
    
    if (!cluster.success) {
      return { success: false, error: 'Failed to get cluster info' };
    }
    
    // Check if all expected services are running
    const runningServices = cluster.data.network.port_mappings || [];
    const expectedServices = modelDeployment.services || [];
    
    for (const expectedService of expectedServices) {
      const runningService = runningServices.find(s => s.internal_port === expectedService.port);
      
      if (!runningService || runningService.status !== 'active') {
        return { 
          success: false, 
          error: `Service ${expectedService.description} is not active` 
        };
      }
      
      // Test service endpoint if health check URL provided
      if (expectedService.healthCheckPath) {
        try {
          const serviceUrl = `${runningService.url}${expectedService.healthCheckPath}`;
          const healthResponse = await fetch(serviceUrl, { timeout: 10000 });
          
          if (!healthResponse.ok) {
            return {
              success: false,
              error: `Service ${expectedService.description} health check failed`
            };
          }
        } catch (error) {
          return {
            success: false,
            error: `Service ${expectedService.description} is not responding`
          };
        }
      }
    }
    
    return {
      success: true,
      servicesValidated: expectedServices.length,
      allServicesHealthy: true
    };
    
  } catch (error) {
    return {
      success: false,
      error: `Validation failed: ${error.message}`
    };
  }
}
```

### Recovery from Errors

Restart clusters to recover from errors with optional state restoration.

```python
def recover_cluster_from_error(cluster_id, recovery_strategy="restart"):
    """Recover cluster from error state using specified strategy"""
    
    # Get current cluster state
    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"}
    
    cluster = cluster_info["data"]
    
    if cluster["status"] != "error":
        return {"success": False, "error": f"Cluster is not in error state (current: {cluster['status']})"}
    
    recovery_actions = []
    
    if recovery_strategy == "restart":
        # Simple restart with force
        restart_config = {
            "force": True,
            "wait_for_ready": True,
            "apply_system_updates": True,
            "restart_reason": "Error recovery - forced restart"
        }
        
        result = requests.post(
            f"https://api.tensorone.ai/v1/clusters/{cluster_id}/restart",
            headers={"Authorization": f"Bearer {API_KEY}"},
            json=restart_config
        ).json()
        
        recovery_actions.append("Forced restart")
        
    elif recovery_strategy == "restore_snapshot":
        # Find latest snapshot and restore
        snapshots = cluster.get("storage", {}).get("snapshots", [])
        
        if not snapshots:
            return {"success": False, "error": "No snapshots available for restore"}
        
        latest_snapshot = max(snapshots, key=lambda s: s["created_at"])
        
        restart_config = {
            "force": True,
            "wait_for_ready": True,
            "restore_from_snapshot": latest_snapshot["id"],
            "restart_reason": f"Error recovery - restore from snapshot {latest_snapshot['id']}"
        }
        
        result = requests.post(
            f"https://api.tensorone.ai/v1/clusters/{cluster_id}/restart",
            headers={"Authorization": f"Bearer {API_KEY}"},
            json=restart_config
        ).json()
        
        recovery_actions.append(f"Restored from snapshot: {latest_snapshot['name']}")
        
    elif recovery_strategy == "rebuild":
        # Restart with fresh image and reset configuration
        original_template = cluster.get("template_info", {})
        
        restart_config = {
            "force": True,
            "wait_for_ready": True,
            "update_docker_image": original_template.get("docker_image"),
            "environment_updates": {
                "RECOVERY_MODE": "true",
                "RECOVERY_TIMESTAMP": datetime.now().isoformat()
            },
            "restart_reason": "Error recovery - rebuild from template"
        }
        
        result = requests.post(
            f"https://api.tensorone.ai/v1/clusters/{cluster_id}/restart",
            headers={"Authorization": f"Bearer {API_KEY}"},
            json=restart_config
        ).json()
        
        recovery_actions.append("Rebuilt from original template")
    
    if result["success"]:
        return {
            "success": True,
            "cluster_id": cluster_id,
            "recovery_strategy": recovery_strategy,
            "recovery_actions": recovery_actions,
            "restart_duration": result.get("data", {}).get("restart_duration_seconds"),
            "new_status": result.get("data", {}).get("status"),
            "recovery_completed_at": result.get("data", {}).get("restart_completed_at")
        }
    
    return result
```

## Error Handling

```json Invalid State
{
  "success": false,
  "error": {
    "code": "INVALID_STATE",
    "message": "Cluster cannot be restarted in current state",
    "details": {
      "current_status": "starting",
      "allowed_states": ["running", "stopped", "error"],
      "suggestion": "Wait for cluster to finish current operation"
    }
  }
}
```

```json Configuration Conflict
{
  "success": false,
  "error": {
    "code": "CONFIGURATION_CONFLICT",
    "message": "Requested configuration changes are incompatible",
    "details": {
      "conflicts": [
        "Cannot reduce GPU count from 8 to 4 while preserving state",
        "Requested memory 1024GB exceeds maximum for GPU type A100 (512GB)"
      ],
      "suggestions": [
        "Use preserve_state=false to allow GPU count reduction",
        "Choose a different GPU type or reduce memory requirement"
      ]
    }
  }
}
```

```json Resource Unavailable
{
  "success": false,
  "error": {
    "code": "RESOURCE_UNAVAILABLE", 
    "message": "Requested resources not available for restart",
    "details": {
      "requested_gpu_count": 8,
      "available_gpu_count": 4,
      "gpu_type": "A100",
      "region": "us-west-2",
      "estimated_availability": "2024-01-15T19:00:00Z"
    }
  }
}
```

```json Restart Timeout
{
  "success": false,
  "error": {
    "code": "RESTART_TIMEOUT",
    "message": "Cluster restart did not complete within timeout",
    "details": {
      "timeout_minutes": 15,
      "current_phase": "starting_services",
      "progress_percentage": 75,
      "cluster_status": "restarting",
      "suggestion": "Check cluster logs or try again with longer timeout"
    }
  }
}
```

## Security Considerations

* **State Preservation**: Be cautious when preserving state during security updates
* **Configuration Validation**: Validate all configuration changes before restart
* **Access Control**: Ensure proper permissions for configuration modifications
* **Audit Logging**: Log restart reasons and configuration changes for compliance

## Best Practices

1. **Graceful Restarts**: Use graceful restarts unless emergency recovery is needed
2. **Configuration Testing**: Test configuration changes in development first
3. **State Management**: Use snapshots for critical workloads before major changes
4. **Monitoring**: Monitor restart progress and validate successful completion
5. **Rollback Planning**: Have rollback procedures ready for failed deployments
6. **Resource Planning**: Consider resource availability during restart operations


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