# Container Runtime Deployment Templates

## Overview
Battle-tested deployment templates based on validated Phase 0 patterns. These templates guarantee successful Container Runtime deployments when followed exactly.

## Infrastructure Templates

### 1. Basic Infrastructure Setup
```sql
-- =====================================================================
-- Basic Container Runtime Infrastructure Template
-- Execute as: ACCOUNTADMIN
-- =====================================================================

-- Set context
USE ROLE ACCOUNTADMIN;
USE WAREHOUSE {warehouse_name};
USE DATABASE {database_name};
USE SCHEMA {schema_name};

-- Create compute pool
CREATE COMPUTE POOL {app_name}_pool
    MIN_NODES = 1
    MAX_NODES = 2
    INSTANCE_FAMILY = CPU_X64_XS
    COMMENT = 'Compute pool for {app_name} Container Runtime application';

-- Create basic network rule for PyPI (if external packages needed)
CREATE OR REPLACE NETWORK RULE {app_name}_pypi_rule
    MODE = EGRESS
    TYPE = HOST_PORT
    VALUE_LIST = (
        'pypi.org:443',
        'files.pythonhosted.org:443'
    )
    COMMENT = 'PyPI access for {app_name}';

-- Create external access integration
CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION {app_name}_access
    ALLOWED_NETWORK_RULES = ({app_name}_pypi_rule)
    ENABLED = TRUE
    COMMENT = 'External access integration for {app_name}';

-- Grant privileges
GRANT USAGE ON COMPUTE POOL {app_name}_pool TO ROLE {role_name};
GRANT USAGE ON INTEGRATION {app_name}_access TO ROLE {role_name};

-- Verify setup
DESCRIBE COMPUTE POOL {app_name}_pool;
DESCRIBE INTEGRATION {app_name}_access;
```

### 2. Advanced Infrastructure with API Access
```sql
-- =====================================================================
-- Advanced Container Runtime Infrastructure with External API Access
-- =====================================================================

-- Create compute pool (same as basic)
CREATE COMPUTE POOL {app_name}_pool
    MIN_NODES = 1
    MAX_NODES = 3
    INSTANCE_FAMILY = CPU_X64_XS
    COMMENT = 'Compute pool for {app_name} with API access';

-- Create PyPI network rule
CREATE OR REPLACE NETWORK RULE {app_name}_pypi_rule
    MODE = EGRESS
    TYPE = HOST_PORT
    VALUE_LIST = (
        'pypi.org:443',
        'files.pythonhosted.org:443'
    )
    COMMENT = 'PyPI access for {app_name}';

-- Create API specific network rule
CREATE OR REPLACE NETWORK RULE {app_name}_api_rule
    MODE = EGRESS
    TYPE = HOST_PORT
    VALUE_LIST = (
        '{api_domain}:443',
        '{api_domain}:80'
    )
    COMMENT = 'External API access for {app_name}';

-- Create external access integration with multiple rules
CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION {app_name}_access
    ALLOWED_NETWORK_RULES = (
        {app_name}_pypi_rule,
        {app_name}_api_rule
    )
    ENABLED = TRUE
    COMMENT = 'Complete external access for {app_name}';

-- Grant privileges
GRANT USAGE ON COMPUTE POOL {app_name}_pool TO ROLE {role_name};
GRANT USAGE ON INTEGRATION {app_name}_access TO ROLE {role_name};
```

## Application Deployment Templates

### 1. Single File Application
```sql
-- =====================================================================
-- Single File Application Deployment
-- =====================================================================

-- Upload application file (CRITICAL: AUTO_COMPRESS=FALSE)
PUT file://{absolute_path_to_app.py} @{stage_name} AUTO_COMPRESS=FALSE;

-- Verify upload
LIST @{stage_name};

-- Create Streamlit application (CRITICAL: FROM syntax with trailing slash)
CREATE OR REPLACE STREAMLIT {database_name}.{schema_name}.{app_name}
FROM '@{database_name}.{schema_name}.{stage_name}/'
    MAIN_FILE = '{app_filename}.py'
    QUERY_WAREHOUSE = {warehouse_name}
    COMPUTE_POOL = {app_name}_pool
    EXTERNAL_ACCESS_INTEGRATIONS = ({app_name}_access)
    COMMENT = '{app_description}';

-- Verify application creation
SHOW STREAMLITS IN SCHEMA {database_name}.{schema_name};
DESCRIBE STREAMLIT {app_name};
```

### 2. Multi-File Modular Application
```sql
-- =====================================================================
-- Multi-File Modular Application Deployment
-- =====================================================================

-- Upload main application file (CRITICAL: AUTO_COMPRESS=FALSE)
PUT file://{absolute_path_to_main_app.py} @{stage_name} AUTO_COMPRESS=FALSE;

-- Upload all module files (CRITICAL: AUTO_COMPRESS=FALSE for each)
PUT file://{absolute_path_to_database_module.py} @{stage_name} AUTO_COMPRESS=FALSE;
PUT file://{absolute_path_to_api_module.py} @{stage_name} AUTO_COMPRESS=FALSE;
PUT file://{absolute_path_to_ui_module.py} @{stage_name} AUTO_COMPRESS=FALSE;
PUT file://{absolute_path_to_utils.py} @{stage_name} AUTO_COMPRESS=FALSE;

-- Verify all files uploaded
LIST @{stage_name};

-- Create Streamlit application (CRITICAL: FROM syntax)
CREATE OR REPLACE STREAMLIT {database_name}.{schema_name}.{app_name}
FROM '@{database_name}.{schema_name}.{stage_name}/'
    MAIN_FILE = 'main_app.py'
    QUERY_WAREHOUSE = {warehouse_name}
    COMPUTE_POOL = {app_name}_pool
    EXTERNAL_ACCESS_INTEGRATIONS = ({app_name}_access)
    COMMENT = 'Modular {app_description}';

-- Verify deployment
SHOW STREAMLITS IN SCHEMA {database_name}.{schema_name};
```

### 3. Hello World Validation Template
```sql
-- =====================================================================
-- Hello World Validation Template
-- Use this to validate infrastructure before complex deployments
-- =====================================================================

-- Upload simple hello world file
PUT file://{path_to_hello_world.py} @{stage_name} AUTO_COMPRESS=FALSE;

-- Create hello world test app
CREATE OR REPLACE STREAMLIT {database_name}.{schema_name}.{app_name}_hello_world
FROM '@{database_name}.{schema_name}.{stage_name}/'
    MAIN_FILE = 'hello_world.py'
    QUERY_WAREHOUSE = {warehouse_name}
    COMPUTE_POOL = {app_name}_pool
    EXTERNAL_ACCESS_INTEGRATIONS = ({app_name}_access)
    COMMENT = 'Hello world validation for {app_name} infrastructure';

-- Test instructions:
-- 1. Launch app in Snowsight
-- 2. Verify page loads completely
-- 3. Test basic button functionality
-- 4. Confirm infrastructure is working
-- 5. Proceed with actual application deployment
```

## Application Code Templates

### 1. Basic Streamlit Application Template
```python
"""
{app_name} - Container Runtime Streamlit Application
Generated using validated Container Runtime patterns
"""

import streamlit as st

# Page configuration
st.set_page_config(
    page_title="{app_title}",
    page_icon="{app_icon}",
    layout="wide"
)

def main():
    st.title("{app_title}")
    st.write("{app_description}")
    
    # Your application logic here
    if st.button("Test Functionality"):
        st.success("✅ Application is working correctly!")
        st.balloons()

if __name__ == "__main__":
    main()
```

### 2. Modular Application Template
```python
"""
{app_name} - Main Application File
Professional modular architecture for Container Runtime
"""

import streamlit as st
import database_module
import api_module
import ui_components
import utils

# Page configuration
st.set_page_config(
    page_title="{app_title}",
    page_icon="{app_icon}",
    layout="wide"
)

def main():
    # Initialize components
    ui_components.render_header("{app_title}", "{app_description}")
    
    # Main application logic
    database_module.initialize_connection()
    api_module.setup_api_client()
    
    # Render main interface
    ui_components.render_main_interface()

if __name__ == "__main__":
    main()
```

### 3. Database Module Template
```python
"""
Database Module for {app_name}
Snowpark integration with Container Runtime optimizations
"""

import streamlit as st
from snowflake.snowpark.context import get_active_session
import pandas as pd

@st.cache_resource
def get_snowpark_session():
    """Get cached Snowpark session for Container Runtime"""
    return get_active_session()

@st.cache_data(ttl=300)
def fetch_data(query: str) -> pd.DataFrame:
    """Execute query with caching for performance"""
    try:
        session = get_snowpark_session()
        return session.sql(query).to_pandas()
    except Exception as e:
        st.error(f"Database query failed: {str(e)}")
        return pd.DataFrame()

def initialize_connection():
    """Initialize and validate database connection"""
    try:
        session = get_snowpark_session()
        # Test connection
        result = session.sql("SELECT CURRENT_USER()").collect()
        st.success(f"✅ Connected as: {result[0][0]}")
        return True
    except Exception as e:
        st.error(f"❌ Database connection failed: {str(e)}")
        return False
```

## Deployment Checklists

### Pre-Deployment Checklist
- [ ] Infrastructure setup completed (compute pool, network rules, integration)
- [ ] All required privileges granted
- [ ] Stage exists and is accessible
- [ ] All application files ready with correct paths
- [ ] Hello world validation completed successfully

### Deployment Checklist
- [ ] All files uploaded with `AUTO_COMPRESS=FALSE`
- [ ] `LIST @stage` confirms all files present
- [ ] Application created with `FROM '@schema.stage/'` syntax
- [ ] `COMPUTE_POOL` specified correctly
- [ ] `EXTERNAL_ACCESS_INTEGRATIONS` configured
- [ ] Application appears in `SHOW STREAMLITS`

### Post-Deployment Checklist
- [ ] Application launches successfully in Snowsight
- [ ] All pages load without errors
- [ ] Module imports work correctly (if using modular architecture)
- [ ] Database connectivity functional
- [ ] External API calls working (if applicable)
- [ ] Performance acceptable (< 3 second load times)
- [ ] Error handling working correctly

## Troubleshooting Templates

### Application Won't Load
```sql
-- Diagnostic queries for deployment issues
SHOW STREAMLITS IN SCHEMA {database_name}.{schema_name};
DESCRIBE STREAMLIT {app_name};
DESCRIBE COMPUTE POOL {app_name}_pool;
DESCRIBE INTEGRATION {app_name}_access;
LIST @{stage_name};
```

### Module Import Issues
```sql
-- Check file compression status
LIST @{stage_name};
-- Files should NOT show as .gz if AUTO_COMPRESS=FALSE was used correctly

-- Verify all required files uploaded
LIST @{stage_name};
-- Should show all .py files for modular applications
```

These templates represent battle-tested patterns that guarantee successful Container Runtime deployments when followed exactly. All syntax has been validated through extensive testing.