fs-filter¶
Segmented ingestion with FilterManager — standard, hybrid, or clone modes.
name: "Feature Store: Filter" description: "Generate code for segmented feature ingestion with a FilterManager — one segment at a time (standard), segments under a TimeManager, hybrid (each segment a (value, date) pair), or a cloned manager. Invoke when a process must run one category / region / partition at a time, when the source is too large for one pass, or for a daily backfill per category." argument-hint: "[filter-column][mode]" allowed-tools: "Read, Edit, Write, Bash, Glob, Grep"
Generate Python code for segmented feature ingestion with a FilterManager.
User context: $ARGUMENTS
Related skills¶
| Step | Skill | Why |
|---|---|---|
| Trigger | fs-analyze |
Decide which column to segment on (ideally a partitioning column of the source). |
| Sibling | fs-upload |
upload_features(..., filtermanager=fm) attaches the manager to the process. |
| Sibling | fs-rollout |
Segments under a TimeManager: roll_out loops over dates, each date over segments. |
| Inspect | fs-inspect |
follow_up_report() has one row per segment (APPLIED_FILTER). |
Demos: demos/notebooks/07 (FilterManager alone), 08 (with a TimeManager), 09 (hybrid).
The model¶
A FilterManager is a table of segments (one row each, numbered filter_id 1..n) and a one-row view showing
the current one. The process view reads the current segment through a scalar subquery on that view.
run(process_id) sees the manager attached to the process and loops over the segments: move the cursor,
ingest, next segment. Each segment gets its own follow-up row, so a failed segment is visible on its own and the
others still complete.
| Mode | Segment | When |
|---|---|---|
| Standard | one value of a column (a category, a region) | One slice at a time: smaller spool and unpivot per ingestion, per-segment trace. |
| With a TimeManager | the same segments, at each business date | A history computed segment by segment (roll_out over dates). |
| Hybrid | a (value, date) pair; the view exposes the column and BUSINESS_DATE |
Daily backfill per category; only the listed pairs are processed. |
| Clone | a copy of another manager's segments | Another process needs the same segments with its own cursor. |
The segments must split the entity. Each segment writes its own rows, so no two segments may produce the same
entity key. Segmenting by Category requires the category in the entity (['CustomerID', 'Category']), or entities
that each fall in one segment. With CustomerID alone, the segment processed last overwrites the values of a
customer active in several categories.
Ask for any missing values before generating code:
- Database of the feature store, data domain, source table.
- Filter column(s) — e.g. 'Category', or Category + a date column for a hybrid manager.
- Entity — must contain the filter column (or be split by it, see above).
- Mode — standard, with a TimeManager, hybrid, or clone.
Standard FilterManager¶
import tdfs4ds # reads the TDFS4DS_* settings of .env
tdfs4ds.reconnect_teradata(raise_error=True) # teradataml context from TDFS4DS_TD_HOST / _USERNAME / _PASSWORD
tdfs4ds.connect(database='<DATABASE>')
tdfs4ds.select_data_domain('<DATA_DOMAIN>')
import teradataml as tdml
from tdfs4ds.utils.filter_management import FilterManager
SOURCE = '<SOURCE_DATABASE>.<SOURCE_TABLE>'
# 1. The segments: one row per value. The view shows the current one.
fm = FilterManager(table_name='<FILTER_TABLE_NAME>', schema_name='<DATABASE>')
fm.load_filter(tdml.DataFrame.from_query(f"SELECT DISTINCT <FILTER_COLUMN> FROM {SOURCE}"))
print(fm.nb_filters, 'segments')
fm.update(filter_id=2); print(fm.display()) # move the cursor by hand to look at one segment
fm.update(filter_id=1)
# 2. The process view reads the current segment through a SCALAR subquery
# (never a join, never a hard-coded value). The filter column is in the entity.
sql = f"""
SELECT
A.<ENTITY_COLUMN>
, A.<FILTER_COLUMN>
, SUM(A.<VALUE_COLUMN>) AS <FEATURE_1>
, COUNT(*) AS <FEATURE_2>
FROM {SOURCE} A
WHERE A.<FILTER_COLUMN> = (SELECT <FILTER_COLUMN> FROM {fm.sql_view})
GROUP BY A.<ENTITY_COLUMN>, A.<FILTER_COLUMN>"""
pid = tdfs4ds.upload_features(
df=None, sql_query=sql, target_view_name='<DATABASE>.<VIEW_NAME>',
entity_id=['<ENTITY_COLUMN>', '<FILTER_COLUMN>'],
feature_names=['<FEATURE_1>', '<FEATURE_2>'],
filtermanager=fm, # attaches the manager: run() loops over its segments
run_now=False, return_process_id=True)
# 3. Run every segment; a failed segment raises once all have been attempted
tdfs4ds.run(pid, on_failure='raise')
# 4. One follow-up row per segment
fu = tdfs4ds.follow_up_report(process_id=pid).to_pandas().reset_index()
print(fu[['APPLIED_FILTER', 'STATUS', 'START_DATETIME']])
Check once that segment by segment equals all at once: build a dataset on the entity and compare it with one
unsegmented GROUP BY of the source (same row count, no differing value). Demo 07 does it: 8,858 rows on both sides,
0 differing values.
Segments under a TimeManager¶
from tdfs4ds.utils.time_management import TimeManager
tm = TimeManager(table_name='<TIME_TABLE_NAME>', schema_name='<DATABASE>') # see fs-rollout
sql = f"""
SELECT A.<FILTER_COLUMN>, SUM(A.<VALUE_COLUMN>) AS <FEATURE_1>
FROM {SOURCE} A
WHERE A.<DATE_COLUMN> <= (SELECT BUSINESS_DATE FROM {tm.sql_view})
AND A.<FILTER_COLUMN> = (SELECT <FILTER_COLUMN> FROM {fm.sql_view})
GROUP BY A.<FILTER_COLUMN>"""
# upload_features(..., filtermanager=fm, run_now=False, return_process_id=True) as above, then:
tdfs4ds.roll_out([pid], time_manager=tm) # each date, every segment: one follow-up row per (segment, date)
# with a domain clock (0.3.6.0): tdfs4ds.roll_out(data_domain='<DOMAIN>') - each date, every process, every segment
Hybrid FilterManager (each segment a (value, date) pair)¶
hf = FilterManager(table_name='<HYBRID_FILTER_TABLE>', schema_name='<DATABASE>')
hf.load_filter(
tdml.DataFrame.from_query(f"""
SELECT DISTINCT <FILTER_COLUMN>, <DATE_COLUMN> FROM {SOURCE}
WHERE <DATE_COLUMN> BETWEEN DATE '<FROM>' AND DATE '<TO>'"""),
time_column='<DATE_COLUMN>') # the view exposes <FILTER_COLUMN> and BUSINESS_DATE
sql = f"""
SELECT A.<FILTER_COLUMN>, A.<DATE_COLUMN>, SUM(A.<VALUE_COLUMN>) AS <FEATURE_1>
FROM {SOURCE} A
WHERE A.<FILTER_COLUMN> = (SELECT <FILTER_COLUMN> FROM {hf.sql_view})
AND A.<DATE_COLUMN> = (SELECT BUSINESS_DATE FROM {hf.sql_view})
GROUP BY A.<FILTER_COLUMN>, A.<DATE_COLUMN>"""
# entity_id=['<FILTER_COLUMN>', '<DATE_COLUMN>']: the pair is the entity, so each segment writes its own rows
Clone a FilterManager¶
fm_copy = FilterManager(table_name='<NEW_TABLE>', schema_name='<DATABASE>')
fm_copy.clone_filter(fm, if_exists='replace') # independent cursor: moving the copy does not move fm
Entity buckets: bound the spool without a staging table¶
A process too large for one pass is often split by a staging table or a loop on months. Split it by entity instead: slicing entities never changes an entity's values, slicing time does. Each segment is a bucket of the entity key, defined once, read by the view as a scalar, and part of the entity:
NB = 16 # fixed once values are stored
BUCKET = ("MOD(HASHBUCKET(HASHROW(CAST(TRIM({col}) AS VARCHAR(40) CHARACTER SET LATIN))), " + str(NB) + ")")
fm = FilterManager(table_name='<BUCKET_TABLE>', schema_name='<DATABASE>')
fm.load_filter(tdml.DataFrame.from_query(
f"SELECT day_of_calendar - 1 AS ENTITY_BUCKET FROM sys_calendar.calendar WHERE day_of_calendar <= {NB}"))
sql = f"""
SELECT
e.<ENTITY_COLUMN>
, {BUCKET.format(col='e.<ENTITY_COLUMN>')} AS ENTITY_BUCKET
, SUM(e.<VALUE_COLUMN>) AS <FEATURE_1>
FROM <SOURCE_DATABASE>.<LARGE_SOURCE> e
WHERE {BUCKET.format(col='e.<ENTITY_COLUMN>')} = (SELECT ENTITY_BUCKET FROM {fm.sql_view})
GROUP BY 1, 2"""
pid = tdfs4ds.upload_features(
df=None, sql_query=sql, target_view_name='<DATABASE>.<VIEW_NAME>',
entity_id=['<ENTITY_COLUMN>', 'ENTITY_BUCKET'], feature_names=['<FEATURE_1>'],
primary_index=['<ENTITY_COLUMN>'],
partitioning=f'PARTITION BY RANGE_N(ENTITY_BUCKET BETWEEN 0 AND {NB - 1} EACH 1)',
filtermanager=fm, close_absent_entities=True, run_now=False, return_process_id=True)
- The bucket is an entity column, so
close_absent_entitiescloses only the current bucket's absent entities. - Use the same entity key (with the bucket) in every process of that entity, or their datasets will not join.
- Put the bucket predicate on the largest source, before its joins: that is what bounds the spool.
- Keep the bucket count once values are stored; changing it means new storage tables (
fs-relocate). - Expect a
redundant_key_columnwarning from the workflow assessment (the key determines the bucket): it is by design here. KeepENTITY_BUCKETout of model features. - Cost: one pass over the large source per bucket. Choose the fewest buckets that fit the spool.
When an incremental or pre-aggregated design is acceptable. Only when all of these hold: the sources are dated and never restated, the rule decomposes per period, a replay gives the same values, and the original also computed per period. Distinct counts, medians, "latest by" across periods and joins on as-of mappings (a rate or a hierarchy at the business date applied to the whole window) do not decompose. Otherwise it is a change of business logic, and the owner decides.
Recursive SQL. A WITH RECURSIVE view is slow and refused in some view shapes. When the depth is bounded,
write the hops as a UNION ALL of joins, and keep a query that proves the bound (no chain has MAX + 1 hops);
when chains are long, use pointer doubling (each step joins the table to itself, doubling the reach). Test it on
synthetic chains against the recursive view before replacing it.
Why a staging table exists. Find the reason before replacing it:
| Reason | Replacement |
|---|---|
| one request over all the entities runs out of spool | entity buckets (above) |
| a view cannot read a recursive view (Error 6926) | a plain view with bounded hops or pointer doubling (below) |
| the SQL is too large to parse as one request (Error 3710) | several processes reading each other's datasets, or helper views |
| a volatile table reused by several statements | a WITH clause, a helper view, or one more process if the result is worth storing |
| data copied period by period "to be faster" | usually nothing: measure the single view first |
If an art_sql staging step must stay, know its limits: its statements cannot contain single quotes (build dates with ADD_MONTHS or EXTRACT, not string literals), and the staging table is outside the lineage the documentation and the app show. State the reason in the notebook.
Buckets cost passes: the large source is read once per bucket. Say so, and fix the number of buckets from the spool of one request (EXPLAIN, then a test on 1/NB of the data).
Two more cases where an incremental design changes the logic: a process that reads its own previous result couples every date to the one before (a cycle in the lineage, and a rebuild then depends on the order of the dates); and a transitive closure (forwarded ids, hierarchies) is not decomposable, so one hop per date is wrong when a whole chain appears on one day.
Bounded hops, with the bound asserted:
def hop(h):
if h == 0:
return "SELECT P.ID AS ORIGINAL_ID, P.ID AS CURRENT_ID FROM <START> P"
joins = "\n".join(f"INNER JOIN <LINKS> M{k} ON M{k}.FROM_ID = {'P.ID' if k == 1 else f'M{k - 1}.TO_ID'}"
for k in range(1, h + 1))
return f"SELECT P.ID AS ORIGINAL_ID, M{h}.TO_ID AS CURRENT_ID FROM <START> P\n{joins}"
view_sql = "\nUNION ALL\n".join(hop(h) for h in range(MAX_HOPS + 1))
too_long = tdml.execute_sql(f"SELECT COUNT(*) FROM ({hop(MAX_HOPS + 1)}) X").fetchone()[0]
assert too_long == 0, "a chain is longer than MAX_HOPS"
Keep every hop if the recursive view returned every hop, only the last if it returned only the end of the chain. Pointer doubling returns only the end of the chain.
Rules¶
runis the only loop on segments. No loop aroundfm.update()+run(), no view rewritten per value, no write toFS_T_*: a refresh would not reproduce it. Seefs-upload, Stay inside the framework.- The segments must split the entity (see above). Put the filter column in
entity_idunless every entity lies in exactly one segment. - Scalar subqueries on the manager view, never a join, never a literal. Teradata reads the one-row view once per request and passes the value to the plan as a parameter.
- Follow the partitioning from its first level. On a source partitioned by day × region, a segment on the region alone reads 366 partitions, on the date 5, on both 1 (365 days × 5 regions, measured). A TimeManager filtering the first level counts. The sanity check reports the rest as
segment_filter_off_hierarchy. - What the plan reads — measured, not assumed (static
EXPLAIN, a small source partitioned by day × category, 50,000 rows): | Filter in the process view | Source read | |---|---| | category and day, each a scalar on a hybrid manager | a single partition | | the same filter written as a join to the manager view | all-rows scan | |date <= literal date| 1,267 partitions | |date <= (SELECT BUSINESS_DATE ...)(TimeManager, a range) | all-rows scan | |category = (SELECT ...)(one level only) | all-rows scan | One level eliminates partitions, and all levels read the fewest. The all-rows lines are this small table's static plan: the manager's value is a parameter, and a small request stays below incremental planning.DYNAMIC EXPLAINunderDynamicPlan=SYSTEMXshows the real pruning (the sanity checks use it). Read the EXPLAIN step that accesses the source; do not count steps. - The scalar must have the column's type.
BUSINESS_DATEisTIMESTAMP WITH TIME ZONE. Compared raw with aTIMESTAMP(0)partitioning column, the plan casts the column and reads all rows, even underDYNAMIC EXPLAIN. Measured: a TimeManager loaded from a pandas datetime storesTIMESTAMP(6) WITH TIME ZONE, andCAST(BUSINESS_DATE AS TIMESTAMP(0))of it is Error 7454. Two forms prune aTIMESTAMP(0)column from either manager type:(SELECT CAST(SUBSTR(CAST(BUSINESS_DATE AS VARCHAR(40)), 1, 19) AS TIMESTAMP(0)) FROM <manager>), or, on a daily calendar,(SELECT CAST(CAST(BUSINESS_DATE AS DATE) AS TIMESTAMP(0)) FROM <manager>). For aDATEcolumn:(SELECT CAST(BUSINESS_DATE AS DATE) FROM <manager>). A manager loaded from a pandas date column stores the date as text (VARCHAR); only theDATEforms work there. - Segmenting pays most when the filter column is a partitioning column of the source.
- Always pass
filtermanager=fmtoupload_features; without itrun()computes only the segment the view shows. run([pid, ...], at=...)computes each process at that one time, and goes through the segments of a process with a FilterManager asrun(pid)does.fm.update(filter_id=N)moves the cursor by hand (1-based), to inspect or test one segment.- Use
on_failure='raise'under a scheduler: every segment is attempted, thenFeatureIngestionErrorlists the failed ones.'stop'halts at the first failure; the default'continue'records it and goes on. - Hybrid managers expose the date as
BUSINESS_DATE; filter both columns, each with its own scalar subquery. - Vantage Cloud Lake + tdstone2 Apply only — OFS manager table + JOIN the filter in. A view scored by Apply runs
on the Analytical Compute Cluster (ACC): create the manager with
FilterManager(..., storage='OFS')and reference it through a JOIN (the ACC rejects scalar subqueries with Error 6881). This is the one exception to the scalar-subquery rule;roll_out/run()cannot drive an Apply model themselves.