Tip: This skill works well with Sonnet. Run /model sonnet before invoking for faster generation.
Generate a SQL Notebook with validation queries for dbt changes.
Arguments: $ARGUMENTS
When to Use
Use this skill when the user wants to validate dbt model or snapshot changes with Monte Carlo SQL Notebook queries, either from a GitHub PR or a local dbt repository.
Parse the arguments:
Target (required): first argument — a GitHub PR URL or local dbt repo path
MC Base URL (optional): --mc-base-url <URL> — defaults to https://getmontecarlo.com
Models (optional): --models <model1,model2,...> — comma-separated list of model filenames (without .sql extension) to generate queries for. Only these models will be included. By default, all changed models are included up to a maximum of 10.
Setup
Prerequisites:
gh (GitHub CLI) — required for PR mode. Must be authenticated (gh auth status).
Note: Generated SQL uses ANSI-compatible syntax that works across Snowflake, BigQuery, Redshift, and Athena. Minor adjustments may be needed for specific warehouse quirks.
This skill includes two helper scripts in ${CLAUDE_PLUGIN_ROOT}/skills/monte-carlo-validation-notebook/scripts/:
resolve_dbt_schema.py - Resolves dbt model output schemas from dbt_project.yml routing rules and model config overrides.
generate_notebook_url.py - Encodes notebook YAML into a base64 import URL and opens it in the browser.
Mode Detection
Auto-detect mode from the target argument:
If target looks like a URL (contains :// or github.com) -> PR mode
If target is a path (, , relative path) ->
.
/path/to/repo
Local mode
Context
This command generates a SQL Notebook containing validation queries for dbt changes. The notebook can be opened in the MC Bridge SQL Notebook interface for interactive validation.
The output is an import URL that opens directly in the notebook interface:
Database Parameters: Two text parameters (prod_db and dev_db) for selecting databases
Schema Inference: Automatically infers schema per model from dbt_project.yml and model configs
Single-table queries: Basic validation queries using {{prod_db}}.<SCHEMA>.<TABLE>
Comparison queries: Before/after queries comparing {{prod_db}} vs {{dev_db}}
Flexible usage: Users can set both parameters to the same database for single-database analysis
Notebook YAML Spec Reference
Key structure:
version:1metadata:id:string# kebab-case + random suffixname:string# display namecreated_at:string# ISO 8601updated_at:string# ISO 8601default_context:# optional database/schema contextdatabase:stringschema:stringcells:-id:stringtype:sql|markdown|parametercontent:string# SQL, markdown, or parameter config (JSON)display_type:table|bar|timeseries
Parameter Cell Spec
Parameter cells allow defining variables referenced in SQL via {{param_name}} syntax:
-id:param-prod-dbtype:parametercontent:name:prod_db# variable nameconfig:type:text# free-form text inputdefault_value:"ANALYTICS"placeholder:"Prod database"display_type:table
Parameter types:
text: Free-form text input (used for database names)
schema_selector: Two dropdowns (database -> schema), value stored as DATABASE.SCHEMA
dropdown: Select from predefined options
Task
Generate a SQL Notebook with validation queries based on the mode and target.
Phase 1: Get Changed Files
The approach differs based on mode:
If PR mode (GitHub PR):
Extract the PR number and repo from the target URL.
Filter the changed files list to only .sql files under models/ or snapshots/ directories (at any depth — e.g., models/, analytics/models/, dbt/models/). These are the dbt models to analyze. If no model SQL files were changed, report that and stop.
For each changed model file, fetch the full file content at the head SHA:
Fetch dbt_project.yml for schema resolution. Detect the dbt project root by looking at the changed file paths — find the common parent directory that contains dbt_project.yml. Try these paths in order until one succeeds:
Filter to only .sql files under models/ or snapshots/ directories (at any depth — e.g., models/, analytics/models/, dbt/models/). If no model SQL files were changed, report that and stop.
Get the diff for each changed file:
git diff <base_branch>...HEAD -- <file_path>
Read model files directly from the filesystem.
Find dbt_project.yml:
find . -name "dbt_project.yml" -type f | head -1
For notebook metadata in local mode, use:
ID: local-<branch-name>-<timestamp>
Title: Local: <branch-name>
Author: Output of git config user.name
Merged: "N/A (local)"
Model Selection (applies to both modes)
After filtering to .sql files under models/ or snapshots/:
If --models was specified: Filter the changed files list to only include models whose filename (without .sql extension, case-insensitive) matches one of the specified model names. If any specified model is not found in the changed files, warn the user but continue with the models that were found. If none match, report that and stop.
Model cap: If more than 10 models remain after filtering, select the first 10 (by file path order) and warn the user:
⚠️ <total_count> models changed — generating validation queries for the first 10 only.
To generate for specific models, re-run with: --models <model1,model2,...>
Skipped models: <list of skipped model filenames>
Phase 2: Parse Changed Models
For EACH changed dbt model .sql file, parse and extract:
2a. Model Metadata
Output table name -- Derive from file name:
<any_path>/models/<subdir>/<model_name>.sql -> table is <MODEL_NAME> (uppercase, taken from the filename)
Output schema -- Use the schema resolution script:
Setup: Save dbt_project.yml and model files to /tmp/validation_notebook_working/<id>/ preserving paths:
Error handling: If the script fails, STOP immediately and report the error. Do NOT proceed with notebook generation if schema resolution fails.
Output: The script prints the resolved schema (e.g., PROD, PROD_STAGE, PROD_LINEAGE)
Note: Do NOT manually parse dbt_project.yml or model configs for schema -- always use the script. It handles model config overrides, dbt_project.yml routing rules, PROD_ prefix for custom schemas, and defaults to PROD.
Config block -- Look for {{ config(...) }} and extract:
SELECT<segmentation_field>,
COUNT(*) AS row_count
FROM {{dev_db}}.<SCHEMA>.<TABLE_NAME>GROUPBY<segmentation_field>ORDERBY row_count DESC
LIMIT 100
Pattern 5: Uniqueness Check
Trigger: Always for new models (verify unique_key constraint from the start).
SELECTCOUNT(*) AS total_rows,
COUNT(DISTINCT<key_fields>) AS distinct_keys,
COUNT(*) -COUNT(DISTINCT<key_fields>) AS duplicate_count
FROM {{dev_db}}.<SCHEMA>.<TABLE_NAME>
SELECT<key_fields>, COUNT(*) AS n
FROM {{dev_db}}.<SCHEMA>.<TABLE_NAME>GROUPBY<key_fields>HAVINGCOUNT(*) >1ORDERBY n DESC
LIMIT 100
Pattern 6-new: NULL Rate Check (all columns)
Trigger: Always. Checks all output columns since everything is new.
SELECTCOUNT(*) AS total_rows,
SUM(CASEWHEN<col1>ISNULLTHEN1ELSE0END) AS<col1>_null_count,
ROUND(100.0*SUM(CASEWHEN<col1>ISNULLTHEN1ELSE0END) /NULLIF(COUNT(*), 0), 2) AS<col1>_null_pct,
SUM(CASEWHEN<col2>ISNULLTHEN1ELSE0END) AS<col2>_null_count,
ROUND(100.0*SUM(CASEWHEN<col2>ISNULLTHEN1ELSE0END) /NULLIF(COUNT(*), 0), 2) AS<col2>_null_pct
-- repeat for each output columnFROM {{dev_db}}.<SCHEMA>.<TABLE_NAME>
Pattern 8: Time-Axis Continuity
Trigger: Model is materialized='incremental' OR a time axis field was identified.
SELECTCAST(<time_axis>ASDATE) ASday,
COUNT(*) AS row_count
FROM {{dev_db}}.<SCHEMA>.<TABLE_NAME>WHERE<time_axis>>=CURRENT_TIMESTAMP-INTERVAL'14'DAYGROUPBYdayORDERBYdayDESC
LIMIT 30
Query Patterns for MODIFIED Models
For modified models, single-table queries use {{prod_db}} and comparison queries use both.
Pattern 7: Total Row Count
Trigger: Always.
SELECTCOUNT(*) AS total_rows
FROM {{prod_db}}.<SCHEMA>.<TABLE_NAME>
SELECT<segmentation_field>,
COUNT(*) AS row_count
FROM {{prod_db}}.<SCHEMA>.<TABLE_NAME>GROUPBY<segmentation_field>ORDERBY row_count DESC
LIMIT 100
Pattern 1: Changed Field Distribution
Trigger: Changed fields found in Phase 2b. Exclude added columns (from "New columns" in Phase 2b) — only include fields that exist in prod.
SELECT<changed_field>,
COUNT(*) AS row_count,
ROUND(COUNT(*) *100.0/SUM(COUNT(*)) OVER(), 2) AS pct
FROM {{prod_db}}.<SCHEMA>.<TABLE_NAME>GROUPBY<changed_field>ORDERBY row_count DESC
LIMIT 100
Pattern 5: Uniqueness Check
Trigger: JOIN condition changed, unique_key changed, or model is incremental.
SELECTCOUNT(*) AS total_rows,
COUNT(DISTINCT<key_fields>) AS distinct_keys,
COUNT(*) -COUNT(DISTINCT<key_fields>) AS duplicate_count
FROM {{dev_db}}.<SCHEMA>.<TABLE_NAME>
SELECT<key_fields>, COUNT(*) AS n
FROM {{dev_db}}.<SCHEMA>.<TABLE_NAME>GROUPBY<key_fields>HAVINGCOUNT(*) >1ORDERBY n DESC
LIMIT 100
Pattern 6: NULL Rate Check
Trigger: New column added, or column wrapped in COALESCE/NULLIF.
Important: Added columns (from "New columns" in Phase 2b) do NOT exist in prod yet. For added columns, query {{dev_db}} only. For modified columns (COALESCE/NULLIF changes), compare both databases.
For added columns (dev only):
SELECTCOUNT(*) AS total_rows,
SUM(CASEWHEN<column>ISNULLTHEN1ELSE0END) AS null_count,
ROUND(100.0*SUM(CASEWHEN<column>ISNULLTHEN1ELSE0END) /NULLIF(COUNT(*), 0), 2) AS null_pct
FROM {{dev_db}}.<SCHEMA>.<TABLE_NAME>
For modified columns (prod vs dev):
SELECT'prod'AS source,
COUNT(*) AS total_rows,
SUM(CASEWHEN<column>ISNULLTHEN1ELSE0END) AS null_count,
ROUND(100.0*SUM(CASEWHEN<column>ISNULLTHEN1ELSE0END) /NULLIF(COUNT(*), 0), 2) AS null_pct
FROM {{prod_db}}.<SCHEMA>.<TABLE_NAME>UNIONALLSELECT'dev'AS source,
COUNT(*) AS total_rows,
SUM(CASEWHEN<column>ISNULLTHEN1ELSE0END) AS null_count,
ROUND(100.0*SUM(CASEWHEN<column>ISNULLTHEN1ELSE0END) /NULLIF(COUNT(*), 0), 2) AS null_pct
FROM {{dev_db}}.<SCHEMA>.<TABLE_NAME>
Pattern 8: Time-Axis Continuity
Trigger: Model is materialized='incremental' OR a time axis field was identified.
SELECTCAST(<time_axis>ASDATE) ASday,
COUNT(*) AS row_count
FROM {{prod_db}}.<SCHEMA>.<TABLE_NAME>WHERE<time_axis>>=CURRENT_TIMESTAMP-INTERVAL'14'DAYGROUPBYdayORDERBYdayDESC
LIMIT 30
Important: Exclude added columns (from "New columns" in Phase 2b) from <group_fields>. Only use fields that exist in BOTH prod and dev. Added columns don't exist in prod and will cause query errors.
WITH prod AS (
SELECT<group_fields>, COUNT(*) AS cnt
FROM {{prod_db}}.<SCHEMA>.<TABLE_NAME>GROUPBY<group_fields>
),
dev AS (
SELECT<group_fields>, COUNT(*) AS cnt
FROM {{dev_db}}.<SCHEMA>.<TABLE_NAME>GROUPBY<group_fields>
)
SELECTCOALESCE(b.<field>, d.<field>) AS<field>,
COALESCE(b.cnt, 0) AS cnt_prod,
COALESCE(d.cnt, 0) AS cnt_dev,
COALESCE(d.cnt, 0) -COALESCE(b.cnt, 0) AS diff
FROM prod b
FULLOUTERJOIN dev d ON b.<field>= d.<field>ORDERBYABS(diff) DESC
LIMIT 100
Pattern 7b: Row Count Comparison
Trigger: Always. Modified models only.
SELECT'prod'AS source, COUNT(*) AS row_count FROM {{prod_db}}.<SCHEMA>.<TABLE_NAME>UNIONALLSELECT'dev'AS source, COUNT(*) AS row_count FROM {{dev_db}}.<SCHEMA>.<TABLE_NAME>
Only include prod_db if there are modified models. If all models are new, only include dev_db.
# Include ONLY if there are modified models:-id:param-prod-dbtype:parametercontent:name:prod_dbconfig:type:textdefault_value:"ANALYTICS"placeholder:"Prod database (e.g., ANALYTICS)"display_type:table# Always include:-id:param-dev-dbtype:parametercontent:name:dev_dbconfig:type:textdefault_value:"PERSONAL_<USER>"placeholder:"Dev database (e.g., PERSONAL_JSMITH)"display_type:table
4c. Markdown Summary Cell
-id:cell-summarytype:markdowncontent:|
# Validation Queries for <PR or Local Branch>
## Summary
- **Title:** <title>
- **Author:** <author>
- **Source:** <PR URL or "Local branch: <branch>">
- **Status:** <merge_timestamp or "Not yet merged" or "N/A (local)">
## Changes
<brief description based on diff analysis>
## Changed Models
- `<SCHEMA>.<TABLE_NAME>` (from `<file_path>`)
## How to Use
1. Select your Snowflake connector above
2. Set **dev_db** to your dev database (e.g., `PERSONAL_JSMITH`)
3. If modified models are present, set **prod_db** to your prod database (e.g., `ANALYTICS`)
4. Run single-table queries first, then comparison queries
display_type:table
4d. SQL Cell Format
-id:cell-<pattern>-<model>-<index>type:sqlcontent:|
/*
========================================
<Pattern Name (human-readable, e.g. "Total Row Count" — do NOT include pattern numbers like "Pattern 7:")>
========================================
Model: <SCHEMA>.<TABLE_NAME>
Triggered by: <why this pattern was generated>
What to look for: <interpretation guidance>
----------------------------------------
*/
<actual_sql_query>
display_type:table
4e. Cell Organization
Cells are ordered consistently for both model types, following this sequence:
New models:
Summary markdown cell (note that model is new)
Parameter cells (dev_db only — no prod_db if all models are new)
The script validates both YAML syntax and notebook schema (required fields on metadata and cells). If validation fails, read the error messages carefully, fix the YAML to match the spec in Phase 4, and re-run.
Phase 6: Output
Present:
# Validation Notebook Generated## Summary-**Source:** PR #<number> - <title> OR Local: <branch>-**Author:**<author>-**Changed Models:**<count> models (of <total_count> changed)
-**Generated Queries:**<count> queries
> ⚠️ If models were capped: "Only the first 10 of <total_count> changed models were included. Re-run with `--models` to select specific models."## Notebook Opened
The notebook has been opened directly in your browser.
Select your Snowflake connector in the notebook interface to begin running queries.
*Make sure MC Bridge is running. Let me know if you want tips on how to install this locally*
Important Guidelines
Do NOT execute queries -- only generate the notebook
Keep SQL readable -- proper formatting and meaningful aliases
Include LIMIT 100 on queries that could return many rows
Use double curly braces -- {{prod_db}} NOT ${prod_db}
Use correct table format -- {{prod_db}}.<SCHEMA>.<TABLE> and {{dev_db}}.<SCHEMA>.<TABLE>
Always use the schema resolution script -- do NOT manually parse dbt_project.yml
Schema is NOT a parameter -- only prod_db and dev_db are parameters
Skip ephemeral models -- they have no physical table
Truncate notebook name -- keep under 50 chars
Generate unique cell IDs -- use pattern like cell-p3-model-1
YAML multiline content -- use | block scalar for SQL with comments
ASCII-only YAML -- the script sanitizes and validates before encoding
Query Pattern Reference
Pattern
Name
Trigger
Model Type
Database
Order
7 / 7-new
Total Row Count
Always
Both
{{prod_db}} (modified) / {{dev_db}} (new)
1
9
Sample Data Preview
Always
Both
{{prod_db}} (modified) / {{dev_db}} (new)
2
2 / 2-new
Core Segmentation Counts
Always
Both
{{prod_db}} (modified) / {{dev_db}} (new)
3
1
Changed Field Distribution
Column modified in diff (not added)
Modified only
{{prod_db}}
4
5
Uniqueness Check
JOIN/unique_key changed (modified) / Always (new)
Both
{{dev_db}}
5
6 / 6-new
NULL Rate Check
New column or COALESCE (modified) / Always (new)
Both
Added col: {{dev_db}} only; COALESCE: Both (modified) / {{dev_db}} (new)
5
8
Time-Axis Continuity
Incremental or time field
Both
{{prod_db}} (modified) / {{dev_db}} (new)
5
3
Before/After Comparison
Changed fields (not added)
Modified only
Both
6
7b
Row Count Comparison
Always
Modified only
Both
6
MC Bridge Setup Help
If the user asks how to install or set up MC Bridge, fetch the README from the mc-bridge repo and show the relevant quick start / setup instructions:
gh api repos/monte-carlo-data/mc-bridge/readme --jq '.content' | base64 --decode
Focus on: how to install, configure connections, and run MC Bridge. Don't dump the entire README — extract just the setup-relevant sections.
Limitations
Use this skill only when the task clearly matches the scope described above.
Do not treat the output as a substitute for enprojectnment-specific validation, testing, or expert review.
Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.