Implement cohort analysis with retention curves, churn probability scoring, and customer lifetime value prediction
harbor run -t snowflake-labs/dbt-customer-churn-cohortsharbor download snowflake-labs/dbt-customer-churn-cohortsBuild a dbt project that performs cohort analysis, calculates customer retention curves, and computes customer lifetime value (CLV) metrics with churn probability scoring.
/app/database/retail.duckdb/app/dbt_models_duckdb/app/dbt_models_snowflakeThis task supports both DuckDB and Snowflake. Run echo $DB_TYPE in a shell BEFORE you write any code or spawn any subagents — the live env determines which backend the verifier runs against. Do NOT assume a default from this prose. Both /app/dbt_models_duckdb/ and /app/dbt_models_snowflake/ exist on disk; the verifier only checks the project matching the live $DB_TYPE.
DB_TYPE=duckdb$DUCKDB_PATH (default: /app/database/retail.duckdb)DB_TYPE=snowflakeSNOWFLAKE_ACCOUNTSNOWFLAKE_USERSNOWFLAKE_PASSWORDSNOWFLAKE_DATABASE - The clone database to useSNOWFLAKE_SCHEMASNOWFLAKE_WAREHOUSESNOWFLAKE_ROLE (optional)Note: For Snowflake, the entrypoint automatically creates a clone database and sets SNOWFLAKE_DATABASE. The clone is destroyed when the task completes.
You must configure dbt to connect to the database:
profiles.yml in the dbt project directory with profile name retail_dw_masterDBT_PROFILES_DIR environment variable to the directory containing profiles.ymlConfigure with type: duckdb and the database path from $DUCKDB_PATH.
Configure with type: snowflake using password authentication:
schema: to $SNOWFLAKE_SCHEMA — do NOT leave it blank. A blank or omitted schema makes Snowflake silently default to PUBLIC, so your models get built in the wrong schema and the verifier cannot find them.You can expect these input schemas to be available in the database:
ANALYTICS.FACT_SALES: Sales transactions
SALE_KEY, DATE_KEY, CUSTOMER_KEY, TOTAL_AMOUNT, ORDER_ID, ORDER_LINE_IDANALYTICS.DIM_CUSTOMER: Customer dimension for linking keys
CUSTOMER_KEY, CUSTOMER_ID, SEGMENT_NAME, CITY, STATE, COUNTRYANALYTICS.DIM_DATE: Date dimension
DATE_KEY, FULL_DATE, YEAR, MONTH_NUMBER, DAY_OF_MONTHCUSTOMER.CUSTOMERS: Detailed customer demographics
CUSTOMER_ID, ACQUISITION_DATE, CUSTOMER_SEGMENT_SNAPSHOT, LEGACY_REGION_CODEA dbt project already exists with the following configurations:
/app/dbt_models_duckdb/app/dbt_models_snowflakeAll the required staging models are already implemented and available for use.
Staging (models/staging/):
stg_analytics__fact_sales.sqlstg_analytics__dim_customer.sqlstg_analytics__dim_date.sqlstg_customer__customers.sqlIntermediate (models/intermediate/):
int_analytics__fact_sales.sqlint_customer__customers.sqlMarts (models/marts/):
customer_cohorts.sqlcohort_retention.sqlcustomer_clv.sqlcustomer_cohorts must contain:
customer_id - unique customer identifiercohort_month - month of first transaction (YYYY-MM format string)first_transaction_date - date of first transactionfirst_transaction_amount - amount of first transactionsignup_to_first_purchase_days - days between signup and first purchase (integer, 0 if same day)acquisition_channel - derived from region: 'NORTH'->'Online', 'SOUTH'->'Retail', 'EAST'->'Partner', 'WEST'->'Direct', NULL or unrecognized->'Unknown'cohort_retention must contain:
cohort_month - the cohort (YYYY-MM format string)period_number - months since cohort month (integer, starting at 0)period_month - the actual month of activity (YYYY-MM format string)cohort_size - number of customers in the cohort (at period 0)active_customers - customers with transactions in this periodretained_customers - customers active in this period who were also active in the previous periodretention_rate - active_customers / cohort_size, rounded to 4 decimalsperiod_revenue - total revenue in this period from cohort customerscumulative_revenue - running total of revenue for this cohort through this periodcustomer_clv must contain:
customer_id - unique customer identifiercohort_month - customer's cohorttotal_transactions - count of all transactionstotal_revenue - sum of all transaction amountsavg_transaction_value - average transaction amount, rounded to 2 decimalscustomer_lifespan_months - the inclusive count of months from first to last transaction (months difference + 1). Minimum 1.monthly_revenue_rate - total_revenue / customer_lifespan_months, rounded to 2 decimalsmonths_since_last_transaction - months from last transaction to reference date (2024-12-31)churn_probability - calculated churn score (see Business Rules), rounded to 2 decimalspredicted_clv_12m - 12-month predicted CLV (see Business Rules), rounded to 2 decimalscustomer_tier - based on predicted_clv_12m:
To estimate churn probability for each customer, consider three main factors:
Recency: The number of months since the customer's last transaction. The longer it has been, the higher the base risk of churn. Divide this number by 12 to get a base score.
Frequency: Adjust the risk based on how many transactions the customer has made in total.
Recency Adjustment: Further adjust the risk based on how recent the last transaction was (months_since_last_transaction).
6 months: Multiplier 1.2
Combine these factors by multiplying the base score by the frequency and recency multipliers. If the result is greater than 1.0, cap the churn probability at 1.0. Round the final value to two decimal places.
The 12-month predicted CLV estimates the revenue a customer will generate over the next 12 months, accounting for their churn risk.
Calculate predicted_clv_12m using this formula:
predicted_clv_12m = monthly_revenue_rate x 12 x (1 - churn_probability)
Where:
monthly_revenue_rate is the customer's total revenue divided by their lifespan in monthschurn_probability is calculated as described in Business Rule #3This formula projects the customer's monthly revenue rate over 12 months, then discounts it by their probability of remaining active (1 - churn_probability).
Your solution will be validated against expected outputs calculated from the source data. The validation process samples records from each output table and verifies that your calculations match the expected results within acceptable tolerances.
Passing Criteria: At least 80% of sampled records must validate successfully for each output table (customer_cohorts, cohort_retention, customer_clv). This allows for minor edge case variations while ensuring the core logic is correct.
Your dbt models must be idempotent, meaning that running the pipeline multiple times with the same source data must produce identical results. This is a critical requirement for production data pipelines. Ensure your models use deterministic logic and avoid non-deterministic functions (like random number generators or current timestamps where not appropriate).
{% if target.type == 'snowflake' %} for DuckDB-specific functions (strftime vs TO_CHAR, date subtraction vs DATEDIFF, etc.)