diff --git a/changelog.d/ITL-1988.md b/changelog.d/ITL-1988.md new file mode 100644 index 000000000..9d6c0cb45 --- /dev/null +++ b/changelog.d/ITL-1988.md @@ -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. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 51da440ec..556cfd465 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -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)) @@ -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 diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 6de5b82bc..8a15fbe67 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -1,6 +1,7 @@ from __future__ import annotations import dataclasses +import html import json import re from collections.abc import Collection, Mapping, Sequence @@ -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, @@ -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): @@ -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"
{html.escape(repr(self))}"
+ if schema.has_logical_types:
+ return (
+ header + "Use .head() to preview stored rows with logical types.
" + ) + return header + super()._repr_html_() + def output_schema( self, *, diff --git a/src/orcapod/core/sources/display_names.py b/src/orcapod/core/sources/display_names.py index f7f3d1a1d..602594d0d 100644 --- a/src/orcapod/core/sources/display_names.py +++ b/src/orcapod/core/sources/display_names.py @@ -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. @@ -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]: diff --git a/src/orcapod/pipeline/diagram.py b/src/orcapod/pipeline/diagram.py index 28b73c2c7..48016c424 100644 --- a/src/orcapod/pipeline/diagram.py +++ b/src/orcapod/pipeline/diagram.py @@ -4,8 +4,8 @@ job displayed at the end of a notebook cell shows one. The diagram is made in two steps: 1. A model (``PipelineDiagram.to_dict()``): plain, JSON-able nodes and edges with labels, - kinds, schemas and, for a job, each node's run status. It is read without computing - anything: each node's ``output_schema()`` (predicted, never computed), its kind and + kinds, schemas and either run status or stored-result availability for a job. It is + read without computing anything: each node's ``output_schema()``, its kind and label, the run state a job node holds in memory and the job's last ``RunSummary``. It calls no user function, reads no source and no database, and writes nothing (the rule of ``head()`` and the notebook preview). @@ -33,19 +33,29 @@ import json import re from collections.abc import Iterable, Mapping, Sequence -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, Protocol from typing_extensions import override -from orcapod.core.sources.display_names import class_dicts, node_display_names +from orcapod.core.sources.display_names import ( + SavedSchemaDisplay, + class_dicts, + class_mro, + node_display_names, + node_kind_text, + schema_pairs, + stored_result_access, +) from orcapod.types.provenance import Highlight from orcapod.utils.in_development import warn_in_development if TYPE_CHECKING: from orcapod.pipeline.dag import OrcaDAG + from orcapod.pipeline.job import PipelineJob from orcapod.pipeline.run_summary import NodeRunSummary + from orcapod.pipeline.source_only_job import SourceOnlyPipelineJob __all__ = ["PipelineDiagram"] @@ -62,16 +72,6 @@ def name(self) -> tuple[str, ...]: ... def dag(self) -> OrcaDAG[Any]: ... -# The kind of each ``node_type``, as the diagram writes it. -_KIND_TEXT: dict[str, str] = { - "source": "source", - "operator": "operator", - "function": "function pod", - "side_effect_function": "function pod with side effects", - "side_effect": "side-effect pod", -} - - @dataclass(frozen=True) class _Node: """One node of the model, with everything shown about it.""" @@ -89,6 +89,7 @@ class _Node: asked: str = "" shown: str = "" keeps: tuple[str, ...] = () + layout_status: str = "" @property def text(self) -> str: @@ -99,7 +100,7 @@ def text(self) -> str: @property def kind_line(self) -> str: """The kind, the detail and the status, as written under the label.""" - parts = [_KIND_TEXT.get(self.kind, self.kind), self.detail, self.status] + parts = [node_kind_text(self.kind), self.detail, self.status] return " · ".join(part for part in parts if part) @@ -125,49 +126,52 @@ def key(self) -> tuple[int, int, bool]: # --------------------------------------------------------------------------- -def _type_text(tp: Any) -> str: - """A short text for a schema type: ``int``, ``list[float]``, ``str | None``.""" - if isinstance(tp, type) and not getattr(tp, "__args__", None): - return tp.__name__ - return str(tp).replace("typing.", "") - - -def _schema_pairs(schema: Mapping[str, Any]) -> tuple[tuple[str, str], ...]: - """A schema's column names and type texts, in schema order.""" - return tuple((name, _type_text(tp)) for name, tp in schema.items()) - - def _node_detail(node: Any) -> str: """What the node is beyond its label: a source's class, an operator's or function's name.""" if node.node_type == "source": bound = getattr(node, "bound_source", None) return type(bound).__name__ if bound is not None else "" - name = _producer_name(node) - if name is None: + producer = getattr(node, "producer", None) + if producer is None: + return "" + name = ( + type(producer).__name__ + if node.node_type == "operator" + else getattr(producer, "label", None) + ) + return _producer_detail(node.label, name) + + +def _producer_detail(label: str, name: object) -> str: + """Show a producer's name when it adds information beyond the node label.""" + if not isinstance(name, str): return "" # A label that is the name, numbered when several steps share it # (``SelectDataColumns_2``), says it already. - label: str = node.label numbered = label.startswith(f"{name}_") and label[len(name) + 1 :].isdigit() return "" if label == name or numbered else name -def _producer_name(node: Any) -> str | None: - """The operator's class name or the function's name, or ``None``. +def _saved_operator_name(node: Any) -> str: + """Read the operator name written in the saved node descriptor.""" + config = node._descriptor.get("operator_config") + name = config.get("class_name") if isinstance(config, dict) else None + return name if isinstance(name, str) else "" - An operator is named by its class, never by its label, which the user chooses - (``Join(label="joined")`` is a ``Join``). - """ - producer = getattr(node, "producer", None) - if producer is None: + +def _operator_type(node: Any, *, saved_name: str | None) -> type | None: + """Find the operator class so the diagram can read its static edge roles.""" + if node.node_type != "operator": return None - if node.node_type == "operator": - return type(producer).__name__ - name = getattr(producer, "label", None) - return name if isinstance(name, str) else None + if saved_name is not None: + from orcapod.pipeline.serialization import OPERATOR_REGISTRY + + return OPERATOR_REGISTRY.get(saved_name) + producer = getattr(node, "producer", None) + return None if producer is None else type(producer) -def _collapsible(node: Any) -> bool: +def _collapsible(node: Any, *, saved: bool, operator_type: type | None) -> bool: """Whether a node's operator only joins, chooses or renames columns. ``collapse=True`` folds such a node into the edge it lies on. Decided by the @@ -186,21 +190,28 @@ def _collapsible(node: Any) -> bool: SelectTagColumns, ) - return node.node_type == "operator" and isinstance( - getattr(node, "producer", None), - ( - Join, - SelectDataColumns, - SelectTagColumns, - SelectColumns, - DropDataColumns, - DropTagColumns, - DropColumns, - MapData, - MapTags, - MapColumns, - ), + if node.node_type != "operator": + return False + foldable_bases = ( + Join, + SelectDataColumns, + SelectTagColumns, + SelectColumns, + DropDataColumns, + DropTagColumns, + DropColumns, + MapData, + MapTags, + MapColumns, ) + if saved: + # ABC subclass checks can visit unrelated classes and invoke metaclass hooks. + return operator_type is not None and any( + ancestor is base + for ancestor in class_mro(operator_type) + for base in foldable_bases + ) + return isinstance(getattr(node, "producer", None), foldable_bases) def _upstream_labels(node: Any, label_of: Mapping[int, str]) -> list[str | None]: @@ -216,24 +227,27 @@ def _upstream_labels(node: Any, label_of: Mapping[int, str]) -> list[str | None] return [label_of.get(id(stream)) for stream in node.upstreams] -def _declared(producer: Any, name: str) -> Any: +def _declared(operator_type: type, name: str) -> Any: """What an operator's class declares, read without running any code of the class. Args: - producer: The operator, or ``None``. + operator_type: The operator's class. name: The class attribute. Returns: The value the class or its nearest base holds, as stored; ``None`` for none. """ - for namespace in class_dicts(type(producer)): + for namespace in class_dicts(operator_type): if name in namespace: return namespace[name] return None def _input_roles( - node: Any, upstream_labels: Sequence[str], label_of: Mapping[int, str] + node: Any, + upstream_labels: Sequence[str], + label_of: Mapping[int, str], + operator_type: type | None, ) -> list[tuple[str, bool]]: """A node's inputs, each with whether it only constrains the others (ITL-1455). @@ -244,15 +258,15 @@ def _input_roles( node: The node. upstream_labels: The labels of the nodes it reads from, in drawing order. label_of: The label of each node of the graph, by the node's ``id()``. + operator_type: The operator's class, when available. Returns: The label and role of each input, in the order of ``upstream_labels``. """ plain = [(label, False) for label in upstream_labels] - if node.node_type != "operator": + if operator_type is None: return plain - producer = getattr(node, "producer", None) - positions = _declared(producer, "CONSTRAINING_INPUTS") + positions = _declared(operator_type, "CONSTRAINING_INPUTS") if type(positions) is not tuple or not positions: return plain ordered = _upstream_labels(node, label_of) @@ -335,7 +349,11 @@ def _failed_rows(node: Any) -> int: def _constraint_fact( - node: Any, label_of: Mapping[int, str], by_label: Mapping[str, Any] + node: Any, + label_of: Mapping[int, str], + by_label: Mapping[str, Any], + operator_type: type, + saved_schemas: Mapping[str, SavedSchemaDisplay] | None, ) -> tuple[str, str] | None: """What a node's constraining inputs do, from its inputs' predicted tag columns. @@ -343,17 +361,21 @@ def _constraint_fact( node: An operator node with a constraining input. label_of: The label of each node of the graph, by the node's ``id()``. by_label: The nodes, by label. + operator_type: The operator's class. + saved_schemas: The saved nodes' schema display metadata for a read-only job. Returns: The tags the rows match on, or ``None`` when the operator does not declare that it matches on the shared tags, or the columns are not available (a loaded node whose saved types cannot be restored). """ - if _declared(node.producer, "CONSTRAINT_MATCHES_SHARED_TAGS") is not True: + if _declared(operator_type, "CONSTRAINT_MATCHES_SHARED_TAGS") is not True: return None try: tag_keys = [ tuple(by_label[label].output_schema()[0]) + if saved_schemas is None + else tuple(name for name, _ in saved_schemas[label].tags) for label in _upstream_labels(node, label_of) if label is not None ] @@ -383,29 +405,20 @@ def _topological_labels( return order -def _is_job(pipeline: _Drawable) -> bool: - """Whether the diagram is a job's: decided by the object drawn, not by its nodes. - - An empty compiled job has no nodes, and is still a job. - """ - from orcapod.pipeline.job import PipelineJob - - return isinstance(pipeline, PipelineJob) - - def _build_model( - pipeline: _Drawable, + dag: OrcaDAG[Any], *, - is_job: bool, + job: PipelineJob | None, + read_only: SourceOnlyPipelineJob | None, collapse: bool, highlight: Highlight | None = None, ) -> tuple[list[_Node], list[_Edge]]: """Read a compiled pipeline or job into the model's nodes and edges. Args: - pipeline: A compiled ``Pipeline`` or ``PipelineJob``. - is_job: Whether it is a job: its nodes then show their run status, and the - job's ``last_run`` gives row counts. + dag: The graph of the pipeline or job. + job: A runnable job, whose nodes show their run status and row counts. + read_only: The descriptor-backed view of a read-only job, when drawn. collapse: Whether to fold the column-choosing, renaming and join operators that feed exactly one node into the edges they lie on. highlight: The nodes and edges to emphasize, by label. A folded edge is @@ -414,9 +427,13 @@ def _build_model( Returns: The nodes in topological order (ties by label) and the edges, sorted. """ - dag = pipeline.dag - # A job's ``last_run`` is a property of ``PipelineJob``; read only for a job. - last_run = getattr(pipeline, "last_run", None) if is_job else None + last_run = job.last_run if job is not None else None + saved_schemas = ( + None if read_only is None else read_only._schemas # pyright: ignore[reportPrivateUsage] # saved diagram metadata + ) + source_details = ( + {} if read_only is None else read_only._source_details # pyright: ignore[reportPrivateUsage] # saved diagram metadata + ) summaries: Mapping[str, NodeRunSummary] = ( last_run.nodes if last_run is not None else {} ) @@ -432,8 +449,21 @@ def _build_model( names.sort() label_of = {id(node): label for label, node in by_label.items()} + saved_operator_names = ( + {} + if read_only is None + else { + label: _saved_operator_name(node) + for label, node in by_label.items() + if node.node_type == "operator" + } + ) + operator_types = { + label: _operator_type(node, saved_name=saved_operator_names.get(label)) + for label, node in by_label.items() + } roles = { - label: _input_roles(node, preds[label], label_of) + label: _input_roles(node, preds[label], label_of, operator_types[label]) for label, node in by_label.items() } @@ -443,8 +473,12 @@ def _build_model( # drawn as data. folded = { label - for label, node in by_label.items() - if _collapsible(node) + for label, operator_type in operator_types.items() + if _collapsible( + by_label[label], + saved=read_only is not None, + operator_type=operator_type, + ) and len(succs[label]) == 1 and not any(constrains for _, constrains in roles[label]) } @@ -490,50 +524,81 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: # Every node's status, folded ones too, in topological order: a node's status can # depend on the statuses of the nodes it reads from. statuses: dict[str, str] = {} - if is_job: + if job is not None: for label in _topological_labels(preds, succs): statuses[label] = _job_status( by_label[label], (statuses[upstream] for upstream in preds[label]) ) - source_names = node_display_names(by_label.values()) + source_names = node_display_names(by_label.values()) if read_only is None else {} nodes: list[_Node] = [] for label in shown: node = by_label[label] summary = summaries.get(label) - facts = _run_facts(summary) if is_job else () + facts = _run_facts(summary) + if read_only is not None: + facts = ( + ( + "stored results", + stored_result_access(read_only.unavailable.get(label)), + ), + ) source_text, source_id = source_names.get(label, ("", "")) if source_id: facts = (("source id", source_id), *facts) - try: - tag_schema, data_schema = node.output_schema() - except ValueError as error: - # A loaded node whose saved column types cannot be restored (a class only - # the writer registered) refuses to give its schema; the diagram still - # draws the graph and says why the columns are missing. - tag_schema, data_schema = {}, {} - facts = (*facts, ("schema", f"not available: {error}")) + if saved_schemas is None: + try: + tag_schema, data_schema = node.output_schema() + except ValueError as error: + # A live schema can be unavailable when a saved type cannot be restored. + tags, data = (), () + facts = (*facts, ("schema", f"not available: {error}")) + else: + tags, data = schema_pairs(tag_schema), schema_pairs(data_schema) + else: + schema = saved_schemas.get(label) + tags, data = ((), ()) if schema is None else (schema.tags, schema.data) keeps: tuple[str, str] | None = None - if any(constrains for _, constrains in roles[label]): - keeps = _constraint_fact(node, label_of, by_label) + operator_type = operator_types[label] + if operator_type is not None and any( + constrains for _, constrains in roles[label] + ): + keeps = _constraint_fact( + node, label_of, by_label, operator_type, saved_schemas + ) if keeps is not None: facts = (*facts, keeps) steps = list(dict.fromkeys(folded_into.get(label, []))) if steps: facts = (*facts, ("folded steps", ", ".join(steps))) + if read_only is None: + detail = _node_detail(node) + elif node.node_type == "source": + detail = source_details.get(label, "") + else: + detail = _producer_detail(label, saved_operator_names.get(label)) + layout_status = "" + if read_only is not None and highlight is None: + # Reserve the same space as a freshly loaded job. These labels are + # inputs to measurement only and never appear in the read-only output. + if node.node_type == "source": + layout_status = "bound" if detail else "unbound" + else: + layout_status = "not run" nodes.append( _Node( index=index[label], label=label, kind=node.node_type, - detail=_node_detail(node), - tag_schema=_schema_pairs(tag_schema), - data_schema=_schema_pairs(data_schema), + detail=detail, + tag_schema=tags, + data_schema=data, # A highlight shows the provenance question only: no run status. status="" if highlight is not None else statuses.get(label, ""), facts=facts, shown=source_text, keeps=keeps or (), + layout_status=layout_status, highlighted=highlight is not None and label in highlight.nodes, mark="" if highlight is None else highlight.mark(label), asked=highlight.asked_text or "asked here" @@ -659,6 +724,8 @@ def _kind_lines(node: _Node) -> tuple[str, ...]: def _node_size(node: _Node) -> tuple[float, float]: """A node's width and height: room for its label and its wrapped kind line.""" + if node.layout_status: + node = replace(node, status=node.layout_status) return ( _text_room(node) + 2 * _PAD, _NODE_H + _LINE_H * (len(_kind_lines(node)) - 1), @@ -1226,7 +1293,7 @@ def _svg( def _table(nodes: Sequence[_Node], inputs: Mapping[int, str]) -> str: - """Every node with its inputs, schema and run facts: shown where scripts do not run.""" + """Every node with its inputs, schema and details, shown without scripts.""" rows = "".join( "" in view.diagram(max_nodes=1).to_html()
+
+ # Reprs share the no-I/O rule of the diagram.
+ assert (
+ str(view)
+ == repr(view)
+ == (
+ "Read-only job 'report' (provisional) — 3 stored-result sources, 4 without a reader\n"
+ " See .nodes for stored sources, .unavailable for reasons and .diagram() for the graph."
+ )
+ )
+ kinds = {
+ "approvals": "source",
+ "measures": "source",
+ "chosen": "operator",
+ "accepted": "operator",
+ "accepted_columns": "operator",
+ "all_results": "function pod",
+ "accepted_results": "function pod",
+ }
+ lines = ["Stored node sources"]
+ for label in view.labels:
+ state = (
+ "reader configured (matching rows checked on read)"
+ if label in view.nodes
+ else f"no reader ({view.unavailable[label]})"
+ )
+ lines.append(f" {label!r} ({kinds[label]}) — {state}")
+ assert repr(view.nodes) == "\n".join(lines)
+ source = view.nodes["accepted_results"]
+ assert str(source) == repr(source)
+ results = repr(source).splitlines()
+ assert (
+ results[0]
+ == "Stored results from job 'report' · 'accepted_results' (function pod)"
+ )
+ assert set(results[1].removeprefix(" Tags (").removesuffix(")").split(", ")) == {
+ "unit: str",
+ "trial: int",
+ }
+ assert results[2] == " Data (total: int, difference: int)"
+
+
+@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is not on PATH")
+def test_selecting_a_saved_node_shows_its_schema_and_availability(
+ saved_job: tuple[Path, InMemoryArrowDatabase], tmp_path: Path
+) -> None:
+ path, db = saved_job
+ view = PipelineJob.load(path, db, read_only=True)
+ available, unavailable = _run_view(
+ view.diagram().to_html(),
+ [
+ {"op": "run", "width": 400},
+ {"op": "select", "label": "accepted_results"},
+ {"op": "observe"},
+ {"op": "select", "label": "accepted"},
+ {"op": "observe"},
+ ],
+ tmp_path,
+ )
+ assert "total: int" in available["panelText"]
+ assert (
+ "stored resultsreader configured (matching rows checked on read)"
+ in available["panelText"]
+ )
+ assert (
+ f"stored resultsno reader ({view.unavailable['accepted']})"
+ in unavailable["panelText"]
+ )
+ assert "not run" not in unavailable["panelText"]
+
+
+def test_stored_node_source_display_uses_head(
+ saved_job: tuple[Path, InMemoryArrowDatabase],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ path, db = saved_job
+ view = PipelineJob.load(path, db, read_only=True)
+ original_head = DerivedSource.head
+ previews: list[tuple[str, dict[str, Any]]] = []
+
+ def forbidden(*_args: object, **_kwargs: object) -> Never:
+ raise AssertionError(
+ "preview computed, checked a source or wrote to the database"
+ )
+
+ def checked_head(source: DerivedSource, **kwargs: Any) -> StreamView:
+ preview = original_head(source, **kwargs)
+ previews.append((preview.label, kwargs))
+ return preview
+
+ monkeypatch.setattr(DerivedSource, "head", checked_head)
+ for cls, methods in (
+ (InMemoryArrowDatabase, ("add_record", "add_records", "flush")),
+ (DerivedSource, ("as_table", "iter_data", "check_for_new_data")),
+ (PythonDataFunction, ("call", "async_call")),
+ (SelectDataColumns, ("process",)),
+ ):
+ for method in methods:
+ monkeypatch.setattr(cls, method, forbidden)
+
+ for label, data_column in (("chosen", "x"), ("accepted_results", "total")):
+ source = view.nodes[label]
+ document = source._repr_html_()
+ assert document.startswith(f"{html.escape(repr(source))}")
+ assert "1 stored row" in document
+ assert f">{data_column}" in document
+ assert previews == [
+ (label, {"columns": {"sort_by_tags": True}})
+ for label in ("chosen", "accepted_results")
+ ]
diff --git a/tests/test_pipeline/loaded_job/test_source_only_display_regressions.py b/tests/test_pipeline/loaded_job/test_source_only_display_regressions.py
new file mode 100644
index 000000000..202d21328
--- /dev/null
+++ b/tests/test_pipeline/loaded_job/test_source_only_display_regressions.py
@@ -0,0 +1,393 @@
+"""Independent review probes for the pinned read-only display."""
+
+from __future__ import annotations
+
+import dataclasses
+from abc import ABC
+from pathlib import Path
+from typing import Any, Never
+
+import pytest
+
+from orcapod import PipelineJob, function_pod
+from orcapod.core.streams import base as stream_base
+from orcapod.databases import InMemoryArrowDatabase
+from orcapod.operators import SelectDataColumns, SemiJoin
+from orcapod.pipeline import diagram as diagram_module
+from orcapod.pipeline.diagram import Direction
+from orcapod.pipeline.serialization import OPERATOR_REGISTRY, SOURCE_REGISTRY
+from orcapod.pipeline.source_only_job import SourceOnlyPipelineJob
+from orcapod.sources import CSVSource, DictSource
+from orcapod.types import CacheMode
+from orcapod.types.provenance import Highlight
+from tests.test_pipeline.loaded_job.test_source_only_diagram import (
+ _geometry,
+ _without_run_facts,
+ summarize,
+)
+from tests.test_pipeline.loaded_job.test_source_only_diagram import (
+ saved_job as saved_job,
+)
+
+
+@pytest.mark.parametrize("reverse", [False, True])
+@pytest.mark.parametrize("collapse,direction", [(True, "TB"), (False, "LR")])
+def test_recoverable_csv_sources_match_loaded_job(
+ tmp_path: Path,
+ reverse: bool,
+ collapse: bool,
+ direction: Direction,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ db = InMemoryArrowDatabase()
+ job = PipelineJob("report", database=db)
+ tables = [
+ ("measures", "unit,trial,x,y", ["a,1,7,3", "b,2,8,4"]),
+ ("approvals", "unit,trial,approved,weight", ["a,1,1,9", "b,2,0,8"]),
+ ]
+ with job:
+ sources = {}
+ for label, header, rows in tables[::-1] if reverse else tables:
+ path = tmp_path / f"{label}.csv"
+ csv_rows = [header, *rows]
+ if reverse:
+ csv_rows = [",".join(line.split(",")[::-1]) for line in csv_rows]
+ path.write_text("\n".join(csv_rows) + "\n")
+ sources[label] = CSVSource(
+ path,
+ source_id=label,
+ label=f"{label} display",
+ tag_columns=["trial", "unit"] if reverse else ["unit", "trial"],
+ tag_only_columns=True,
+ )
+ chosen = sources["measures"].select_data_columns(
+ ("y", "x") if reverse else ("x", "y"), label="chosen"
+ )
+ accepted = SemiJoin(label="accepted")(chosen, sources["approvals"])
+ _ = summarize.pod(chosen, label="all_results")
+ selected = accepted.select_data_columns(("x", "y"), label="accepted_columns")
+ _ = summarize.pod(selected, label="accepted_results")
+ job.nodes["chosen"].attach_databases(db.at(*job.name), cache_mode=CacheMode.LOG)
+ assert job.run().ok
+ path = tmp_path / "job.json"
+ job.save(path)
+ normal = PipelineJob.load(path, db)
+ assert not normal.unbound_sources
+
+ def unexpected_source(*_args: object, **_kwargs: object) -> CSVSource:
+ raise AssertionError("read-only display must not reconstruct a source")
+
+ monkeypatch.setattr(CSVSource, "from_config", unexpected_source)
+ view = PipelineJob.load(path, db, read_only=True)
+ highlight = Highlight(
+ nodes=frozenset({"accepted", "accepted_columns", "accepted_results"}),
+ edges=frozenset(
+ {("accepted", "accepted_columns"), ("accepted_columns", "accepted_results")}
+ ),
+ )
+ expected = normal.diagram(
+ collapse=collapse, direction=direction, highlight=highlight
+ )
+ actual = view.diagram(collapse=collapse, direction=direction, highlight=highlight)
+ assert _geometry(actual) == _geometry(expected)
+ assert _without_run_facts(actual.to_dict()) == _without_run_facts(
+ expected.to_dict()
+ )
+
+
+def test_availability_does_not_claim_rows_in_an_empty_store(
+ saved_job: tuple[Path, InMemoryArrowDatabase],
+) -> None:
+ path, db = saved_job
+ view = PipelineJob.load(
+ path, db, result_database=InMemoryArrowDatabase(), read_only=True
+ )
+ label = "accepted_results"
+ assert view.nodes[label].stored_result_origin is None
+ with pytest.raises(RuntimeError, match="no matching stored rows"):
+ _ = view.nodes[label].head()
+ node = next(n for n in view.diagram().to_dict()["nodes"] if n["label"] == label)
+ state = "reader configured (matching rows checked on read)"
+ assert dict(node["facts"])["stored results"] == state
+ assert f"'{label}' (function pod) — {state}" in repr(view.nodes)
+
+
+class ObservedType(type):
+ active = False
+ names: list[str] = []
+
+ def __getattribute__(cls, name: str) -> object:
+ if ObservedType.active:
+ ObservedType.names.append(name)
+ return super().__getattribute__(name)
+
+
+@dataclasses.dataclass
+class Reading(metaclass=ObservedType):
+ value: int
+
+
+@function_pod(output_keys=("reading", "difference"))
+def logical_summary(x: int, y: int) -> tuple[Reading, int]:
+ """Return a logical column and a primitive column from the saved pod."""
+ return Reading(x + y), x - y
+
+
+@pytest.fixture
+def logical_view(tmp_path: Path) -> SourceOnlyPipelineJob:
+ db = InMemoryArrowDatabase()
+ job = PipelineJob("logical", database=db)
+ with job:
+ source = DictSource(
+ [{"unit": "a", "trial": 1, "x": 7, "y": 3}],
+ source_id="input",
+ tag_columns=["unit", "trial"],
+ tag_only_columns=True,
+ )
+ _ = logical_summary.pod(source, label="summary")
+ assert job.run().ok
+ path = tmp_path / "job.json"
+ job.save(path)
+ return PipelineJob.load(path, db, read_only=True)
+
+
+@pytest.mark.parametrize("display", ["diagram", "bundle", "repr", "str", "html"])
+def test_schema_display_runs_no_user_type_hooks(
+ logical_view: SourceOnlyPipelineJob, display: str
+) -> None:
+ view = logical_view
+ source = view.nodes["summary"]
+ methods = {
+ "diagram": lambda: view.diagram().to_html(),
+ "bundle": view._repr_mimebundle_,
+ "repr": lambda: repr(source),
+ "str": lambda: str(source),
+ "html": source._repr_html_,
+ }
+ ObservedType.names = []
+ ObservedType.active = True
+ try:
+ result = methods[display]()
+ finally:
+ ObservedType.active = False
+ assert ObservedType.names == []
+ assert "Reading" in str(result)
+
+
+def test_default_diagrams_have_the_same_geometry(
+ saved_job: tuple[Path, InMemoryArrowDatabase],
+) -> None:
+ path, db = saved_job
+ normal = PipelineJob.load(path, db)
+ view = PipelineJob.load(path, db, read_only=True)
+ assert _geometry(view.diagram()) == _geometry(normal.diagram())
+
+
+def test_registered_operator_class_descriptor_does_not_run_during_display(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ touched: list[str] = []
+
+ class Naming(type(SelectDataColumns)):
+ @property
+ def __name__(cls) -> str: # pyright: ignore[reportIncompatibleVariableOverride] # intentionally replace the name with a descriptor
+ touched.append("operator name")
+ return "LiveSelect"
+
+ class ReviewSelect(SelectDataColumns, metaclass=Naming):
+ def to_config(self) -> dict[str, Any]:
+ return {**super().to_config(), "class_name": "ReviewSelect"}
+
+ monkeypatch.setitem(OPERATOR_REGISTRY, "ReviewSelect", ReviewSelect)
+ db = InMemoryArrowDatabase()
+ job = PipelineJob("report", database=db)
+ with job:
+ source = DictSource(
+ [{"unit": "a", "trial": 1, "x": 7, "y": 3}],
+ source_id="input",
+ tag_columns=["unit", "trial"],
+ tag_only_columns=True,
+ )
+ selected = ReviewSelect(("x", "y"), label="chosen")(source)
+ _ = summarize.pod(selected, label="summary")
+ assert job.run().ok
+ path = tmp_path / "job.json"
+ job.save(path)
+ view = PipelineJob.load(path, db, read_only=True)
+ touched.clear()
+ diagram = view.diagram()
+ bundle = view._repr_mimebundle_()
+ folded = view.diagram(collapse=True)
+ assert touched == []
+ assert "chosen (operator · ReviewSelect)" in diagram.to_text()
+ assert bundle["text/plain"] == diagram.to_text()
+ assert "chosen" not in {node["label"] for node in folded.to_dict()["nodes"]}
+
+
+def test_registered_source_class_descriptor_does_not_run_during_display(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ data = tmp_path / "measurements.csv"
+ data.write_text("unit,trial,x,y\na,1,7,3\n")
+ db = InMemoryArrowDatabase()
+ job = PipelineJob("report", database=db)
+ with job:
+ source = CSVSource(
+ data,
+ source_id="input",
+ tag_columns=["unit", "trial"],
+ tag_only_columns=True,
+ )
+ _ = summarize.pod(source, label="summary")
+ assert job.run().ok
+ path = tmp_path / "job.json"
+ job.save(path)
+ touched: list[str] = []
+
+ class Naming(type(CSVSource)):
+ @property
+ def __name__(cls) -> str: # pyright: ignore[reportIncompatibleVariableOverride] # intentionally replace the name with a descriptor
+ touched.append("source name")
+ return "ReviewCSV"
+
+ class ReviewCSV(CSVSource, metaclass=Naming):
+ pass
+
+ monkeypatch.setitem(SOURCE_REGISTRY, "csv", ReviewCSV)
+ view = PipelineJob.load(path, db, read_only=True)
+ bundle = view._repr_mimebundle_()
+ assert touched == []
+ assert "input (source · CSVSource)" in bundle["text/plain"]
+
+
+def test_normal_job_diagram_preserves_schema_formatter_errors(
+ saved_job: tuple[Path, InMemoryArrowDatabase], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ path, db = saved_job
+ normal = PipelineJob.load(path, db)
+
+ def fail(_schema: object) -> Never:
+ raise ValueError("schema formatter failed")
+
+ monkeypatch.setattr(diagram_module, "schema_pairs", fail)
+ with pytest.raises(ValueError, match="schema formatter failed"):
+ _ = normal.diagram()
+
+
+def test_collapse_does_not_visit_other_operator_metaclasses(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ touched: list[str] = []
+
+ class Naming(type(SelectDataColumns)):
+ def __getattribute__(cls, name: str) -> object:
+ touched.append(name)
+ return super().__getattribute__(name)
+
+ class ReviewSelect(SelectDataColumns, metaclass=Naming):
+ pass
+
+ class ReviewSemiJoin(SemiJoin):
+ def to_config(self) -> dict[str, Any]:
+ return {**super().to_config(), "class_name": "ReviewSemiJoin"}
+
+ monkeypatch.setitem(OPERATOR_REGISTRY, "ReviewSelect", ReviewSelect)
+ monkeypatch.setitem(OPERATOR_REGISTRY, "ReviewSemiJoin", ReviewSemiJoin)
+ db = InMemoryArrowDatabase()
+ job = PipelineJob("review", database=db)
+ with job:
+ measures = DictSource(
+ [{"unit": "a", "trial": 1, "x": 7, "y": 3}],
+ source_id="measures",
+ tag_columns=["unit", "trial"],
+ tag_only_columns=True,
+ )
+ approvals = DictSource(
+ [{"unit": "a", "trial": 1, "approval": 1, "detail": "checked"}],
+ source_id="approvals",
+ tag_columns=["unit", "trial"],
+ tag_only_columns=True,
+ )
+ kept = ReviewSemiJoin(label="kept")(measures, approvals)
+ _ = summarize.pod(kept, label="summary")
+ assert job.run().ok
+ path = tmp_path / "job.json"
+ job.save(path)
+ view = PipelineJob.load(path, db, read_only=True)
+ touched.clear()
+ assert "kept" in view.diagram().to_text()
+ assert "kept" in view.diagram(collapse=True).to_text()
+ assert touched == []
+
+
+def test_ordinary_diagram_keeps_operator_metaclass_name() -> None:
+ class Naming(type(SelectDataColumns)):
+ def __getattribute__(cls, name: str) -> object:
+ if name == "__name__":
+ return "RenderedSelect"
+ return super().__getattribute__(name)
+
+ class ReviewSelect(SelectDataColumns, metaclass=Naming):
+ pass
+
+ job = PipelineJob("name-test", database=InMemoryArrowDatabase())
+ with job:
+ source = DictSource(
+ [{"unit": "a", "trial": 1, "x": 7, "y": 3}],
+ source_id="input",
+ tag_columns=["unit", "trial"],
+ tag_only_columns=True,
+ )
+ selected = ReviewSelect(("x", "y"), label="chosen")(source)
+ _ = summarize.pod(selected, label="summary")
+ node = next(n for n in job.diagram().to_dict()["nodes"] if n["label"] == "chosen")
+ assert node["detail"] == "RenderedSelect"
+
+
+@pytest.mark.parametrize("display", ["repr", "str", "html"])
+def test_saved_source_display_never_visits_registered_source_classes(
+ saved_job: tuple[Path, InMemoryArrowDatabase],
+ monkeypatch: pytest.MonkeyPatch,
+ display: str,
+) -> None:
+ path, db = saved_job
+ touched: list[str] = []
+ watch = False
+
+ class Observed(type(CSVSource)):
+ def __getattribute__(cls, name: str) -> object:
+ if watch:
+ touched.append(name)
+ return super().__getattribute__(name)
+
+ class RegisteredCSV(CSVSource, metaclass=Observed):
+ pass
+
+ monkeypatch.setitem(SOURCE_REGISTRY, "csv", RegisteredCSV)
+ source = PipelineJob.load(path, db, read_only=True).nodes["accepted_results"]
+
+ class UnrelatedABC(ABC):
+ pass
+
+ class Virtual:
+ pass
+
+ # Invalidate negative ABC results before exercising the display.
+ _ = UnrelatedABC.register(Virtual)
+ # Exercise the HTML header independently of the existing stored-row preview.
+ monkeypatch.setattr(stream_base, "preview_html", lambda _source: "Preview
")
+ methods = {
+ "repr": lambda: repr(source),
+ "str": lambda: str(source),
+ "html": source._repr_html_,
+ }
+ watch = True
+ try:
+ value = methods[display]()
+ finally:
+ watch = False
+
+ assert touched == []
+ assert "accepted_results" in value
+ if display == "html":
+ assert value.endswith("Preview
")