Skip to content

kedro.inspection

kedro.inspection

Kedro inspection API for read-only project snapshot.

Name Type Description
get_project_snapshot Function Return a read-only snapshot of a Kedro project.
validate_deployment_grouping Function Check that a node grouping can run with each group as a separate task.
DeploymentGroupingResult Dataclass Outcome of validate_deployment_grouping.
DeploymentGroupingIssue Dataclass A problem found when checking a node grouping for deployment.
DeploymentGroupingError Exception Raised by raise_if_failed when a grouping has errors.

kedro.inspection.get_project_snapshot

get_project_snapshot(project_path=None, env=None, conf_source=None, metadata=None, runtime_params=None, group_by='namespace')

Return a read-only snapshot of the Kedro project.

This is the primary entry point for the inspection API. It initialises the project, loads configuration and pipelines, and assembles a ProjectSnapshot without executing any pipeline nodes or writing data.

At least one of project_path or metadata must be supplied. When both are given and point to different directories, metadata.project_path takes precedence and a UserWarning is emitted.

Parameters:

  • project_path (str | Path | None, default: None ) –

    Path to the project root directory (the directory that contains pyproject.toml). Optional when metadata is provided.

  • env (str | None, default: None ) –

    Optional run environment override (e.g. "staging"). When None, the project's default run environment is used.

  • conf_source (str | None, default: None ) –

    Optional path to the configuration directory. When None, defaults to <project_path>/<settings.CONF_SOURCE>.

  • metadata (ProjectMetadata | None, default: None ) –

    Optional pre-computed ProjectMetadata returned by a prior bootstrap_project call. When provided, bootstrap_project is skipped. Pass this when calling get_project_snapshot repeatedly in the same process to avoid redundant initialisation.

    For example, in a long-running server the project is bootstrapped once at startup and the result is forwarded to every snapshot call::

    # --- server startup ---
    metadata = bootstrap_project(project_path)
    
    # --- per-request snapshot (bootstrap_project not called again) ---
    snapshot = get_project_snapshot(metadata=metadata)
    

    The same pattern applies to programmatic callers that need multiple snapshots across different environments::

    from kedro.framework.startup import bootstrap_project
    from kedro.inspection import get_project_snapshot
    
    metadata = bootstrap_project(project_path)
    snapshot_default = get_project_snapshot(metadata=metadata)
    snapshot_staging = get_project_snapshot(env="staging", metadata=metadata)
    
  • runtime_params (dict[str, Any] | None, default: None ) –

    Optional dictionary of runtime parameters forwarded to the config loader for ${runtime_params:...} interpolation. This mirrors kedro run --params / KedroSession.create(runtime_params=...) for configuration resolution::

    snapshot = get_project_snapshot(
        metadata=metadata,
        runtime_params={"version": "02"},
    )
    
  • group_by (Literal['namespace', 'none'] | None, default: 'namespace' ) –

    Strategy used to build the node groups in each pipeline's groups, passed to Pipeline.group_nodes_by. Accepted values are "namespace" (the default), which groups nodes by their top-level namespace, and "none" or None, which makes every node a group of its own. Matching is case-insensitive, and the value used is recorded in PipelineSnapshot.group_by.

Returns:

Raises:

  • ValueError –

    If group_by is not a supported strategy. Raised before the project is bootstrapped or any configuration is loaded.

Source code in kedro/inspection/__init__.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def get_project_snapshot(  # noqa: PLR0913
    project_path: str | Path | None = None,
    env: str | None = None,
    conf_source: str | None = None,
    metadata: ProjectMetadata | None = None,
    runtime_params: dict[str, Any] | None = None,
    group_by: Literal["namespace", "none"] | None = "namespace",
) -> ProjectSnapshot:
    """Return a read-only snapshot of the Kedro project.

    This is the primary entry point for the inspection API. It initialises
    the project, loads configuration and pipelines, and assembles a
    ``ProjectSnapshot`` without executing any pipeline nodes or writing data.

    At least one of *project_path* or *metadata* must be supplied.  When both
    are given and point to different directories, *metadata.project_path* takes
    precedence and a ``UserWarning`` is emitted.

    Args:
        project_path: Path to the project root directory (the directory that
            contains ``pyproject.toml``). Optional when *metadata* is provided.
        env: Optional run environment override (e.g. ``"staging"``). When
            ``None``, the project's default run environment is used.
        conf_source: Optional path to the configuration directory. When
            ``None``, defaults to ``<project_path>/<settings.CONF_SOURCE>``.
        metadata: Optional pre-computed ``ProjectMetadata`` returned by a prior
            ``bootstrap_project`` call. When provided, ``bootstrap_project`` is
            skipped. Pass this when calling ``get_project_snapshot`` repeatedly
            in the same process to avoid redundant initialisation.

            For example, in a long-running server the project is bootstrapped
            once at startup and the result is forwarded to every snapshot call::

                # --- server startup ---
                metadata = bootstrap_project(project_path)

                # --- per-request snapshot (bootstrap_project not called again) ---
                snapshot = get_project_snapshot(metadata=metadata)

            The same pattern applies to programmatic callers that need multiple
            snapshots across different environments::

                from kedro.framework.startup import bootstrap_project
                from kedro.inspection import get_project_snapshot

                metadata = bootstrap_project(project_path)
                snapshot_default = get_project_snapshot(metadata=metadata)
                snapshot_staging = get_project_snapshot(env="staging", metadata=metadata)

        runtime_params: Optional dictionary of runtime parameters forwarded to
            the config loader for ``${runtime_params:...}`` interpolation. This
            mirrors ``kedro run --params`` / ``KedroSession.create(runtime_params=...)``
            for configuration resolution::

                snapshot = get_project_snapshot(
                    metadata=metadata,
                    runtime_params={"version": "02"},
                )

        group_by: Strategy used to build the node groups in each pipeline's
            `groups`, passed to `Pipeline.group_nodes_by`. Accepted values are
            `"namespace"` (the default), which groups nodes by their top-level
            namespace, and `"none"` or `None`, which makes every node a group
            of its own. Matching is case-insensitive, and the value used is
            recorded in `PipelineSnapshot.group_by`.

    Returns:
        A fully populated ``ProjectSnapshot``.

    Raises:
        ValueError: If `group_by` is not a supported strategy. Raised before
            the project is bootstrapped or any configuration is loaded.
    """
    return _build_project_snapshot(
        project_path=project_path,
        env=env,
        conf_source=conf_source,
        metadata=metadata,
        runtime_params=runtime_params,
        group_by=group_by,
    )

kedro.inspection.grouping.validate_deployment_grouping

validate_deployment_grouping(pipeline, catalog, groups=None, group_by='namespace')

Check that a node grouping can run with each group as a separate task.

Deployment platforms such as Airflow or Databricks run each group from Pipeline.group_nodes_by as its own task, usually in its own container, so groups do not share memory or local disk. This function reports the problems that only appear once that happens:

  • invalid_grouping (error): only for groups passed in. A node is in no group, in more than one group or not in the pipeline, a group is empty, or a group name is repeated. The remaining checks are skipped.
  • group_cycle (error): groups depend on each other in a loop, usually because a namespace is interrupted by a node outside it.
  • ephemeral_boundary (error): a dataset produced in one group and used in another is only kept in memory.
  • local_boundary (warning): a dataset passed between groups is saved to local disk. Databricks shared paths such as /dbfs/ and /Volumes/ are not reported.
  • single_node_groups (info): groups that contain one node.

Datasets are resolved the way the catalog resolves them at run time, including dataset factories and catch-all patterns, but from configuration only: no data is loaded and no dataset class is imported. The function never raises for issues it finds; call raise_if_failed on the result to raise.

Parameters:

  • pipeline (Pipeline) –

    The pipeline to deploy.

  • catalog (CatalogProtocol) –

    The catalog the deployed pipeline will use.

  • groups (list[GroupedNodes] | None, default: None ) –

    Groups to check. Defaults to pipeline.group_nodes_by(group_by).

  • group_by (str | None, default: 'namespace' ) –

    Grouping strategy passed to Pipeline.group_nodes_by when groups is not given.

Returns:

Example:

    from kedro.inspection import validate_deployment_grouping

    result = validate_deployment_grouping(pipeline, catalog)
    if not result:
        for issue in result.errors:
            print(issue.message)

Source code in kedro/inspection/grouping.py
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
def validate_deployment_grouping(
    pipeline: Pipeline,
    catalog: CatalogProtocol,
    groups: list[GroupedNodes] | None = None,
    group_by: str | None = "namespace",
) -> DeploymentGroupingResult:
    """Check that a node grouping can run with each group as a separate task.

    Deployment platforms such as Airflow or Databricks run each group from
    `Pipeline.group_nodes_by` as its own task, usually in its own container, so
    groups do not share memory or local disk. This function reports the
    problems that only appear once that happens:

    - `invalid_grouping` (error): only for `groups` passed in. A node is in no
      group, in more than one group or not in the pipeline, a group is empty, or
      a group name is repeated. The remaining checks are skipped.
    - `group_cycle` (error): groups depend on each other in a loop, usually
      because a namespace is interrupted by a node outside it.
    - `ephemeral_boundary` (error): a dataset produced in one group and used in
      another is only kept in memory.
    - `local_boundary` (warning): a dataset passed between groups is saved to
      local disk. Databricks shared paths such as `/dbfs/` and `/Volumes/` are
      not reported.
    - `single_node_groups` (info): groups that contain one node.

    Datasets are resolved the way the catalog resolves them at run time,
    including dataset factories and catch-all patterns, but from configuration
    only: no data is loaded and no dataset class is imported. The function
    never raises for issues it finds; call `raise_if_failed` on the result to
    raise.

    Args:
        pipeline: The pipeline to deploy.
        catalog: The catalog the deployed pipeline will use.
        groups: Groups to check. Defaults to `pipeline.group_nodes_by(group_by)`.
        group_by: Grouping strategy passed to `Pipeline.group_nodes_by` when
            `groups` is not given.

    Returns:
        A `DeploymentGroupingResult`, truthy when no errors were found.

    Example:
    ```python
        from kedro.inspection import validate_deployment_grouping

        result = validate_deployment_grouping(pipeline, catalog)
        if not result:
            for issue in result.errors:
                print(issue.message)
    ```
    """
    if groups is None:
        groups = pipeline.group_nodes_by(group_by)
    group_names = tuple(g.name for g in groups)

    structural = _check_structure(pipeline, groups)
    if structural:
        return DeploymentGroupingResult(groups=group_names, issues=tuple(structural))

    node_to_group = {node_name: g.name for g in groups for node_name in g.nodes}
    boundaries = _find_dataset_boundaries(pipeline, node_to_group)
    issues = [
        *_check_cycles(group_names, boundaries),
        *_check_dataset_boundaries(catalog, boundaries),
        *_check_single_node_groups(groups),
    ]
    issues.sort(key=lambda issue: _SEVERITY_ORDER[issue.severity])
    return DeploymentGroupingResult(groups=group_names, issues=tuple(issues))

kedro.inspection.grouping.DeploymentGroupingResult dataclass

DeploymentGroupingResult(groups, issues=tuple())

Outcome of validate_deployment_grouping.

Truthy when no issue has severity "error", so if not result: detects a grouping that will fail once deployed.

Attributes:

  • groups (tuple[str, ...]) –

    Names of the checked groups.

  • issues (tuple[DeploymentGroupingIssue, ...]) –

    Issues found, ordered errors first, then warnings, then info.

errors property

errors

Issues with severity "error".

status property

status

"failed" if there is at least one error, otherwise "passed".

warnings property

warnings

Issues with severity "warning".

raise_if_failed

raise_if_failed()

Raise DeploymentGroupingError if there is at least one error.

Source code in kedro/inspection/grouping.py
122
123
124
125
def raise_if_failed(self) -> None:
    """Raise `DeploymentGroupingError` if there is at least one error."""
    if self.errors:
        raise DeploymentGroupingError(self)

to_dict

to_dict()

Return a JSON-safe dictionary representation.

Source code in kedro/inspection/grouping.py
127
128
129
130
131
132
133
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-safe dictionary representation."""
    return {
        "status": self.status,
        "groups": list(self.groups),
        "issues": [issue.to_dict() for issue in self.issues],
    }

kedro.inspection.grouping.DeploymentGroupingIssue dataclass

DeploymentGroupingIssue(code, severity, message, datasets=(), groups=(), nodes=())

A problem found when checking a node grouping for deployment.

Attributes:

  • code (IssueCode) –

    Kind of issue, one of "invalid_grouping", "group_cycle", "ephemeral_boundary", "local_boundary" or "single_node_groups".

  • severity (IssueSeverity) –

    Fixed for each code. "error" means the pipeline will fail with each group run as a separate task, "warning" means it may fail depending on where the tasks run, and "info" is an observation that needs no change. Severity only describes the issue: nothing is stopped because of it, and the caller decides how to act.

  • message (str) –

    Description of the issue and how to fix it.

  • datasets (tuple[str, ...]) –

    Names of the datasets involved.

  • groups (tuple[str, ...]) –

    Names of the groups involved.

  • nodes (tuple[str, ...]) –

    Names of the nodes involved.

to_dict

to_dict()

Return a JSON-safe dictionary representation.

Source code in kedro/inspection/grouping.py
77
78
79
80
81
82
83
84
85
86
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-safe dictionary representation."""
    return {
        "code": self.code,
        "severity": self.severity,
        "message": self.message,
        "datasets": list(self.datasets),
        "groups": list(self.groups),
        "nodes": list(self.nodes),
    }

kedro.inspection.grouping.DeploymentGroupingError

DeploymentGroupingError(result)

Bases: Exception

Raised by DeploymentGroupingResult.raise_if_failed when a grouping has errors.

Attributes:

  • result –

    The result that contained the errors.

Source code in kedro/inspection/grouping.py
143
144
145
146
def __init__(self, result: DeploymentGroupingResult):
    self.result = result
    details = "\n".join(f"- {issue.message}" for issue in result.errors)
    super().__init__(f"Node grouping failed validation:\n{details}")