Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
fix(streamlit-snowflake): Address doc review findings
Jez9387621fbb15
diff --git a/skills/streamlit-snowflake/SKILL.md b/skills/streamlit-snowflake/SKILL.mdindex 8b4d8df7..26fb6038 100644--- a/skills/streamlit-snowflake/SKILL.md+++ b/skills/streamlit-snowflake/SKILL.md@@ -82,6 +82,55 @@ snow streamlit deploy --replace --open- Building general Snowpark pipelines (use a Snowpark-specific skill)- Need custom Streamlit components (not supported in SiS)+## Runtime Environments++Snowflake offers **two runtime options** for Streamlit apps:++### Warehouse Runtime (Default)++- Creates a **personal instance** for each viewer+- Uses `environment.yml` with Snowflake Anaconda Channel+- Python 3.9, 3.10, or 3.11+- Streamlit 1.22.0 - 1.35.0+- Best for: Sporadic usage, isolated sessions++### Container Runtime (Preview)++- Creates a **shared instance** for all viewers+- Uses `requirements.txt` or `pyproject.toml` with **PyPI packages**+- Python 3.11 only+- Streamlit 1.49++- **Significantly lower cost** (~$2.88/day vs ~$48/day for equivalent compute)+- Best for: Frequent usage, cost optimization++**Container Runtime Configuration:**++```sql+CREATE STREAMLIT my_app+ FROM '@my_stage/app_folder'+ MAIN_FILE = 'streamlit_app.py'+ RUNTIME_NAME = 'SYSTEM$ST_CONTAINER_RUNTIME_PY3_11'+ COMPUTE_POOL = my_compute_pool+ QUERY_WAREHOUSE = my_warehouse;+```++**Key difference:** Container runtime allows **external PyPI packages** - not limited to Snowflake Anaconda Channel.++See: [Runtime Environments](https://docs.snowflake.com/en/developer-guide/streamlit/app-development/runtime-environments)++## Security Model++Streamlit apps run under **owner's rights** (like stored procedures):++- Apps execute with the **owner's privileges**, not the viewer's+- Apps use the warehouse provisioned by the owner+- Viewers can interact with data using all owner role privileges++**Security implications:**+- Exercise caution when granting write privileges to app roles+- Use dedicated roles for app creation/viewing+- Viewers can access any data the owner role can access+## Project Structure```@@ -144,13 +193,15 @@ dependencies:| Error | Cause | Prevention ||-------|-------|------------|-| `PackageNotFoundError` | Using conda-forge or external channel | Always use `channels: - snowflake` only |-| Missing Streamlit features | Default version 1.22.0 | Explicitly set `streamlit=1.35.0` |+| `PackageNotFoundError` | Using conda-forge or external channel | Use `channels: - snowflake` (or Container Runtime for PyPI) |+| Missing Streamlit features | Default version 1.22.0 | Explicitly set `streamlit=1.35.0` (or use Container Runtime for 1.49+) || `ROOT_LOCATION deprecated` | Old CLI syntax | Use Snowflake CLI 3.14.0+ with `FROM source_location` || Auth failures (2026+) | Password-only authentication | Use key-pair or OAuth (see references/authentication.md) |-| File upload fails | File >250MB | Keep files under 250MB limit |-| `page_title not supported` | SiS limitation | Don't use `st.set_page_config(page_title=...)` |-| Custom component error | SiS limitation | Custom Streamlit components not supported |+| File upload fails | File >200MB | Keep uploads under 200MB limit |+| DataFrame display fails | Data >32MB | Paginate or limit data before display |+| `page_title not supported` | SiS limitation | Don't use `page_title`, `page_icon`, or `menu_items` in `st.set_page_config()` |+| Custom component error | SiS limitation | Only components without external service calls work |+| `_snowflake module not found` | Container Runtime | Use `from snowflake.snowpark.context import get_active_session` instead |## Deployment Commands@@ -226,12 +277,30 @@ See: [Snowpark Python Packages Explorer](https://snowpark-python-packages.stream## Known Limitations-1. **No custom Streamlit components** - Only built-in components work-2. **Package restrictions** - Only Snowflake Anaconda Channel-3. **No Azure Private Link / GCP Private Service Connect** for app access-4. **page_title and page_icon** not supported in `st.set_page_config()`-5. **File size limit** - 250MB per file-6. **Session timeout** - Apps may timeout after inactivity+### Data & Size Limits+- **32 MB message size** between backend/frontend (affects large `st.dataframe`)+- **200 MB file upload limit** via `st.file_uploader`+- **No `.so` files** - Native compiled libraries unsupported+- **No external stages** - Internal stages only (client-side encryption)++### UI Restrictions+- **`st.set_page_config`** - `page_title`, `page_icon`, `menu_items` not supported+- **`st.bokeh_chart`** - Not supported+- **Custom Streamlit components** - Only components without external service calls+- **Content Security Policy** - Blocks external scripts, styles, fonts, iframes+- **`eval()` blocked** - CSP prevents unsafe JavaScript execution++### Caching (Warehouse Runtime)+- **Session-scoped only** - `st.cache_data` and `st.cache_resource` don't persist across users+- Container runtime has full caching support across viewers++### Package Restrictions (Warehouse Runtime)+- **Snowflake Anaconda Channel only** - No conda-forge, no pip+- Container runtime allows PyPI packages++### Network & Access+- **No Azure Private Link / GCP Private Service Connect**+- **No replication** of Streamlit objects## Authentication (Important - 2026 Deadline)diff --git a/skills/streamlit-snowflake/templates-container-runtime/README.md b/skills/streamlit-snowflake/templates-container-runtime/README.mdnew file mode 100644index 00000000..74d9e5d7--- /dev/null+++ b/skills/streamlit-snowflake/templates-container-runtime/README.md@@ -0,0 +1,114 @@+# Container Runtime Templates++Templates for deploying Streamlit apps using **Container Runtime** (Preview) instead of Warehouse Runtime.++## Key Differences from Warehouse Runtime++| Aspect | Warehouse Runtime | Container Runtime |+|--------|-------------------|-------------------|+| Instance | Per-viewer | Shared across viewers |+| Packages | Snowflake Anaconda only | PyPI packages allowed |+| Config file | `environment.yml` | `requirements.txt` or `pyproject.toml` |+| Python | 3.9, 3.10, 3.11 | 3.11 only |+| Streamlit | 1.22 - 1.35 | 1.49+ |+| Cost | ~$48/day (XS warehouse) | ~$2.88/day (XS compute pool) |+| Caching | Session-scoped only | Full cross-viewer caching |++## When to Use Container Runtime++**Use Container Runtime when:**+- App has frequent usage across multiple viewers+- You need PyPI packages not in Snowflake Anaconda Channel+- Cost optimization is important+- You want cross-viewer caching++**Stick with Warehouse Runtime when:**+- You need Python 3.9 or 3.10+- You need isolated sessions per viewer+- Your app is rarely used (warehouse auto-suspend saves costs)+- You need the stability of the Snowflake Anaconda Channel++## Setup++### 1. Create Compute Pool++```sql+-- Create compute pool for Streamlit apps+CREATE COMPUTE POOL streamlit_pool+ MIN_NODES = 1+ MAX_NODES = 3+ INSTANCE_FAMILY = CPU_X64_XS;++-- Check pool status+DESCRIBE COMPUTE POOL streamlit_pool;+```++### 2. Create External Access Integration (Optional)++Required if you need to install packages from PyPI:++```sql+-- Create network rule for PyPI+CREATE OR REPLACE NETWORK RULE pypi_network_rule+ TYPE = HOST_PORT+ VALUE_LIST = ('pypi.org', 'files.pythonhosted.org')+ MODE = EGRESS;++-- Create external access integration+CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION pypi_access+ ALLOWED_NETWORK_RULES = (pypi_network_rule)+ ENABLED = TRUE;+```++### 3. Deploy with Container Runtime++```sql+CREATE OR REPLACE STREAMLIT my_app+ FROM '@my_stage/app_folder'+ MAIN_FILE = 'streamlit_app.py'+ RUNTIME_NAME = 'SYSTEM$ST_CONTAINER_RUNTIME_PY3_11'+ COMPUTE_POOL = streamlit_pool+ QUERY_WAREHOUSE = my_warehouse+ EXTERNAL_ACCESS_INTEGRATIONS = (pypi_access);+```++## Session Handling Difference++Container Runtime does NOT have the `_snowflake` module. Update your session code:++**Warehouse Runtime:**+```python+from _snowflake import get_active_session+session = get_active_session()+```++**Container Runtime:**+```python+from snowflake.snowpark.context import get_active_session+session = get_active_session()++# OR use Streamlit's connection (works in both):+import streamlit as st+conn = st.connection("snowflake")+session = conn.session()+```++## Cost Comparison++| Compute Type | Credits/Hour | USD/Day (at $2/credit) |+|--------------|--------------|------------------------|+| XS Warehouse | 1.0 | ~$48 (24 hours) |+| CPU_X64_XS Pool | 0.06 | ~$2.88 (24 hours) |++Container Runtime is **~94% cheaper** for always-on apps.++## Files in This Directory++- `requirements.txt` - Package dependencies for PyPI+- `pyproject.toml` - Alternative to requirements.txt (optional)+- `streamlit_app.py` - Entry point compatible with Container Runtime++## References++- [Runtime Environments](https://docs.snowflake.com/en/developer-guide/streamlit/app-development/runtime-environments)+- [Container Runtime Preview](https://dev.to/tsubasa_tech/sis-container-runtime-run-streamlit-apps-at-a-fraction-of-the-cost-2mn8)diff --git a/skills/streamlit-snowflake/templates-container-runtime/requirements.txt b/skills/streamlit-snowflake/templates-container-runtime/requirements.txtnew file mode 100644index 00000000..eccd0a56--- /dev/null+++ b/skills/streamlit-snowflake/templates-container-runtime/requirements.txt@@ -0,0 +1,31 @@+# Container Runtime Requirements+# These packages are installed from PyPI (not Snowflake Anaconda Channel)+# Requires EXTERNAL_ACCESS_INTEGRATION with pypi.org access++# Streamlit (Container Runtime supports 1.49+)+streamlit>=1.49.0++# Snowflake connectivity+snowflake-snowpark-python>=1.20.0+snowflake-connector-python>=3.10.0++# Data processing+pandas>=2.0.0+numpy>=1.24.0++# Visualization+plotly>=5.18.0+altair>=5.0.0+# matplotlib>=3.8.0 # Uncomment if needed++# Optional: ML packages (uncomment as needed)+# scikit-learn>=1.4.0+# xgboost>=2.0.0++# Optional: Additional utilities+# pillow>=10.0.0+# scipy>=1.12.0+# httpx>=0.27.0++# Note: With Container Runtime, you can use ANY PyPI package+# as long as your External Access Integration allows it.diff --git a/skills/streamlit-snowflake/templates/.gitignore b/skills/streamlit-snowflake/templates/.gitignoreindex 64ac53c6..7211283b 100644--- a/skills/streamlit-snowflake/templates/.gitignore+++ b/skills/streamlit-snowflake/templates/.gitignore@@ -20,6 +20,15 @@ env/.env.local.env.*.local+# RSA Keys (from key-pair authentication setup)+*.p8+*.pub+rsa_key*++# Local snowflake.yml overrides (may contain credentials)+snowflake.yml.local+snowflake.local.yml+# IDE.idea/.vscode/@@ -31,8 +40,9 @@ env/.DS_StoreThumbs.db-# Streamlit-.streamlit/secrets.toml+# Streamlit local config+.streamlit/+secrets.toml# Logs*.log@@ -46,3 +56,7 @@ htmlcov/# Build artifactsdist/build/++# Container Runtime specific+pyproject.toml.local+requirements.local.txtdiff --git a/skills/streamlit-snowflake/templates/pages/data_explorer.py b/skills/streamlit-snowflake/templates/pages/data_explorer.pyindex 8e52c09b..bb4c2de4 100644--- a/skills/streamlit-snowflake/templates/pages/data_explorer.py+++ b/skills/streamlit-snowflake/templates/pages/data_explorer.py@@ -6,11 +6,16 @@ This page demonstrates:- Table/schema browsing- Interactive data filtering- Visualization with Plotly+- Safe identifier handling"""+import reimport streamlit as stimport pandas as pd+# Import shared utilities+from common.utils import get_snowpark_session+# Try to import plotly (optional dependency)try:import plotly.express as px@@ -23,23 +28,54 @@ st.title("Data Explorer")# ------------------------------------------------------------------------------# Connection (reuse pattern from main app)+# Identifier Validation (Security)# -----------------------------------------------------------------------------[email protected]_resource-def get_session():- conn = st.connection("snowflake")- return conn.session()+def validate_identifier(name: str) -> bool:+ """+ Validate Snowflake identifier to prevent SQL injection.++ Valid identifiers:+ - Start with letter or underscore+ - Contain only letters, numbers, underscores+ - Max 255 characters+ """+ if not name or len(name) > 255:+ return False+ # Snowflake unquoted identifier pattern+ pattern = r'^[A-Za-z_][A-Za-z0-9_$]*$'+ return bool(re.match(pattern, name))+++def quote_identifier(name: str) -> str:+ """+ Quote identifier for safe use in SQL.+ Escapes any double quotes within the identifier.+ """+ if not validate_identifier(name):+ # For complex identifiers, quote them+ escaped = name.replace('"', '""')+ return f'"{escaped}"'+ return name++# -----------------------------------------------------------------------------+# Data Functions+# -----------------------------------------------------------------------------@st.cache_data(ttl=600)def get_tables(database: str, schema: str) -> pd.DataFrame:- """Get list of tables in a schema."""- session = get_session()+ """Get list of tables in a schema with safe identifier handling."""+ if not validate_identifier(database) or not validate_identifier(schema):+ st.error("Invalid database or schema name. Use alphanumeric characters and underscores only.")+ return pd.DataFrame()++ session = get_snowpark_session()+ # Use quoted identifiers for safetyquery = f"""SELECT table_name, row_count, bytes- FROM {database}.information_schema.tables- WHERE table_schema = '{schema}'+ FROM {quote_identifier(database)}.information_schema.tables+ WHERE table_schema = '{schema.upper()}'AND table_type = 'BASE TABLE'ORDER BY table_name"""@@ -52,9 +88,19 @@ def get_tables(database: str, schema: str) -> pd.DataFrame:@st.cache_data(ttl=300)def preview_table(database: str, schema: str, table: str, limit: int = 100) -> pd.DataFrame:- """Preview rows from a table."""- session = get_session()- query = f'SELECT * FROM {database}.{schema}.{table} LIMIT {limit}'+ """Preview rows from a table with safe identifier handling."""+ # Validate all identifiers+ for name, label in [(database, "Database"), (schema, "Schema"), (table, "Table")]:+ if not validate_identifier(name):+ st.error(f"Invalid {label} name: {name}")+ return pd.DataFrame()++ # Validate limit is reasonable+ limit = max(1, min(limit, 10000))++ session = get_snowpark_session()+ # Use quoted identifiers+ query = f'SELECT * FROM {quote_identifier(database)}.{quote_identifier(schema)}.{quote_identifier(table)} LIMIT {limit}'try:return session.sql(query).to_pandas()except Exception as e:@@ -73,6 +119,12 @@ with st.sidebar:database = st.text_input("Database", value="MY_DATABASE")schema = st.text_input("Schema", value="PUBLIC")+ # Validate inputs+ if database and not validate_identifier(database):+ st.warning("Database name contains invalid characters")+ if schema and not validate_identifier(schema):+ st.warning("Schema name contains invalid characters")+# Row limitrow_limit = st.slider("Preview Rows", 10, 500, 100)@@ -93,7 +145,7 @@ if tables_df.empty:st.warning("No tables found or unable to access schema.")st.stop()-# Table selector+# Table selector - these come from query results, so they're safetable_names = tables_df["TABLE_NAME"].tolist()selected_table = st.selectbox("Select Table", table_names)@@ -104,7 +156,11 @@ if selected_table:table_info = tables_df[tables_df["TABLE_NAME"] == selected_table].iloc[0]col1, col2 = st.columns(2)with col1:- st.metric("Row Count", f"{table_info.get('ROW_COUNT', 'N/A'):,}")+ row_count = table_info.get('ROW_COUNT')+ if row_count is not None:+ st.metric("Row Count", f"{int(row_count):,}")+ else:+ st.metric("Row Count", "N/A")with col2:bytes_val = table_info.get("BYTES", 0) or 0st.metric("Size", f"{bytes_val / 1024 / 1024:.2f} MB")diff --git a/skills/streamlit-snowflake/templates/streamlit_app.py b/skills/streamlit-snowflake/templates/streamlit_app.pyindex aece3213..3c7da12e 100644--- a/skills/streamlit-snowflake/templates/streamlit_app.py+++ b/skills/streamlit-snowflake/templates/streamlit_app.py@@ -13,8 +13,12 @@ Deploy: snow streamlit deploy --replaceimport streamlit as stimport pandas as pd+# Import shared utilities (session management, query helpers)+from common.utils import get_snowpark_session, run_query_safe, show_connection_info+# Page configuration-# Note: page_title and page_icon are NOT supported in Streamlit in Snowflake+# Note: page_title, page_icon, and menu_items are NOT supported in Streamlit in Snowflake+# Only use layout and initial_sidebar_statest.set_page_config(layout="wide",initial_sidebar_state="expanded",@@ -25,20 +29,6 @@ st.title("My Streamlit App")st.markdown("Built with Streamlit in Snowflake")-# ------------------------------------------------------------------------------# Database Connection-# ------------------------------------------------------------------------------[email protected]_resource-def get_snowpark_session():- """- Get Snowpark session using native Streamlit connection.- Cached to avoid reconnection on every rerun.- """- conn = st.connection("snowflake")- return conn.session()--# -----------------------------------------------------------------------------# Data Loading (Cached)# -----------------------------------------------------------------------------