Run a project as notebooks: explore, register, roll out¶
This page describes one way to run a team's feature-store project. It is an operating model,
not a feature of the package: the code is a template you copy
(tdfs4ds/examples/project_template/, see tdfs4ds.examples_path()), and it uses the same
synthetic data and the same eight flavors as the tutorial.
The idea is small. A project folder holds numbered notebooks, one stage each, and one configuration file. No notebook writes a database, data domain, view or clock name: they all read it from the file. The same notebooks then run for any variant of the project.
project_folder/
project_config.json the only place with names and databases
project_config.py loads and checks it (project code, copy it)
00_setup.py data, feature store, clock of the data domain (once per variant)
01_explore.py read and look. Writes nothing to the store.
02_register_process.py SQL in pieces -> view -> EXPLAIN -> upload_features
03_roll_out.py history of this process alone -> check -> keep current
Each stage ends with something you can check before you go on. A notebook that fails stops the chain: the next one is not started.
Not the tutorial
The tutorial teaches the functions one by one. This page shows how a team organises its
work around them. Read the tutorial first if upload_features or roll_out is new.
The configuration file¶
The file is plain JSON:
{
"feature_store_database": "",
"source_database": "",
"data_domain": "PROJECT_TEMPLATE",
"name_suffix": "",
"time_manager_name": "PROJECT_CLOCK",
"scenario": "retail",
"start_month": "2023-01",
"end_month": "2023-12"
}
| Key | Meaning |
|---|---|
feature_store_database |
the database of the feature store. You edit it: the template refuses an empty value and says so. |
source_database |
where the source tables are. Empty means the same database. |
data_domain |
the data domain of the project. |
name_suffix |
added to every object name of the project (views, dataset, clock). Empty for the main variant. |
time_manager_name |
the clock of the data domain. |
scenario |
the tutorial flavor (retail, ...). |
start_month, end_month |
the months the clock covers. |
How the file is found¶
project_config.load() finds the file the way a .env is found:
- the environment variable
PROJECT_CONFIG: an absolute path, or a path relative to the module's folder, else to the current folder; - else
project_config.jsonin the current folder, then in each parent folder; - else
project_config.jsonnext toproject_config.py.
The file is read with utf-8-sig, so a file saved by Notepad with a byte order mark still loads.
Why the values are checked¶
These values are pasted into SQL text: a database name, a view name, a suffix. A value with
a quote or a space would break the statement, or change it. load() therefore accepts only
letters, digits, _, $ and #, and the message names the key that is wrong. Missing keys,
an empty feature store database and a malformed month are refused the same way.
The module¶
"""One configuration file for every notebook of a project.
The notebooks never write a database, data domain, view or clock name. They read it
here, so the same notebooks run unchanged for another variant (a test copy, another
source database, another flavor): point PROJECT_CONFIG at another JSON file.
This module is project code, not part of tdfs4ds: copy it and adapt it.
"""
import dataclasses
import json
import os
import re
HERE = os.path.dirname(os.path.abspath(__file__))
FILE_NAME = "project_config.json"
ENV_VAR = "PROJECT_CONFIG"
REQUIRED = ("feature_store_database", "source_database", "data_domain", "name_suffix",
"time_manager_name", "scenario", "start_month", "end_month")
# These values are pasted into SQL text: only plain identifier characters are accepted.
SQL_KEYS = ("feature_store_database", "source_database", "data_domain", "name_suffix",
"time_manager_name", "scenario")
_IDENT = re.compile(r"[A-Za-z0-9_$#]*")
_MONTH = re.compile(r"\d{4}-(0[1-9]|1[0-2])")
class ProjectConfigError(ValueError):
"""The configuration is missing, incomplete or unsafe; the message names the key."""
def _candidates(path=None):
"""The files to try, in order. Pure apart from reading the environment and the cwd."""
if path is None:
path = os.environ.get(ENV_VAR)
if path:
if os.path.isabs(path):
return [path], f"{ENV_VAR}={path}"
return [os.path.join(HERE, path), os.path.abspath(path)], f"{ENV_VAR}={path}"
found = []
folder = os.path.abspath(os.getcwd())
while True:
found.append(os.path.join(folder, FILE_NAME))
parent = os.path.dirname(folder)
if parent == folder:
break
folder = parent
found.append(os.path.join(HERE, FILE_NAME))
return found, f"{FILE_NAME} in the current folder, its parents or {HERE}"
class Config(dict):
"""The values of the JSON file, plus a few helpers."""
path = None
def name(self, base):
"""An object name of this variant: *base* followed by ``name_suffix``."""
return f"{base}{self['name_suffix']}"
def fq(self, base):
"""The name of a view or table of the feature store, qualified with its database."""
return f"{self['feature_store_database']}.{self.name(base)}"
@property
def source_db(self):
"""The database holding the source tables (the feature store's by default)."""
return self["source_database"] or self["feature_store_database"]
@property
def clock(self):
"""The qualified name of the clock of the data domain."""
return self.fq(self["time_manager_name"])
@property
def scenario(self):
"""The tutorial scenario, its tables placed in the source database."""
import tdfs4ds
return dataclasses.replace(tdfs4ds.tutorial_scenario(self["scenario"]), database=self.source_db)
def _validate(values, where):
missing = [k for k in REQUIRED if k not in values]
if missing:
raise ProjectConfigError(f"{where}: missing key(s) {', '.join(missing)}.")
if not str(values["feature_store_database"]).strip():
raise ProjectConfigError(
f"{where}: feature_store_database is empty. Edit the file: set it to the database "
"of your feature store.")
for key in SQL_KEYS:
value = values[key]
if not isinstance(value, str) or not _IDENT.fullmatch(value):
raise ProjectConfigError(
f"{where}: {key}={value!r} is not allowed; it goes into SQL text, so use only "
"letters, digits, _, $ and #.")
for key in ("data_domain", "time_manager_name", "scenario"):
if not values[key]:
raise ProjectConfigError(f"{where}: {key} is empty.")
for key in ("start_month", "end_month"):
if not isinstance(values[key], str) or not _MONTH.fullmatch(values[key]):
raise ProjectConfigError(f"{where}: {key}={values[key]!r} must look like 2023-01.")
if values["start_month"] > values["end_month"]:
raise ProjectConfigError(f"{where}: start_month is after end_month.")
def load(path=None):
"""Find the file like a .env, read it, check it, return a :class:`Config`.
Order: the environment variable PROJECT_CONFIG (an absolute path, or relative to this
module's folder, else to the current folder), else project_config.json in the current
folder, then each parent folder, then this module's folder.
"""
files, how = _candidates(path)
for candidate in files:
if os.path.isfile(candidate):
break
else:
raise ProjectConfigError(f"no configuration file found ({how}).")
with open(candidate, encoding="utf-8-sig") as handle: # utf-8-sig: a file saved with a BOM loads
try:
values = json.load(handle)
except ValueError as exc:
raise ProjectConfigError(f"{candidate}: not valid JSON ({exc}).") from exc
_validate(values, candidate)
cfg = Config(values)
cfg.path = candidate
return cfg
def _norm(name):
return str(name).replace('"', "").strip().upper()
def _same_view(a, b):
a, b = _norm(a), _norm(b)
if a == b:
return True
if "." in a and "." in b:
return False
return a.split(".")[-1] == b.split(".")[-1]
def check_names(process_frame, names, data_domain, bases=()):
"""Refuse a name clash before anything is registered.
*process_frame*: the process catalog as pandas (PROCESS_ID, VIEW_NAME, DATA_DOMAIN).
*names*: the process views this variant will register.
*bases*: the same views without the suffix; used to spot another variant in this domain.
Refuses (1) a view already registered by a process of ANOTHER data domain (the catalog
is keyed by view name: registering it again would re-point that process), (2) a data
domain that already holds this project's processes under ANOTHER name_suffix (one
domain, one clock: its roll_out would run both variants).
"""
if process_frame is None or len(process_frame) == 0:
return
domain = _norm(data_domain)
for _, row in process_frame.iterrows():
row_domain, view = _norm(row["DATA_DOMAIN"]), row["VIEW_NAME"]
in_names = any(_same_view(view, n) for n in names)
if in_names and row_domain != domain:
raise ProjectConfigError(
f"{view} is already registered by a process of the data domain {row['DATA_DOMAIN']}. "
"Registering it again would re-point that process. Set another name_suffix.")
if row_domain == domain and not in_names:
bare = _norm(view).split(".")[-1]
if any(bare.startswith(_norm(b).split(".")[-1]) for b in bases):
raise ProjectConfigError(
f"the data domain {data_domain} already holds {view}, a process of this project "
"under another name_suffix. One data domain has one clock: use another data_domain "
"for this variant.")
def __getattr__(name):
"""``from project_config import cfg``: the configuration is read on first use, so importing
this module never fails and an unsafe or incomplete file is reported by name (ProjectConfigError)
when a notebook asks for ``cfg``."""
if name == "cfg":
return load()
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
cfg["data_domain"] reads a value. cfg.name("V_MONTHLY_SPEND") adds the suffix.
cfg.fq(...) also adds the database. cfg.clock is the qualified name of the clock.
cfg.scenario is the tutorial scenario with its tables placed in the source database.
Two guards against a name clash¶
check_names runs before anything is registered. It refuses:
- a view already registered by a process of another data domain. The process catalog is keyed by the view name, so registering the view again would re-point that process.
- a data domain that already holds the project's processes under another
name_suffix. A data domain has one clock; itsroll_out(data_domain=...)would run both variants.
tdfs4ds has its own guard for the first case: tdfs4ds.PROCESS_DOMAIN_CHECK is 'warn' by
default (the process is moved, with a warning), 'error' raises
ProcessDomainConflictError before anything is created, 'off' skips the check;
upload_features(force_domain_change=True) skips it for one call. The template check is
earlier and stricter, and it covers the second case, which tdfs4ds cannot know about.
The stages¶
00 - Setup¶
It writes the source data (and keeps it when it is there), creates the feature store when it
is missing, and creates the clock: a monthly calendar over the months of the configuration,
declared the clock of the data domain with tdfs4ds.set_domain_time_manager.
clock = TimeManager(cfg.name(cfg["time_manager_name"]), cfg["feature_store_database"],
calendar=tdfs4ds.Calendar.monthly(day="last"), start=start, until=until)
tdfs4ds.set_domain_time_manager(clock, data_domain=cfg["data_domain"])
01 - Explore¶
It reads the source: counts, dates, an aggregate per month, a chart drawn in the database
with tdfs4ds.plot_in_database. It writes nothing to the feature store, so you can run it
as often as you like.
02 - Register the process¶
The SQL is built in readable pieces, one Python variable per piece: the period taken from the clock, the source rows of that period, the statistics, then the view.
period_end = f"CAST((SELECT BUSINESS_DATE FROM {cfg.clock}) AS DATE)"
period_start = f"ADD_MONTHS({period_end}, -1)"
source_rows = f"""source_rows AS (
SELECT {S.entity} AS ENTITY, {S.amount} AS AMOUNT
FROM {S.table('events')}
WHERE {S.event_date} > {period_start}
AND {S.event_date} <= {period_end}
)"""
The period comes from the clock, never from the data. That is what lets roll_out replay
every date: each date moves the clock, and the view follows it.
Then the view is created, and EXPLAIN shows how the table is read. Look for a read of the
partitions of the period, not an all-rows scan of the whole table. Then:
process_id = tdfs4ds.upload_features(
df=PROCESS_VIEW,
entity_id=[S.entity],
feature_names=FEATURE_NAMES,
metadata={"project": "project_template", "variant": cfg["name_suffix"]},
primary_index=[S.entity],
dataset_view_name=DATASET_VIEW,
dataset_time_manager=True,
run_now=True,
return_process_id=True,
)
entity_idis a list of columns.run_now=Trueregisters and computes only the current date of the clock. The history is the next stage.dataset_time_manager=Truemakes the dataset follow the clock.document=Truewould add the documentation. It needs an instruct model, so the template leaves it out.
Because the view reads the clock of the data domain, registration finds it and gives the
process its own soft clone of the clock (<view>_TM: same dates, own cursor). The log
says so. See Manage time with the domain clock.
The notebook does not take this on trust. Before the registration it sets
tdfs4ds.PROCESS_DOMAIN_CHECK = "error", and after it, it checks that the process follows a
clone of its own:
dep = tdfs4ds.time_manager_dependency(process_id)
if not dep["declared"] or dep["declared"] == cfg.clock.upper():
raise SystemExit(f"{PROCESS_VIEW} follows {dep['declared'] or 'no TimeManager'}, not a clone of its own: "
"roll out the whole data domain, not this process alone")
A view that reaches the clock through another view keeps the shared clock. It then has to be rolled out with the whole data domain, never alone.
03 - Roll out¶
It builds the history of this process alone.
result = tdfs4ds.roll_out([pid], time_id_start=1, force_compute=True,
on_failure="raise", check_upstream=True)
The process id is found from the view name in the process catalog. Before the call, the
notebook shows tdfs4ds.domain_clock_status(domain) and tdfs4ds.dataset_time_managers()
(does the input dataset follow the clock?). roll_out returns {date: {process id: status}};
the notebook stops when a status does not start with COMPLETED. Then
tdfs4ds.completed_dates(pid) shows the history.
A history is built forward
Start from the first date (time_id_start=1) with force_compute=True. A date already
computed is skipped otherwise.
Alone, or the whole domain?¶
A process can be rolled out alone when its input follows the clock (a dataset built with
dataset_time_manager=True, or a source filtered by the clock) and it has its own clone.
Moving the clone then does not disturb any other process.
Roll out the whole domain with tdfs4ds.roll_out(data_domain=...) when several processes
depend on one another, or when they must share every date: the clock drives and every clone
follows, in dependency order.
To keep a process current afterwards, add the dates now due and compute them:
Variants¶
The same notebooks, another variant: copy the JSON, change what differs, and point
PROJECT_CONFIG at it.
| What changes | Keys |
|---|---|
| a test copy next to the real one, in the same database | data_domain and name_suffix |
| another source database | source_database |
| another flavor of data | scenario |
Two variants in one database need their own data_domain and their own name_suffix.
The storage tables follow the data domain, but the views, the datasets and the clock are
named objects of the database: without a suffix, the second variant would replace the
first one's views. check_names catches both mistakes.
To run all the notebooks for one variant, set PROJECT_CONFIG and run them in order, for
example with papermill or jupyter nbconvert --execute, stopping at the first failure.
That is optional, and it is a shell script, not tdfs4ds.
Sharing the configuration between folders¶
A second project folder (a use case built on the first one's features) must not copy the
file. Its own small project_config.py loads the first folder's module and re-exports its
names, so both folders always read the same values:
import importlib.util
import os
_first = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "first_folder", "project_config.py")
_spec = importlib.util.spec_from_file_location("first_project_config", _first)
_module = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_module)
cfg = _module.load()
check_names = _module.check_names
ProjectConfigError = _module.ProjectConfigError
How this becomes production¶
The notebooks are a way to design and prove a workflow. Production runs the definitions, not the notebooks:
- the processes, datasets and managers are exported as definitions and deployed with the bundle (Deploy definitions with CI/CD); the configuration file plays the role of the environment file: one set of values per environment;
- history and schedule: From prototype to production;
- the clock and its calendar: Manage the clock, end to end.
What this gives a team¶
- One place for names. A review reads one file.
- The same notebooks run on a colleague's variant, on a test database, on another system.
- A stage is small and has a result to check. A failure stops where it happens.
- The SQL in pieces is easy to read and to change; the period always comes from the clock.
- The notebooks are plain
.pyfiles with cell markers: clean diffs in git.