Skip to content

td-analytics-workflow

The reference architecture for an analytics project on Vantage: rules and features in tdfs4ds, ML in tdstone2, everything stored in the feature store, with a consumer agent on top.


name: "td-analytics-workflow" description: "Use when the user wants to design or implement an end-to-end analytics workflow on Teradata Vantage — anomaly detection, risk scoring, churn prediction, fraud detection, demand forecasting, or any similar pipeline. This skill establishes the canonical architecture: tdfs4ds for feature engineering and governance, tdstone2 for in-database ML, with everything persisted in the feature store and no data movement outside Teradata." argument-hint: "[use-case][entity] [target-variable]" allowed-tools: "Read, Edit, Write, Bash, Glob, Grep"


Teradata Vantage — End-to-End Analytics Workflow

The canonical pattern for any Teradata analytics project is a staged progression that keeps all computation and data inside Vantage. Each stage delivers standalone value and feeds the next. Use tdfs4ds for feature engineering and governance; tdstone2 for in-database ML.


The Three-Tier Architecture

Tier Question answered Primary tools Key artifact
1.0 — Descriptive What happened? SQL + tdfs4ds Feature views + rule scores
2.0 — Predictive What is likely? tdstone2 → tdfs4ds ML risk scores as features
3.0 — Agentic What should we do? tdfs4ds consumer agent + Gradio Investigation queue + NL interface

Each tier is independently valuable. Start at 1.0; bolt on 2.0 when labelled data or patterns justify ML; add 3.0 when business consumers need self-service answers.


Phase Map — Translate This to Any Use Case

Phase 0  ──  Data initialisation        raw_table, transactions, events, ...
Phase 1  ──  Rule-based analytics       vw_feat_<entity>_risk  (tdfs4ds process)
                                        ds_rule_risk           (tdfs4ds dataset)
Phase 2  ──  Feature engineering        ds_temporal_features   (Tier 1 - time windows)
                                        ds_aggregate_features  (Tier 2 - lifetime stats)
                                        ds_derived_features    (Tier 3 - computed signals)
                                        ds_<entity>_ml         (consolidated - all tiers)
Phase 3  ──  ML risk scoring            vw_feat_ml_risk        (tdstone2 → tdfs4ds)
                                        ds_ml_risk             (tdfs4ds dataset)
Phase 4  ──  Explainability             vw_feat_scoring        (combined rule + ML)
                                        vw_feat_risk_band      (tdfs4ds process)
                                        ds_investigation_queue (tdfs4ds dataset)
Phase 5  ──  Agentic consumption        consumer agent + Gradio chatbot

Phase 0 — Data Initialisation

Load source data into Teradata and profile it. Use teradataml.copy_to_sql() for bulk loads — never row-by-row INSERT.

import pandas as pd
import teradataml as tdml

df = pd.read_csv('data.csv')
df['date_col'] = pd.to_datetime(df['date_col']).dt.date
tdml.copy_to_sql(df, table_name='raw_table', schema_name='<DATABASE>',
                 if_exists='append', index=False)

Phase 1 — Rule-Based Analytics (Teradata 1.0)

Implement SQL rules, z-scores, and threshold flags as tdfs4ds processes. Every rule output becomes a registered feature — versioned, traceable, and documented.

from teradataml import execute_sql
from tdfs4ds import upload_features

# Compute rule-based features in SQL
execute_sql(f"""
REPLACE VIEW {db}.vw_feat_rule_risk AS
LOCKING ROW FOR ACCESS
SELECT
    entity_id,
    CASE WHEN amount_zscore > 3 THEN 1 ELSE 0 END AS flag_high_zscore,
    CASE WHEN claim_count_7d > 10 THEN 1 ELSE 0 END AS flag_volume_spike,
    -- weighted rule score 0-1
    (flag_high_zscore * 0.5 + flag_volume_spike * 0.5) AS rule_based_score
FROM {db}.vw_stats
""")

df_rule = tdml.DataFrame(tdml.in_schema(db, 'vw_feat_rule_risk'))

upload_features(
    df_rule,
    entity_id        = ['entity_id'],   # type auto-detected from the source DataFrame
    feature_names    = ['flag_high_zscore', 'flag_volume_spike', 'rule_based_score'],
    metadata         = {'project': '<project>', 'phase': '1-rules'},
    dataset_view_name= 'ds_rule_risk',
    document         = True,
)

Skill: fs-upload


Phase 2 — Feature Engineering (Teradata 1.0 → 2.0 bridge)

Engineer ML-ready features in logical tiers using temporal window functions, cross-entity aggregations, and derived ratios. Register each tier as a separate dataset in tdfs4ds so features are modular, reusable, and independently documented.

Best practice: three-tier feature hierarchy:

Tier 1: Temporal Features (ds_temporal_features) - 7d/30d rolling windows: claim counts, average amounts, unique drug counts - Compute once per claim_id with window functions - Register with upload_features(dataset_view_name='ds_temporal_features')

Tier 2: Aggregate Features (ds_aggregate_features) - Lifetime statistics: provider/pharmacy/region averages, standard deviations - Drug normalization: average quantity and days_supply - Register with upload_features(dataset_view_name='ds_aggregate_features')

Tier 3: Derived Features (ds_derived_features) - Computed signals: z-scores, velocity ratios, amount deviations - Built by joining Tier 1 + Tier 2 datasets (not raw tables) - Register with upload_features(dataset_view_name='ds_derived_features')

Consolidated Dataset (ds_<entity>_ml) - Union all three tiers plus raw columns (amount, quantity, etc.) - Single dataset for Phase 3 ML input - Assemble with upload_features() pulling from registered vw_* views that join the three tiers

This pattern: - ✅ Avoids redundant computation (Phase 3+ reuses registered datasets) - ✅ Makes feature lineage explicit (temporal → aggregate → derived) - ✅ Enables per-tier documentation and versioning - ✅ Keeps intermediate vw_temp_* views as SQL-only scaffolding

Teradata SQL constraints (see also fs-upload): - No COUNT(DISTINCT col) OVER (PARTITION BY …) — use a correlated subquery instead - No ORDER BY in view bodies or in DataFrame.from_query() — sort with .sort() on the DataFrame - REPLACE VIEW … AS SELECT *, extra AS alias is rejected — enumerate all columns explicitly - Add LOCKING ROW FOR ACCESS immediately after REPLACE VIEW … AS in every view body — prevents read-lock contention on busy feature views

Skill: fs-upload, fs-dataset


Phase 3 — In-Database ML (Teradata 2.0)

Train a scikit-learn model inside Vantage with tdstone2. Scores come back as a Teradata view, which is then registered as a tdfs4ds feature — making ML scores first-class citizens in the feature store alongside rule-based scores.

from tdstone2.tdstone import TDStone
from tdstone2.tdshypermodel import HyperModel
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import IsolationForest
from tdfs4ds import upload_features, build_dataset
from tdfs4ds.feature_store.feature_query_retrieval import get_feature_versions

sto = TDStone(schema_name='<DATABASE>', SEARCHUIFDBPATH='<USER>')

# --- Step 1: Build a purpose-specific feature dataset from the store ---
# Training input MUST be a tdfs4ds dataset (not a transformation view).
# Use get_feature_versions() to resolve exact versions, then build_dataset()
# to create the dataset view. Never construct the selection dict manually.
FEATURES = ['col1', 'col2', ..., 'colN']   # only the features this model needs

feature_selection = get_feature_versions(entity_name='entity_id', features=FEATURES)
build_dataset(
    entity_id=['entity_id'],
    selected_features=feature_selection,
    view_name='ds_<entity>_ml_training',
    comment='<Entity> ML features for Phase 3 model training',
)

# --- Step 2: Join dataset with raw table for partition key and/or raw source fields ---
# Use this join for two things only:
#   (a) the partition column (e.g. region) if not registered as a feature, and
#   (b) raw source attributes (e.g. amount) that are used as ML inputs but must
#       NOT be registered in the feature store (1:1 copies = pure data duplication).
# No feature transformations here. Add LOCKING ROW FOR ACCESS on every view.
feature_cols_sql = ',\n    '.join([f'd.{c}' for c in FEATURES])
execute_sql(f"""
REPLACE VIEW {db}.vw_feat_<entity>_ml AS
LOCKING ROW FOR ACCESS
SELECT
    d.entity_id,
    r.partition_col,
    {feature_cols_sql},
    'train' AS fold_col
FROM {db}.ds_<entity>_ml_training d
JOIN {db}.raw_table r ON d.entity_id = r.entity_id
""")

# --- Step 3: Train ---
model = HyperModel(
    tdstone            = sto,
    metadata           = {'project': '<project>', 'owner': '<owner>'},
    skl_pipeline_steps = [('scaler', StandardScaler()), ('clf', IsolationForest(contamination=0.05))],
    model_parameters   = {
        # For unsupervised models (IsolationForest, LOF): omit 'target' and 'column_categorical'
        # For supervised models: add 'target': 'label_col', 'column_categorical': ['label_col']
        'column_names_X': FEATURES + ['amount'],   # append raw fields joined from source table
    },
    dataset            = tdml.in_schema(db, 'vw_feat_<entity>_ml'),
    id_row             = 'entity_id',
    id_partition       = 'partition_col',
    id_fold            = 'fold_col',
    fold_training      = 'train',
    store_pickle       = True,
)
model.train()
model.score()

# --- Step 4: Register ML scores back into the feature store ---
# Use the live STO view (re-scores on every query against the latest model).
# Carry ID_TRAINED_MODEL as a feature for model lineage — NOT as an entity key.
# See tdstone2-hypermodel "Governance & Lineage with tdfs4ds" for details.
mapper_uuid   = str(model.mapper_scoring.id).replace('-', '_')
sto_view_name = f"TDS_STO_SCORING_{mapper_uuid}"
execute_sql(f"SET SESSION SEARCHUIFDBPATH = '{sto.SEARCHUIFDBPATH}'")

execute_sql(f"""
REPLACE VIEW {db}.vw_feat_ml_risk AS
LOCKING ROW FOR ACCESS
SELECT
    p.entity_id,
    p.ID_TRAINED_MODEL                                              AS id_trained_model,
    CAST(
        1.0 - (CAST(p.anomaly_score AS FLOAT) - s.mn) / NULLIFZERO(s.mx - s.mn)
    AS FLOAT)                                                       AS ml_risk_score,
    CASE
        WHEN CAST(1.0 - (CAST(p.anomaly_score AS FLOAT) - s.mn) / NULLIFZERO(s.mx - s.mn)
             AS FLOAT) >= s.p95
        THEN 1 ELSE 0
    END                                                             AS is_anomaly
FROM {db}.{sto_view_name} p
CROSS JOIN (
    SELECT
        MIN(CAST(anomaly_score AS FLOAT))  AS mn,
        MAX(CAST(anomaly_score AS FLOAT))  AS mx,
        PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY CAST(anomaly_score AS FLOAT)) AS p95
    FROM {db}.{sto_view_name}
) s
""")

df_ml = tdml.DataFrame(tdml.in_schema(db, 'vw_feat_ml_risk'))
upload_features(df_ml, entity_id=['entity_id'],
                feature_names=['ml_risk_score', 'is_anomaly', 'id_trained_model'],
                metadata={'project': '<project>', 'phase': '3-ml'},
                dataset_view_name='ds_ml_risk', document=True)

Critical tdstone2 rules: - id_fold and fold_training are required even when all data is used for training — omitting them silently sets mapper_training = None, causing a crash at .train() - Call TDStone.setup() exactly once per schema before any HyperModel (see the tdstone2-setup skill, which ships with tdstone2) - model_parameters must omit target and column_categorical for unsupervised models (IsolationForest, LocalOutlierFactor); add them only for supervised classifiers/regressors - Use the live STO view (TDS_STO_SCORING_<uuid>) as the source for vw_feat_ml_risk, not the static snapshot TDS_SCORES_<uuid>; derive the UUID via model.mapper_scoring.id - Call SET SESSION SEARCHUIFDBPATH before the first query against the STO view in a fresh session

Skills: tdstone2-hypermodel, tdstone2-setup (both ship with tdstone2), fs-upload


Phase 4 — Explainability & Governance (Teradata 2.0)

Combine rule and ML scores, classify into risk bands, identify top drivers. Assemble the operational investigation dataset. Everything stays in tdfs4ds processes — no standalone tables.

# Process 1: combined score (all entities)
execute_sql(f"""
REPLACE VIEW {db}.vw_feat_scoring AS
SELECT ml.entity_id,
       (ml.ml_risk_score + r.rule_based_score) / 2.0 AS combined_score
FROM {db}.vw_feat_ml_risk ml
JOIN {db}.vw_feat_rule_risk r ON ml.entity_id = r.entity_id
""")
upload_features(df_scoring, entity_id=['entity_id'],
                feature_names=['combined_score'], ...)

# Process 2: risk band + top driver (Medium + High only)
execute_sql(f"""
REPLACE VIEW {db}.vw_feat_risk_band AS
SELECT cf.entity_id,
       CASE WHEN ml.ml_risk_score >= pct.p90 THEN 'High' ELSE 'Medium' END AS risk_band,
       CASE WHEN ... THEN 'driver_name' ... END AS top_driver,
       'pending' AS investigation_status
FROM {db}.vw_feat_<entity> cf
JOIN {db}.vw_feat_ml_risk ml ON cf.entity_id = ml.entity_id
CROSS JOIN (SELECT PERCENTILE_CONT(0.70) ... AS p70, PERCENTILE_CONT(0.90) ... AS p90
            FROM {db}.vw_feat_ml_risk) pct
WHERE ml.ml_risk_score >= pct.p70
""")
upload_features(df_risk_band, entity_id=['entity_id'],
                feature_names=['risk_band', 'top_driver', 'investigation_status'], ...)

# Dataset: investigation queue (INNER join keeps only Medium + High)
from tdfs4ds.feature_store.feature_query_retrieval import get_feature_versions
from tdfs4ds import build_dataset

feature_selection = get_feature_versions(entity_name='entity_id',
    features=['rule_based_score', 'ml_risk_score', 'combined_score',
              'risk_band', 'top_driver', 'investigation_status', ...])

build_dataset(entity_id=['entity_id'], selected_features=feature_selection,
              view_name='ds_investigation_queue',
              comment='Medium + High risk entities for operational triage.',
              grouped=True)

Skills: fs-upload, fs-dataset


Phase 5 — Agentic Consumption (Teradata 3.0)

Business consumers query the feature store in natural language. The agent answers from the business dictionary populated automatically by document=True in Phases 1–4.

Requires LLM configuration in .env:

TDFS4DS_INSTRUCT_MODEL_PROVIDER=openai   # or bedrock | vllm | azure
TDFS4DS_INSTRUCT_MODEL_API_KEY=...
TDFS4DS_INSTRUCT_MODEL_MODEL=gpt-4o
TDFS4DS_EMBEDDING_MODEL_PROVIDER=openai
TDFS4DS_EMBEDDING_MODEL_MODEL=text-embedding-3-small

tdfs4ds.CHROMA_MODE = 'local'
tdfs4ds.CHROMA_PATH = './tdfs4ds_chroma'

from tdfs4ds.agent import build_vector_index, consumer_agent, launch_chatbot

build_vector_index(force_rebuild=False)   # incremental — safe to re-run

print(consumer_agent('What features detect anomalous amounts?', thread_id='s1'))
print(consumer_agent('How is ml_risk_score calculated?', thread_id='s2'))

demo = launch_chatbot(title='<Use Case> — Feature Store Assistant', port=7860)

Skill: fs-agent


How tdfs4ds and tdstone2 Compose

Phase 1/2          Phase 3                  Phase 4           Phase 5
──────────         ──────────────────────   ───────────────   ─────────────
tdfs4ds            tdstone2                 tdfs4ds           tdfs4ds
upload_features    HyperModel.train()       upload_features   consumer_agent
   │                   │                       │                  │
vw_feat_rule  ──►  vw_train  ──(STO/Apply)──► vw_feat_ml_risk ──► ds_investigation_queue
vw_feat_<ent>          │                       vw_feat_scoring     (INNER join of ALL
                   get_model_predictions()     vw_feat_risk_band    registered features)
                       │
                  register scores back
                  into tdfs4ds as features

The ML model in tdstone2 reads from a tdfs4ds feature view and writes back its predictions as a new tdfs4ds process. The feature store is the single source of truth for all derived data.


Decision Guide

Situation Tool Note
Time-series features (7d/30d windows) tdfs4ds Tier 1: ds_temporal_features Register separately; reusable by Phases 3+
Lifetime / baseline aggregations tdfs4ds Tier 2: ds_aggregate_features Join with raw tables once; register as dataset
Derived signals (z-scores, ratios) tdfs4ds Tier 3: ds_derived_features Join Tier 1 + Tier 2; avoid raw table joins
Consolidate features for ML Create vw_feat_* joining all 3 tiers Register as ds_<entity>_ml for Phase 3 input
SQL aggregations, z-scores tdfs4ds + REPLACE VIEW Enumerate all columns explicitly
One global model for all data tdstone2 HyperModel, id_partition = constant column Add fold_col='train' constant
One model per region / segment / entity tdstone2 HyperModel, id_partition = segment column Parallel training per AMP
Normalize anomaly scores 0→1 Register in tdfs4ds as vw_feat_ml_risk Post-process via REPLACE VIEW
Combine rule + ML scores New tdfs4ds process vw_feat_scoring (ml_score + rule_score) / 2.0
Risk bands + top driver explanation New tdfs4ds process vw_feat_risk_band CROSS JOIN percentile subquery
Operational triage queue build_dataset() with INNER join Naturally filters to flagged rows
NL queries by business users tdfs4ds consumer agent Needs document=True in all phases

Anti-patterns to Avoid

Anti-pattern Why bad Correct approach
Creating intermediate features without registering in feature store Not versioned; Phase 3+ recomputes everything Register each feature tier (temporal, aggregate, derived) as separate datasets
Single monolithic feature view with all tiers mixed Hard to reuse; couples feature engineering to specific use case Split into three tiers; register each with upload_features()
Joining raw tables repeatedly in each feature layer Scales poorly; joins recomputed on every downstream query Join once per tier; reuse registered ds_temporal_features, ds_aggregate_features, etc.
A Python loop around run() / roll_out(), or a custom step on FS_T_* between dates A refresh does not reproduce it, with no error Managers + one roll_out; close_absent_entities. See fs-upload, Stay inside the framework
Writing ML predictions to a standalone table Not versioned, not joinable via feature store Register as a tdfs4ds process with upload_features()
Moving data to pandas/local for feature engineering Doesn't scale; breaks lineage Write feature logic as REPLACE VIEW + upload_features()
Using SELECT * with extra columns in REPLACE VIEW Teradata syntax error Enumerate all columns explicitly
ORDER BY inside REPLACE VIEW or DataFrame.from_query() Syntax error / teradataml error Remove ORDER BY; use .sort() on the DataFrame
copy_to_sql(..., if_exists='append') of a read_csv frame with blank text cells "bound parameter N type FLOAT differs from batch row 1 type VARCHAR": the column holds str and NaN; types= does not help on an append df[c] = df[c].astype(object).where(df[c].notna(), None) before loading
COUNT(DISTINCT col) OVER (PARTITION BY …) Teradata doesn't support DISTINCT in window functions Use a correlated subquery
Omitting id_fold / fold_training in HyperModel mapper_training silently becomes None Always supply both; add constant 'train' AS fold_col if needed
tdfs4ds.select_data_domain() before first upload_features() ValueError — domain not in DB until first upload Use create_data_domain() everywhere (idempotent)
tdfs4ds.connect(database=db) on a database that has no feature store yet Returns False with the warning "Feature store components missing and create_if_missing=False"; nothing is created First time: tdfs4ds.setup(database=db), or tdfs4ds.connect(database=db, create_if_missing=True)
document_dataset_incremental(view_name=...) TypeError — takes dataset_id UUID not view name Look up UUID: dataset_catalog().to_pandas() then filter by name
Using a transformation view as Phase 3 ML training input Not traceable; features re-computed outside the store; violates lineage Build a dedicated ds_<entity>_ml_training dataset via build_dataset() + get_feature_versions(); JOIN raw table only for the partition key and/or raw source attributes that must not be duplicated in the store
Registering a 1:1 copy of a raw source field (e.g. amount) in the feature store Pure data duplication; no transformation = no governance value Join the source table in the training query instead; append the column to column_names_X
Choosing tdstone2 without checking that the Script table operator runs Error 9854 at the first training: Script is not licensed on every system (AI Studio) Run a one-row SCRIPT test first; otherwise train in the client, export ONNX and score in the database with BYOM ONNXPredict as a tdfs4ds process (see fs-upload), with a parity check on a sample
Training on a snapshot when the label is in the future Leakage or no label Training = build_historical_dataset with lags and a lead label, window ending at the training date; scoring = snapshot following the TimeManager (see fs-dataset)
Omitting LOCKING ROW FOR ACCESS from REPLACE VIEW bodies Read-lock contention blocks writers on busy feature views Add LOCKING ROW FOR ACCESS as the first line of every view body

Notebook Skeleton

For any new use case, create one notebook per phase:

Notebook Phase Key calls
00_DataInit.ipynb 0 copy_to_sql(), tdfs4ds.setup(), create_data_domain()
01_RuleAnalytics.ipynb 1 REPLACE VIEW, upload_features(document=True)
02_FeatureEng.ipynb 2 Tier 1 temporal → ds_temporal_features / Tier 2 aggregate → ds_aggregate_features / Tier 3 derived → ds_derived_features / All tiers → ds_<entity>_ml
03_MLScoring.ipynb 3 TDStone.setup(), HyperModel, upload_features()
04_Governance.ipynb 4 vw_feat_scoring, vw_feat_risk_band, build_dataset(grouped=True)
05_AgentConsumption.ipynb 5 build_vector_index(), consumer_agent(), launch_chatbot()

Each notebook opens with the same connection block — see fs-setup.


Skill Purpose
fs-setup Connection + setup() + create_data_domain() boilerplate
fs-upload Register features from a SQL view
fs-dataset Assemble feature versions into a dataset view
fs-inspect Audit catalogs, follow-up history, re-run processes
fs-document LLM documentation + EXPLAIN score for a process
fs-agent Launch the consumer agent chatbot
tdstone2 Decision guide — when to use tdstone2 vs td_sklearn
tdstone2-setup One-time TDStone.setup() per schema
tdstone2-hypermodel Train/score a hyper-segmented sklearn pipeline
tdstone2-troubleshooting Fix Apply / mapper / ONNX errors

The tdstone2* skills ship with the tdstone2 package, not with tdfs4ds.