fs-rollout¶
Drive processes with a TimeManager: run() at the current business date, roll_out() over a range of dates,
and roll_out(force_compute=True) from the first date to rebuild a history.
From 0.3.6.0, also one clock per data domain (soft clones per process, roll_out / run over a
whole domain at one time), an alternative to a TimeManager attached per process.
name: "Feature Store: Rollout" description: "Generate code to drive feature processes with a TimeManager: generate its dates from a Calendar rule and refresh a domain up to now (refresh_domain(until='now')), attach it at registration, run() at the current business date, roll_out() over a range of dates to build a history, roll_out(force_compute=True) from the first date to rebuild one, and keep processes synchronised (one clock per data domain with automatic soft clones, roll_out / run over a whole domain or a list at one time, shared manager, lockstep parallel runs, split_time_manager for an own cursor). Invoke when the user wants to backfill features over past periods, schedule processes on a business date, recompute a history after a logic change, or check which manager drives a process." argument-hint: "[process-view-name][date-column] [start-id][end-id]" allowed-tools: "Read, Edit, Write, Bash, Glob, Grep"
Generate Python code that drives registered feature processes with a TimeManager: one business date with run(),
a range of dates with roll_out().
User context: $ARGUMENTS
Related skills¶
| Step | Skill | Why |
|---|---|---|
| Before | fs-upload |
Register the processes first, with time_manager=tm and run_now=False so they are only computed under the manager. |
| Sibling | fs-filter |
Combine a TimeManager with a FilterManager: each date is computed segment by segment. |
| After | fs-dataset |
Read the history: as_of=, time_manager=, build_historical_dataset. |
| Monitor | fs-inspect |
follow_up_report() has one row per process and date (VALIDTIME_DATE). |
| Promote | fs-migrate |
Production rebuilds its own history with the same roll_out. |
Demos: demos/notebooks/05 - Time management.ipynb, 05b - Synchronising processes.ipynb, 08 (a TimeManager
with a FilterManager) and A2 (lockstep parallel runs).
Read a dataset at a date: no cursor to move and put back¶
To look at a dataset at one business date, do not tm.update(i) a shared manager and restore it afterwards:
tdfs4ds.read_dataset('db.ds', as_of='2024-03-31') (or dataset_sql(...) for the text) reads it as of that date with
no DDL and no cursor change. A bare date is read in the zone of the manager's calendar (see fs-dataset).
A dataset that follows the manager¶
upload_features(..., time_manager=tm, dataset_view_name="db.ds") builds the dataset with
build_dataset(time_manager=tm): since 0.3.7.19 that is the default whenever the process has a TimeManager (recorded as a
process setting; run/roll_out keep it, dataset_time_manager=False gives a CURRENT VALIDTIME dataset). After roll_out,
tm.update(i) shows date i with no re-run. With no time_manager= the dataset follows the manager recorded for the
process; under a domain clock, a process reading its soft clone gets a dataset on the clock itself.
tdfs4ds.dataset_time_managers() says which manager each dataset follows (clock / clone / own). With neither it warns and stays current;
a dataset already built current is not rebuilt: use tdfs4ds.rebuild_dataset("db.ds", time_manager=tm, replace=True).
The model: two calls, two jobs¶
| Call | What it does |
|---|---|
upload_features(..., time_manager=tm) |
Attaches the manager at registration, the way a FilterManager is attached: the pairing is recorded in FS_TIME_MANAGER, so run(process_id) needs no argument afterwards. |
run(process_id) / run(process_id, time_manager=tm) |
Computes one date: the attached (or passed) manager's current one. It does not loop over the manager's dates. The values are stored valid from that business date. This is the scheduler's daily call. |
roll_out(process_list, time_manager=tm, time_id_start=, time_id_end=, max_workers=None) |
The loop. For each date in the range: move the cursor, run every process of the list at that date. This is how a history is built (backfill). |
Every process attached to the same manager is synchronised: - same ingestion time: values are stored valid from the business date, not from the clock time of each run; - same visibility: a value is visible from its business date, so a dataset read at a date sees every process at that same date.
Without a manager (or FEATURE_STORE_TIME), a run is stamped with the database clock: two processes run a minute
apart get two valid times. Real time is a fallback, never the recommended way.
What the view reads is checked. Before run(..., time_manager=), roll_out or upload_features(...,
time_manager=) use a manager, tdfs4ds looks in the lineage graph (through any intermediate views) for the manager
the process view really reads. A manager it does not read would stamp values with a date they were not computed at.
tdfs4ds.TIME_MANAGER_CHECK decides: 'warn' (default) runs as before, logs a warning and records no pairing;
'error' refuses before anything runs (generate code with 'error'); 'off' skips the check. A process missing
from the lineage graph is only warned about, with the rebuild_lineage_graph(objects=[...]) command to run.
tdfs4ds.time_manager_dependency(pid) shows declared vs read; tdfs4ds.link_time_managers(dry_run=True) records the
pairing for processes registered without it (older code, or a manager read through another view).
Ask for any missing values before generating code:
- Database of the feature store, and the data domain.
- Process view name(s) — to look the process ids up (or the ids returned by upload_features(..., return_process_id=True)).
- TimeManager table name (e.g. 'BUSINESS_DATE') and the dates: where they come from (e.g. month-ends of a date column).
- What to do: run the current date, build a history over a range, or rebuild a history after a logic change.
Emit the following pattern, substituting real values for every <PLACEHOLDER>:
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.time_management import TimeManager
# ---------------------------------------------------------------------------
# 1. The TimeManager: a table of business dates and a one-row view showing the
# current one (the cursor). Creating it does not run anything.
# ---------------------------------------------------------------------------
tdfs4ds.TIME_MANAGER_CHECK = 'error' # refuse a manager the process view does not read
tm = TimeManager(table_name='<TIME_TABLE_NAME>', schema_name='<DATABASE>')
tm.load_time_steps( # first time only; later sessions reconnect to the table
tdml.DataFrame.from_query(
"SELECT DISTINCT LAST_DAY(<DATE_COLUMN>) AS business_date FROM <SOURCE_DATABASE>.<SOURCE_TABLE>"),
'business_date')
print(tm.nb_time_steps, 'dates')
# The process views read the cursor with a SCALAR subquery (see fs-upload / fs-filter):
# WHERE A.<DATE_COLUMN> <= (SELECT BUSINESS_DATE FROM <DATABASE>.<TIME_TABLE_NAME>)
# and measure recency from that date, not from CURRENT_DATE.
# ---------------------------------------------------------------------------
# 2. The processes (registered with upload_features(..., time_manager=tm, run_now=False,
# return_process_id=True)); for older processes: tdfs4ds.link_time_managers(dry_run=False)
# ---------------------------------------------------------------------------
cat = tdfs4ds.process_catalog().to_pandas()
def process_id_for(view): # exact match on the view name, never a substring
hits = cat[cat['VIEW_NAME'].str.split('.').str[-1].str.strip('"').str.upper() == view.upper()]
return hits['PROCESS_ID'].iloc[0]
process_list = [process_id_for('<PROCESS_VIEW_1>'), process_id_for('<PROCESS_VIEW_2>')]
# ---------------------------------------------------------------------------
# 3a. ONE date: run() at the manager's current date (the daily scheduler call)
# ---------------------------------------------------------------------------
tm.update(time_id=tm.nb_time_steps) # e.g. the latest business date
tdfs4ds.run(process_list, time_manager=tm, on_failure='raise') # that date, in dependency order
# ---------------------------------------------------------------------------
# 3b. A RANGE of dates: roll_out() is the loop that builds the history
# (replay in date order, from the first date)
# ---------------------------------------------------------------------------
tdfs4ds.roll_out(process_list, time_manager=tm, time_id_start=1, time_id_end=None)
# ---------------------------------------------------------------------------
# 3b'. Many processes over many dates from a remote client: independent processes of one date
# run in N worker processes (own session each, from TDFS4DS_TD_*). Same values, same
# follow-up rows, same return; dates stay sequential. Off by default (max_workers=None).
# ---------------------------------------------------------------------------
# tdfs4ds.roll_out(process_list, time_manager=tm, max_workers=3)
# It pays when the processes of a date write different tables (same-table writers are serialised) and the range
# has more than about 3 dates. It needs TDFS4DS_TD_* credentials (each worker opens its own session).
# Not for a latency you have not measured: profile first (tdfs4ds.profile()).
# ---------------------------------------------------------------------------
# 3c. REBUILD a history after the process logic changed: replay every date
# from the first one, forcing the dates already COMPLETED
# ---------------------------------------------------------------------------
# tdfs4ds.roll_out(process_list, time_manager=tm, time_id_start=1, force_compute=True)
# ---------------------------------------------------------------------------
# 4. Check: one COMPLETED follow-up row per process and date
# ---------------------------------------------------------------------------
fu = tdfs4ds.follow_up_report().to_pandas().reset_index()
fu = fu[fu['PROCESS_ID'].isin(process_list) & (fu['STATUS'] == 'COMPLETED')]
print(fu.groupby('PROCESS_ID')['VALIDTIME_DATE'].nunique()) # = tm.nb_time_steps for each process
One clock per data domain (0.3.6.0 and later)¶
Check tdfs4ds.__version__ first. From 0.3.6.0, an alternative to attaching a manager per process: declare the
domain's calendar once. It is the simplest way to keep every process of a domain in step; a manager attached per
process (time_manager=) stays valid and gives more control (own calendar, hand-made clones):
tm = TimeManager('<DOMAIN>_CLOCK', '<DATABASE>')
tm.load_time_steps(dates_df, '<DATE_COLUMN>') # once; dates_df: a teradataml DataFrame (not pandas)
tdfs4ds.set_domain_time_manager(tm) # clock of tdfs4ds.DATA_DOMAIN
# the process SQL reads the clock itself:
# WHERE A.<DATE_COLUMN> <= (SELECT BUSINESS_DATE FROM <DATABASE>.<DOMAIN>_CLOCK)
pid = tdfs4ds.upload_features(None, sql_query=sql, target_view_name='<DATABASE>.<PROCESS_VIEW>',
entity_id=['<ENTITY_COLUMN>'], feature_names=['<FEATURE_1>'],
run_now=False, return_process_id=True)
# -> no time_manager= needed: the clock is found in the view's lineage, the process gets
# its own soft clone <PROCESS_VIEW>_TM and its view is rewritten to read it
tdfs4ds.roll_out(data_domain='<DOMAIN>') # history: every process, date by date
tdfs4ds.run(data_domain='<DOMAIN>') # every process at ONE "now" (database clock)
tdfs4ds.run(['<PID_1>', '<PID_2>'], at='2024-03-31', force_compute=True) # a list at a past date
- 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 with the date known; with the value of the column's type, it eliminates partitions. 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. A plainEXPLAINleaves the value as a parameter and understates elimination: judge a date filter withDYNAMIC EXPLAINunderDynamicPlan=SYSTEMX, which is what the sanity checks read. - Register at the first date. A history is built forward: put the cursor on step 1, register (the run at registration computes date 1), then
roll_outthe rest.run_now=True, force_compute=Falsecomputes a date only when it is not COMPLETED yet, so registering again only updates the definition.upload_featuresdefaults toforce_compute=True. - Business dates are only appended.
load_time_stepsreplaces the steps and puts the cursor back on 1: reload earlier dates first, add newer ones after, thentm.update(time_id=<previous cursor>). A date inserted before computed ones shifts every step id. - A clone starts at the clock's current step: move the clock before registering (
tm.update(time_id=1)to build a history from the first date), and register withrun_now=False, or the first run happens at that date. runover a list or a domain computes at one time (at=, default the database clock read once): every clone is swapped for that literal date during the computation and put back on its cursor afterwards. No cursor moves, so a refresh "now" after a roll-out leaves the roll-out where it was. It returns{pid: 'COMPLETED' | 'FAILED: ...' | 'SKIPPED: ...' | 'NOT RUN: stopped after a failure'};run(pid, at=...)returns whatrun(pid)returns. A setFEATURE_STORE_TIMEreplaces the database clock as the default.at=withtime_manager=is aValueError,dataset_view_name=refuses several processes, anddata_domain=takes the primary store's processes only.- Dependency order: both
run(list) androll_outrun upstream processes first (lineage graph, stable sort);order='given'keeps the list's order. A failed process's downstream processes are skipped byrun. - A process reading no TimeManager is computed on current data and stored at the same time (warning). A view reading
the clock only through an intermediate view keeps the clock (no clone;
NOT_DIRECT). - Shared time-filtered view (0.3.6.8): processes reading the clock through one view they share cannot get a clone
each; they share the clock's cursor (values right, a partial run at another date is seen by the others). The
registration warning names the view and its readers; the workflow assessment reports
processes_share_time_filtered_view. Fixes: remove the date filter from the view and filter in each process view (or a copy of the view per process) — the user's SQL, never done by tdfs4ds; ortdfs4ds.clone_shared_view_time_manager('<DB>.<VIEW>', dry_run=True)thendry_run=False: one soft clone<VIEW>_TM, only the clock reference in the view rewritten, every reader recorded on it (they move together). - An object already named like a clone is reused only if it is a soft clone over the same dates; otherwise refused,
unchanged (
clone_name=to choose another name). - Processes registered before the clock:
tdfs4ds.align_domain_time_managers('<DOMAIN>', dry_run=True)lists them,dry_run=Falsegives each its clone. The workflow assessment reportsprocess_not_on_domain_clock. - An interrupted run can leave a clone on the literal date (only its selected value changes, it still reads its
table at its cursor); the next
run/roll_outrestores it, orTimeManager('<PROCESS_VIEW>_TM', '<DATABASE>').restore_cursor(). - An explicit
time_manager=tmat registration keeps the 0.3.5 pairing even whentmis the clock (no clone);soft_clone=Trueforces one.run(pid, time_manager=clock)on a clone reader sets the clone to the clock's date. - Document the clock once: clones copy its documentation. Migration carries the clock.
- In the admin app: the process card (Explore › Feature catalog) has a Domain clock row, the dataset builder lists the clocks first, the Report's Time drivers lists each clock with the processes on and off it.
- Without a domain clock nothing changes, except that
upload_featuresnow records the one manager the view reads (tdfs4ds.TIME_MANAGER_DETECT = Falseturns that off).
Calendar rules and scheduled refresh (0.3.7.31 and later)¶
Check tdfs4ds.__version__. Before 0.3.7.31 the dates were loaded by hand and the next one computed by hand. A
Calendar is the rule that produces the business dates: the table of dates is generated from it, extended up to
now by it, and the scheduled call needs no date at all. Without a rule nothing below applies and everything above is
unchanged.
| Rule | Business dates |
|---|---|
Calendar.monthly(day='last') / monthly(day=1) / monthly(day=15, at='06:00') |
month ends / month starts / the 15th (clamped to the month length) |
Calendar.weekly(weekday='FRI') |
every Friday |
Calendar.daily(at='02:00') |
every day |
Calendar.every('15min'), every('1h', anchor='2026-01-01') |
a fixed interval |
Calendar.from_pandas('W-FRI') |
any pandas offset alias |
Every form takes due= (when the data is available, after the business date: due='+3d 06:00'), tz= and dtype=.
The business date is never shifted by due: it stays the valid time of the features; due only decides when the
step may be added (a month-end date is not added before its data is there).
import tdfs4ds
tdfs4ds.require('0.3.7.31') # first line of a scheduled script: stop early on an older install
from tdfs4ds import Calendar
from tdfs4ds.utils.time_management import TimeManager
rule = Calendar.monthly(day='last', due='+3d 06:00')
tm = TimeManager('<DOMAIN>_CLOCK', '<DATABASE>', calendar=rule, start='2024-01-31', until='now') # generates and loads the dates
print(tm.calendar.describe(), tm.nb_time_steps, 'dates')
tdfs4ds.set_domain_time_manager(tm) # the clock of tdfs4ds.DATA_DOMAIN, as above
# an existing table of dates: record the rule it follows, or let tdfs4ds infer one
rule_found, reason = tdfs4ds.infer_calendar(['2024-01-31', '2024-02-29', '2024-03-31']) # (Calendar or None, why)
# tm.set_calendar(rule, dry_run=True) # stores the rule, changes no date; dry_run=False to write
print(tm.missing_steps(until='now')) # the dates due by now and not in the table
print(tm.extend(until='now', dry_run=True)) # what extending would append (rule, missing, statements)
The scheduled call is one line, whatever the number of processes:
res = tdfs4ds.refresh_domain('<DATA_DOMAIN>', until='now') # the same, from a process: run(data_domain='<DATA_DOMAIN>', advance_clock=True)
print(res['status'], res['missing'], res['next_due']) # res['statuses'] = {business_date: {process_id: status}}
It extends the clock by its rule (the stored one, else inferred), then rolls out the new dates in dependency order.
Defaults for this mode: on_failure='raise', check_upstream=True, TIME_MANAGER_CHECK='error'. Nothing due and
nothing after the cursor: status='up to date' and nothing runs, so the call is safe to schedule more often than
the rule. dry_run=True returns the plan and writes nothing.
Gaps. A small backlog is caught up, a large one is refused. More than max_catch_up (default 3) missing dates
raises CatchUpRefused (its .result carries missing and estimate_seconds) and nothing is written or run. Choose:
| Choice | Effect |
|---|---|
catch_up='all' |
add and roll out every missing date |
catch_up='latest' |
add only the last date; the skipped ones are recorded as gaps (setting CALENDAR_GAPS) |
a larger max_catch_up= |
the same as 'all' for this backlog |
The sanity check reports a clock that is behind (clock_behind) and recorded gaps (calendar_gap).
Look before running. tdfs4ds.domain_clock_status('<DATA_DOMAIN>') is read-only: the rule (and whether it was
inferred), the dates held, the cursor, the dates missing until now, the next due date, the recorded gaps, and per process
the last business date computed and how many steps it is behind (behind is True when anything is late).
roll_out returns what happened: {business_date: {process_id: status}}; a FeatureIngestionError carries the
same dictionary in .statuses. Read it instead of querying the follow-up table to know which date failed.
Backward compatible. TimeManager(table_name, schema_name) without calendar= is the 0.3.7.30 constructor.
run(data_domain=...) without advance_clock computes every process at one instant and does not move the clock.
refresh_domain(domain, new_dates=[...]) (explicit dates) is unchanged. The rule lives in the optional table
FS_MANAGER_SETTINGS (created by setup() / connect()); without it, the rule is inferred from the dates when needed.
Windows that follow the calendar, and changing the frequency (0.3.7.31 and later)¶
A process that needs a period must not hard-code its length (ADD_MONTHS(BUSINESS_DATE, -1)): the day the clock goes
from monthly to weekly the window would still span a month. Read the clock and its previous view: the window is
(previous, current], without gap or overlap whatever the frequency.
clock = tdfs4ds.get_domain_time_manager('<DATA_DOMAIN>') # or any TimeManager
clock.enable_previous(dry_run=True) # shows <view>_PREVIOUS; drop dry_run to create it
clock.enable_previous() # first_previous=None: from the calendar rule; a date, or 'unbounded'
# clock.disable_previous()
# TimeManager(..., previous=True) creates it with the manager
WHERE A.<DATE_COLUMN> > (SELECT BUSINESS_DATE FROM <DATABASE>.<CLOCK_VIEW>_PREVIOUS)
AND A.<DATE_COLUMN> <= (SELECT BUSINESS_DATE FROM <DATABASE>.<CLOCK_VIEW>)
<view>_PREVIOUS follows update, roll_out and run(at=) by itself. Each soft clone gets its own
<clone>_PREVIOUS; the rewrite of a process view to its clone covers both references. With DYNAMIC EXPLAIN
(DynamicPlan=SYSTEMX) only the window's partitions are read; a static EXPLAIN shows all rows, as with one scalar.
A process on the previous view, or a cumulative one (d <= clock), needs no SQL change when the frequency changes.
Change the frequency (monthly to weekly) converts the calendar in place (same table and view names, no process SQL touched). In this order:
# 1. find the hand-written windows (info hand_written_window, warning window_mismatch_calendar)
tdfs4ds.sanity_check('windows.html') # the cheap scope includes the windows check
# 2. switch those processes ONCE to the previous view (upload_features again with the new view: same process id)
clock.enable_previous()
# 3. plan: nothing is written. Read review (hand-written windows), agnostic (nothing to do) and refused
weekly = tdfs4ds.Calendar.weekly(weekday='FRI')
plan = tdfs4ds.change_domain_calendar('<DATA_DOMAIN>', weekly, dry_run=True)
print(plan['review'], plan['agnostic'], plan['refused'])
# 4. apply (force=True only after reading refused); an interrupted call is resumed by calling again with the same calendar
tdfs4ds.change_domain_calendar('<DATA_DOMAIN>', weekly, dry_run=False)
# 5. replay the history, forward only: the change never runs it
tdfs4ds.roll_out(data_domain='<DATA_DOMAIN>', time_id_start=1, force_compute=True)
# 6. keep going weekly
tdfs4ds.refresh_domain('<DATA_DOMAIN>', until='now')
refused names what blocks it now: a literal view left by an interrupted run(at=), RUNNING runs, a hard copy of the
calendar elsewhere. TimeManager.change_calendar(calendar, until='now', dry_run=True, force=False) does it for one
manager. After a half-finished change the sanity check clock reports calendar_off_rule_dates.
Parallel runs and own cursors¶
generate_execution_script(analyze_parallel_plan(seeds=...))runs the processes of a wave that share a manager in lockstep: the script moves the cursor one date at a time and runs them in parallel at that date, with a barrier before the next date. Never generate a per-workerroll_outover a shared manager: several workers would move one cursor at once.tdfs4ds.split_time_manager(process_ids, '<NEW_NAME>', clone_mode='soft', dry_run=True)gives processes their own cursor over the same dates (a soft clone, the views rewritten onto it, lineage refreshed);unify_time_managersis the inverse. A process that reads the manager only through an intermediate view is reportednot_direct.- The admin app's Report → Time drivers lists, per process, the declared and read manager (
OK,UNDECLARED,MISMATCH,DECLARED_UNUSED,NONE,UNKNOWN) and the groups: synchronised (one view), soft clones (one table of dates, own cursors), hard clones (copies), independent.
When to clone, and what to watch¶
Share one manager by default: one cursor, one business date for every process, consistent datasets. Clone only when a process must stand at another date: catching up a late process, back-filling a new one, another cadence on the same calendar, independent timelines in parallel.
| share | soft clone | hard clone | |
|---|---|---|---|
| same dates | yes | yes, always (reads the original's table) | only at copy time |
| own cursor | no | yes | yes |
- Soft clone:
load_time_stepson the original changes the clone's dates (that is the point); dropping the original's table breaks it. - Hard clone: drifts silently, a date added to the original is not in the copy.
- One
roll_outover processes on a manager AND on its soft clones (0.3.5.15): the clones' cursors move with the manager at each date, so all of them compute at the same date.roll_out(process_list)without a manager uses the attached one when they share one table of dates (the original drives). A process on a hard clone, or any other manager, is refused before anything runs: roll it out with its own manager. - Outside a shared
roll_out, moving one cursor does not move the other. Once cursors differ, a dataset joining their features at one instant mixes business dates: read itas_ofa date both computed, orunify_time_managersand re-run the late ones from the first divergent date withforce_compute=True(a history is built forward only). - Freshness is per cursor; the Report's Time drivers groups show which processes are still aligned.
A reference process in a clocked domain (0.3.7.22)¶
A data domain with a clock can also hold a reference process (rules, mappings) that reads no TimeManager: register it with upload_features(..., domain_roll_out=False) or switch it later with set_process_options(pid, domain_roll_out=False). roll_out(data_domain=...), run(data_domain=...) and refresh_domain leave it out and log which ones; run it explicitly (run(pid)) when its source changes. If its view reads a TimeManager, a warning says it goes stale between roll-outs. The sanity check and the Time managers report list it as a reference process, not as off the clock.
Inventory of the TimeManagers (0.3.7.22)¶
When a project has several managers (a clock, clones, copies), list them before changing any:
inventory = tdfs4ds.time_manager_inventory() # data_domains=[...] to scope
tdfs4ds.write_time_manager_report('time_managers.html') # .md / .csv (the findings)
Per manager: role (clock / clone of clock / soft clone / hard copy / own calendar), dates,
cursor, processes and datasets following it; findings with their fix (table missing, literal
date left by run(at=), followed by nothing, clone not at the clock's date, declared vs read,
off the clock, several managers and no clock). Reads only. App: Run & monitor → Time managers.
To bring a domain's managers onto its clock, plan first:
ALIGN moves a clone's cursor to the clock's step; REPOINT replaces a manager holding exactly
the clock's dates with a soft clone of the clock (history unchanged); REPOINT_REPLAY does the same
for a manager holding some of the clock's dates and lists in REPLAY the roll_out to run for the
missing ones; KEEP_OWN_CALENDAR (other dates) is never moved: keep it, or re-register it on the
clock and rebuild its history from the first date. A clone kept apart on purpose
(split_time_manager) goes in exclude=. Never drops a manager, never recomputes. Docs:
Design & operate → Keep the TimeManagers under control.
History already in the source: valid_time_column¶
If the source holds one row per entity and valid time, you do not need one run per date. Register the process with
valid_time_column (see fs-upload); the first run writes the whole history:
pid = tdfs4ds.upload_features(
'<DATABASE>.<HISTORY_VIEW>',
entity_id=['<ENTITY_COLUMN>'],
feature_names=['<FEATURE_1>'],
valid_time_column='<EVENT_TS>',
return_process_id=True,
)
A re-run is a no-op; an incremental load rewrites only from its own earliest valid time; a backdated correction is a
full load. The TimeManager date does not set the values' valid time for such a process. Use roll_out instead when
each date must be recomputed with the view's logic as of that date.
The guard on stored values does not check such a process, so its first run can happen at any date. A view bounded by
the manager then computes the last date before the earlier ones exist. If it ran first at the last date, roll out with
force_compute=True: without it that date is skipped as COMPLETED and a value reading across an earlier date stays as it was
(seen live: entities at a period boundary stayed unmatched, with every date reported as a success). roll_out warns when it
is about to do this, naming the process and the dates.
Long roll-outs and the connection¶
A network cut can leave the client waiting with no error, while the database session is idle. Stop it and roll out
again: roll_out(..., force_compute=True) from the first date of the range replays safely, and an interrupted date is
recomputed anyway (only COMPLETED is skipped). To make a hang fail, bound the requests with a value above the
longest statement. TDFS4DS_TD_REQUEST_TIMEOUT reaches only the connections tdfs4ds opens (reconnect_teradata,
open_session); a notebook that opens its own context passes the limit itself:
tdml.create_context(host=HOST, username=USER, password=PASSWORD, sql_timeout=3600) # seconds
``` Afterwards check the cursor, then `tdfs4ds.close_interrupted_runs(dry_run=True)` lists the follow-up rows
left `RUNNING` (`dry_run=False` closes them). A Ctrl-C or kernel stop records `FAILED,interrupted: ...` by itself.
## Replace hand-made date handling
What a clean-up ([`fs-modernize`](../fs-modernize/)) usually finds, and what replaces it.
| The project does | Replace with |
|---|---|
| a loop on dates calling `run` or `roll_out` | one `roll_out(data_domain=...)`: every date in order, upstream first |
| month-end (or weekly) dates generated by hand, `add_time_steps` in a loop, the next date computed in the scheduler | a `Calendar` rule on the clock and one `refresh_domain('<DATA_DOMAIN>', until='now')` |
| sets `tdfs4ds.FEATURE_STORE_TIME` before each run | the domain clock, or `run(..., at=...)` for one instant |
| moves a manager's cursor by hand to read a past date | `build_dataset(..., as_of=...)` for a frozen dataset; the cursor only for a check |
| ends validity periods with `UPDATE` / `DELETE` | `upload_features(..., close_absent_entities=True)` |
| a date literal in the view | the manager's date, read as a scalar subquery |
**The date in the view.** Read the business date from the manager as a scalar subquery, cast to the type of the
column it is compared with, and keep the project's own window convention (for example `[D-N, D)`), written once:
```sql
WHERE e.EVENT_DATE >= (SELECT CAST(BUSINESS_DATE AS DATE) FROM <DATABASE>.<CLOCK_VIEW>) - 90
AND e.EVENT_DATE < (SELECT CAST(BUSINESS_DATE AS DATE) FROM <DATABASE>.<CLOCK_VIEW>)
Against a TIMESTAMP(0) partitioning column cast to that type instead:
(SELECT CAST(SUBSTR(CAST(BUSINESS_DATE AS VARCHAR(40)), 1, 19) AS TIMESTAMP(0)) FROM <clock view>). A cast to
the wrong type can cost the partition elimination, and a direct CAST(BUSINESS_DATE AS TIMESTAMP(0)) is Error 7454
when the manager stores TIMESTAMP(6). Set tdfs4ds.TIME_MANAGER_CHECK = 'error' while you rewrite: a process
registered with a manager its view does not read is then refused.
A view over sources with no date of their own still has to read the clock, or it is not on the domain's calendar.
A no-op filter does it, WHERE (SELECT BUSINESS_DATE FROM <clock view>) IS NOT NULL; label it as such in a SQL
comment, because the health check may report it as a manager read that is not a time filter.
Loading the business dates. From 0.3.7.31 prefer a Calendar rule (above): TimeManager(..., calendar=rule, start=..., until='now') replaces the SQL and the reload below, and refresh_domain(domain, until='now') replaces the dates added by hand. Without it, read them from sys_calendar.calendar (a UNION ALL of SELECT DATE '...'
without a FROM is refused, Error 3888). load_time_steps replaces every step and puts the cursor back on 1, so
reload the whole calendar, earlier dates first and newer ones appended, and put the cursor back where it was:
import teradataml as tdml
from tdfs4ds.utils.time_management import TimeManager
tm = TimeManager(table_name='<CLOCK_TABLE>', schema_name='<DATABASE>')
cursor = tm.get_current_timeid() # where the clock is now
dates = tdml.DataFrame.from_query("""
SELECT calendar_date AS BUSINESS_DATE
FROM sys_calendar.calendar
WHERE day_of_week = 2 -- Mondays
AND calendar_date BETWEEN DATE '<FIRST_DATE>' AND DATE '<LAST_DATE>'""")
tm.load_time_steps(dates, 'BUSINESS_DATE') # earlier TIME_IDs keep their date: only newer ones are added
tm.update(time_id=cursor)
Soft clones. Since 0.3.6.0 roll_out moves every soft clone to the clock's TIME_ID at each step, so the
processes of a domain stay on one date. The remaining risk is run(pid) called alone on a clone reader, which
moves no cursor: drive a clocked domain with roll_out(data_domain=...) or run(data_domain=..., at=...).
soft_clone=False keeps a process on the clock itself: one cursor for the domain, so clock.update(i) then
run(pid) stays aligned too, but moving the clock to recompute one process moves every dataset of the domain.
With clones (the default) each process can run alone at its own date without moving the others. Either way the
process's dataset follows the clock (0.3.7.19). A process that must read its upstream at another date needs its
own cursor: split_time_manager, and say why in the notebook.
One call for the history. After a logic change, replay from the first date; a date already COMPLETED is otherwise skipped:
tdfs4ds.roll_out(data_domain='<DATA_DOMAIN>', time_id_start=1, force_compute=True,
on_failure='raise', check_upstream=True)
fu = tdfs4ds.follow_up_report(process_id='<PROCESS_ID>').to_pandas().reset_index()
print(fu.groupby('STATUS').size()) # one COMPLETED row per date
After a replay¶
After rebuilding a history (roll_out(data_domain=..., time_id_start=1, force_compute=True) or roll_out([...], ...)), run the cheap checks on the processes just replayed:
Look at, in this order:
| Look at | Check or finding | Good result |
|---|---|---|
| One COMPLETED follow-up row per process and date | tdfs4ds.completed_dates(pids); the segments check |
no missing date, no FAILED segment |
| Empty dates | COMPLETED,0 rows in completed_dates (column EMPTY) |
none, or each one explained |
| Dates in order | order check (date_order_findings) |
no process computed before its upstream, none ahead of it |
| No validity gap | validity_gap_without_flag in usage; it reads storage, so use scope='full' or process_usage_for(pid, closed=True) |
none: a run leaves no gap |
| Absent entities | closed_entities, when close_absent_entities=True |
no entity closed without the flag; the closed ones are the expected ones |
| The domain roll-out | rollout_refused, manager_shared_across_domains |
absent |
Fix the first finding of each process before the next replay: a replay rewrites every date from the first one.
Rules¶
-
For a
valid_time_columnprocess, the warningroll_outlogs before skipping a date alreadyCOMPLETEDis the only signal (the history guard does not apply). An ordinary process run first at a later date is refused by the history guard instead. -
roll_outis the only loop on dates. No loop around it or aroundrun, noroll_outone step at a time with a custom step between dates (closing periods, for example:close_absent_entities=Truedoes that), no write toFS_T_*: a refresh would not reproduce it. Seefs-upload, Stay inside the framework. run(time_manager=tm)computes one date;roll_outis the loop. Never describe or userunas iterating over the manager's dates. (With a FilterManager attached,runloops over the segments of that one date.)- Synchronise processes on one manager. Processes whose features are combined in a dataset must share the same TimeManager (its soft clones count: same table of dates), so their values have the same valid times.
- Build a history forward, from its first date. Each run writes its value from its business date onward
(a sequenced MERGE over
[business date, end of time)). A run at a date earlier than the first value already stored adds nothing in front of it. Since 0.3.5.16roll_outchecks this before step 1: when a process's stored values start after the first date it would roll out, it raisesValueErrorand runs nothing.roll_out(..., rebuild_history=True)deletes those processes' stored values from the first date rolled out onward (all of them in this case; logged inFS_REMOVAL_LOG, kindVALUES) and replays every date withforce_compute=True. A process whose valid time comes from a source column is not checked (see History already in the source); an unreadable start is a warning. So do not run an ordinary process first at the last date: register withrun_now=False, thenroll_outfrom step 1. - Rebuild =
roll_out(..., time_id_start=1, force_compute=True). Replayed in order from the first date, the runs rewrite every stored period with the new logic (checked live: same periods, every value replaced, no old value left). Withoutforce_compute=True,roll_outskips the dates alreadyCOMPLETEDin the follow-up table and nothing changes. - Entities that leave and come back: a process registered with
close_absent_entities=True(seefs-upload) ends, at each date, the validity of the entities its view no longer returns; one that comes back later gets a new period, the absence is a gap. Same forward rule as the values: replay from the first date.roll_out(..., close_absent_entities=True|False)overrides the recorded option for one roll-out. time_id_start/time_id_endare 1-based positions in the ordered dates, not timestamps.- A monthly calendar with lags: use month STARTS, not month ends. A lag of
-1 monthisADD_MONTHS, which clamps month ends (30 Apr - 1 month = 30 Mar, not 31 Mar), so a lag read at a month end misses the previous month's value. Month starts shift exactly; let the process read the month that just ended (< BUSINESS_DATE). - A process first run in real time blocks the backfill.
upload_featuresruns at once by default, storing values valid from today; a laterroll_outover past dates then adds nothing before them (forward rule above). Register withtime_manager=tm, run_now=False, thenroll_out. If it already happened: remove the process and its features, then register again and roll out from the first date. - Before 0.3.5.14 (check
tdfs4ds.__version__):load_time_stepsfailed with Error 3515 when the source frame already had aBUSINESS_DATE/TIME_IDcolumn (rename it), andupload_features(run_now=False, dataset_view_name=...)dropped the dataset (build it withbuild_datasetafter the roll-out). roll_outrestores the session'sFEATURE_STORE_TIMEat the end;run()restores it too.- Register the processes with
time_manager=tmandrun_now=Falsewhen they must only run under the manager: an immediate real-time run would store values valid from today, after the business dates. - Look processes up by an exact view name (as above), never with
'X' in view_name(it also matchesX_DAILY,X_2). - Pass
on_failure='raise'under a scheduler so a failed run raises (FeatureIngestionError, carryingprocess_id,n_failed,n_total,failures); the default'continue'records the failure in the follow-up table and continues,'stop'stops at the first failed segment. An ingestion of 0 rows is recordedCOMPLETED,0 rowsand is recomputed by the next run. Never testSTATUS == 'COMPLETED'to find the dates a process has computed: usetdfs4ds.completed_dates(pid)(columnEMPTYmarks the empty dates) ortdfs4ds.is_completed_status(status). A first date that returned no row does not block a laterroll_outfrom that date (0.3.7.18). - Don't compute on a failed upstream:
run(..., check_upstream=True)/roll_out(..., check_upstream=True)refuses a process when the latest row of an upstream process (from the persisted lineage graph) isFAILEDat this valid time, so re-running a fixed upstream clears it;strict_upstream=Truealso refuses onRUNNING. By default a refusedrunreturns androll_outcarries on, listing the refusals at the end. Under a scheduler addon_failure='raise': a refusal then raisesUpstreamRefusedError. Check without running withtdfs4ds.check_upstream_health(pid): its verdict separatesokfromverified, and when lineage is missing or stale it says so and gives therebuild_lineage_graph(...)command (fail-open, never a silent pass). - Generated scripts:
generate_execution_script(plan, wave_on_failure='skip_descendants')(default) skips the processes downstream of a failure and lets independent branches finish;'continue','stop_after_wave'and'raise'are the alternatives. The script's workers callrun(..., on_failure='raise'). - Re-running a fixed upstream does not repair downstream processes that already ran
COMPLETEDon its empty or stale output: re-run them withforce_compute=True. - Vantage Cloud Lake + tdstone2 Apply only — OFS manager table + JOIN the date in. A view scored by Apply runs on
the Analytical Compute Cluster (ACC). Create the manager with
TimeManager(..., storage='OFS')and reference the date through a JOIN to the manager view: the ACC rejects the scalar subquery with Error 6881. This is the one exception to the scalar-subquery rule.roll_out/run()cannot drive a view that inlines an Apply invocation (its ingestion CTAS also hits 6881): call the model'sscore()first, thenupload_featuresover the scores. A view that merely reads a tdstone2 repository table is an ordinary read and is driven like any other.