td-uaf-feature¶
Register a UAF diagnostic whose whole result is inline (TD_ACF, TD_DICKEY_FULLER) as a recomputable feature.
Source file
Lives at tdfs4ds/skills/td-uaf-feature/SKILL.md.
name: "Teradata UAF diagnostics as recomputable features"
description: "Generate Python and SQL to register a Teradata UAF operator whose whole result is inline (TD_ACF, TD_DICKEY_FULLER and similar diagnostics) as a governed, recomputable tdfs4ds feature, by writing the EXECUTE FUNCTION inside a CTE of a view rather than letting teradataml stage it in a volatile table. Invoke when the user wants per-series autocorrelation or stationarity tests as features that survive the session. SKIP when the value lives in an ART layer, such as ARIMA fit metrics, residual tests or TD_PACF (use td-uaf-art), and for a forecast (use td-uaf-forecast)."
argument-hint: "[source-table][series-id-column(s)] [row-axis-column][value-column]"
allowed-tools: "Read, Edit, Write, Bash, Glob, Grep"
Generate code to compute a per-series UAF diagnostic (autocorrelation TD_ACF, partial autocorrelation TD_PACF, Dickey-Fuller stationarity TD_DICKEY_FULLER, and similar) and register it as a persistable, recomputable tdfs4ds feature.
User context: $ARGUMENTS
The one thing this skill exists to get right: a UAF operator's output must live in a SQL view that invokes the operator inline via EXECUTE FUNCTION — not in the volatile table that teradataml's operator wrappers produce — and each operator must sit inside its own CTE. The CTE placement is not cosmetic: tdfs4ds ingests (and run() refreshes) by wrapping the view in CREATE VOLATILE TABLE AS (SELECT * FROM <view>), and a UAF EXECUTE FUNCTION nested as a top-level derived table crashes that statement with Error 3610 (a Teradata engine crash) — even though a bare SELECT from the same view works. Wrapping each operator in a WITH … AS (…) CTE survives ingestion. This is the difference between "looks fine when I test it with SELECT" and "actually works through tdfs4ds."
Related skills¶
| Before / After | Skill | Why |
|---|---|---|
| Before | fs-setup |
Open the Teradata context and activate a data domain. |
| Before | fs-filter |
If registering per partition (e.g. per store), build the FilterManager first. |
| Sibling | td-uaf-art |
When the value lives in a secondary ART layer: two statements instead of one view. |
| Sibling | td-uaf-forecast |
For ARIMA and Holt-Winters forecasts. |
| After | td-plot |
Plot the diagnostic distributions in-database. |
| After | fs-document |
LLM business description for the registered diagnostic process. |
Ask for any missing values before generating code¶
- Source table/view — one row per (series, observation).
- Series ID column(s) — identify the series (e.g.
item_id, store_id). - Row axis —
TIMECODE(a real date/timestamp) orSEQUENCE(an integer offset). AROW_NUMBER() OVER (PARTITION BY <series> ORDER BY <date>)sequence is typical. - Value column — the payload field the operator runs on.
- Which diagnostic(s) — ACF at specific lags, PACF, Dickey-Fuller T-stat, etc.
- Partitioned registration? — whether to scope per partition via a
FilterManager(recommended for large series counts / small PERM quota).
The core problem (why the naive path fails)¶
teradataml's UAF wrappers (tdml.ACF, tdml.DickeyFuller, …) do not return an inline result. They emit:
The output is a session-scoped volatile table. Confirm it yourself:
acf_out = tdml.ACF(data=series, max_lags=365, volatile=True)
print(acf_out.show_query()) # -> EXECUTE FUNCTION INTO VOLATILE ART(...) TD_ACF(...)
print(acf_out.result._table_name) # -> "db"."ml__td_uaf_volatile_out__..." (vanishes at session end)
A REPLACE VIEW ... AS SELECT * FROM <that volatile table> registers into tdfs4ds, but the moment the session ends the volatile table is gone — so tdfs4ds.run() / build_dataset() re-execute the stored view text against an object that no longer exists. The feature is permanently unservable. (Symptom seen in practice: only the last-computed partition's rows are present, or the dataset errors on refresh.)
crystallize_view does not save you here — it calls SHOW VIEW internally and errors (3854) against a volatile table, and even if wrapped in a view first, the underlying volatile object is the problem.
ART output modes — pick the right one¶
A UAF operator writes its result into an ART (Analytical Result Table). There are three ways to consume it:
| Clause | Lifetime | Recomputable by tdfs4ds.run()? |
Use for |
|---|---|---|---|
EXECUTE FUNCTION ... INTO VOLATILE ART(name) |
session only | No — vanishes at session end | scratch / capture only |
EXECUTE FUNCTION ... INTO ART(name) |
permanent table | No — static snapshot, and needs PERM space | a one-off materialised result you will not refresh |
EXECUTE FUNCTION ... (no INTO) inside a CTE, in a view |
as long as the view | Yes — the view re-runs the operator on every read | governed, recomputable features (this skill) |
INTO ART is persistable, so it's tempting — but it's a frozen snapshot (a scheduled tdfs4ds refresh won't recompute it) and it consumes PERM quota (which small users often lack — Error 2644 "No more room"). The inline-CTE-in-view form is the right default for a governed feature: zero storage, always recomputed. INTO ART is manipulation-locked too (no user INSERT/UPDATE/DELETE). Note the mandatory CTE placement (see the fix below) — inline EXECUTE FUNCTION in a view only survives tdfs4ds ingestion when each operator sits in its own CTE, never as a top-level derived table.
The fix — inline EXECUTE FUNCTION (no INTO), each operator in its own CTE¶
Written by hand, the operator returns an inline result set. It must be referenced from a CTE, not a top-level derived table — see the box below. Correct shape:
REPLACE VIEW db.vw_feat_uaf_diag AS
LOCKING ROW FOR ACCESS
WITH acf AS (
SELECT item_id, store_id, ...pivot...
FROM (
EXECUTE FUNCTION
TD_ACF(
SERIES_SPEC(
TABLE_NAME(db.vw_series_in), -- a base table OR view is accepted here
ROW_AXIS(SEQUENCE(seq_no)),
SERIES_ID(item_id, store_id),
PAYLOAD(FIELDS(sales_qty), CONTENT(REAL))
),
FUNC_PARAMS(MAXLAGS(365))
)
) a
WHERE ROW_I IN (7, 365)
GROUP BY item_id, store_id
)
SELECT * FROM acf
CRITICAL — the CTE is load-bearing, verified end-to-end on live Vantage 20.
tdfs4dsingests (andrun()refreshes — same code path) by wrapping the view inCREATE VOLATILE TABLE AS (SELECT * FROM <view>). A UAFEXECUTE FUNCTIONreferenced as a top-level derived table (... FROM ( EXECUTE FUNCTION TD_ACF(...) ) acfdirectly under the final SELECT) crashes thatCREATE VOLATILE TABLE ASwith Error 3610 — a Teradata engine crash ("Please do not resubmit … CrashCode 7934"). BOTHCREATE VOLATILE TABLE AS SELECTandINSERT … SELECTcrash this way. A bareSELECT * FROM <view>to the client works, which is why this is invisible unless you test the realupload_features/runpath. Wrapping each operator inside a CTE (WITH acf AS (…), adf AS (…)) survives the CTAS. Proven through the fullupload_features(..., filtermanager=...)path, andrun(force_compute=True)in a new session completes. Do NOT "simplify" the CTEs back into inline derived tables — it will pass aSELECTtest and then crash ingestion.
SERIES_SPEC grammar (documented clause order)¶
SERIES_SPEC(
TABLE_NAME( [db.] table_or_view ),
ROW_AXIS( { TIMECODE | SEQUENCE } ( field ) ),
SERIES_ID( field-list ),
[ ID_SEQUENCE( ... ) ]
PAYLOAD( FIELDS( field-list ), CONTENT( REAL | COMPLEX | ... ) )
[, LAYER( ... ) ] [, INTERVAL( ... ) ]
)
Write clauses in this order (ROW_AXIS, SERIES_ID, PAYLOAD). The engine also tolerates the PAYLOAD-before-SERIES_ID order that show_query() emits, but the documented order is the safe form.
Chaining operators with ART_SPEC¶
Some diagnostics take another operator's ART output as input, not a raw series — the "R/Python-like" reference. Those use ART_SPEC (which references a result table) instead of SERIES_SPEC (which references raw observations):
ART_SPEC(
TABLE_NAME( [db.] table-name ),
[ ID_SEQUENCE( ... ), ]
[ PAYLOAD( FIELDS( field-list ), CONTENT( REAL | ... ) ), ]
[ LAYER( layer-name ) ]
)
Operators that accept an ART_SPEC input (and the operator that must produce it):
| Diagnostic | Required upstream ART |
|---|---|
TD_PACF |
TD_ACF |
TD_DICKEY_FULLER, TD_DURBIN_WATSON, TD_BREUSCH_GODFREY, TD_WHITES_GENERAL |
a regression/smoother: TD_LINEAR_REGR, TD_ARIMAESTIMATE, TD_SIMPLEEXP, TD_HOLT_WINTERS_FORECASTER, … |
TD_CUMUL_PERIODGRAM, TD_SIGNIF_PERIODICITIES, TD_PORTMAN, TD_FITMETRICS |
the ARTFITRESIDUALS layer of an ARIMA/smoother fit (LAYER(ARTFITRESIDUALS)) |
TD_ARIMAVALIDATE / TD_ARIMAFORECAST |
TD_ARIMAESTIMATE (the latter needs FIT_PERCENTAGE(100)) |
TD_DICKEY_FULLER here takes a SERIES_SPEC in the plain stationarity case (this skill's default) — the ART_SPEC form is for testing the residuals of a fitted model instead. A chained diagnostic cannot be written in one view: nesting EXECUTE FUNCTION as an argument is Error 3706. Use td-uaf-art.
Multi-layer ARTs (LAYER(name)) let one result table hold several row compositions (e.g. a fit plus its residuals); reference a specific one with the LAYER clause, and use TD_EXTRACT_RESULTS to pull a named layer out.
Full pattern¶
Step 1 — capture the exact operator SQL (once, to get column names right)¶
Run the teradataml wrapper once (with volatile=True so it fits in spool) purely to read its show_query() and result columns — then hand-write the inline form. Do not ship the wrapper call.
series = tdml.TDSeries(
data=tdml.DataFrame.from_query("SELECT ... FROM src WHERE ..."),
id=['item_id', 'store_id'], row_index='seq_no',
row_index_style='SEQUENCE', payload_field='sales_qty', payload_content='REAL',
)
op = tdml.ACF(data=series, max_lags=365, volatile=True)
print(op.show_query()) # the TD_ACF(...) SQL to inline
print(list(op.result.columns)) # e.g. ['item_id','store_id','ROW_I','OUT_sales_qty']
Typical result shapes (confirm against your call — they vary by operator/payload name):
- TD_ACF → item_id, store_id, ROW_I, OUT_<payload> — one row per lag; pivot with MAX(CASE WHEN ROW_I = <lag> THEN OUT_<payload> END).
- TD_DICKEY_FULLER (ALGORITHM('NONE')) → item_id, store_id, ROW_I, NUM_SAMPLES, ALGORITHM, T_STAT, P_VALUE, NULL_HYP — one row per series; take T_STAT.
Step 2 — build the store-filtered series input view¶
When registering per partition, put the FilterManager scalar subquery in this input view, so the operators recompute for whichever partition the filter currently points at:
tdml.execute_sql(f"""
REPLACE VIEW {DB}.vw_series_in AS
LOCKING ROW FOR ACCESS
SELECT item_id, store_id,
ROW_NUMBER() OVER (PARTITION BY item_id, store_id ORDER BY cal_date) AS seq_no,
sales_qty
FROM {SRC_DB}.sales
WHERE is_evaluation = 0
AND store_id = (SELECT store_id FROM {fm.sql_view})
""")
Step 3 — build the self-contained feature view (each operator in its OWN CTE)¶
One REPLACE VIEW. Each operator runs inline via EXECUTE FUNCTION inside its own CTE
(WITH acf AS (…), adf AS (…)) — NOT as a top-level derived table, which crashes tdfs4ds
ingestion (Error 3610; see the CRITICAL box above). Pivot ACF to wide; LEFT JOIN (not INNER)
so a series defined in only one operator's output still registers with NULL rather than dropped:
tdml.execute_sql(f"""
REPLACE VIEW {DB}.vw_feat_uaf_diag AS
LOCKING ROW FOR ACCESS
WITH acf AS (
SELECT item_id, store_id,
MAX(CASE WHEN ROW_I = 7 THEN OUT_sales_qty END) AS acf_lag7,
MAX(CASE WHEN ROW_I = 365 THEN OUT_sales_qty END) AS acf_lag365
FROM ( EXECUTE FUNCTION TD_ACF(
SERIES_SPEC(TABLE_NAME({DB}.vw_series_in), ROW_AXIS(SEQUENCE(seq_no)),
SERIES_ID(item_id, store_id), PAYLOAD(FIELDS(sales_qty), CONTENT(REAL))),
FUNC_PARAMS(MAXLAGS(365))) ) a
WHERE ROW_I IN (7, 365)
GROUP BY item_id, store_id
),
adf AS (
SELECT item_id, store_id, T_STAT AS adf_stat
FROM ( EXECUTE FUNCTION TD_DICKEY_FULLER(
SERIES_SPEC(TABLE_NAME({DB}.vw_series_in), ROW_AXIS(SEQUENCE(seq_no)),
SERIES_ID(item_id, store_id), PAYLOAD(FIELDS(sales_qty), CONTENT(REAL))),
FUNC_PARAMS(ALGORITHM('NONE'))) ) d
)
SELECT acf.item_id, acf.store_id, acf.acf_lag7, acf.acf_lag365, adf.adf_stat
FROM acf LEFT JOIN adf ON acf.item_id = adf.item_id AND acf.store_id = adf.store_id
""")
Step 4 — register with tdfs4ds (one call: run() goes through the partitions)¶
Because the view is self-contained SQL, this is the ordinary upload_features path. The filter column (store_id) is part of the entity:
import tdfs4ds
process_id = tdfs4ds.upload_features(
tdml.DataFrame(tdml.in_schema(DB, 'vw_feat_uaf_diag')),
entity_id=['item_id', 'store_id'],
feature_names=['acf_lag7', 'acf_lag365', 'adf_stat'],
filtermanager=fm, # run() goes through the partitions
return_process_id=True,
)
Rules¶
- Each operator MUST sit in its own CTE (
WITH acf AS (…), adf AS (…)), never as a top-level derived table under the final SELECT. Top-level derived-table nesting crashes tdfs4ds ingestion with Error 3610 (engine crash); the CTE form survives. This is THE rule — see the CRITICAL box. Do not refactor CTEs back to inline derived tables. - Test through the real
upload_features/runpath, not a bareSELECT. ASELECT * FROM <view>succeeds even for the broken derived-table form; only the CTAS ingestion exposes the 3610. Confirm with an actualupload_features(..., filtermanager=...)and ideally atdfs4ds.run(process_id, force_compute=True). - Never register a view over a
volatile=Trueoperator result. It is unservable after the session ends. Wrap inlineEXECUTE FUNCTION(noINTO) in CTEs instead. This is the entire point of the skill. - Use the
teradatamlwrapper only to capture SQL/columns, then hand-write the inlineEXECUTE FUNCTION. Do not leave the wrapper call in the pipeline. - Put the
FilterManagerscalar subquery in the series input view, not around the operator — the operators readTABLE_NAME(<input view>), so filtering there makes them recompute per partition. Then passfiltermanager=fmtoupload_features; never write a loop overfm.updateandrun(see Stay inside the framework infs-upload). TABLE_NAME(...)accepts a base table or a view — verified. So the filtered input view is a valid operator input.- Never
INTO ART/INTO VOLATILE ARTfor a registered feature. The CTE-of-inline-EXECUTE FUNCTIONform is the only supported governed form. - CHAINED operators / secondary-layer features are the hard case — the single-view CTE trick does NOT extend to them. Use the
td-uaf-artskill (tdfs4ds'uaf art view') instead.TD_PACFconsumes aTD_ACFART; residual tests (TD_PORTMAN,TD_DURBIN_WATSON,TD_BREUSCH_GODFREY,TD_SIGNIF_RESIDEMEAN,TD_FITMETRICS) consumeLAYER(ARTFITRESIDUALS)of aTD_ARIMAESTIMATE(FIT_PERCENTAGE(100))/TD_ARIMAVALIDATEART; ARIMA fit-metrics (R_SQUARE/MAPE/AIC) live inLAYER(ARTFITMETADATA);TD_ARIMAVALIDATEconsumes aTD_ARIMAESTIMATEART. These useART_SPEC(TABLE_NAME(...))/LAYER(...), and a CTE is not a validTABLE_NAME— nestedEXECUTE FUNCTIONas a function argument is a syntax error (3706, verified). A two-step chain needs a real intermediate ART, which conflicts with this skill's no-INTO rule.td-uaf-artsolves this: it stores theEXECUTE FUNCTION ... INTO VOLATILE ARTstatements asart_sqland runs them per partition, in the session, right before ingestion. TDSeries.row_index_stylemust match the column type:'SEQUENCE'for an integer offset,'TIMECODE'for a real date/timestamp.LEFT JOIN, notINNER, when combining two operators' outputs, so a series undefined in one (short/near-constant) still registers withNULL.- Confirm result column names empirically (
show_query()+.result.columns) before hardcoding — payload-derived names likeOUT_<payload>vary with the value column. - Validate a derived form against operator ground truth if you ever replace an operator with hand-rolled SQL (e.g. computing ACF via window functions): compute both on a few real series and diff — expect agreement to ~1e-14. (
TD_ACFmatches the divide-by-N Box-Jenkins autocovariance definition, andTD_DICKEY_FULLER(ALGORITHM('NONE'))the no-constant OLS slope t-statdelta/SE.) But prefer the inline operator — it's exact and simpler. - The inline
EXECUTE FUNCTIONoperator output is clean floats —MIN/MAX/BETWEEN/comparisons work normally (no NaN-bit-pattern issues; those were an artifact of the old volatile path). - The AI steps follow your configuration:
documentandoptimize_querydefault toNone. Seefs-upload.