Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 6 additions & 0 deletions changelog.d/ITL-1988.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
### Added

- Read-only loaded jobs display their saved pipeline diagram in notebooks.
Select a node to see its saved schema and whether a stored-result reader is configured.
- Read-only jobs, their node mappings and stored sources have readable text
representations. Stored sources show their schema and a row preview in notebooks.
23 changes: 23 additions & 0 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,17 @@ with TemporaryDirectory() as directory:
saved = Path(directory) / "bmi.json"
job.save(saved)
view = PipelineJob.load(saved, database=database, read_only=True)
print(view)
# Read-only job 'bmi' (provisional) — 1 stored-result source, 1 without a reader
# See .nodes for stored sources, .unavailable for reasons and .diagram() for the graph.
print(view.nodes)
# Stored node sources
# 'mice' (source) — no reader (source slots do not store their original data)
# 'bmi' (function pod) — reader configured (matching rows checked on read)
print(view.nodes["bmi"])
# Stored results from job 'bmi' · 'bmi' (function pod)
# Tags (subject_id: str)
# Data (bmi: float)
print(sorted(view.labels))
# ['bmi', 'mice']
print(sorted(view.nodes))
Expand All @@ -152,8 +163,20 @@ with TemporaryDirectory() as directory:
# ['mice']
print(view.nodes["bmi"].as_table().sort_by("subject_id").to_pylist())
# [{'subject_id': 'mouse_01', 'bmi': 1756.9444444444446}, {'subject_id': 'mouse_02', 'bmi': 2209.9999999999995}]
print(view.diagram())
# Job 'bmi': 2 nodes
# mice (source)
# bmi (function pod) <- mice
```

In a notebook, put `view` or `view.diagram()` at the end of a cell to see the saved
graph. Select a node to see its schema and whether a stored-result reader is
configured. Drawing the diagram uses saved source and schema metadata. Readers
check for matching rows when used.
Display a stored source such as `view.nodes["bmi"]` to see its columns and the same
stored-row preview as `head()`. For columns with logical types, the notebook shows the
saved schema and leaves row previews to an explicit `head()` call.

`view.labels` lists every saved label. `view.nodes` holds the stored sources for
function nodes with a saved run key and a result database and operators with an
existing cache. The sources preserve the identity, Arrow schemas, provenance and
Expand Down
48 changes: 48 additions & 0 deletions src/orcapod/core/sources/derived_source.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import dataclasses
import html
import json
import re
from collections.abc import Collection, Mapping, Sequence
Expand All @@ -26,6 +27,7 @@
require_current_bindings,
)
from orcapod.core.sources.base import RootSource
from orcapod.core.sources.display_names import SavedSchemaDisplay, node_kind_text
from orcapod.core.sources.provisional import (
TagsAsDataRoute,
warn_provisional_source,
Expand Down Expand Up @@ -483,6 +485,9 @@ def __init__(
# methods explicitly identify their route.
route: TagsAsDataRoute = kwargs.pop("_tags_as_data_route", "DerivedSource")
source_only = bool(kwargs.pop("_source_only", False))
self._saved_display_schema: SavedSchemaDisplay | None = kwargs.pop(
"_saved_display_schema", None
)
key_columns = normalize_record_id_columns(record_id_columns)
if tags_as_data is None:
if isinstance(origin, RootSource):
Expand Down Expand Up @@ -746,6 +751,49 @@ def from_config(
# Stream interface
# -------------------------------------------------------------------------

@override
def __repr__(self) -> str:
"""Describe a saved job's stored source without reading its rows."""
schema = self._saved_display_schema
if schema is None:
return super().__repr__()
# The read-only loader only provides display metadata for saved job nodes.
origin = cast("FunctionJobNode | OperatorJobNode", self._origin)
name = ".".join(origin.job_name or ())
header = f"Stored results from job {name!r} · {origin.label!r} ({node_kind_text(origin.node_type)})"
lines = [header]
for group, fields in (("Tags", schema.tags), ("Data", schema.data)):
columns = ", ".join(f"{key}: {text}" for key, text in fields)
lines.append(f" {group} ({columns or 'none'})")
return "\n".join(lines)

@override
def __str__(self) -> str:
"""Use the saved source's description when printed."""
if self._source_only:
return repr(self)
return super().__str__()

@override
def _display_name(self) -> str:
"""Use the saved node label in the notebook preview."""
if self._source_only:
return self._origin.label
return super()._display_name()

@override
def _repr_html_(self) -> str:
"""Show the saved source's metadata alongside its usual head preview."""
schema = self._saved_display_schema
if schema is None:
return super()._repr_html_()
header = f"<pre>{html.escape(repr(self))}</pre>"
if schema.has_logical_types:
return (
header + "<p>Use .head() to preview stored rows with logical types.</p>"
)
return header + super()._repr_html_()

def output_schema(
self,
*,
Expand Down
86 changes: 83 additions & 3 deletions src/orcapod/core/sources/display_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,91 @@
from __future__ import annotations

from collections.abc import Collection, Iterable, Mapping
import re
from dataclasses import dataclass
from types import GetSetDescriptorType
from typing import Any


_NODE_KIND_TEXT = {
"source": "source",
"operator": "operator",
"function": "function pod",
"side_effect_function": "function pod with side effects",
"side_effect": "side-effect pod",
}


def node_kind_text(kind: str) -> str:
"""Return the display name of a node's kind."""
return _NODE_KIND_TEXT.get(kind, kind)


def schema_pairs(schema: Mapping[str, object]) -> tuple[tuple[str, str], ...]:
"""Format the column names and types of a live schema."""
return tuple((name, _schema_type_text(tp)) for name, tp in schema.items())


def _schema_type_text(tp: object) -> str:
"""Format a Python type as it appears in a pipeline diagram."""
if isinstance(tp, type) and not getattr(tp, "__args__", None):
return tp.__name__
return str(tp).replace("typing.", "")


_SAVED_EXTENSION = re.compile(r"extension<([^;<>]+);[0-9a-f]*>")


@dataclass(frozen=True)
class SavedSchemaDisplay:
"""The displayable columns of a saved node, independent of registered classes."""

tags: tuple[tuple[str, str], ...]
data: tuple[tuple[str, str], ...]
has_logical_types: bool

@classmethod
def from_descriptor(cls, schema: Mapping[str, Any]) -> SavedSchemaDisplay:
"""Build display text from the Arrow type declarations stored in a job."""
from orcapod.pipeline.serialization import parse_arrow_type_string
from orcapod.semantic_types.universal_converter import UniversalTypeConverter

converter = UniversalTypeConverter()
has_logical_types = False

def columns(group: str) -> tuple[tuple[str, str], ...]:
nonlocal has_logical_types
declarations: dict[str, str] = schema.get(group, {})
nullable = set(schema.get("nullable", {}).get(group, ()))
descriptions: list[tuple[str, str]] = []
for name, text in declarations.items():
if "extension<" in text:
has_logical_types = True
description = _SAVED_EXTENSION.sub(r"\1", text)
else:
try:
arrow_type = parse_arrow_type_string(text)
description = _schema_type_text(
converter.arrow_type_to_python_type(arrow_type)
)
except (ValueError, TypeError, NotImplementedError):
description = text
descriptions.append(
(name, f"{description} | None" if name in nullable else description)
)
return tuple(descriptions)

tags, data = columns("tag"), columns("data")
return cls(tags, data, has_logical_types)


def stored_result_access(reason: str | None) -> str:
"""Describe a saved node's reader without making a claim about stored rows."""
if reason is not None:
return f"no reader ({reason})"
return "reader configured (matching rows checked on read)"


@dataclass(frozen=True)
class LabelledSource:
"""A source with an assigned label, as a display names it.
Expand All @@ -36,19 +116,19 @@ class LabelledSource:
_TYPE_DICT: Any = type.__dict__["__dict__"]


def _mro(cls: type) -> tuple[type, ...]:
def class_mro(cls: type) -> tuple[type, ...]:
"""Return a class and its bases, read past any metaclass hook."""
return _TYPE_MRO.__get__(cls)


def class_dicts(cls: type) -> list[Mapping[str, Any]]:
"""Return the dictionaries of a class and its bases, read past any metaclass hook."""
return [_TYPE_DICT.__get__(base) for base in _mro(cls)]
return [_TYPE_DICT.__get__(base) for base in class_mro(cls)]


def _is_a(source: object, cls: type) -> bool:
"""Whether ``source`` is an instance of ``cls`` by its real type."""
return any(b is cls for b in _mro(type(source)))
return any(b is cls for b in class_mro(type(source)))


def _stored(source: object) -> Mapping[str, Any]:
Expand Down
Loading
Loading