Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions backend/ml_pipeline/_execution/_cycle_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,27 @@ def validate_no_cycles(nodes: list[NodeConfig]) -> None:
"""
known = {node.node_id for node in nodes}
inputs = {node.node_id: [i for i in node.inputs if i in known] for node in nodes}

in_degree = {nid: len(ups) for nid, ups in inputs.items()}
children: dict[str, list[str]] = {nid: [] for nid in known}
for nid, ups in inputs.items():
for up in ups:
children[up].append(nid)

ordered = _order_acyclic_nodes(inputs, children)
if len(ordered) == len(known):
return

stuck = _prune_downstream_nodes(known - ordered, children)
loop = _trace_loop(stuck, inputs)
raise PipelineCycleError(
"Pipeline contains a cycle: "
+ " -> ".join([*loop, loop[0]])
+ ". Remove one of these connections so the pipeline flows in one direction."
)


def _order_acyclic_nodes(inputs: dict[str, list[str]], children: dict[str, list[str]]) -> set[str]:
"""Consume zero-indegree nodes using the graph's existing traversal order."""
in_degree = {nid: len(ups) for nid, ups in inputs.items()}
ready = [nid for nid, deg in in_degree.items() if deg == 0]
ordered: set[str] = set()
while ready:
Expand All @@ -39,24 +53,19 @@ def validate_no_cycles(nodes: list[NodeConfig]) -> None:
in_degree[child] -= 1
if in_degree[child] == 0:
ready.append(child)
if len(ordered) == len(known):
return
return ordered


stuck = known - ordered
def _prune_downstream_nodes(stuck: set[str], children: dict[str, list[str]]) -> set[str]:
"""Remove blocked descendants so cycle diagnostics name only loop members."""
# A stuck node with no stuck successor is merely downstream of the loop,
# not part of it — prune those so the message targets the loop only.
while True:
removable = {nid for nid in stuck if not any(c in stuck for c in children[nid])}
if not removable:
break
stuck -= removable

loop = _trace_loop(stuck, inputs)
raise PipelineCycleError(
"Pipeline contains a cycle: "
+ " -> ".join([*loop, loop[0]])
+ ". Remove one of these connections so the pipeline flows in one direction."
)
return stuck


def _trace_loop(stuck: set[str], inputs: dict[str, list[str]]) -> list[str]:
Expand Down
143 changes: 107 additions & 36 deletions backend/ml_pipeline/_execution/_leakage_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,53 @@ def validate_no_preprocessing_before_split(
splitter_ids = {n.node_id for n in nodes if n.step_type in train_test_split_step_types()}
descendants = _build_descendant_map(nodes)
nodes_by_id = {n.node_id: n for n in nodes}
execution_ids = (
execution_ids = _execution_node_ids(nodes, nodes_by_id, descendants, target_node_id)
execution_splitters = splitter_ids & execution_ids
execution_nodes = [n for n in nodes if n.node_id in execution_ids]
data_dependent = data_dependent_step_types()

checked, exempted, messages = _inspect_pre_split_nodes(
nodes,
execution_ids,
execution_nodes,
nodes_by_id,
descendants,
splitter_ids,
execution_splitters,
data_dependent,
on_leakage,
)

detail = {"splitters": sorted(execution_splitters), "checked": checked, "exempted": exempted}
if not splitter_ids:
if on_leakage != "ignore":
logger.warning(NO_SPLIT_DIAGNOSTIC)
return {"status": "no_split", "messages": [NO_SPLIT_DIAGNOSTIC], **detail}
training_leaves = _training_leaves(nodes, execution_ids)
_inspect_training_branches(
training_leaves,
nodes_by_id,
splitter_ids,
data_dependent,
execution_nodes,
checked,
messages,
on_leakage,
)

if messages:
return {"status": "warnings", "messages": messages, **detail}
return {"status": "passed", "messages": [], **detail}


def _execution_node_ids(
nodes: list[NodeConfig],
nodes_by_id: dict[str, NodeConfig],
descendants: dict[str, set[str]],
target_node_id: str | None,
) -> set[str]:
"""Limit admission checks to the selected node and its ancestors."""
return (
{
n.node_id
for n in nodes
Expand All @@ -382,10 +428,20 @@ def validate_no_preprocessing_before_split(
if target_node_id in nodes_by_id
else set(nodes_by_id)
)
execution_splitters = splitter_ids & execution_ids
execution_nodes = [n for n in nodes if n.node_id in execution_ids]
data_dependent = data_dependent_step_types()


def _inspect_pre_split_nodes(
nodes: list[NodeConfig],
execution_ids: set[str],
execution_nodes: list[NodeConfig],
nodes_by_id: dict[str, NodeConfig],
descendants: dict[str, set[str]],
splitter_ids: set[str],
execution_splitters: set[str],
data_dependent: frozenset[str],
on_leakage: OnLeakage,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[str]]:
"""Collect ordered exemptions and violations before reachable splitters."""
checked: list[dict[str, Any]] = []
exempted: list[dict[str, Any]] = []
messages: list[str] = []
Expand Down Expand Up @@ -421,24 +477,50 @@ def validate_no_preprocessing_before_split(
"FeatureTargetSplitter before it if you only need to separate "
"the target column (that does not create a train/test boundary)."
)
if on_leakage == "raise":
raise ValueError(message)
if on_leakage == "warn":
logger.warning(message)
messages.append(message)
_report_violation(message, on_leakage, messages)

detail = {"splitters": sorted(execution_splitters), "checked": checked, "exempted": exempted}
if not splitter_ids:
if on_leakage != "ignore":
logger.warning(NO_SPLIT_DIAGNOSTIC)
return {"status": "no_split", "messages": [NO_SPLIT_DIAGNOSTIC], **detail}
training_leaves = [
return checked, exempted, messages


def _training_leaves(nodes: list[NodeConfig], execution_ids: set[str]) -> list[NodeConfig]:
"""Find terminal trainers inside the requested execution subgraph."""
return [
n
for n in nodes
if n.node_id in execution_ids
and n.step_type in _TRAINING_LEAF_STEP_TYPES
and not any(n.node_id in other.inputs for other in nodes if other.node_id in execution_ids)
]


def _mark_branch_learners(branch_learners: list[NodeConfig], checked: list[dict[str, Any]]) -> None:
"""Update existing verdict rows without changing their order or split flags."""
for learner in branch_learners:
existing = next((item for item in checked if item["node_id"] == learner.node_id), None)
if existing is None:
checked.append(
{
"node_id": learner.node_id,
"step_type": learner.step_type,
"before_split": False,
"violation": True,
}
)
else:
existing["violation"] = True


def _inspect_training_branches(
training_leaves: list[NodeConfig],
nodes_by_id: dict[str, NodeConfig],
splitter_ids: set[str],
data_dependent: frozenset[str],
execution_nodes: list[NodeConfig],
checked: list[dict[str, Any]],
messages: list[str],
on_leakage: OnLeakage,
) -> None:
"""Check unsplit trainer branches and preserve fold-refit exemptions."""
for training_node in training_leaves:
branch_learners = _find_unprotected_learners(
training_node,
Expand All @@ -461,25 +543,14 @@ def validate_no_preprocessing_before_split(
"these nodes, or enable cross-validation with a linear preprocessing "
"path that can be refitted per fold."
)
for learner in branch_learners:
existing = next((item for item in checked if item["node_id"] == learner.node_id), None)
if existing is None:
checked.append(
{
"node_id": learner.node_id,
"step_type": learner.step_type,
"before_split": False,
"violation": True,
}
)
else:
existing["violation"] = True
if on_leakage == "raise":
raise ValueError(message)
if on_leakage == "warn":
logger.warning(message)
messages.append(message)
_mark_branch_learners(branch_learners, checked)
_report_violation(message, on_leakage, messages)

if messages:
return {"status": "warnings", "messages": messages, **detail}
return {"status": "passed", "messages": [], **detail}

def _report_violation(message: str, on_leakage: OnLeakage, messages: list[str]) -> None:
"""Apply the requested error policy while retaining diagnostic messages."""
if on_leakage == "raise":
raise ValueError(message)
if on_leakage == "warn":
logger.warning(message)
messages.append(message)
59 changes: 37 additions & 22 deletions backend/ml_pipeline/_execution/diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,42 @@
_HIDDEN_FAMILIES = {"loader"}


def _preprocessing_entry(
step_type: str, metadata: Mapping[str, Any], summary: str | None
) -> dict[str, Any]:
"""Build one preprocessing label using its optional human display name."""
display = metadata.get("display_name")
entry: dict[str, Any]
if display and display != step_type:
entry = {"name": display, "transformer": step_type}
else:
entry = {"name": step_type}
entry["details"] = summary
return entry


def _diagram_stages(
node_results: dict[str, NodeExecutionResult],
model_type: str | None,
node_params: Mapping[str, Mapping[str, Any]] | None,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""Collect visible preprocessing and the first modeling stage in execution order."""
steps: list[dict[str, Any]] = []
modeling: dict[str, Any] = {}
for result in node_results.values():
step_type = result.step_type or "unknown"
family = _family_of(step_type)
if family in _HIDDEN_FAMILIES:
continue
metadata = result.metadata or {}
summary = metadata.get("summary") or params_summary((node_params or {}).get(result.node_id))
if family in _MODELING_FAMILIES and not modeling:
modeling = {"type": model_type or step_type, "details": summary}
continue
steps.append(_preprocessing_entry(step_type, metadata, summary))
return steps, modeling


def build_pipeline_diagram(
node_results: dict[str, NodeExecutionResult],
model_type: str | None = None,
Expand All @@ -40,28 +76,7 @@ def build_pipeline_diagram(
the build fails — the diagram is advisory and must never block a run.
"""
try:
steps: list[dict[str, Any]] = []
modeling: dict[str, Any] = {}
for result in node_results.values():
step_type = result.step_type or "unknown"
family = _family_of(step_type)
if family in _HIDDEN_FAMILIES:
continue
metadata = result.metadata or {}
summary = metadata.get("summary") or params_summary(
(node_params or {}).get(result.node_id)
)
if family in _MODELING_FAMILIES and not modeling:
modeling = {"type": model_type or step_type, "details": summary}
continue
display = metadata.get("display_name")
entry: dict[str, Any]
if display and display != step_type:
entry = {"name": display, "transformer": step_type}
else:
entry = {"name": step_type}
entry["details"] = summary
steps.append(entry)
steps, modeling = _diagram_stages(node_results, model_type, node_params)
if not steps and not modeling:
return None
return build_mermaid_diagram(steps, modeling)
Expand Down
20 changes: 12 additions & 8 deletions backend/ml_pipeline/_execution/engine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,17 @@ def _dispatch_node(self, node: NodeConfig, job_id: str) -> tuple[str | None, dic
# Try to run as a single transformer step
return self._dispatch_transformer_fallback(node, job_id)

def _summary_input_shape(self, node: NodeConfig) -> tuple[int, int] | None:
"""Probe the first upstream frame shape without making summaries fail execution."""
try:
if node.inputs:
upstream = self.artifact_store.load(node.inputs[0])
if isinstance(upstream, (pd.DataFrame, pl.DataFrame)):
return upstream.shape
except Exception: # noqa: BLE001 - upstream shape probe is best-effort
return None
return None

def _build_node_metadata(self, node: NodeConfig, metrics: dict[str, Any]) -> dict[str, Any]:
"""Best-effort assembly of the one-line node-card summary metadata.

Expand All @@ -344,14 +355,7 @@ def _build_node_metadata(self, node: NodeConfig, metrics: dict[str, Any]) -> dic
output = self.artifact_store.load(node.node_id)
except Exception: # noqa: BLE001 - best-effort load; failure just skips summary
logger.debug("summary: output load skipped for %s", node.node_id, exc_info=True)
input_shape: tuple[int, int] | None = None
try:
if node.inputs:
upstream = self.artifact_store.load(node.inputs[0])
if isinstance(upstream, (pd.DataFrame, pl.DataFrame)):
input_shape = upstream.shape
except Exception: # noqa: BLE001 - upstream shape probe is best-effort
input_shape = None
input_shape = self._summary_input_shape(node)
try:
summary = build_summary(
step_type=node.step_type,
Expand Down
Loading
Loading