# Streamlit Container Runtime Troubleshooting Guide

## Overview
Comprehensive troubleshooting guide based on extensive Phase 0 testing experience. This guide covers every known issue and validated solution for Container Runtime deployments.

## Critical Success Factors (NEVER COMPROMISE)

### 1. File Upload Requirements
- ✅ **ALWAYS** use `AUTO_COMPRESS=FALSE` for every file upload
- ✅ **ALWAYS** use absolute file paths in PUT commands
- ✅ **ALWAYS** verify files uploaded correctly with `LIST @stage`

### 2. Application Creation Requirements
- ✅ **ALWAYS** use `FROM '@schema.stage/'` syntax (not ROOT_LOCATION)
- ✅ **ALWAYS** include trailing slash in stage path
- ✅ **ALWAYS** specify `COMPUTE_POOL` for Container Runtime apps
- ✅ **ALWAYS** use `CREATE OR REPLACE` for updates

## Common Issues and Solutions

### Issue 1: Application Won't Load / Blank Page

#### Symptoms
- App appears in SHOW STREAMLITS but won't launch
- Blank page in Snowsight
- Loading spinner that never completes

#### Root Causes & Solutions

**1. File Compression Issue (MOST COMMON)**
```sql
-- Check if files are compressed
LIST @stage_name;
-- If you see .gz extensions, files were compressed

-- Solution: Re-upload with AUTO_COMPRESS=FALSE
PUT file:///absolute/path/to/app.py @stage_name AUTO_COMPRESS=FALSE;
```

**2. Incorrect Application Creation Syntax**
```sql
-- Wrong syntax (will fail)
CREATE STREAMLIT app_name
    ROOT_LOCATION = '@stage_name'  -- WRONG
    
-- Correct syntax
CREATE OR REPLACE STREAMLIT app_name
FROM '@schema.stage_name/'  -- CORRECT with trailing slash
```

**3. Missing Compute Pool**
```sql
-- Verify compute pool exists and is active
SHOW COMPUTE POOLS LIKE 'pool_name';
DESCRIBE COMPUTE POOL pool_name;

-- Add compute pool to app
ALTER STREAMLIT app_name SET COMPUTE_POOL = pool_name;
```

### Issue 2: Module Import Errors

#### Symptoms
- "ModuleNotFoundError" in application
- "No module named 'module_name'" errors
- Application loads but import statements fail

#### Root Causes & Solutions

**1. Files Not Uploaded or Compressed**
```sql
-- Verify all modules uploaded
LIST @stage_name;
-- Should show all .py files without .gz extensions

-- Re-upload missing modules
PUT file:///path/to/missing_module.py @stage_name AUTO_COMPRESS=FALSE;
```

**2. Incorrect File Structure**
```python
# Ensure import statements match uploaded file names
import database_module  # File must be database_module.py
import api_client      # File must be api_client.py
```

**3. Path Resolution Issues**
- All modules must be in stage root directory
- No subdirectory support (upload all files to same level)

### Issue 3: Database Connection Failures

#### Symptoms
- "Database connection failed" errors
- Snowpark session errors
- Query execution failures

#### Root Causes & Solutions

**1. Use Correct Snowpark Pattern**
```python
# Correct pattern for Container Runtime
from snowflake.snowpark.context import get_active_session

@st.cache_resource
def get_snowpark_session():
    return get_active_session()

# Wrong pattern (don't use in Container Runtime)
# st.connection("snowflake")  # NOT recommended
```

**2. Session Caching Issues**
```python
# Clear cache if needed
st.cache_resource.clear()

# Or restart application
# DROP STREAMLIT app_name;
# CREATE OR REPLACE STREAMLIT app_name ...
```

### Issue 4: External API Connection Failures

#### Symptoms
- Network connection timeouts
- "requests.exceptions.ConnectionError"
- API calls fail with network errors

#### Root Causes & Solutions

**1. Network Rules Not Configured**
```sql
-- Create specific network rule
CREATE NETWORK RULE api_access_rule
    MODE = EGRESS
    TYPE = HOST_PORT
    VALUE_LIST = (
        'api.example.com:443',
        'api.example.com:80'
    );

-- Add to external access integration
ALTER INTEGRATION integration_name 
SET ALLOWED_NETWORK_RULES = (existing_rule, api_access_rule);
```

**2. Wildcard Rules (Security Risk)**
```sql
-- Wrong (don't use wildcards)
CREATE NETWORK RULE bad_rule
    VALUE_LIST = ('*:443', '*:80');  -- WRONG

-- Correct (specific endpoints only)
CREATE NETWORK RULE good_rule
    VALUE_LIST = ('specific-api.com:443');  -- CORRECT
```

### Issue 5: Performance Issues

#### Symptoms
- Slow page load times (> 5 seconds)
- Slow query execution
- UI freezing or unresponsive

#### Root Causes & Solutions

**1. Missing Caching**
```python
# Add caching for expensive operations
@st.cache_data(ttl=300)  # 5 minute cache
def expensive_query():
    session = get_snowpark_session()
    return session.sql("EXPENSIVE QUERY").to_pandas()

@st.cache_resource
def initialize_resources():
    # Cache resource initialization
    return expensive_setup()
```

**2. Inefficient Queries**
```python
# Use LIMIT for large datasets
@st.cache_data(ttl=300)
def fetch_sample_data():
    query = """
    SELECT * FROM large_table 
    ORDER BY date DESC 
    LIMIT 1000  -- Add LIMIT
    """
    return session.sql(query).to_pandas()
```

**3. Compute Pool Sizing**
```sql
-- Scale up compute pool if needed
ALTER COMPUTE POOL pool_name SET MAX_NODES = 3;
```

### Issue 6: Privilege and Permission Errors

#### Symptoms
- "Insufficient privileges" errors
- "Access denied" messages
- Unable to create or access resources

#### Root Causes & Solutions

**1. Missing Compute Pool Privileges**
```sql
GRANT USAGE ON COMPUTE POOL pool_name TO ROLE role_name;
```

**2. Missing Integration Privileges**
```sql
GRANT USAGE ON INTEGRATION integration_name TO ROLE role_name;
```

**3. Missing Database/Schema Privileges**
```sql
GRANT USAGE ON DATABASE database_name TO ROLE role_name;
GRANT ALL PRIVILEGES ON SCHEMA schema_name TO ROLE role_name;
```

## Diagnostic Procedures

### 1. Infrastructure Diagnostics
```sql
-- Check compute pool status
SHOW COMPUTE POOLS LIKE 'pool_name';
DESCRIBE COMPUTE POOL pool_name;

-- Check integration status
SHOW INTEGRATIONS LIKE 'integration_name';
DESCRIBE INTEGRATION integration_name;

-- Check network rules
SHOW NETWORK RULES LIKE 'rule_name';
DESCRIBE NETWORK RULE rule_name;
```

### 2. Application Diagnostics
```sql
-- Check application status
SHOW STREAMLITS IN SCHEMA schema_name;
DESCRIBE STREAMLIT app_name;

-- Check stage contents
LIST @stage_name;

-- Verify privileges
SHOW GRANTS ON COMPUTE POOL pool_name;
SHOW GRANTS ON INTEGRATION integration_name;
```

### 3. Code Diagnostics
```python
# Add debug information to application
import streamlit as st
import sys
import os

st.write("Debug Information:")
st.write(f"Python version: {sys.version}")
st.write(f"Current directory: {os.getcwd()}")
st.write(f"Python path: {sys.path}")

# Test module imports individually
try:
    import module_name
    st.success("✅ module_name imported successfully")
except ImportError as e:
    st.error(f"❌ Import failed: {e}")
```

## Prevention Best Practices

### 1. Pre-Deployment Validation
- Always test hello world first
- Validate infrastructure setup
- Confirm all files uploaded correctly
- Test module imports before complex logic

### 2. Progressive Development
- Start simple, add complexity incrementally
- Test each addition before proceeding
- Use modular architecture from the start
- Implement error handling early

### 3. Performance Planning
- Design with caching in mind
- Plan for efficient database queries
- Consider data freshness requirements
- Monitor performance from start

### 4. Security Planning
- Use specific network rules only
- Follow least-privilege principles
- Validate input and handle errors gracefully
- Regular security reviews

## Emergency Recovery Procedures

### 1. Application Not Working
```sql
-- Quick recovery steps
DROP STREAMLIT IF EXISTS app_name;
REMOVE @stage_name;  -- Clear stage
-- Re-upload files with correct syntax
-- Recreate application with validated pattern
```

### 2. Infrastructure Issues
```sql
-- Reset infrastructure
DROP COMPUTE POOL IF EXISTS pool_name;
DROP INTEGRATION IF EXISTS integration_name;
DROP NETWORK RULE IF EXISTS rule_name;
-- Recreate using validated templates
```

### 3. Cache Issues
```python
# Clear Streamlit caches
st.cache_data.clear()
st.cache_resource.clear()

# Or restart application completely
```

## Success Validation Checklist

### ✅ Working Application Indicators
- [ ] App launches immediately (< 3 seconds)
- [ ] All pages load without errors
- [ ] Module imports work correctly
- [ ] Database queries execute successfully
- [ ] External API calls work (if applicable)
- [ ] Performance is acceptable
- [ ] Error handling works correctly

### ✅ Infrastructure Health Indicators
- [ ] Compute pool shows ACTIVE status
- [ ] External access integration ENABLED
- [ ] All network rules configured correctly
- [ ] Required privileges granted
- [ ] Stage contains all required files
- [ ] No compressed (.gz) files in stage

This troubleshooting guide represents comprehensive solutions to every known Container Runtime issue, validated through extensive testing experience.