API reference¶
The public API, generated from the docstrings and grouped by what you use each name for.
Build steps¶
step ¶
step(fn=None, /, *, name=None, output=None, outputs=None, nogil=False, id=None, suppress_checks=())
Make a function a step, directly or as a decorator.
Only needed to override defaults: plain functions convert wherever a step
is expected. Two plain functions can't be joined with | (Python has no
| for functions): write step(f) | g or flow(f, g).
Plain arguments are request fields (or earlier steps' outputs), read per
record by name. param() arguments are configuration from the params
document, fixed for the run; never declare request data as a param()::
def affordable(ratio: float, min_ratio: float = param(0.3)) -> bool:
return ratio >= min_ratio # ratio: per record; min_ratio: params document
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
the step's name in paths (default: the function's name). |
None
|
output
|
str | None
|
the one name it writes (default: the function's name, or
|
None
|
outputs
|
tuple[str, ...] | None
|
several names it writes; the return annotation must be a
|
None
|
nogil
|
bool
|
release the GIL in compiled code. |
False
|
id
|
str | None
|
an optional opaque 12-hex durable id ( |
None
|
suppress_checks
|
Sequence[str]
|
check aliases or codes to silence for this step (by alias, e.g. |
()
|
Example::
@step(output="term_cap", suppress_checks=["int64_overflow"])
def cap_by_income(term_cap: float, cap: float = param(48.0)) -> float:
return min(term_cap, cap)
@step(outputs=("band", "band_score"))
def banding(ratio: float) -> tuple[int, float]:
return (1, 10.0) if ratio > 2 else (0, 0.0)
double = step(lambda x: x * 2, name="dbl") # writes "dbl"
frame_step ¶
frame_step(fn=None, /, *, name=None, reads=None, writes=None, id=None, suppress_checks=())
Make a DataFrame -> DataFrame function a step, directly or as a decorator.
Arguments after the frame are param()s, set from the params document
like a plain step's. With both reads and writes declared, the step can
be .relabel()ed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reads
|
list[str] | dict[str, Any] | None
|
the columns it reads. |
None
|
writes
|
list[str] | dict[str, Any] | None
|
the columns it adds or replaces; |
None
|
suppress_checks
|
Sequence[str]
|
check aliases or codes to silence for this step. |
()
|
Example::
@frame_step(reads=["client_id"], writes=["bureau_score"])
def join_bureau(df: pl.DataFrame, floor: float = param(300.0)) -> pl.DataFrame:
return df.join(BUREAU, on="client_id", how="left").with_columns(
pl.col("bureau_score").clip(lower_bound=floor))
flow ¶
flow(*steps, name=None, inputs=None, id=None, suppress_checks=())
Run steps in written order; a later write of a name wins.
a | b | c builds the same flow. Anonymous flows inside are merged in; a
named flow stays one unit (its members sit under its name). Plain
functions have no |, so a flow of only functions is written flow(f, g)
or step(f) | g.
The output holds the input columns plus the values nothing reads;
intermediates are dropped. .emit(...) keeps them (one version or every
version of a name) and .drop(...) removes columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Sequence[str] | None
|
request fields a step reads that resemble a name another step
produces, e.g. |
None
|
suppress_checks
|
Sequence[str]
|
check aliases or codes to silence for every step inside. |
()
|
Example::
term = flow(term_cap, cap_by_income, cap_by_sector, name="term")
term.emit("term_cap@*").drop("requested_term").run(df)
dag ¶
dag(*steps, name=None, inputs=None, id=None, suppress_checks=())
Run steps in dependency order: a step reading a name runs after the step writing it.
Two members writing one name is an error: use flow for a waterfall, or
.relabel(writes=...) one of them when they are different values. A
single unnamed step is returned unchanged. As with flow, intermediates
are dropped from the output unless kept with .emit(...); .drop(...)
removes columns. inputs declares request fields the typo heuristic would
otherwise flag, as flow(inputs=...) does; suppress_checks silences check
aliases or codes for every step inside.
Example::
affordability = dag(affordable, ratio, disposable_income, name="affordability")
affordability.emit("ratio", "disposable_income").run(df)
branch ¶
branch(condition, *arms, modifies, name, id=None, suppress_checks=())
Run one arm per row: a bool condition picks the first arm (true) or the second; an int picks by index.
A bool condition sends True to arm 0, while an int picks arm i, so
switching a flag from bool to 0/1 swaps the arms. An arm may be one step
or a flow of several; the arms of one branch must agree on the type of
each name they modify. A single arm is allowed for a bool condition: the
false rows run nothing and keep their earlier modifies values, or null
when there is none, so a later step reading it needs missing_as.
A bare column name is a condition too: branch("on_card", ...) reads the
existing bool column on_card, the same as an identity step
def on_card(on_card: bool) -> bool: return on_card.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
modifies
|
Sequence[str]
|
the names the branch passes on; they keep their earlier
value on rows whose arm doesn't write them. Anything else an arm
(or the condition) writes stays inside the branch: reading it
after the branch, or emitting it by bare name, is an error, but
|
required |
suppress_checks
|
Sequence[str]
|
check aliases or codes to silence for every step inside. |
()
|
Example::
by_sector = branch(is_private, cap_private, cap_public, modifies=["term_cap"], name="by_sector")
flow(term_cap, by_sector, name="term").emit("is_private@term/by_sector/is_private")
loop ¶
loop(condition, body, *, carries, max_iterations, name, id=None, suppress_checks=())
Run body while condition holds, checked per row before each iteration.
The body may be one step or a flow of several. A row that reaches
max_iterations stops there, without an error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
carries
|
Sequence[str]
|
the names each iteration updates: the condition and body see the latest values, the body writes every one of them, and they are all that leaves the loop. |
required |
max_iterations
|
int
|
the most iterations any row may take; required, since compiled code can't be interrupted. |
required |
suppress_checks
|
Sequence[str]
|
check aliases or codes to silence for every step inside. |
()
|
Example::
def unpaid(balance: float) -> bool:
return balance > 0.0
@step(output="balance")
def pay(balance: float, payment: float) -> float:
return balance * 1.01 - payment
@step(output="months")
def tick(months: int) -> int:
return months + 1
repay = loop(unpaid, flow(pay, tick, name="month"), carries=["balance", "months"],
max_iterations=360, name="repay")
each ¶
each(column, item, *, name=None, execution_mode=EachMode.PER_ROW, output=None, id=None, suppress_checks=())
Run item on every element of the list column column, writing the enriched list back.
item is a flow of ordinary steps reading the item's fields; its outputs
are added as new fields of each item. The list is read under column and,
by default, written back to it in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
str | None
|
the column to write the enriched list to (default: |
None
|
suppress_checks
|
Sequence[str]
|
check aliases or codes to silence for every step inside. |
()
|
Example::
def heavy(weight: float = missing_as(0.0), heavy_kg: float = param(20.0)) -> bool:
return weight > heavy_kg
pipeline = flow(each("items", flow(heavy, name="item"), name="items"), name="order")
optimise ¶
optimise(count, evaluate, *, score='score', disqualify=None, max_candidates, name, record=None, id=None, suppress_checks=())
Run evaluate once per candidate and keep the best one, per row.
evaluate is a flow of ordinary steps that read index (the candidate,
from 1 to count) plus the request data, and write score (and any other
values). count is a step producing one int, the number of candidates
(e.g. (1 << len(loans)) - 1). The candidate with the highest score
wins; negate the score to minimise. A tie keeps the earlier candidate.
disqualify is an optional bool step run after evaluate; a disqualified
candidate is counted and excluded. To skip expensive work, have evaluate
return -inf for a candidate you reject cheaply and disqualify -inf.
The winner is best_index (-1 when no candidate survived), its score
best_score (-1e300 when there is no winner), and the counts evaluated
/ disqualified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
score
|
str
|
the |
'score'
|
max_candidates
|
int
|
the most candidates any row may test, the loop's bound.
|
required |
record
|
Any
|
an |
None
|
suppress_checks
|
Sequence[str]
|
check aliases or codes to silence for every step inside. |
()
|
Example::
@step(output="count")
def bundles(items: Columnar[Item]) -> int:
return (1 << len(items.price)) - 1
@step(output="score")
def margin(index: int, items: Columnar[Item]) -> float:
total = 0.0
for j in range(len(items.price)):
if (index >> j) & 1:
total += items.price[j]
return total
best = optimise(bundles, flow(margin, name="evaluate"), max_candidates=1 << 12, name="best")
out = flow(best, name="order").run(orders) # best_index, best_score, evaluated, disqualified
EachMode ¶
Bases: Enum
How an each step runs its child over a list column (kept for compatibility; both now scatter).
allow_fallback ¶
allow_fallback(fn)
Accept how this step runs: no FallbackWarning, and strict_compile=True allows it.
On a step it says the author accepts a step compiled modes can't put in a
kernel; Executable.fallbacks() still reports it, marked
@allow_fallback. On a function a step calls it marks an intentional
Python boundary, so the step runs in Python rather than compiling it.
Prefer a step that compiles; use this only for an intentional Python boundary.
Example::
@allow_fallback
def order_total(items: list[dict]) -> float:
return sum(item["price"] for item in items)
helper ¶
helper(*, signatures)
Mark a function for compiled use with its supported input and output types.
Example::
@helper(signatures=[((float,), float), ((int,), int)])
def discounted(price: float | int) -> float | int:
return round(price * 0.9, 2)
param ¶
param(default=_NO_DEFAULT, *, required=False, shared_key=None, on_invalid='error', **field_kwargs)
Declare a tunable param as a function argument's default.
Params are configuration from the params document, the same for every record of a run; they are not request data. A request field is a plain argument, read from the record by its name::
def affordable(ratio: float, # request field / earlier step's output
min_ratio: float = param(0.3)) -> bool: # config from the params document
return ratio >= min_ratio
Every extra keyword (ge, le, description, ...) is passed to pydantic's
Field, so the params document is validated against it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
Any
|
the value used when the params document doesn't set it. Any
value works, including |
_NO_DEFAULT
|
required
|
bool
|
declare a param with no default; a params document that doesn't set it is invalid. |
False
|
shared_key
|
str | None
|
read the value from the document's top-level |
None
|
on_invalid
|
OnInvalid
|
|
'error'
|
Example::
def cap_by_income(term_cap: float,
cap: float = param(48.0, ge=6, le=60),
base_rate: float = param(5.0, shared_key="base_rate")) -> float:
return min(term_cap, cap)
cap_by_income(60.0) # 48.0: the function is still plain Python
A bool or None default comes back as a marker that tests like its
value (if flag: works on a direct call), but flag is False doesn't
hold; write if not flag:. Param names must be Python identifiers.
param_table ¶
param_table(columns, default=_NO_DEFAULT, *, required=False, shared_key=None, seeded_from=None, allow_override=False)
Declare a table-valued param as a function argument's default: rows from the params document.
columns maps each column to int, float or bool. In the params
document the rows sit where a param() value would, as a list with one
dict per row and a value for every column; they are checked when the
document arrives. The step receives the table as a namedtuple with one
read-only numpy array per column (rates.band[i], len(rates.band)),
the same in every mode, so a compiled kernel reads it too. Editing the
rows or how many there are never recompiles; only changing columns
does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
Any
|
the rows used when the params document doesn't set them. |
_NO_DEFAULT
|
required
|
bool
|
declare a table with no default rows; a document that doesn't set it is invalid. |
False
|
shared_key
|
str | None
|
read the rows from the document's top-level |
None
|
seeded_from
|
str | None
|
the config document the default rows were read from. Staging a config version
whose params document sets this table warns with |
None
|
allow_override
|
bool
|
the params document is meant to replace the seeded rows; no warning for this table. |
False
|
Example::
def rate(score: int, rates: ParamTable = param_table({"floor": int, "rate": float},
default=[{"floor": 0, "rate": 0.2}])) -> float:
r = 0.0
for i in range(len(rates.floor)):
if score >= rates.floor[i]:
r = rates.rate[i]
return r
# params document: {"rate": {"rates": [{"floor": 0, "rate": 0.2}, {"floor": 600, "rate": 0.1}]}}
missing_as ¶
missing_as(value)
Declare that a null in this input is replaced by value.
To let the null through instead, annotate the input T | None
(missing_as(None) is refused). A bool fill comes back as a marker
that tests like its value on a direct call; use if not x:, not x is False.
Example::
def score(bureau_score: float = missing_as(0.0),
deceased: bool = missing_as(False),
bonus: float | None = None) -> float:
return bureau_score * 0.01
ParamTable
module-attribute
¶
ParamTable = Any
The annotation of a param_table() argument: a namedtuple with one read-only numpy array per column.
load_flow ¶
load_flow(path, *, components=None, documents=None, project_dir=None)
Load a flow file into the same Step tree flow/branch/loop would build by hand.
components names (or is) the module or package whose public functions
and Step instances a step: node can reference by name; it defaults to
the file's own components: key. documents maps a name to a parsed
tree, table or scorecard document that step: can reference instead.
path may also be the parsed flow itself, a mapping, in which case project_dir
is where flows/ and relative components resolve from.
Example::
# flow.yaml: {flow: credit, steps: [{step: approved}]}
load_flow("flow.yaml", components="credit_risk.steps")
Configurable steps¶
TreeConfig ¶
Bases: ConfigurableStep
A decision tree as a step: a v3 tree document or decikit 0.3 flat rules, run once per row.
The tree's output columns are the step's outputs (<rule>.<column> per
rule in a prioritized document with mode: "all"). A threshold, bound,
value or pattern written {"param": "hi_thresh", "default": 0.7} is a
param of the step, so retuning it never rebuilds or recompiles anything.
A feature's type is inferred from how the tree uses it (string_match:
str; only is_true/is_false: bool; otherwise float); declare it
in feature_types to compare an int64 column exactly.
A mode: "all" tree writes one output per rule and column, and a tree of
more than part_outputs outputs (64 by default) is run as several parts
of whole rules, each its own node <name>/part_<k>, because compile time
grows with the square of the outputs one call returns. A part costs about
15-20 us per request, so a bigger part_outputs (or None, no parts) makes
run() on a record faster and the first build slower (a 521-rule tree takes about
4 minutes to bind unsplit); a smaller one (32) makes run() over a big frame
up to twice as fast. A tree with params is never split.
null_handling says what a null numeric or boolean feature does.
"otherwise" (the default, as decikit 0.3 trees behave): a test on it
is unknown, NOT keeps it unknown, AND/OR follow three-valued logic and
the node takes its otherwise branch (a cases node tries its next case).
"error": a null is a MissingInputError. A string match has its own
null_handling (no_match, match or error).
path_output names an extra String column holding the id of the leaf
that answered (null when the default row answered); in mode: "all"
one per rule, <rule>.<path_output>. trace_output names a String
column holding the ordered path, the ids of every node walked joined
with > ("root>mid>hi", or "root>mid" when mid's branch leads
nowhere), so the decision record says how the tree got there, also
through a node shared by two parents. In mode: "first_match" over
several rules it is the path in the rule that answered (else the last
rule's); in mode: "all" one per rule.
path_columns is a function fn(route, tree) -> dict that adds the
dict's keys as output columns, for a route format of your own. It is
called once per route when the step is built, never per row: the tree
is unfolded so every route, each branch of a node told apart, ends at a
leaf of its own whose row holds the route's columns (so path_output
names a leaf even where the default row answers). A Route has
visits, a Visit(node_id, node, branch, child) per node passed, and
result_idx. Set it in Python, or with path_columns: fn on a flow
file's step: node naming a function in components; a document
never holds it. A first-match tree must have one rule.
Params are per call, not per row: params={"risk_tree": {"hi_thresh": 2.0}}
moves the threshold for every row of that run. For a threshold that
differs per row, compare against a computed feature over a column
instead, e.g. {"op": ">", "feature": {"type": "computed", "expression":
"ratio - customer_limit"}, "threshold": 0.0} reads customer_limit from
each row. A param name is a Python identifier (it becomes a field name):
write rule CF-0412's threshold as {"param": "cf_0412_amount"}.
nodes maps each node id to its node: the locators a session breaks on,
e.g. session.break_at("risk_tree#high").
Example::
risk = TreeConfig.load({
"type": "tree", "name": "risk_tree",
"tree": {
"nodes": [
{"id": "root", "data": {"type": "unary", "condition": {
"op": ">", "feature": "ratio", "threshold": {"param": "hi_thresh", "default": 0.7}}}},
{"id": "high", "data": {"type": "leaf", "result_idx": 0}},
],
"edges": [{"source": "root", "target": "high", "data": {"sourceIndex": 0}}],
"output": {"data": [{"risk_band": 1}], "default": {"risk_band": 0},
"dtypes": [["risk_band", "Int64"]]},
},
})
risk.run(df) # writes risk_band
risk.run(df, params={"risk_tree": {"hi_thresh": 2.0}})
# With "path_output": "risk_leaf" in the document, run() also writes risk_leaf: "high" or null;
# with "trace_output": "risk_path", risk_path: "root>high", or "root" when ratio <= 0.7.
The same tree as flat rules: "tree": {"type": "flat_rule", "rule": {"rule": {"type": "unary",
"condition": {...}, "then": {"type": "leaf", "result_idx": 0}}}, "output": {...}}.
DecisionTableConfig ¶
Bases: ConfigurableStep
A decision table as a step: each record takes the outputs of the first row it matches, else default.
columns declares every column of the table (polars dtype names, or
{"type": "List", "inner": "String"}); expression says how a record
matches a row; outputs are the columns written, one output column each.
A null input never matches. A number is compared as float64, exact up to
2**53. Declare a variable in variable_types ({"channel": "int"}) to
compare it as int64, exactly: its eq / in / between conditions then
use integer columns only, and a step that writes it must write an int.
An int variable's null is -2**63, so that value never matches.
rows are the rows inline, or
{"table": "bands"} to read them from the params document, where they
are checked against columns when the document arrives. Editing rows,
or how many there are, never recompiles. decikit 0.3's
"parameters": {"data": [...], "dtypes": {...}} spelling loads too.
Row r is the locator <name>#<r> a session breaks on.
Example::
bands = DecisionTableConfig.load({
"type": "decision_table", "name": "bands",
"columns": {"lo": "Float64", "hi": "Float64", "band": "String"},
"rows": [{"lo": None, "hi": 30.0, "band": "low"}, {"lo": 30.0, "hi": None, "band": "high"}],
"expression": {"type": "between", "variable": "score",
"lower_bound_column": "lo", "upper_bound_column": "hi"},
"outputs": ["band"], "default": ["other"],
})
bands.run(df) # writes band
Rows from params (a parameter table): write "rows": {"table": "<param>"}
and the rows become a required param of the step, named <param>. The
params document holds them under the step's node path, as a list with
one dict per row, a value for every declared column (None for null)::
pricing = DecisionTableConfig.load({
"type": "decision_table", "name": "pricing",
"columns": {"product": "String", "lo": "Float64", "hi": "Float64", "rate": "Float64"},
"rows": {"table": "prices"},
"expression": {"type": "and", "expressions": [
{"type": "eq", "variable": "product", "value_column": "product"},
{"type": "between", "variable": "amount", "lower_bound_column": "lo", "upper_bound_column": "hi"}]},
"outputs": ["rate"],
})
pipeline = flow(pricing, name="loans")
pipeline.parameters()
# {'loans/pricing': {'prices': {'type': 'table', 'schema':
# {'product': 'String', 'lo': 'Float64', 'hi': 'Float64', 'rate': 'Float64'}, 'required': True}}}
params = {"loans": {"pricing": {"prices": [
{"product": "loan", "lo": None, "hi": 10000.0, "rate": 0.20},
{"product": "loan", "lo": 10000.0, "hi": None, "rate": 0.15},
]}}}
pipeline.run(df, params=params) # df has product and amount; writes rate
The table has no default: pipeline.parameters().defaults() shows it
as [] (no rows, so every record takes default), and a document
without it is a ParamsError ("param 'prices' is required but
missing"). The rows are checked against columns when the
document arrives: an undeclared or missing column, or a value of the
wrong type, is a ParamsError naming the step, the param, the row and
the column. A table on its own (not inside flow) is keyed by its name
alone: {"pricing": {"prices": [...]}}. Changing the rows, or how many
there are, never recompiles. A String output of such a table must be
an {"type": "Enum", "categories": [...]} column, so its values are
known before the rows arrive.
In a between condition, rows with the same eq values (here, one
product's bands) form one ladder: its first row may leave its lower
bound None and its last its upper, and a missing bound between is the
neighbouring band's.
Run¶
Engine ¶
Bases: BaseRegistryModule
Turns a step (or its IR) into an Executable: a settings document, named by its type tag.
The built-in tags are "interpreted", "stepped" and "fused"; an
installed package adds an engine as an entry point in decikit.engines.
Engine.resolve(tag) gives the class, and pipeline.compile(tag) or
pipeline.compile(instance) binds one.
Attributes:
| Name | Type | Description |
|---|---|---|
params_validation |
Literal['eager', 'lazy']
|
|
Example::
exe = Engine.resolve("fused")(params_validation="lazy").bind(pipeline)
out = exe.run(df, params={"term": {"cap_by_income": {"cap": 36.0}}})
bind
abstractmethod
¶
bind(step_or_ir)
An Executable running step_or_ir: a step, a plain function or an IR node.
Example::
exe = FusedEngine().bind(pipeline)
Executable ¶
A bound pipeline: run a polars frame or one record (a dict).
report describes the params validation of the latest call on the
calling thread; step is what it was bound from (a step, a function or
an IR) and engine the engine document that bound it. Safe to call from
many threads at once.
Example::
exe = pipeline.compile("fused")
exe.run(df) # a polars DataFrame
exe.run({"net_income": 4100.0, ...}) # a dict
fallbacks ¶
fallbacks()
Every step that runs outside the shared kernel, keyed by step path, with the reason why.
A step the author accepted with @allow_fallback is reported too, with
"@allow_fallback: " in front of its reason. A kernel numba refuses
only when it is launched runs each of its steps in Python from then on,
and each is listed then, as "split at launch: <numba's error>". Fused
mode warns about each with a FallbackWarning, stepped mode does not.
Example::
exe.fallbacks() # {"order/order_total": "reads 'items' as list[dict], which no kernel takes"}
output ¶
output(state)
The output frame of a finished run: unread frame columns, then every produced output.
prepare ¶
prepare(df, params=None, n=None)
The state and params a runner starts from; eager validation happens here.
Example::
state, params = exe.prepare(df)
for checkpoint in exe.runner.iterate(exe.plan, state, params):
...
run ¶
run(data, params=None, trace=None)
Run a polars frame, or one record given as a dict of input values.
A DataFrame returns a DataFrame: the input columns plus every
output, minus drops. A LazyFrame is collected first. A dict returns
a dict of the output row, through the same kernels; a pipeline without
frame steps never builds a polars frame for it, so this is the fast
path for one record.
params is treated as immutable: pass the same document object call
after call and it is never hashed or validated again, so a value
edited in place is not seen. To change a value, pass a new dict
(copy.deepcopy(doc), then edit the copy). trace is an optional
TraceSink: when it is not given, nothing is captured (no-op).
Example::
out = exe.run(df, params={"shared": {"min_ratio": 0.4}})
exe.run({"net_income": 4100.0, "expenses": 1500.0})["disposable_income"] # 2600.0
session ¶
session(df, params=None)
A debug Session over df, paused before anything runs.
Example::
s = exe.session(df)
s.break_at("term")
s.resume()
warn_shadowed_tables ¶
warn_shadowed_tables(params)
Warn with ShadowedTableWarning for each seeded_from table that the params document params sets.
RequestHandler.stage() calls this for the version it stages.
Example::
exe.warn_shadowed_tables({"pricing": {"priced": {"ladder": [{"floor": 0, "rate": 0.3}]}}})
describe ¶
describe(step)
The static structure of step as a FlowDescription.
Layers over the IR and wiring: nodes and control edges come from the IR
tree, data edges and value slots from resolve (which knows which node
wrote each value). A wiring problem raises the engine's own WiringError.
Also importable as decikit.describe.
Example::
desc = describe(pipeline)
[n.path for n in desc.nodes]
[e.values for e in desc.edges if e.kind == "data"]
Extend¶
Step ¶
Bases: ABC
Base of everything that can sit in a pipeline.
Steps combine with | (in written order), flow, dag, branch and
loop; a plain function converts automatically wherever a step is
expected. Every step turns itself into IR through to_ir.
Example::
pipeline = step(disposable_income) | ratio | affordable
pipeline.parameters().defaults()
kind
class-attribute
¶
kind
What sort of step this is: "function", "frame", "sequence", "dag", "branch", "loop", "each", "optimise" or "configurable".
compile ¶
compile(engine=None)
Compile the pipeline once; call the returned Executable many times.
engine is an engine's tag ("interpreted", "stepped", "fused",
or an installed engine's) or an Engine instance, e.g.
FusedEngine(strict_compile=True), which raises instead of falling back.
None takes the default engine: fused, unless a decikit.engine(...)
block sets another.
Example::
exe = pipeline.compile()
exe.run({"income": 1000.0, "debt": 200.0})
with decikit.engine("interpreted"):
pipeline.compile() # interpreted
named ¶
named(name)
A copy of this step under another name, e.g. to place it twice.
Example::
flow(cap, cap.named("cap_again"))
parameters ¶
parameters()
Every param this step needs, by node path, without running anything.
Example::
pipeline.parameters().defaults() # a complete params document of defaults
relabel ¶
relabel(*, reads=None, writes=None)
A copy that reads and writes other names at its boundary.
reads maps a name the step reads to the column it should read
instead; writes maps a name it writes to the name to write. Names
produced and consumed inside the step follow its writes. Relabels
chain: a key may be the original name or the current one. A key the
step doesn't read or write is an error.
Example::
ratio.relabel(reads={"instalment": "monthly_instalment"}, writes={"ratio": "dti"})
ratio.relabel(writes={"ratio": "dti"}).relabel(writes={"dti": "dti_pct"}) # writes dti_pct
run ¶
run(data, params=None, trace=None, *, engine=None)
Run the step over a polars frame or one record (a dict); trace is an optional TraceSink.
A frame returns a frame and a dict returns a dict, as Executable.run.
engine is a tag or an Engine instance, as for compile; None
takes the default engine: fused, unless a decikit.engine(...) block
sets another. A LazyFrame with engine=None runs on the polars engine
(the default's own settings when the default is a PolarsEngine), and returns a LazyFrame to collect, stream or
sink; a numba engine named explicitly collects it first. Each call binds
the pipeline again; for repeated runs, compile once instead.
Example::
out = pipeline.run(df, params={"term": {"cap_by_income": {"cap": 36.0}}}) # fused
with decikit.engine("interpreted"): # instant while editing
out = pipeline.run(df)
pipeline.run(df, engine="stepped")
pipeline.run(pl.scan_parquet("in.parquet")).sink_parquet("out.parquet") # polars
session ¶
session(data, params=None, engine='interpreted')
Open a debug Session over a polars frame.
engine is a tag or an Engine instance, as for compile, but it
does not follow the default engine: a session opens interpreted, which
pauses at every node and inside trees, unless given another. "fused"
pauses at kernel boundaries only. Pass an instance for its settings,
e.g. InterpretedEngine(params_validation="lazy").
Example::
s = pipeline.session(df, engine="stepped")
s.break_at("term/cap_by_income")
s.resume()
s.set("term_cap", 36.0)
s.resume()
s.output()
to_ir
abstractmethod
¶
to_ir(ctx)
This step's IR, placed under ctx. Name nodes with ctx.origin(self).
walk ¶
walk()
The authoring tree as (path, step) pairs; anonymous flows are transparent.
Example::
for path, s in pipeline.walk():
print(path, type(s).__name__)
ConfigurableStep ¶
Bases: Step, BaseRegistryModule
A serialisable, config-driven step (trees, tables, scorecards): subclass it and implement to_ir.
Every subclass loads by its import path ("credit.steps:Scaled"), or by a
short alias it declares as type: Literal["scaled"] = "scaled". Loading
an import path only ever returns a registered ConfigurableStep. Configs
are frozen: changing one means a new object, whose IR is built afresh.
A Value[T] field holds a literal (2.0) or a ParamRef
({"param": "factor", "default": 2.0}). ctx.call passes a literal as
is and turns a ref into a param, so retuning it never rebuilds anything.
To build a config from other steps instead, return
ctx.expand(self, helper_step).
Example::
from typing import Literal
from decikit import ConfigurableStep, Value
def scale(x: float, factor: float) -> float:
return x * factor
class Scaled(ConfigurableStep):
type: Literal["scaled"] = "scaled"
column: str
factor: Value[float] = 1.0
def to_ir(self, ctx):
return ctx.call(self, scale, inputs={"x": self.column}, values={"factor": self.factor})
cfg = ConfigurableStep.load({"type": "scaled", "name": "doubled", "column": "income",
"factor": {"param": "factor", "default": 2.0}})
cfg.run(df) # writes column "doubled"
cfg.run(df, params={"doubled": {"factor": 3.0}}) # retuned, nothing rebuilt
ConfigurableStep.load(cfg.model_dump_json()) == cfg # True
check ¶
check(ctx)
Findings about this step's own document, which AST checks can't see; checks.run calls it for each such step.
ctx is the CheckContext: build findings with ctx.finding(ctx.node, message, code=..., check=...).
Example::
def check(self, ctx):
if self.low > self.high:
yield ctx.finding(ctx.node, "low is above high", code="ACME010", check="empty_range")
load
classmethod
¶
load(source)
A config from a JSON file path, JSON text or a parsed dict, loaded as the class its type names.
On a subclass the tag may be left out, and must name that subclass (or one of its own) if given.
Example::
rules = ConfigurableStep.load("rules/risk.json")
rule = ConfigurableStep.load({"type": "threshold_rule", "name": "hi", ...})
same = ConfigurableStep.load(rule.model_dump_json())
Value
module-attribute
¶
Value = t.Union[T, ParamRef]
Value[float] accepts a literal (0.7) or a ParamRef dict.
ParamRef ¶
Bases: BaseModel
A config value read from the params document instead of written inline.
{"param": "hi_thresh", "default": 0.7} is a local param of the step;
{"param": "base_rate", "shared": true} reads shared.base_rate.
Example::
ThresholdRule(name="hi", column="score", threshold=ParamRef(param="hi_thresh", default=0.7))
# params document: {"hi": {"hi_thresh": 0.8}}
StepRef
module-attribute
¶
StepRef = ref(ConfigurableStep)
A pydantic field type holding any ConfigurableStep, chosen by its type tag.
Not decikit.lab.StepRef, which names a node in a FlowDescription.
Example::
class RuleSet(ConfigurableStep):
rules: list[StepRef]
def to_ir(self, ctx):
return ctx.expand(self, flow(*self.rules))
Errors¶
DecikitError ¶
Bases: Exception
Base class of every error decikit raises; catch it to handle them all.
_STATUS_CODE is the HTTP status a server answers with (500 unless a subclass says otherwise).
Example::
try:
exe.run(df)
except DecikitError as e:
print(e)
FallbackWarning ¶
Bases: UserWarning
A compiled-mode step runs outside the shared kernel; the message names the step and says why.
Example::
warnings.filterwarnings("ignore", category=FallbackWarning) # or @allow_fallback per step
HiddenStateWarning ¶
Bases: UserWarning
A step reads a Python object that no config document, diff or kernel can see; the message names it and where.
@allow_fallback does not silence it: the check is about what a release
check can compare, not about speed.
Example::
warnings.filterwarnings("ignore", category=HiddenStateWarning)
ShadowedTableWarning ¶
Bases: UserWarning
A params document sets a table whose default rows come from a config document, so the document's rows are ignored.
Emitted when a config version is staged (decikit build, RequestHandler.stage()) for a
param_table(..., seeded_from="<document>"). Run-time overrides (experiments) stay silent.
Three ways to switch it off: filter the category, set DECIKIT_BUILD__WARN_SHADOWED_TABLES=false,
or declare the table with allow_override=True.
Example::
warnings.filterwarnings("ignore", category=ShadowedTableWarning)
StrictCompileError ¶
Bases: EngineError
A step that would run in Python, refused by strict_compile=True.
Example::
try:
FusedEngine(strict_compile=True).bind(pipeline).run(df)
except StrictCompileError as e: # 'p/label runs in Python, row by row: ...'
...
Value types¶
Text ¶
A string column a compiled step reads without copying it.
Annotate an input Text instead of str and the step stays in the kernel:
==, !=, len, in, startswith and endswith compile and answer as
they would on a str. Compare against a literal, a module-level constant or
a str param(). Anything else a str can do (.upper(), slicing,
f-strings) needs a str input, which runs in Python.
A null is not a string: it equals nothing, not even another null, and holds
no prefix, suffix or part. Declare it Text | None to accept one. An output
declared Text is written as a str column, in Python.
Example::
from decikit.types import Text
def is_government(employer: Text) -> bool:
return employer.startswith("GOV") or "DEPT" in employer
Text("private") == "private" # True
Text(None) == Text(None) # False
Currency ¶
Bases: Decimal
A Decimal with four decimal places (up to 922,337,203,685,477.5807).
Currency(2.65) rounds a float to the scale. Currency(major, minor) is
exact: minor counts 0.0001 units, so Currency(2, 6500) is 2.65 and
Currency(2, 6) is 2.0006. The sign of major applies to the whole value,
and minor stays between 0 and 9999, so write -0.0005 as -Currency(0, 5).
units is a display string shown before the amount; Currency["R"] in an
annotation sets it for a step's input or output. Negation and abs stay a
Currency; the other arithmetic returns a plain Decimal.
Example::
Currency(2, 6500, units="R") # R 2.6500
Currency(-2, 5) # Currency('-2.0005')
Decimal ¶
A fixed-point number: an int64 raw count of 10**-scale units.
Decimal(2.675, 2), Decimal("2.675", 2) and Decimal(3) build one. A
float is rounded to the scale from its exact binary value (2.67 here), a str
from its digits (2.68 under half-even). scale defaults to 0 for an int and
to the digits after the point for a str; a float needs it. units is a
display string and never takes part in a comparison or in a compiled step.
+ - * / between Decimals give the larger scale and round half-even once per
operation. An int counts as whole units, so Decimal(2.5, 1) + 1 is 3.5, and
a float multiplier or divisor gives a Decimal at the same scale. A result
outside int64 raises OverflowError here and wraps in a compiled step (a float
product outside int64 has no defined value there).
Example::
a = Decimal("2.50"); b = Decimal("0.05")
a * b # Decimal('0.12'), 0.125 rounded half-even
a + 1 # Decimal('3.50')
a < 2.6 # True
from_raw
classmethod
¶
from_raw(raw, scale, units=None)
The Decimal whose int64 is raw at scale: Decimal.from_raw(265, 2) is 2.65.
Percent
dataclass
¶
Duration
dataclass
¶
Struct ¶
Bases: Generic[T]
Marker: a struct column of Item's fields, as one record per row, read in a kernel.
Columnar ¶
Bases: Generic[T]
Read a list[dict] column as one flat array per Item field, so a compiled step can loop over it.
This is a columnar (struct-of-arrays) shape: items.price is one array of
every item's price, read by item position items.price[j]. It is not a
list of per-item dicts — for i in items iterates the fields, not the
items, so index each field by position. An Item field may be float,
int, bool, str, or float | None / str | None (a null reads as NaN
/ a null span); any other null raises, naming the item it is in. A field
that is itself a list or struct is nested data, which Columnar cannot
hold: annotate the input list[dict] instead (runs in Python; accept with
@allow_fallback). A null or absent list follows the input's null policy,
and missing_as([]) reads it as a row with no items.
Reach for it when the work per item is heavy or the lists are long: it
costs about 20 us a record run() call to build the arrays, so a short list
with a one-line body is faster left as a plain list[dict] step.
Example::
class Item(TypedDict):
price: float
def total(items: Columnar[Item]) -> float:
t = 0.0
for j in range(len(items.price)):
t += items.price[j]
return t
FieldMetadata
dataclass
¶
What a step's input, output or param measures. Subclass it for a new kind.
Attach it with Annotated; the engine ignores it and runs the plain type.
The flow debugger formats values by it, and without it guesses from the
name (and says it guessed).
Example::
from typing import Annotated
from decikit.types.measures import Duration, Percent
def instalment(rate: Annotated[float, Percent()], term: Annotated[int, Duration("months")]) -> float:
return rate / term
Serving¶
RequestHandler
dataclass
¶
Serves a pipeline from code with params and ConfigurableStep documents from a config store.
pipeline is a Step, or a function returning one, or the import path of
either ("myapp.pipeline:build"). Each argument of the function names a
key of the config version; that document is loaded with
ConfigurableStep.load and passed in. The version's "params" document
is the params document every request runs with.
Config changes are explicit: stage(version) binds a version with
engine (FusedEngine() unless given; an Engine or its tag) and warms it off the request
path, activate() swaps it in atomically, rollback() goes back to the
previous one. Errors propagate to the caller, and the
active version keeps serving. POST /invocations with a JSON object
scores one record; a JSON array, JSONL, CSV, Parquet or Arrow IPC body
runs as a frame. Send one record as JSON: Arrow IPC costs more to encode
and decode than the pipeline takes to run.
Override any *_fn method in a Handler subclass in inference.py to
change how requests are parsed, scored or formatted. The hooks are plain
methods, not coroutines; one defined with async def is rejected when the
class is created. run(record_or_frame) is the in-process entry. JSON dates arrive as
ISO strings and are converted to the pipeline's declared date and
datetime inputs, including inside list[date], date | None and
TypedDict fields (accounts: list[Account]); a bare dict is left as sent.
stage warms a version by scoring sample_request (a JSON file, by
default sample_request.json in code_path) if it exists, else a
synthetic record; override warm_fn to warm another way.
Example::
# myapp/pipeline.py
def build(tree: ConfigurableStep) -> Step: # the version's "tree" document
return flow(prepare, tree, decide, name="credit")
store = JsonFileStore(basepath="configs")
store.create_version({"tree": tree_doc, "params": {"credit": {"decide": {"cut": 0.7}}}})
handler = RequestHandler(store, "myapp.pipeline:build")
handler.stage() # latest version; or stage("1.2.0")
handler.activate()
handler.rollback() # back to the previously active version
# or serve it: DECIKIT_API__PIPELINE=myapp.pipeline:build, then
# uvicorn --factory decikit._tooling.serving._servers.starlette:create_app
activate ¶
activate()
Serve the staged version; the one it replaces is kept for rollback().
Example::
handler.stage()
handler.activate() # Version(1, 3, 0), now answering requests
rollback ¶
rollback()
Serve the previously active version again.
Example::
handler.rollback() # Version(1, 2, 0)
run ¶
run(request)
Run a record (a dict) or a frame through the active version, as a request would be.
Date strings in the record or frame are converted to the pipeline's declared
date and datetime inputs, so a parsed JSON body can be passed as it is.
The active version is read once, so one call never mixes two versions.
Example::
handler.run({"income": 1000, "debt": 250, "applied_on": "2026-01-15"})
handler.run(pl.DataFrame({"income": [1000], "debt": [250], "applied_on": ["2026-01-15"]}))
stage ¶
stage(version=None)
Build and warm version (default: the store's latest) without serving it.
Example::
handler.stage("1.3.0")
handler.activate()
Config store¶
ConfigStore ¶
Bases: BaseRegistryModule
Versioned params and ConfigurableStep documents; subclass it for a new backend.
A store holds immutable versions and never loads one by itself: a caller
reads the version it wants. Backends implement versions, read and _write.
Example::
store = JsonFileStore(basepath="configs")
store.create_version({"params": {"cut": 0.7}, "tree": tree.model_dump(mode="json")})
doc = store.read(store.latest_version()).config["tree"]
tree = ConfigurableStep.load(doc)
create_version ¶
create_version(config, bump=VersionPart.MINOR)
Write config as a new version one bump past the latest; the first version is 0.0.0.
Example::
store.create_version({"params": {"cut": 0.8}}, bump=VersionPart.PATCH) # 0.1.0 -> 0.1.1
latest_version ¶
latest_version()
The newest stored version, or None for an empty store.
Example::
store.read(store.latest_version())
read
abstractmethod
¶
read(version)
One stored version.
Example::
store.read("0.1.0").config["params"]
versions
abstractmethod
¶
versions()
Every stored version, oldest first.
Example::
store.versions() # [Version(0, 0, 0), Version(0, 1, 0)]
JsonFileStore ¶
Bases: ConfigStore
A config store in a directory: {basepath}/{version}/{key}.json.
A dotted key is a subdirectory, so "credit.params" is
{basepath}/1.2.0/credit/params.json.
Example::
store = JsonFileStore(basepath="configs")
store.create_version({"params": {"cut": 0.7}}) # configs/0.0.0/params.json
Version ¶
Bases: NamedTuple
A major.minor.patch config version; compares and sorts numerically.
Example::
Version.parse("0.10.0") > Version(0, 9, 0) # True
str(Version(1, 2, 0).bump(VersionPart.PATCH)) # "1.2.1"
parse
classmethod
¶
parse(version)
Version.parse("1.2.0") == Version(1, 2, 0); a Version passes through.
VersionPart ¶
Bases: Enum
Which part of a Version a new config version bumps.
Example::
store.create_version(config, bump=VersionPart.MAJOR)
VersionedConfig ¶
Bases: NamedTuple
One stored version: config maps a key ("params", "tree") to its document.
Example::
versioned = store.read("1.2.0")
versioned.config["params"]
Debug¶
Session ¶
Bases: Edits
Run a pipeline one checkpoint at a time: break, inspect, override, resume.
Nothing runs until a command moves the session. Each command runs
synchronously and returns the checkpoint it paused at, or None once the
run is over. Everything that happens is appended to events.
Breakpoints: a path ("term/cap_by_income") or prefix ("term") pauses
just before the first node at or under it, each time the run enters it; "risk_tree#n17" pauses just
after the row node risk_tree if any row reached n17 inside it (only
runners that report positions, such as the interpreted one); a predicate
is called with every checkpoint.
Every numba engine supports sessions. Interpreted and stepped pause at every
node. Fused pauses only at kernel boundaries: a kernel running several
steps is one checkpoint with its first step's path, and a breakpoint (or
rewind) on any of its steps stops just before the whole kernel, with
the kernel's steps in Paused.kernel. Values a kernel uses only inside
itself are never stored, so value and set on one raise a KeyError
that suggests engine="stepped". A fused branch or loop of plain scalar
steps is one such kernel, with the branch's or loop's own path.
Branches and loops: step() runs one whole; step_into() enters it.
Each step is one node over every row that reaches it, so entering a
branch whose rows go both ways visits the first taken arm, then the next
one, in arm order; an arm no row takes is skipped. A loop is entered
once per iteration, over the rows still looping. Checkpoints and
NodeStarted/Paused events carry arm and iteration (from 1).
replace(path, step) and delete(path) edit the pipeline mid-run and
re-run from the edit, keeping every value upstream of it; reload(pipeline)
diffs a whole edited pipeline, and watch reloads after each notebook cell.
Not thread-safe: use one per thread.
Example::
s = pipeline.session(df)
s.break_at("affordability_ratio")
s.resume() # paused before affordability_ratio
s.value("disposable_income") # a polars Series
s.set("disposable_income", 1200.0) # recorded as override@affordability_ratio
s.resume() # runs to the end
s.output()["affordability_ratio"] # computed from 1200.0
s.state.versions("disposable_income@*") # the override is in the trail
apply ¶
apply(command)
Run a command object (e.g. one decoded from JSON); returns what the matching method returns.
Example::
session.apply(SetValue("disposable_income", 1200.0))
break_at ¶
break_at(target)
Add a breakpoint: a path, a prefix, path#locator, or a predicate on each Checkpoint.
Example::
s.break_at("term/cap_by_income")
s.break_at("risk_tree#n17")
s.break_at(lambda cp: cp.when == "after" and cp.origin.path.startswith("term/"))
clear_break ¶
clear_break(target)
Remove a breakpoint added with the same target.
Example::
s.clear_break("term/cap_by_income")
output ¶
output()
The frame Executable.run returns, overrides applied; only once the run has finished.
Example::
s.resume()
s.output()["term_cap"]
pause ¶
pause()
Stop at the next checkpoint; safe to call while another thread is inside resume.
Example::
threading.Thread(target=s.resume).start()
s.pause()
resume ¶
resume()
Run to the next breakpoint, or to the end.
Example::
s.break_at("term")
s.resume() # paused before "term"
s.resume() # None: the run finished
rewind ¶
rewind(path)
Re-run from just before the node at (or first under) path, keeping every value computed upstream of it.
Values upstream of path, overrides included, are kept as they are
now; everything from path on runs again when the session moves.
Example::
session.set("disposable_income", 1200.0)
session.rewind("affordability_ratio")
session.resume()
set ¶
set(name, value)
Override name, an input column or a value produced so far, from here on.
value is one value for every row or a list of one per row (None is
null), cast to the name's declared dtype; a failed cast raises
ValueError. Nodes that run later read the override, and it is
recorded as a version produced by override@<current path>.
Example::
session.set("disposable_income", 1200.0)
session.state.versions("disposable_income@*")[-1].producer # "override@affordability_ratio"
step ¶
step()
Advance one node: from just before a call, branch or loop, run it and stop just after it.
Example::
cp = s.step() # Checkpoint(origin=..., when="after"), or None at the end
step_into ¶
step_into()
Advance to the very next checkpoint: into a sequence, each taken arm in turn, or the next iteration.
Example::
s.step_into().arm # the arm a branch is running, when inside one
structure ¶
structure()
The pipeline's nodes as they are now, parents before children: path, kind and source of each.
kind is "scalar", "row" or "frame" for a call, else "sequence",
"branch" or "loop". Ask again after an edit or reload adds or
deletes steps.
Example::
s.structure()
# [{"path": "", "kind": "sequence", "source": "decikit.pipeline.steps:SequentialStep"},
# {"path": "ratio", "kind": "scalar", "source": "credit.rules:ratio"}, ...]
value ¶
value(spec)
The full current value of name, or of name@path (the version that node produced).
Example::
session.value("term_cap")
session.value("term_cap@term/cap_by_income")
RunSummary
dataclass
¶
What an event says about a column: never the full values, which may be personal data.
Example::
summarize(pl.Series([1.0, None, 3.0]))
# RunSummary(dtype="Float64", rows=3, nulls=1, preview=(1.0, None, 3.0))
Event
module-attribute
¶
Event = Union[RunStarted, NodeStarted, NodeFinished, NodeVisited, Paused, Overridden, ParamsValidated, WarningEvent, ErrorEvent, Edited, ReloadFailed, RunFinished]
Paused
dataclass
¶
The session stopped at a checkpoint; reason is "breakpoint", "step", "pause", "rewind" or "edit".
kernel lists the steps a fused kernel runs when the checkpoint is one
(the first is origin); a breakpoint on any of them pauses here. arm
and iteration are the checkpoint's: which branch arm and which loop
iteration (from 1) it is inside.
NodeStarted
dataclass
¶
A node is about to run; arm and iteration place it inside a branch arm or loop iteration, as on Checkpoint.
NodeFinished
dataclass
¶
A node ran; outputs summarises every value it produced, by name.
NodeVisited
dataclass
¶
A position inside a row node (origin.locator) was reached on rows rows.
Overridden
dataclass
¶
name was set; producer is the recorded version's producer, override@<path>.
Edited
dataclass
¶
The step at path was replaced, added or deleted; the run goes on from there (a Paused follows).
ParamsValidated
dataclass
¶
Params of the nodes at paths were validated; invalid lists those that failed.
RunStarted
dataclass
¶
A session opened over rows rows; nothing has run yet.
RunFinished
dataclass
¶
The run reached the end; output summarises every column of session.output().
ReloadFailed
dataclass
¶
A watched reload couldn't import or build the edited pipeline; the session keeps the one it had and can go on.
WarningEvent
dataclass
¶
A params value was replaced by its default.
ErrorEvent
dataclass
¶
The run raised while in the node at path; the session can rewind but not go on.
Trace¶
TraceSink ¶
Where a run's decision evidence goes: capture, conservation, adapter handoff.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adapter
|
Adapter | None
|
an |
None
|
max_events
|
int | None
|
drop events past this many (reported as |
None
|
sample_rate
|
float
|
keep this fraction of events (a deterministic 1-in-N sample), for batch runs where full capture is not wanted. |
1.0
|
strict
|
bool
|
raise |
True
|
Events are ordered within one record's stream; cross-record order is the
driver's, unspecified. status() reports delivery and loss, never silently.
Not thread-safe: use one per call.
Example::
sink = TraceSink()
exe.run(df, trace=sink)
[e.origin.path for e in sink.events() if e.kind is Kind.STEP]
drain_kernel ¶
drain_kernel(headers, offsets, table, written, expected=None)
Decode a kernel's raw events, verify conservation, and hand them to the adapter.
headers is the kernel's int64 buffer; offsets[i] is the cursor at
the end of row i, so each event resolves to the record it belongs to.
Conservation runs before the adapter: if expected is set and written
falls short, evidence was dropped and (when strict) this raises rather
than let redaction downstream hide it.
emit ¶
emit(kind, origin, *, step=0, arm=None, iteration=None, record=None, value=None)
Record one driver-emitted event (a Python step, a frame step, an override).
TraceEvent
dataclass
¶
One decision-trace event, decoded: what ran, where, in what flow context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema_version
|
int
|
the envelope version this event was written against. |
required |
kind
|
Kind
|
the event kind (see |
required |
step
|
int
|
the 1-based index of the step's |
required |
origin
|
Origin | None
|
the durable step reference — |
required |
arm
|
int | None
|
the branch arm (from 0), or |
required |
iteration
|
int | None
|
the loop iteration (from 1), or |
required |
record
|
int | None
|
the row index within the run the event belongs to; |
required |
value
|
int | float | None
|
a fixed-width numeric payload for the kinds that carry one. |
None
|
Kind ¶
Bases: IntEnum
What one trace event records.
STEP, BRANCH_ARM, LOOP_ITERATION and FRAME are structural: they say what
ran, in what flow context. TABLE_ROW, TREE_PATH, BAND, ROUNDING, REASON
and VALUE carry a fixed-width numeric payload in TraceEvent.value, and
OVERRIDE records a value replaced mid-run by a debug session.
Adapter ¶
Bases: Protocol
What a TraceSink hands decoded events to.
Called synchronously on the request path (conservation runs there too), but a client may enqueue the events and deliver them on another thread or process. It must not raise for the run to go on; an exception is counted in the sink's manifest and the run proceeds.
PassThroughAdapter ¶
Collects every event it receives, for inspection; a named pass-through.
Example::
adapter = PassThroughAdapter()
exe.run(df, trace=TraceSink(adapter))
adapter.events[0].kind
TraceLossError ¶
Bases: RuntimeError
A kernel emitted fewer trace events than its program declares: evidence was dropped.
Lab: data¶
read ¶
read(source, *, format=None)
Read source, a .json/.jsonl/.csv/.parquet path, bytes or a polars frame, into a frame.
JSON is one object per line (a Redshift UNLOAD) or an array of objects.
format is required only when the source has no file extension.
Example::
df = read("loans.parquet")
LoadedData ¶
Bases: BaseModel
A loaded dataset: the polars frame plus the summary a run manifest records.
frame is the data; summary is the InputFingerprint (schema, row count,
content fingerprint) a run manifest binds; suggested_key is the record-key
suggestion, None when no column looks like an id.
Example::
data = LoadedData.from_frame(frame, dataset="loans")
data.summary.row_count, data.summary.columns, data.suggested_key
InputFingerprint ¶
Bases: BaseModel
Identity and shape of the input data: dataset, schema, row count, content fingerprint.
columns lists (column, dtype) pairs in column order, which is part of
identity; fingerprint is the content hash that binds the exact data.
Example::
InputFingerprint(dataset="loans.parquet", fingerprint="ab12", columns=(("client_id", "str"),), row_count=1000)
LoadError ¶
Lab: checks¶
run ¶
run(pipeline, checks=None, *, config=None, data=None, params=None)
Run checks over pipeline and collect a Report.
checks is a flat list of Check instances, aliases, config dicts or check
sets such as checks.standard. With none, the project's checks.yaml is
used if there is one, else standard. config names another file; it sets
the check list when checks is omitted, and its disable and fail_on apply
either way. A check that needs a frame (data=) and wasn't given one is
listed in report.skipped. A step's suppress_checks marks matching
findings suppressed instead of dropping them.
Example::
report = checks.run(pipeline)
report = checks.run(pipeline, [checks.standard, NoFloatMoney(allow=["fee"])])
report = checks.run(pipeline, config="ci/checks.yaml", data=frame, params=doc)
report.ok, report.to_text()
standard
module-attribute
¶
standard = STANDARD
The static checks (no data, no execution), as a check set for a run list.
catalogue ¶
catalogue()
Every registered check: alias, code, family, needs_data, executes, severity and config schema.
Example::
[(c["code"], c["alias"]) for c in checks.catalogue()]
check ¶
check(code, severity=Severity.WARNING, alias=None)
Turn a function f(ctx) yielding findings into a check, for a one-off rule.
The alias defaults to the function's name. The result is a Check instance,
ready for a checks.run list.
Example::
@checks.check(code="ACME002", severity="warning")
def no_print(ctx):
for node in ctx.calls():
yield ctx.finding(node, "prints")
checks.run(pipeline, [checks.standard, no_print])
Check ¶
Bases: BaseRegistryModule
One diagnostic. Subclass it with a type alias; config names it by alias or "module:Class".
Set code (stable, never reused; a third-party check uses its own prefix),
needs_data when it only runs given a frame, and executes when it runs
the flow. run yields findings built with ctx.finding.
Example::
from typing import Literal
from decikit.lab.checks import Check
class NoPrint(Check):
type: Literal["no_print"] = "no_print"
code = "ACME002"
def run(self, ctx):
for node in ctx.calls():
...
yield ctx.finding(node, "prints", fix="log instead")
checks.run(pipeline, [checks.standard, NoPrint(severity="error")])
CheckContext ¶
What a check sees: the flow's IR, plan and description, the data and params if given.
Built once per checks.run and shared; every attribute is computed on first use.
calls() are the call nodes of authored code, source(node) its parsed source,
and finding(...) builds a Finding with code, check, step reference, file and
line filled in, marked suppressed when the node or an ancestor suppresses it.
Example::
for node in ctx.calls():
src = ctx.source(node)
yield ctx.finding(node, "message", fix="do this", line=src.line(expr), expression="a * b")
outputs
cached
property
¶
outputs
The output frame of running the flow over data, and the node producing each output column.
None when the run crashes, with the exception in crash; the run-error check reports it,
so checks that need outputs stay quiet.
calls ¶
calls()
Call nodes of authored code; generated kernels from decikit.pipeline.steps are skipped.
finding ¶
finding(node, message, fix=None, *, line=None, code=None, check=None, severity=None, **detail)
A finding at node. code, check and severity default to the running check's.
Finding ¶
Bases: BaseModel
One check result: what was found, where, and how serious.
code is what CI pins and users suppress ("DCD101"), check the alias
("int64_overflow"). step is the contract reference, so it joins with
describe() nodes; fix is one line saying what to do instead and
detail holds machine-readable specifics. A suppressed finding stays in
the report and doesn't count against ok.
Example::
Finding(code="ACME001", check="no_float_money", severity=Severity.WARNING,
message="fee is held as a float", step=StepRef(path="term/cap"), line=12)
Severity ¶
Bases: Enum
How serious a finding is; the client maps this to advice or a release gate.
decikit only reports. Report.fail_on and decikit check --fail-on are the gate.
Example::
Severity.ERROR in {f.severity for f in report.findings}
Report ¶
Bases: BaseModel
The result of one checks.run: the flow checked, its findings and the checks that were skipped.
ok is True when no unsuppressed finding is an error. gate is the
severity fail_on() uses by default (the project's fail_on).
model_dump_json() is the JSON form.
Example::
report = checks.run(pipeline)
print(report.to_text())
report.ok, report.counts, report.fail_on("warning")
sarif = report.to_sarif()
fail_on ¶
fail_on(severity=None)
True when an unsuppressed finding is at least severity (default: the report's gate).
to_sarif ¶
to_sarif()
SARIF 2.1.0, readable by GitHub code scanning; partialFingerprints is flow_id/step_id/code.
to_text ¶
to_text()
One line per finding (file:line: severity code check: message), then skipped checks and a summary.
SkippedCheck ¶
Bases: BaseModel
A check that didn't run, and why (it needs data it wasn't given).
Example::
SkippedCheck(check="missing_required", code="DCD504", reason="needs data=")
Suppression ¶
Bases: BaseModel
Why a finding is silenced: the step path whose suppress_checks named name.
Example::
Suppression(path="legacy", name="int64_overflow")
Lab: diff and proof¶
structure ¶
structure(old, new)
Compare two pipelines' structure, params and wiring.
Example::
s = diff.structure(old, new)
s.changed_steps[0].consts # True: a constant of that step changed
outputs ¶
outputs(old, new, frame, params=None, key=None, rtol=1e-06, atol=1e-09)
Run both pipelines over frame and report which rows and columns change.
params goes to both; leave it out and each runs with its own defaults.
key names a column that labels rows in samples and table().
Example::
diff.outputs(old, new, frame, key="application_id").rows_changed
revisions ¶
revisions(base, head, entry)
Compare two git revisions of the pipeline that entry ("module:factory") builds.
Example::
diff.revisions("main", "HEAD", entry="credit.pipeline:build").outputs(frame)
prove ¶
prove(old, new)
Prove two pipelines identical, or say what differs.
Trees and decision tables that changed are compared with z3 when decikit[prove] is installed.
Example::
diff.prove(old, new) # Proof(tier="ir_hash", identical=True) for a pure refactor
Revisions ¶
Two git revisions of one pipeline, each loaded in its own subprocess.
Example::
r = diff.revisions("main", "HEAD", entry="credit.pipeline:build")
r.structure().changed_steps
r.outputs(frame, key="application_id").rows_changed
StructureDiff ¶
Bases: BaseModel
What changed between two versions of a pipeline, without running either.
Steps match by (flow_id, step_id) durable id first, then by path.
identical is True only when the IR content hashes are equal; a rename
alone leaves it True, an unhashable constant makes it False.
OutputDiff ¶
Bases: BaseModel
Which rows and columns differ between two versions' outputs over one frame.
Example::
o = diff.outputs(old, new, frame, key="application_id")
o.columns["offer"].max_abs
o.table()
table ¶
table()
One row per changed value: the key (or row number), column, old, new and numeric delta.
Proof ¶
Bases: BaseModel
Whether two pipelines provably compute the same thing, and by which tier.
tier="ir_hash": equal IR content hashes. tier="smt": the flows differ only in tree and decision-table
steps, and z3 found no input on which those steps disagree (identical=True). Otherwise identical is None, not False:
nothing here proves them the same or different. If z3 found an input on which a step differs, it is
evidence.counterexample (the step alone, which the flow may never reach); else evidence shows what
differs and reason why z3 wasn't used.
SmtEvidence ¶
Bases: BaseModel
What a z3 proof covered: the steps compared, what was modelled, and a counterexample if they differ.
counterexample is an input row (None is a null) for the step at step, on which the two versions
write different outputs. The step is judged on its own, so the flow around it may never produce that row.
StepChange ¶
Bases: BaseModel
A matched step whose code, consts, inputs, outputs or params declarations differ.
StepMove ¶
Bases: BaseModel
A step matched across versions whose name or parent changed.
EdgeChange ¶
Bases: BaseModel
ParamChange ¶
Bases: BaseModel
One param declaration that differs; old and new are short displays (None when absent).
ColumnDiff ¶
Bases: BaseModel
How one column differs. Deltas are new - old over the changed rows, left out where non-finite or null.
max_abs is an exact int for integer columns (an amount held as int).
Lab: testing¶
assert_equivalent ¶
assert_equivalent(step, frame, params=None, engines=None, script=None)
Assert every engine gives exactly the same answer; returns the first engine's output frame.
engines holds tags or Engine instances, by default every built-in
engine: interpreted, stepped, fused and polars. Against the first
engine's run(frame) each one checks:
run(frame)(on polars,run(frame.lazy()).collect()): same columns, dtypes and values (NaN equals NaN, nothing else is approximate), except that polars may type a column or nested field the others leaveNull;run(record)for every row, as a dict: the same dict as that row of itsrun(frame), except that a declared optional key the record omits is null in the row (at any depth), or, when the pipeline has a frame step, as its run of a one-row frame of that record, since a cross-row step sees only that row;- on the numba engines, a debug
Sessionresumed to the end: the same frame asrun; withscript, a second session driven byscript(session)(then resumed to the end): the same frame on every numba engine.
An error on the first engine propagates as it is; raising only on a later
engine is a divergence. A later engine that refuses the pipeline with an
EngineError (polars and an untyped dict output, say) is skipped with
a warning naming it and the reason.
Example::
assert_equivalent(pipeline, df, params={"term": {"cap": 36.0}})
assert_equivalent(pipeline, df, engines=("fused", "polars"))
def override(s):
s.break_at("affordability_ratio")
s.resume()
s.set("disposable_income", 1200.0)
assert_equivalent(pipeline, df, script=override)
corpus ¶
corpus(step, baseline=1.0)
Boundary-value frames for every input column step reads.
"boundary" has a baseline row plus, per input, one row moving only that
column to zero, to a negative value (not for bool or str), to null
(only when no step reading it declares it required, since a required null
is an error) and, for an int, to 253 + 1. A float also gets the
rounding ties 0.125, 2.675, -2.5... ("tie:2.675:rate"), and an int
a Decimal or Currency input is a polars Decimal(38, scale) column and
gets large amounts up to one whose raw int64 times 1000 nears the int64
edge ("large:10**11:principal"); its int_near_2**53 row is raw 253 + 1. A
case column names each row, e.g. "zero:net_income". "single" is its
first row, "chunked" the same rows in two chunks, "empty" no rows.
A step with no inputs gets a one-row "boundary" holding only case.
Example::
for name, frame in corpus(pipeline).items():
assert_equivalent(pipeline, frame)
no_recompile ¶
no_recompile()
Fail if numba compiles anything inside the block, e.g. across a retune.
Only real compilations count: calls served by an existing specialisation (or loaded from numba's disk cache) don't.
Example::
exe = pipeline.compile("fused")
exe.run(df)
with no_recompile():
exe.run(df, params={"term": {"cap": 24.0}})
Lab: experiments¶
Experiment ¶
A builder for one experiment in a notebook: scenarios, metrics, plots, callbacks, then run(data).
The caller supplies the data (a polars DataFrame or LazyFrame) to run.
params is the baseline's params document; without one, each revision
runs on its own code's defaults.
Example::
result = (Experiment("drift", pipeline)
.scenario("limit_0.3", params={"demo": {"approved": {"limit": 0.3}}})
.metric(Divergence(column="approved"))
.plot(Changes(metric="divergence"))
.run(df))
result.summaries["divergence"]["limit_0.3"].changed
callback ¶
callback(*callbacks)
Add callbacks that see every scenario (progress, writers); they are not saved with the definition.
from_def
classmethod
¶
from_def(def_, step=None, *, params=None)
An experiment from a whole ExperimentDef, including its protocol-only fields (flow, determinism).
Without step the flow is imported from flow.entry.
Example::
exp = Experiment.from_def(ExperimentDef(name="x", flow={"entry": "credit:build"}))
load
classmethod
¶
load(path, *, step=None, params=None)
An experiment from an experiment.json, ready to change further or run.
Without step the flow is imported from flow.entry.
Example::
result = Experiment.load("experiments/premium_sweep/experiment.json").run(df)
report ¶
report(*blocks, title='')
Lay out the report result.show() draws, top to bottom; see decikit.lab.experiments.report.
run ¶
run(data, *, out_dir=None)
Run the baseline and every scenario to the end over data; out_dir gets each scenario's output and result.json.
save ¶
save(path)
Write the definition to path as JSON; Experiment.load reads it back.
An empty flow.entry is filled from the pipeline when it can be inferred, so the file runs elsewhere.
start ¶
start(data, *, out_dir=None)
Run in a background thread and return a handle with .status, .progress, .cancel() and .result().
Example::
handle = experiment.start(df)
handle.cancel() # stops at the next batch
handle.result().status # RunStatus.CANCELLED
ExperimentDef ¶
Bases: BaseModel
The experiment.json asset: everything one experiment runs and measures.
The baseline is the unchanged flow, always run first, under the name
"baseline". batch_size records run per batch, so progress shows and no
metric needs the whole input; determinism reruns each baseline batch and
flags a differing rerun as non-reproducible. report lays out what
result.show() and result.save_html() show.
ExperimentResult ¶
Bases: BaseModel
A finished (or stopped) run: the manifest, statuses, and what the metrics and plots produced.
summaries is {metric: {scenario: Summary}}, for scenarios that
completed; plots is {plot: Figure}. In a notebook, show() draws the
report and plots[name].show() one chart; save_html writes the report.
Scenario ¶
Bases: BaseModel
One controlled change to run next to the baseline.
params merge over the run's params document; overrides write values at a
declared point — at names the step whose output to override, or is None
for an input column before anything runs. revision runs the scenario on
another git revision (e.g. "HEAD^"); row overrides one record only.
ScenarioResult ¶
Bases: BaseModel
One scenario's outcome: its status, error, resolved revision and how many records it ran.
RunStatus ¶
Bases: str, Enum
The terminal quality of an experiment run.
NON_REPRODUCIBLE means a baseline rerun differed; PARTIAL means some
scenario failed; FAILED means the baseline did. None of them reads as
COMPLETED.
run ¶
run(def_, frame, *, out_dir=None, callbacks=())
Run an experiment headlessly over frame: load the flow by flow.entry from an ExperimentDef or an experiment.json path.
callbacks see every scenario; out_dir gets
each scenario's output as parquet plus result.json. A failing scenario never stops
the others; a failing baseline stops the run.
Example::
result = run("experiments/drift/experiment.json", df, out_dir="results/drift")
result.status # RunStatus.COMPLETED, or NON_REPRODUCIBLE / PARTIAL / FAILED
start ¶
start(def_, frame, *, out_dir=None, callbacks=())
run in a background thread; the handle has .status, .progress, .cancel() and .result().
Example::
handle = start("experiments/drift/experiment.json", df)
handle.result().status
validate ¶
validate(def_, step)
Every problem in def_ against step, returned rather than raised so a caller shows them all.
Checks scenario names, that a scenario on another revision has a flow
entry to import (or one that can be inferred from the pipeline), that each override targets an input or a produced
value (a produced one needs at), that metric and plot names are unique,
and that each plot's metric exists and gives the summary the plot requires.
Lab: references¶
resolve_step ¶
resolve_step(description, ref)
The node of description that ref names.
A durable reference matches by (flow_id, step_id); when neither is set
(or none matches) it falls back to the derived path. A durable reference
that matches nothing warns and returns ref unchanged, so its capture-time
name, source and path survive for repair instead of vanishing.
Example::
node = resolve_step(desc, StepRef(step_id="cap", path="term/cap_by_income", source="credit.rules:cap_by_income"))
source_location ¶
source_location(source)
The (file, line) an import-path source points at, or None when it can't be resolved.
A step whose module can't be imported, or that is built in, has no source location; callers treat that as unavailable rather than an error.
Example::
source_location("credit.rules:cap_by_income") # ("credit/rules.py", 41)
FlowDescription ¶
Bases: BaseModel
The static structure of one flow: its nodes, edges and value slots.
Static only. Runtime facts — the values a run observed, the params it
validated, the events a session emitted — live on RunReport and
Session.events, not here. contract_version is the contract the document
was written against.
Example::
from decikit.lab._describe import describe
desc = describe(pipeline)
desc.nodes[0].path
FlowRef ¶
Bases: BaseModel
A whole pipeline, the root of a flow description.
flow_id is the durable identity a committed source declares (see the ID
command); it is None until then. name, source and revision are
capture-time description kept for repair when the durable id no longer
resolves. source is the import path of the step that produced the root,
revision the resolved source revision (a git SHA) when one is known.
Example::
FlowRef(name="term", source="credit.pipeline:build")
StepRef ¶
Bases: BaseModel
One node of a flow.
Not decikit.StepRef, the field type for a nested step.
The durable global reference is (flow_id, step_id): both come from
committed source, so a trace or finding links to a step that survives
renames and reordering. path is the derived path (Origin.path), unique
within one build but only development context. source is the import path
of the code that produced the node, locator a position inside a row
node. inputs/outputs are the value names the node reads/writes
(kind is the call kind for a call node).
Example::
StepRef(path="term/cap_by_income", source="credit.rules:cap_by_income", node_type="call", kind="scalar")
EdgeRef ¶
Bases: BaseModel
An edge between two nodes of one flow.
kind="control" is structural: to_path runs inside from_path. kind="data"
is a dependency: to_path reads each name in values from the node at
from_path. Edges name nodes by path; the nodes themselves are the
FlowDescription.nodes entries.
Example::
EdgeRef(from_path="affordability", to_path="affordability/ratio", kind="control")
EdgeRef(from_path="affordability/ratio", to_path="affordability/affordable", kind="data", values=("ratio",))
ValueSlotRef ¶
Bases: BaseModel
A static value slot: one written version of a value, name produced at path.
This is the place a value is read from or written to, not a runtime value:
the value observed during a run and the trace evidence of that run are
separate concepts owned by the run/debug layer. path is None for a
pipeline input column. spec spells the slot as State.versions reads it:
"name" or "name@path".
Example::
ValueSlotRef(name="term_cap", path="term/cap_by_income").spec # "term_cap@term/cap_by_income"
RecordRef ¶
Bases: BaseModel
A reference to one record of a data source.
A durable reference needs an explicit record key: key maps the key
columns to the values that identify the record, and is empty (not durable)
until a caller supplies a validated one. ordinal is a row number within
one session and is display-only: it is never part of identity and must not
be persisted, because row order is not stable across loads.
Example::
RecordRef(dataset="loans.parquet", key={"client_id": "C-1182"})
Trees and expressions¶
TreeConfig ¶
Bases: ConfigurableStep
A decision tree as a step: a v3 tree document or decikit 0.3 flat rules, run once per row.
The tree's output columns are the step's outputs (<rule>.<column> per
rule in a prioritized document with mode: "all"). A threshold, bound,
value or pattern written {"param": "hi_thresh", "default": 0.7} is a
param of the step, so retuning it never rebuilds or recompiles anything.
A feature's type is inferred from how the tree uses it (string_match:
str; only is_true/is_false: bool; otherwise float); declare it
in feature_types to compare an int64 column exactly.
A mode: "all" tree writes one output per rule and column, and a tree of
more than part_outputs outputs (64 by default) is run as several parts
of whole rules, each its own node <name>/part_<k>, because compile time
grows with the square of the outputs one call returns. A part costs about
15-20 us per request, so a bigger part_outputs (or None, no parts) makes
run() on a record faster and the first build slower (a 521-rule tree takes about
4 minutes to bind unsplit); a smaller one (32) makes run() over a big frame
up to twice as fast. A tree with params is never split.
null_handling says what a null numeric or boolean feature does.
"otherwise" (the default, as decikit 0.3 trees behave): a test on it
is unknown, NOT keeps it unknown, AND/OR follow three-valued logic and
the node takes its otherwise branch (a cases node tries its next case).
"error": a null is a MissingInputError. A string match has its own
null_handling (no_match, match or error).
path_output names an extra String column holding the id of the leaf
that answered (null when the default row answered); in mode: "all"
one per rule, <rule>.<path_output>. trace_output names a String
column holding the ordered path, the ids of every node walked joined
with > ("root>mid>hi", or "root>mid" when mid's branch leads
nowhere), so the decision record says how the tree got there, also
through a node shared by two parents. In mode: "first_match" over
several rules it is the path in the rule that answered (else the last
rule's); in mode: "all" one per rule.
path_columns is a function fn(route, tree) -> dict that adds the
dict's keys as output columns, for a route format of your own. It is
called once per route when the step is built, never per row: the tree
is unfolded so every route, each branch of a node told apart, ends at a
leaf of its own whose row holds the route's columns (so path_output
names a leaf even where the default row answers). A Route has
visits, a Visit(node_id, node, branch, child) per node passed, and
result_idx. Set it in Python, or with path_columns: fn on a flow
file's step: node naming a function in components; a document
never holds it. A first-match tree must have one rule.
Params are per call, not per row: params={"risk_tree": {"hi_thresh": 2.0}}
moves the threshold for every row of that run. For a threshold that
differs per row, compare against a computed feature over a column
instead, e.g. {"op": ">", "feature": {"type": "computed", "expression":
"ratio - customer_limit"}, "threshold": 0.0} reads customer_limit from
each row. A param name is a Python identifier (it becomes a field name):
write rule CF-0412's threshold as {"param": "cf_0412_amount"}.
nodes maps each node id to its node: the locators a session breaks on,
e.g. session.break_at("risk_tree#high").
Example::
risk = TreeConfig.load({
"type": "tree", "name": "risk_tree",
"tree": {
"nodes": [
{"id": "root", "data": {"type": "unary", "condition": {
"op": ">", "feature": "ratio", "threshold": {"param": "hi_thresh", "default": 0.7}}}},
{"id": "high", "data": {"type": "leaf", "result_idx": 0}},
],
"edges": [{"source": "root", "target": "high", "data": {"sourceIndex": 0}}],
"output": {"data": [{"risk_band": 1}], "default": {"risk_band": 0},
"dtypes": [["risk_band", "Int64"]]},
},
})
risk.run(df) # writes risk_band
risk.run(df, params={"risk_tree": {"hi_thresh": 2.0}})
# With "path_output": "risk_leaf" in the document, run() also writes risk_leaf: "high" or null;
# with "trace_output": "risk_path", risk_path: "root>high", or "root" when ratio <= 0.7.
The same tree as flat rules: "tree": {"type": "flat_rule", "rule": {"rule": {"type": "unary",
"condition": {...}, "then": {"type": "leaf", "result_idx": 0}}}, "output": {...}}.
expr_condition ¶
expr_condition(source, *, name, feature_types=None)
A boolean expression as a one-output step: a bool column name, true where the expression holds.
source is a Python boolean expression over column names: numeric
comparisons ("score >= 600"), string equality ('crc_model == "CrC3.0"'),
and/or/not, and a bare name as a boolean column. An arithmetic side
("income - expenses > 1000") is validated the same way as a tree's
computed feature. A null input makes the expression false. feature_types
is passed through to TreeConfig (e.g. {"months": "int"}).
Example::
good = expr_condition('score >= 600 and crc_model == "CrC3.0"', name="good")
good.run(df)["good"]
Route ¶
Bases: NamedTuple
One way through a tree: the nodes passed, root first, and the output row it ends at (-1 for the default).
Example::
def depth(route: Route, tree: Tree) -> dict:
return {"depth": len(route.visits), "hit": route.result_idx >= 0}
Visit ¶
Bases: NamedTuple
One node a route passes: its id, what it tests, the branch taken, and where that branch leads (None: the default row).
Flow files¶
load_flow ¶
load_flow(path, *, components=None, documents=None, project_dir=None)
Load a flow file into the same Step tree flow/branch/loop would build by hand.
components names (or is) the module or package whose public functions
and Step instances a step: node can reference by name; it defaults to
the file's own components: key. documents maps a name to a parsed
tree, table or scorecard document that step: can reference instead.
path may also be the parsed flow itself, a mapping, in which case project_dir
is where flows/ and relative components resolve from.
Example::
# flow.yaml: {flow: credit, steps: [{step: approved}]}
load_flow("flow.yaml", components="credit_risk.steps")
read_flow ¶
read_flow(path)
Read a flow file (YAML or JSON) into its raw dict, without building steps.
Example::
read_flow(Path("flows/credit.yaml"))["flow"] # "credit"
components ¶
components(module)
The steps and step functions a components module (and its submodules) defines, by name.
Example::
import my_project.components
components(my_project.components)["full_limit"]