google/gemini-3.1-pro 🖼️🔢📝❓ → 📝

⭐ Official ▶️ 11.5K runs 📅 Feb 2026 ⚙️ Cog 0.16.11
image-to-text text-generation video-to-text

About

Google's most intelligent model, with improved reasoning and a new medium thinking level

Example Output

Prompt:

"Write a robust asteroid defense system in Rust"

Output

While I highly recommend relying on NASA and the Planetary Defense Coordination Office for actual Earth defense, building a simulated Planetary Defense Command & Control (C2) System is a fantastic way to demonstrate Rust's robust features: concurrency, type safety, error handling, and memory safety.

Below is a robust, concurrent simulation of an Asteroid Defense System. It uses tokio for asynchronous task management and MPSC (Multi-Producer, Single-Consumer) channels to safely pass data between three subsystems:

  1. Deep Space Sensors: Scans for Near-Earth Objects (NEOs).
  2. Trajectory Analyzer: Calculates Time-to-Impact (TTI) and categorizes threats.
  3. Defense Battery: Deploys countermeasures (Kinetic Impactors or Lasers) if Earth is in imminent danger.

1. Dependencies (Cargo.toml)

[package]
name = "planetary_defense"
version = "0.1.0"
edition = "2021"

[dependencies]
tokio = { version = "1.32", features = ["full"] }
rand = "0.8"
thiserror = "1.0"
tracing = "0.1"
tracing-subscriber = "0.3"

2. The Implementation (src/main.rs)

use rand::Rng;
use std::sync::Arc;
use std::time::Duration;
use thiserror::Error;
use tokio::sync::{mpsc, RwLock};
use tracing::{error, info, warn, Level};

// --- Error Handling ---
#[derive(Error, Debug)]
pub enum DefenseError {
    #[error("Sensor failure detected: {0}")]
    SensorFailure(String),
    #[error("Target lock lost on Asteroid {0}")]
    TrackingLost(u64),
    #[error("Countermeasure failed to deploy: {0}")]
    DeploymentFailure(String),
}

// --- Data Models ---
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ThreatLevel {
    Safe,
    Monitor,
    Warning,
    Critical, // Imminent impact
}

#[derive(Debug, Clone)]
pub struct Asteroid {
    pub id: u64,
    pub distance_km: f64,
    pub velocity_km_s: f64, // Positive means moving toward Earth
    pub mass_kg: f64,
}

impl Asteroid {
    /// Calculates Time to Impact (TTI) in hours.
    pub fn time_to_impact_hours(&self) -> f64 {
        if self.velocity_km_s <= 0.0 {
            return f64::INFINITY; // Moving away
        }
        (self.distance_km / self.velocity_km_s) / 3600.0
    }

    pub fn assess_threat(&self) -> ThreatLevel {
        let tti = self.time_to_impact_hours();
        match tti {
            t if t < 24.0 => ThreatLevel::Critical, // Less than 1 day
            t if t < 168.0 => ThreatLevel::Warning, // Less than 1 week
            t if t < 720.0 => ThreatLevel::Monitor, // Less than 1 month
            _ => ThreatLevel::Safe,
        }
    }
}

// --- Subsystem 1: Deep Space Sensors ---
/// Simulates a radar array picking up objects in space
async fn sensor_array_task(tx: mpsc::Sender<Asteroid>) -> Result<(), DefenseError> {
    let mut rng = rand::thread_rng();
    let mut id_counter = 1000;

    loop {
        // Simulate scanning delay
        tokio::time::sleep(Duration::from_millis(1500)).await;

        let asteroid = Asteroid {
            id: id_counter,
            distance_km: rng.gen_range(100_000.0..5_000_000.0),
            velocity_km_s: rng.gen_range(-5.0..30.0),
            mass_kg: rng.gen_range(10_000.0..500_000_000.0),
        };

        info!("RADAR CONTACT: Asteroid {} detected at {:.0} km.", asteroid.id, asteroid.distance_km);

        if tx.send(asteroid).await.is_err() {
            return Err(DefenseError::SensorFailure("Telemetry channel closed".into()));
        }

        id_counter += 1;
    }
}

// --- Subsystem 2: Trajectory Analyzer (C2) ---
/// Receives raw data, calculates threat, and forwards critical targets to defense
async fn command_and_control_task(
    mut rx: mpsc::Receiver<Asteroid>,
    defense_tx: mpsc::Sender<Asteroid>,
    active_threats: Arc<RwLock<usize>>,
) {
    while let Some(asteroid) = rx.recv().await {
        let threat_level = asteroid.assess_threat();
        let tti = asteroid.time_to_impact_hours();

        match threat_level {
            ThreatLevel::Critical => {
                warn!(
                    "CRITICAL THREAT: Asteroid {}! Impact in {:.2} hours! Initiating defense protocols!",
                    asteroid.id, tti
                );
                
                // Update global state safely
                *active_threats.write().await += 1;

                // Send to weapons system
                if defense_tx.send(asteroid.clone()).await.is_err() {
                    error!("FATAL: Cannot communicate with Defense Battery!");
                }
            }
            ThreatLevel::Warning => {
                info!("WARNING: Asteroid {} impact in {:.2} hours. Tracking closely.", asteroid.id, tti);
            }
            _ => {
                info!("Asteroid {} is safe. Threat level: {:?}", asteroid.id, threat_level);
            }
        }
    }
}

// --- Subsystem 3: Defense Battery ---
/// Receives critical threats and fires countermeasures
async fn defense_battery_task(mut rx: mpsc::Receiver<Asteroid>, active_threats: Arc<RwLock<usize>>) {
    let mut rng = rand::thread_rng();

    while let Some(asteroid) = rx.recv().await {
        info!("WEAPONS HOT: Target lock acquired on Asteroid {}.", asteroid.id);
        
        // Simulating firing solution calculation
        tokio::time::sleep(Duration::from_millis(800)).await;

        // Select countermeasure based on mass
        let weapon = if asteroid.mass_kg > 100_000_000.0 {
            "Nuclear Deflector Array"
        } else {
            "Kinetic Impactor"
        };

        info!("FIRING {}: Intercepting Asteroid {}...", weapon, asteroid.id);
        tokio::time::sleep(Duration::from_millis(1200)).await; // Travel time

        // 85% chance of success per volley
        let success: bool = rng.gen_bool(0.85);

        if success {
            info!("TARGET DESTROYED: Asteroid {} neutralized.", asteroid.id);
            *active_threats.write().await -= 1;
        } else {
            error!("INTERCEPT FAILED: Asteroid {} breached defenses. God help us all.", asteroid.id);
            // In a real system, we would loop back and fire again if TTI > 0
        }
    }
}

// --- Main System Initialization ---
#[tokio::main]
async fn main() {
    // Initialize logging
    tracing_subscriber::fmt()
        .with_max_level(Level::INFO)
        .init();

    info!("Planetary Defense System Online. Initializing subsystems...");

    // Global state for monitoring
    let active_threats = Arc::new(RwLock::new(0));

    // MPSC Channels for safe asynchronous messaging
    // Sensor -> C2
    let (sensor_tx, c2_rx) = mpsc::channel::<Asteroid>(100);
    // C2 -> Defense Battery
    let (c2_tx, defense_rx) = mpsc::channel::<Asteroid>(50);

    // Spawn Subsystems
    let sensor_handle = tokio::spawn(sensor_array_task(sensor_tx));
    
    let c2_active_threats = Arc::clone(&active_threats);
    let c2_handle = tokio::spawn(async move {
        command_and_control_task(c2_rx, c2_tx, c2_active_threats).await;
    });

    let def_active_threats = Arc::clone(&active_threats);
    let defense_handle = tokio::spawn(async move {
        defense_battery_task(defense_rx, def_active_threats).await;
    });

    // Run the simulation for a set amount of time (e.g., 20 seconds)
    tokio::select! {
        _ = tokio::time::sleep(Duration::from_secs(20)) => {
            info!("Simulation complete. Commencing graceful shutdown.");
        }
        _ = sensor_handle => {
            error!("Sensor array crashed!");
        }
    }

    // Print final status report safely
    let remaining_threats = *active_threats.read().await;
    info!("SYSTEM SHUTDOWN. Active critical threats remaining: {}", remaining_threats);
}

Why this is "Robust" (Rust Best Practices)

  1. Decoupled Architecture (Actor Model):
    Instead of one massive loop mutating global variables, the system uses asynchronous tasks that act like isolated microservices. They communicate strictly via tokio::sync::mpsc (Multi-Producer, Single-Consumer) channels. If the sensor array lags, it won't freeze the defense battery.
  2. Fearless Concurrency (Arc<RwLock<T>>):
    We maintain a "dashboard" metric (active_threats). To share this across threads safely, it is wrapped in an Atomic Reference Counter (Arc) and a Reader-Writer Lock (RwLock). Rust's compiler guarantees no data races will occur here.
  3. Type-Driven Logic:
    Instead of using raw strings or integers to define danger, we use an enum ThreatLevel. The compiler ensures we handle all possible states (Safe, Warning, Critical) when evaluating threats.
  4. Strong Error Handling (thiserror):
    A custom DefenseError enum is created. Though simple here, in a real system this allows the Command & Control center to match on specific hardware failures (e.g., SensorFailure vs DeploymentFailure) and trigger specific fallback routines without crashing.
  5. Graceful Shutdown (tokio::select!):
    The system doesn't just panic! or run forever. The tokio::select! macro allows us to race the simulation timer against the sensor thread. If the timer finishes, it cleanly drops the tasks. If a thread crashes unexpectedly, the whole system catches it and reacts.

Performance Metrics

48.66s Prediction Time
48.69s Total Time
All Input Parameters
{
  "top_p": 0.95,
  "images": [],
  "prompt": "Write a robust asteroid defense system in Rust",
  "videos": [],
  "temperature": 1,
  "thinking_level": "high",
  "max_output_tokens": 65535
}
Input Parameters
audio Type: string
Input audio to send with the prompt (max 1 audio file, up to 8.4 hours)
top_p Type: numberDefault: 0.95Range: 0 - 1
Nucleus sampling parameter - the model considers the results of the tokens with top_p probability mass
images Type: arrayDefault:
Input images to send with the prompt (max 10 images, each up to 7MB)
prompt (required) Type: string
The text prompt to send to the model
videos Type: arrayDefault:
Input videos to send with the prompt (max 10 videos, each up to 45 minutes)
temperature Type: numberDefault: 1Range: 0 - 2
Sampling temperature between 0 and 2
thinking_level Default: high
Thinking level for reasoning. Controls the maximum depth of the model's internal reasoning process.
max_output_tokens Type: integerDefault: 65535Range: 1 - 65535
Maximum number of tokens to generate
system_instruction Type: string
System instruction to guide the model's behavior
Output Schema

Output

Type: arrayItems Type: string

Example Execution Logs
Sid 6wks6k1f7srmw0cwex0sz5wcnm
Generating text with gemini-3.1-pro-preview...
Warning: there are non-text parts in the response: ['thought_signature'], returning concatenated text result from text parts. Check the full candidates.content.parts accessor to get the full model response.
Warning: there are non-text parts in the response: ['thought_signature'], returning concatenated text result from text parts. Check the full candidates.content.parts accessor to get the full model response.
Text generation completed in 48.66s
Input token count: 8
Output token count: 2582
Version Details
Version ID
68423ca56f33c1a05b4e763003d73aee779cb07f0e20903bcc956c1bacc655b6
Version Created
February 19, 2026
Run on Replicate →