Skip to content

tdfs4ds.process_store.process_followup

tdfs4ds.process_store.process_followup

logger module-attribute

logger = logging.getLogger(__name__)

STATUS_MAX_LEN module-attribute

STATUS_MAX_LEN = 2048

EMPTY_INGESTION_STATUS module-attribute

EMPTY_INGESTION_STATUS = 'COMPLETED,0 rows'

_FOLLOWUP_UNION_COLUMNS module-attribute

_FOLLOWUP_UNION_COLUMNS = ['RUN_ID', 'PROCESS_TYPE', 'PROCESS_ID', 'START_DATETIME', 'END_DATETIME', 'VALIDTIME_DATE', 'CAST(APPLIED_FILTER AS VARCHAR(2000) CHARACTER SET LATIN) AS APPLIED_FILTER', 'STATUS']

RUN_GAP_MINUTES module-attribute

RUN_GAP_MINUTES = 10

INTERRUPTED_CLOSE_SECONDS module-attribute

INTERRUPTED_CLOSE_SECONDS = 15

INTERRUPTED_STATUS_PREFIX module-attribute

INTERRUPTED_STATUS_PREFIX = 'FAILED,interrupted: '

execute_query_wrapper

execute_query_wrapper(f)

Decorator to execute a query. It wraps around the function and adds exception handling.

This decorator is used to wrap around a function that generates a query and execute that query. It handles exceptions during query execution and prints the error message along with the query. The decorator works with both TeradataML's tdml and legacy tdml.get_context() execution methods, depending on the TeradataML version.

Parameters:

Name Type Description Default
f function

Function to be decorated.

required

Returns:

Name Type Description
function

Decorated function.

Example

To decorate a function that generates and executes a query:

@execute_query_wrapper def my_query_function(): return "SELECT * FROM my_table"

This decorator can be applied to functions that generate and execute queries with ease.

execute_query

execute_query(query, raise_error=False, fetch_results=False, quiet_errors=(), log_errors=True)

Execute a SQL query or a list of queries using the tdml module.

Parameters:

Name Type Description Default
query str or list

A single SQL query string or a list of SQL query strings.

required
raise_error bool

If True, re-raise exceptions after printing them. Default is False.

False
fetch_results bool

If True, fetch and return the results of the SQL execution. Default is False.

False
quiet_errors tuple

Lowercase substrings identifying failures the caller EXPECTS and will handle itself. A matching failure is logged at DEBUG instead of ERROR; whether it is re-raised is still governed by raise_error alone. Default () — every existing call site keeps byte-identical behaviour.

()
log_errors bool

False when the caller re-raises (raise_error=True) and logs the failure itself, so each failure is logged once.

True

Returns: The result of the SQL execution if a single query is passed. None if a list of queries is passed or an exception occurs.

create_object_if_missing

create_object_if_missing(create_query, label, follow_up=())

Run an idempotent CREATE and report honestly what happened.

This exists because of a structural trap: execute_query defaults to raise_error=False, so it logs the failure itself and returns normally — an except wrapped around it never sees anything. Every catalog-creation block written that way therefore logged an ERROR for a store that was simply already provisioned, then went on to log "has been created" for a table it had not created, while its own already-exists handling sat unreachable.

Parameters

create_query : str The CREATE statement. label : str Human-readable object name for the log lines (e.g. "TABLE DB.FS_X"). follow_up : iterable of str Statements to run once the object is known to be present, whether this call created it or found it. They must be idempotent — COMMENT ON and REPLACE VIEW are the intended uses.

Returns

bool True if this call created the object, False if it was already there.

Raises

Exception The original driver exception for any failure that is NOT "already exists" — logged at ERROR with the full message, because the half that names the fault is often the later half.

sql_literal

sql_literal(value)

Escape value for use inside a single-quoted SQL string literal.

For the DBC probes and catalog predicates that compare a name as data (WHERE DatabaseName = '…'). The caller supplies the surrounding quotes.

logger_safe

logger_safe(level, message, *args, **kwargs)

Wrapper around the global logger that only emits logs when tdfs4ds.DISPLAY_LOGS is True. level is a string like "info", "error", etc.

phase

phase(name)

Name what the statements sent inside the block are for (nesting: the innermost wins).

Nothing is sent by this; the name travels in each statement (see the module docstring) and is recorded by tdfs4ds.profile() with the block's own wall time.

is_completed_status

is_completed_status(status) -> bool

True for every successful run status: COMPLETED and COMPLETED,<note> (an empty run is COMPLETED,0 rows). Test this, never STATUS == 'COMPLETED', to ask whether a run succeeded. Pure.

is_empty_status

is_empty_status(status) -> bool

True for a run that succeeded and staged no row (COMPLETED,0 rows). Pure.

follow_up_table_queries

follow_up_table_queries()

Build the follow-up table's CREATE, its COMMENT and its public view.

Pure builder: returns the SQL without executing it. Exposed as follow_up_table_creation.__wrapped__ so the package-wide "give me the SQL without running it" convention still holds now that the function no longer carries @execute_query_wrapper.

Returns:

Name Type Description
list

the three SQL strings (table, comment, view).

follow_up_table_creation

follow_up_table_creation()

Create the follow-up table, its comment and its public view, idempotently.

Not decorated with @execute_query_wrapper since 0.3.1.211: that decorator printed the first error line and the entire CREATE statement to stdout whenever the table was already there -- the nominal case on any provisioned store. The comment and the REPLACE VIEW are idempotent and replayed either way, exactly as the decorator did.

Returns:

Type Description

None

followup_open

followup_open(run_id, process_type, process_id, timemanager=None, filtermanager=None)

Generates an SQL query to insert a new record into the follow-up table for a given run.

Parameters:

Name Type Description Default
run_id str

The unique identifier for the run.

required
process_type str

The type of process being executed.

required
process_id str

The unique identifier for the process.

required
timemanager object

An object managing time-related data. Defaults to None.

None
filtermanager object

An object managing filter-related data. Defaults to None.

None

Returns:

Name Type Description
str

The generated SQL query string.

_status_literal

_status_literal(status)

Return status truncated to the STATUS column width and escaped for SQL.

Truncation happens before escaping because escaping doubles quotes: the value that has to fit in VARCHAR(2048) is the stored (un-escaped) one. Escaping matters because a FAILED status embeds a raw Teradata error message, and several common ones quote the offending object (Object 'X' does not exist) — unescaped, that produced a malformed UPDATE whose failure was in turn swallowed, leaving the row RUNNING.

_validtime_predicate

_validtime_predicate(feature_store_time)

Return the VALIDTIME_DATE predicate matching what followup_open wrote.

followup_open writes a literal SQL NULL when FEATURE_STORE_TIME is unset and the quoted timestamp otherwise, so the close must mirror both forms. Without this predicate the UPDATE matched every RUNNING row for the same (RUN_ID, PROCESS_TYPE, PROCESS_ID, APPLIED_FILTER) whatever its valid time — and because RUN_ID is generated once per import rather than per run (see tdfs4ds.RUN_ID), a success at one time step could silently close, as COMPLETED, the stale RUNNING row left by a failed earlier time step.

_followup_close_query

_followup_close_query(run_id, process_type, process_id, status='COMPLETED', filtermanager=None, feature_store_time=None)

Build the UPDATE that closes a follow-up record. Pure — executes nothing.

followup_close

followup_close(run_id, process_type, process_id, status='COMPLETED', filtermanager=None)

Close a follow-up record: set its STATUS and END_DATETIME.

A status starting with 'FAIL' records the failure — it is an ordinary write like any other. This function does not raise on a FAILED status.

History (why this is not decorated with @execute_query_wrapper): from v0.3.1.x until 0.3.1.210 the body ended with ::

if status.startswith('FAIL'):
    raise
return query

A bare raise placed before return query, inside a function whose decorator is query = f(...) and only then execute_sql(query). The exception escaped f(...) before the wrapper reached execution, so the UPDATE was built and thrown away: FAILED could never be written, on any install. Callers then wrapped the call in except Exception: pass to absorb that raise, hiding it completely, and the row stayed RUNNING forever.

Executing through execute_query rather than the decorator is deliberate: the decorator swallows an execution error with a bare print, and this write happens precisely when something has already gone wrong — a silent failure here reproduces the original symptom. execute_query logs at ERROR and, on a dropped connection, reconnects and retries once.

Returns:

Name Type Description
bool

True when the UPDATE was executed without error.

_followup_source

_followup_source() -> Optional[str]

The run history of every attached store that offers one, as a derived table (FS_V_FOLLOW_UP of each, tagged FEATURE_STORE), or None with a single store -- then the primary's table is read exactly as before.

Run rows are keyed by PROCESS_ID, a UUID, so a row always belongs to the process of the store it came from.

_filter_manager_subquery

_filter_manager_subquery(fm: object) -> str

The FILTER_MANAGER derived table: the JSON_AGG of the manager's current row.

completed_runs_sql

completed_runs_sql(process_id: str, valid_time, filtermanager: Optional[object] = None) -> str

SELECT COUNT(*) of the COMPLETED follow-up rows of process_id at valid_time (for the manager's current segment when filtermanager is given). Pure.

The same rows follow_up_report(...) filtered by STATUS == 'COMPLETED', a non-null VALIDTIME_DATE equal to valid_time (the comparison teradataml writes: the column against the text literal) and the process id: that read built a DataFrame over the table, sorted and counted it, about 9 statements per run, where this is one.

completed_runs_at

completed_runs_at(process_id: str, valid_time, filtermanager: Optional[object] = None) -> int

How many COMPLETED follow-up rows process_id has at valid_time (see :func:completed_runs_sql).

missing_segments_sql

missing_segments_sql(process_id: str, valid_time, filtermanager) -> str

SELECT COUNT(*) of the FilterManager's segments with no COMPLETED follow-up row of process_id at valid_time (0.3.7.22). Pure.

One statement for every segment, where the per-segment loop of run() moves the manager's view and counts once per segment. A segment is matched exactly as :func:completed_runs_sql matches the current one: the JSON_AGG of the manager's columns for that filter_id (here read from the hidden table, grouped by filter_id), compared as text with APPLIED_FILTER. A segment whose text does not match counts as missing, so a mismatch only makes run() take the full path.

missing_segments_at

missing_segments_at(process_id: str, valid_time, filtermanager) -> int

How many of the manager's segments have no COMPLETED row at valid_time (see :func:missing_segments_sql).

_followup_rows_base

_followup_rows_base(filtermanager: Optional[object] = None) -> str

The follow-up rows a skip check reads: the table (or its cross-store union), restricted to the manager's current segment when filtermanager is given. The text :func:completed_runs_sql always used.

_upstream_done_after

_upstream_done_after(upstream, empty_alias: str) -> str

EXISTS of a COMPLETED row of an upstream process at the valid time of the empty row empty_alias that started after that row ended: the upstream recomputed, the empty result may be out of date.

Only a run that WROTE rows counts (status exactly COMPLETED): an upstream re-run that wrote 0 rows again gives this process nothing new to read (seen live: an empty upstream forced twice made every date of its reader recompute). The sanity check ignores 0 -> 0 re-runs for the same reason.

completed_state_sql

completed_state_sql(process_id: str, valid_time, filtermanager: Optional[object] = None) -> str

One statement, two counts for process_id at valid_time (the manager's current segment when filtermanager is given): the rows COMPLETED and the rows COMPLETED,0 rows. The same rows as :func:completed_runs_sql, which counts the first kind only; this one replaces it in the skip decision so that recognising an empty run costs no statement. Pure.

completed_state_at

completed_state_at(process_id: str, valid_time, filtermanager: Optional[object] = None)

(n_completed, n_empty): see :func:completed_state_sql.

final_empty_sql

final_empty_sql(process_id: str, valid_time, upstream, filtermanager: Optional[object] = None) -> str

SELECT COUNT(*) of the COMPLETED,0 rows rows of process_id at valid_time (current segment with filtermanager) that no run of an upstream process followed: no upstream row COMPLETED at the same valid time started after the empty row ended. With no upstream, every empty row counts. Pure.

upstream_pids

upstream_pids(process_id: str)

The upstream processes of process_id from the persisted lineage (the graph core check_upstream uses), or None when lineage cannot say (graph empty or unreadable, process absent from it): unknown is not "no upstream", and the caller then recomputes.

_resolved_upstream

_resolved_upstream(process_id, resolve_upstream)

Sorted upstream process ids (the process itself left out), or None when unknown.

_empty_is_final

_empty_is_final(process_id, valid_time, filtermanager, resolve_upstream) -> bool

Is a COMPLETED,0 rows row of process_id at valid_time still the last word? True when no upstream process completed after it. Conservative: False when the upstream is unknown or a read fails.

followup_grid_sql

followup_grid_sql(process_id: str, valid_time, filtermanager) -> str

ONE statement for the skip decision of every segment of a FilterManager: one row per filter_id with its count of COMPLETED rows and of COMPLETED,0 rows rows of process_id at valid_time. A segment is matched like :func:missing_segments_state_sql matches it (the JSON_AGG of the manager's columns for the filter_id, compared as text with APPLIED_FILTER), so the decisions taken from it are the ones that statement gives. Pure.

_call_memo

_call_memo()

_grid_key

_grid_key(process_id)

forget_followup_state

forget_followup_state(process_id, segment=None) -> None

Drop the skip state kept for process_id (a batch of it wrote a follow-up row): the whole state, or, with segment (a filter_id), that segment's entry only: the other segments' rows did not change, and a decision about the forgotten one is asked again with the historical statement.

followup_state

followup_state(process_id: str, valid_time, filtermanager=None)

{segment: (n_completed, n_empty)} for process_id at valid_time, read with ONE statement and kept for the call (roll_out / run memo): {None: (...)} without a FilterManager (the statement the skip check always sent), one entry per filter_id with one. None when no call memo is active or the read fails: the caller then asks the historical statements. Dropped by :func:forget_followup_state when a batch of the process writes its follow-up row.

final_runs_at

final_runs_at(process_id: str, valid_time, filtermanager: Optional[object] = None, resolve_upstream=None, segment=None) -> int

How many follow-up rows of process_id at valid_time make a recomputation unnecessary (0.3.7.37).

COMPLETED rows count as in :func:completed_runs_at. A COMPLETED,0 rows row counts as well when no upstream process (resolve_upstream(process_id), default :func:upstream_pids) completed at the same valid time after it ended: a source that legitimately holds no rows is not asked again at every pass. An unknown upstream (no lineage, process absent from it) leaves the empty run to be recomputed, as before. One statement, plus the upstream check only for a process that has an empty run and no completed one. segment (the filter_id the manager currently shows) lets the decision come from the call's one read of every segment (:func:followup_state) instead of one statement per segment.

missing_segments_state_sql

missing_segments_state_sql(process_id: str, valid_time, filtermanager) -> str

One statement, two counts over the manager's segments: those without a COMPLETED row, and those with neither a COMPLETED nor a COMPLETED,0 rows row. The segments are matched as in :func:missing_segments_sql. Pure.

missing_segments_state_at

missing_segments_state_at(process_id: str, valid_time, filtermanager)

(n_missing_completed, n_missing_neither): see :func:missing_segments_state_sql.

missing_final_segments_sql

missing_final_segments_sql(process_id: str, valid_time, filtermanager, upstream) -> str

:func:missing_segments_sql for a segment counting as done when it has a COMPLETED row OR a COMPLETED,0 rows row that no run of an upstream process followed (see :func:final_empty_sql).

nothing_to_compute

nothing_to_compute(process_id: str, valid_time, filtermanager: Optional[object] = None, resolve_upstream=None) -> bool

True when every run of process_id at valid_time is already final: no segment missing with a FilterManager, at least one final row without (0.3.7.22). A row is final when it is COMPLETED, or COMPLETED,0 rows with no upstream run after it (0.3.7.37, see :func:final_runs_at). False when the read fails, so run() then takes its full path and decides as before.

follow_up_report

follow_up_report(filtermanager: Optional[object] = None, process_id: Optional[str] = None)

Return a follow-up report as a tdml.DataFrame, optionally filtered by process_id and/or a filtermanager's applied filter.

Behavior by arguments
  • process_id is None and filtermanager is None: Return all rows from SCHEMA.FOLLOW_UP_NAME, sorted by START_DATETIME desc.
  • process_id is not None and filtermanager is None: Return rows for the given PROCESS_ID.
  • process_id is not None and filtermanager is not None: Return rows for the given PROCESS_ID whose APPLIED_FILTER matches the JSON_AGG of filtermanager's columns coming from its schema/view.
  • process_id is None and filtermanager is not None: Return rows whose APPLIED_FILTER matches the JSON_AGG of filtermanager (no PROCESS_ID constraint).

Parameters:

Name Type Description Default
filtermanager Optional[object]

An object exposing col_names, schema_name, and view_name. Its columns are aggregated via JSON_AGG(col1, col2, ...) to compare against A.APPLIED_FILTER.

None
process_id Optional[str]

Optional process identifier used to filter by PROCESS_ID.

None

Returns:

Type Description

tdml.DataFrame: The resulting dataframe sorted by START_DATETIME (descending).

Raises:

Type Description
ValueError

If filtermanager is provided but is missing required attributes or has an empty col_names list.

RuntimeError

If the query fails.

follow_up_report_many

follow_up_report_many(process_ids)

Return follow-up rows for several process_ids in a single query.

Batched counterpart to follow_up_report(process_id=…): issues one WHERE PROCESS_ID IN (…) query instead of one round-trip per process. Callers group the result by PROCESS_ID in pandas to reproduce the per-process aggregation. Returns a tdml.DataFrame sorted by START_DATETIME descending.

Parameters:

Name Type Description Default
process_ids

Iterable of process identifier strings. Empty/None entries are dropped; duplicates are collapsed.

required

Returns:

Type Description

tdml.DataFrame with the same columns as the follow-up table. When the

id list is empty, an empty result (WHERE 1=0) is returned so the

caller's downstream pandas logic still works.

Raises:

Type Description
RuntimeError

If the query fails.

execution_run_ids

execution_run_ids(g, gap_minutes: int = RUN_GAP_MINUTES)

The run each follow-up row belongs to, as an integer Series aligned on g.

A run is one call: a FilterManager run writes one row per segment and a roll_out one row per business date, back to back, so counting rows overstates how often a process runs (seen live: a 10-date roll-out read as "5,634 runs a day"). A run = the rows of one process with the same RUN_ID, each starting within gap_minutes of the previous row's end. The gap matters because RUN_ID is drawn once per Python process: a long-lived session (the app, a scheduler) that runs a process every day keeps one RUN_ID. Pure.

execution_starts

execution_starts(g, gap_minutes: int = RUN_GAP_MINUTES)

Start times of a process's runs (see :func:execution_run_ids), sorted.

_segment_key

_segment_key(row) -> str

The segment of a follow-up row: its applied filter, '' when unsegmented.

followup_business_dates

followup_business_dates(followup, as_of=None) -> dict

What the follow-up says about each process, in business dates (0.3.1.240).

followup: the FS_FOLLOW_UP rows (pandas). FS_FOLLOW_UP is an event log, not a temporal table; every run row carries two times:

  • START_DATETIME / END_DATETIME - when the run happened;
  • VALIDTIME_DATE - the business date it computed (the TimeManager's date or FEATURE_STORE_TIME). A real-time run leaves it NULL: its business date is then its own start.

as_of: only runs started at or before that instant count ("what was known then"). Returns {PROCESS_ID: {"last_business_date", "last_run_at", "last_failure_at", "n_runs", "segments": {segment: {"last_business_date", "last_run_at", "failed"}}}} - timestamps as pandas Timestamps (UTC). Pure.

completed_dates_frame

completed_dates_frame(rows)

The business dates each process has computed, from follow-up rows. Pure.

rows: (PROCESS_ID, VALIDTIME_DATE, APPLIED_FILTER, STATUS, START_DATETIME) tuples. Returns a pandas DataFrame, one row per (process, business date) with at least one successful run (COMPLETED or COMPLETED,<note>): PROCESS_ID, BUSINESS_DATE, N_SEGMENTS (distinct segments completed), EMPTY (True when every successful run of that date staged no row: COMPLETED,0 rows), LAST_COMPLETED_AT. Real-time runs (no business date) are left out. Sorted by process then date.

completed_dates_aggregate_sql

completed_dates_aggregate_sql(where: str = '') -> str

The grouping :func:completed_dates_frame does, done by the database (0.3.8.1): one row per (process, business date) instead of one per run and segment, which for a long history over many processes was most of what a remote client waited for. (PROCESS_ID, VALIDTIME_DATE, distinct segments, 1 when every successful run of that date staged no row, last start); the segment text is cut and normalised as :func:completed_dates_frame does. Pure.

completed_dates_frame_from_aggregates

completed_dates_frame_from_aggregates(rows)

:func:completed_dates_frame from the rows of :func:completed_dates_aggregate_sql. Pure.

completed_dates

completed_dates(process_ids=None)

The business dates each process has computed, read from the follow-up table.

A run that succeeded is COMPLETED or COMPLETED,<note>: a run whose source returned no row is recorded COMPLETED,0 rows (so that it is recomputed by the next run). Code that tests STATUS == 'COMPLETED' therefore misses those dates; use this function, or :func:is_completed_status. process_ids: one id, a list, or None for every process of the primary store. Returns the frame of :func:completed_dates_frame (EMPTY tells the empty dates apart). One read, raw SQL.

run_with_time_limit

run_with_time_limit(fn, seconds)

Run fn() in a daemon thread and wait at most seconds.

Returns (finished, result). When the call is still blocked after the limit (a dead connection never answers), finished is False and the thread is left behind: a daemon thread never stops the interpreter from exiting. An exception raised by fn is returned as the result, never raised.

close_interrupted_followup

close_interrupted_followup(run_id, process_type, process_id, exc, filtermanager=None, seconds=None)

Best-effort FAILED,interrupted: <ExceptionClassName> for a batch that is being interrupted by exc (KeyboardInterrupt, SystemExit...). Never raises, and never waits longer than seconds: on a dead connection the UPDATE would block as long as the original statement did. Returns True when the row was closed.

interrupted_rows

interrupted_rows(fu, now=None, live=None, stuck_hours=None, stuck_factor=10, min_dead_age_seconds=120)

The follow-up rows left RUNNING by a run that stopped. Pure.

fu: the frame of workflow_assessment.prepare_followup (pid, run_id, start, end, status, dkey, seg). Three kinds:

  • superseded: a RUNNING row followed, for the same process, business date and segment, by a later row (the date was run again). Whatever the later row says, the first run recorded no outcome. Not reported when live says the session of that run still exists (a second run of the same date may be in progress).
  • dead: a RUNNING row with nothing after it, when live (a set of (run_id, process_id) carried by sessions of the database) is known and lacks the run's pair, and the row is at least min_dead_age_seconds old.
  • stuck: a RUNNING row with nothing after it older than max(stuck_hours or 1 h, stuck_factor x longest COMPLETED run of the process).

Each item: pid, run_id, start, dkey, seg, kind, later_start, later_status, threshold_hours, detail.

parse_live_runs

parse_live_runs(band_texts)

{(run_id, process_id)} carried by the query bands of live sessions. Pure.

read_live_runs

read_live_runs()

Runs that a session of the database is executing now, read from DBC.SessionInfoV.QueryBand; None when it cannot be read (no right on the view, no connection): the caller then falls back to age only.

_interrupted_close_sql

_interrupted_close_sql(pid, run_id, start_key, closed_at)

close_interrupted_runs

close_interrupted_runs(process_ids=None, include_stale=False, dry_run=True, days=90)

Close the follow-up rows of runs that stopped without recording an outcome.

By default only the rows the interrupted_run finding names: a RUNNING row followed by a later row for the same process, business date and segment. include_stale=True also closes a RUNNING row with nothing after it that no session of the database carries any more (the session test must be readable). Each row gets FAILED,interrupted: no outcome recorded (closed <time>) and an END_DATETIME. A row still carried by a session is never closed. Primary store only.

dry_run=True (default) executes nothing: the report lists the rows and the SQL. Returns {dry_run, rows, closed, failed, sql, live_sessions_read, message}.