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( "" f"{_escape(node.text)}" @@ -1375,7 +1442,8 @@ class PipelineDiagram: operators, function pods, side-effect pods) and the streams between them. Where the notebook runs scripts, the picture can be dragged and zoomed, and selecting a node shows its tag and data schema and, for a job, its run status and the last run's row - counts. Without scripts the picture and a table of the nodes remain. + counts. A read-only job shows stored-result availability in the details panel. + Without scripts the picture and a table of the nodes remain. ``print`` gives a plain-text listing. Making a diagram computes nothing: it reads each node's predicted ``output_schema()``, @@ -1385,7 +1453,7 @@ class PipelineDiagram: diagram made in a process issues ``InDevelopmentWarning`` (once per process). Args: - pipeline: A compiled ``Pipeline`` or ``PipelineJob``. + pipeline: A compiled pipeline, a runnable job or a read-only loaded job. direction: ``"LR"`` lays the graph out left to right, ``"TB"`` top to bottom. collapse: Fold the operators that only choose, rename or join columns (joins, column selections, drops and maps) and feed exactly one node into the edges @@ -1408,13 +1476,16 @@ class PipelineDiagram: def __init__( self, - pipeline: _Drawable, + pipeline: _Drawable | SourceOnlyPipelineJob, *, direction: Direction = "LR", collapse: bool = False, max_nodes: int = 400, highlight: Highlight | None = None, ) -> None: + from orcapod.pipeline.job import PipelineJob + from orcapod.pipeline.source_only_job import SourceOnlyPipelineJob + if direction not in ("LR", "TB"): raise ValueError(f"direction must be 'LR' or 'TB', not {direction!r}") if max_nodes < 1: @@ -1425,8 +1496,15 @@ def __init__( "PipelineDiagram and the notebook display of a pipeline or job) is in " "development: its interface and appearance may change in any release.", ) + job = pipeline if isinstance(pipeline, PipelineJob) else None + if isinstance(pipeline, SourceOnlyPipelineJob): + dag = pipeline._dag # pyright: ignore[reportPrivateUsage] # descriptor-backed graph for rendering + read_only = pipeline + else: + dag = pipeline.dag + read_only = None if highlight is not None: - labels = {node.label for node in pipeline.dag.nodes()} + labels = {node.label for node in dag.nodes()} unknown = sorted( { *highlight.nodes, @@ -1442,21 +1520,30 @@ def __init__( "pipeline" ) self._highlight: Highlight | None = highlight - is_job = _is_job(pipeline) - self._kind: str = "job" if is_job else "pipeline" + self._kind: str = ( + "job" if job is not None or read_only is not None else "pipeline" + ) self._name: str = ".".join(pipeline.name) self._direction: Direction = direction self._max_nodes: int = max_nodes self._collapse: bool = collapse nodes, edges = _build_model( - pipeline, is_job=is_job, collapse=collapse, highlight=highlight + dag, + job=job, + read_only=read_only, + collapse=collapse, + highlight=highlight, ) self._nodes: list[_Node] = nodes self._edges: list[_Edge] = edges # The other layout, for the notebook's collapse checkbox: kept only when folding # changes something. Built from the same read of the graph, computing nothing. other_nodes, other_edges = _build_model( - pipeline, is_job=is_job, collapse=not collapse, highlight=highlight + dag, + job=job, + read_only=read_only, + collapse=not collapse, + highlight=highlight, ) self._other: tuple[list[_Node], list[_Edge]] | None = ( None if len(other_nodes) == len(nodes) else (other_nodes, other_edges) @@ -1484,7 +1571,7 @@ def to_dict(self) -> dict[str, Any]: Returns: ``{"kind", "name", "title", "nodes", "edges"}``. Each node has ``index``, ``label``, ``kind`` (its ``node_type``), ``kind_text``, ``detail``, - ``status`` (``""`` for a pipeline), ``tag_schema`` and ``data_schema`` + ``status`` (``""`` for pipelines and read-only jobs), ``tag_schema`` and ``data_schema`` (lists of ``[column, type text]``) and ``facts`` (lists of ``[name, text]``); a source node whose bound source has an assigned label also has ``text``, the name drawn, and the fact ``source id``; @@ -1523,7 +1610,7 @@ def _plain_model(self, nodes: list[_Node], edges: list[_Edge]) -> dict[str, Any] "index": node.index, "label": node.label, "kind": node.kind, - "kind_text": _KIND_TEXT.get(node.kind, node.kind), + "kind_text": node_kind_text(node.kind), "detail": node.detail, "status": node.status, "tag_schema": [list(pair) for pair in node.tag_schema], diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 4e35f2e34..3662f1190 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -2587,6 +2587,7 @@ def _load_saved_job( if isinstance(node, SourceNodeBase) } sources: dict[str, cp.StreamProtocol] = {} + saved_source_details: dict[str, str] = {} unresolved_sources: dict[str, dict[str, Any]] = {} sources_by_config: dict[str, cp.StreamProtocol | None] = {} for spec_name, src_config in ( @@ -2612,6 +2613,12 @@ def _load_saved_job( except ValueError as exc: raise ValueError(f"{path}: source {spec_name!r}: {exc}") from exc if read_only: + from orcapod.pipeline.serialization import saved_source_display_class + + if spec_name in slots: + saved_source_details[slots[spec_name].label] = ( + saved_source_display_class(src_config) + ) continue failure: Exception | None = None source: cp.StreamProtocol | None = None @@ -2959,12 +2966,21 @@ def _load_saved_job( job._distribute_databases() if read_only: - saved_order = { - label: job._nodes[label] + saved_descriptors = { + label: descriptor for descriptor in data["pipeline"]["nodes"].values() if (label := descriptor.get("label")) in job._nodes } - return SourceOnlyPipelineJob._from_nodes(job.name, saved_order) # pyright: ignore[reportPrivateUsage] # loader builds the view + return SourceOnlyPipelineJob._from_nodes( # pyright: ignore[reportPrivateUsage] # loader builds the view + job.name, + {label: job._nodes[label] for label in saved_descriptors}, + job_dag, + { + label: descriptor["output_schema"] + for label, descriptor in saved_descriptors.items() + }, + saved_source_details, + ) # Restore run metadata (run_block was already parsed earlier in this method) status = run_block.get("status", "pending") diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index f9d1ec617..2e180e0f1 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -558,6 +558,36 @@ def saved_source_kind(config: Any) -> str: return "unknown source kind" +_SAVED_SOURCE_DISPLAY_NAMES = { + "cached": "CachedSource", + "csv": "CSVSource", + "delta_table": "DeltaTableSource", + "derived": "DerivedSource", + "postgresql_table": "PostgreSQLTableSource", + "spiraldb_table": "SpiralDBTableSource", + "sqlite_table": "SQLiteTableSource", +} + + +def saved_source_display_class(config: dict[str, Any]) -> str: + """Name a reconstructible source from its saved kind, without inspecting its class.""" + kind = config.get("source_type") + if not isinstance(kind, str) or kind in { + "dict", + "list", + "arrow_table", + "data_frame", + }: + return "" + if kind == "derived": + origin = config.get("origin") + if not isinstance(origin, dict) or not saved_source_display_class(origin): + return "" + return ( + _SAVED_SOURCE_DISPLAY_NAMES.get(kind, kind) if kind in SOURCE_REGISTRY else "" + ) + + def saved_connector_kind(config: Any) -> str | None: """The kind of connector a saved database configuration is over, or ``None``. diff --git a/src/orcapod/pipeline/source_only_job.py b/src/orcapod/pipeline/source_only_job.py index 9c9c48048..1612f8287 100644 --- a/src/orcapod/pipeline/source_only_job.py +++ b/src/orcapod/pipeline/source_only_job.py @@ -2,25 +2,43 @@ from __future__ import annotations -from collections.abc import Iterator, Mapping -from dataclasses import dataclass +from collections.abc import Iterable, Iterator, Mapping +from dataclasses import dataclass, field from types import MappingProxyType -from typing import Never +from typing import TYPE_CHECKING, Any, Never + +from typing_extensions import override from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.derived_source import DerivedSource +from orcapod.core.sources.display_names import ( + SavedSchemaDisplay, + node_kind_text, + stored_result_access, +) from orcapod.core.sources.source_ids import derived_source_job_path from orcapod.utils.provisional import warn_provisional_use +if TYPE_CHECKING: + from orcapod.core.nodes import JobNode + from orcapod.pipeline.dag import OrcaDAG + from orcapod.pipeline.diagram import Direction, PipelineDiagram + from orcapod.side_effects import SideEffectJobNode + from orcapod.types.provenance import Highlight + class _StoredSources(Mapping[str, "DerivedSource"]): def __init__( - self, sources: dict[str, DerivedSource], unavailable: Mapping[str, str] + self, + sources: dict[str, DerivedSource], + unavailable: Mapping[str, str], + kinds: dict[str, str], ) -> None: self._sources = sources self._unavailable = unavailable + self._kinds: dict[str, str] = kinds def __getitem__(self, label: str) -> DerivedSource: if label in self._unavailable: @@ -35,6 +53,15 @@ def __iter__(self) -> Iterator[str]: def __len__(self) -> int: return len(self._sources) + @override + def __repr__(self) -> str: + lines = ["Stored node sources"] + for label, kind in self._kinds.items(): + reason = self._unavailable.get(label) + state = stored_result_access(reason) + lines.append(f" {label!r} ({node_kind_text(kind)}) — {state}") + return "\n".join(lines) + @dataclass(frozen=True) class SourceOnlyPipelineJob: @@ -54,10 +81,18 @@ class SourceOnlyPipelineJob: labels: tuple[str, ...] nodes: Mapping[str, DerivedSource] unavailable: Mapping[str, str] + _dag: OrcaDAG[JobNode | SideEffectJobNode] = field(repr=False, compare=False) + _schemas: Mapping[str, SavedSchemaDisplay] = field(repr=False, compare=False) + _source_details: Mapping[str, str] = field(repr=False, compare=False) @classmethod def _from_nodes( - cls, name: tuple[str, ...], nodes: Mapping[str, object] + cls, + name: tuple[str, ...], + nodes: Mapping[str, JobNode | SideEffectJobNode], + dag: OrcaDAG[JobNode | SideEffectJobNode], + saved_schemas: Mapping[str, Mapping[str, Any]], + source_details: Mapping[str, str], ) -> SourceOnlyPipelineJob: """Build the view from descriptor-backed job nodes in saved order.""" warn_provisional_use( @@ -67,6 +102,10 @@ def _from_nodes( ) sources: dict[str, DerivedSource] = {} unavailable: dict[str, str] = {} + schemas = { + label: SavedSchemaDisplay.from_descriptor(schema) + for label, schema in saved_schemas.items() + } path_error = None try: derived_source_job_path(name) @@ -79,7 +118,10 @@ def _from_nodes( reason = reason or path_error if reason is None: sources[label] = DerivedSource( - origin=node, config=node.orcapod_config, _source_only=True + origin=node, + config=node.orcapod_config, + _source_only=True, + _saved_display_schema=schemas[label], ) continue except Exception as exc: @@ -92,7 +134,73 @@ def _from_nodes( unavailable[label] = reason reasons = MappingProxyType(unavailable) - return cls(name, tuple(nodes), _StoredSources(sources, reasons), reasons) + kinds = {label: node.node_type for label, node in nodes.items()} + return cls( + name, + tuple(nodes), + _StoredSources(sources, reasons, kinds), + reasons, + dag, + MappingProxyType(schemas), + MappingProxyType(source_details), + ) + + @override + def __repr__(self) -> str: + """Summarize the view and point to its inspection methods.""" + count = len(self.nodes) + readers = "source" if count == 1 else "sources" + return ( + f"Read-only job {'.'.join(self.name)!r} (provisional) — " + f"{count} stored-result {readers}, {len(self.unavailable)} without a reader\n" + " See .nodes for stored sources, .unavailable for reasons and .diagram() for the graph." + ) + + def diagram( + self, + *, + direction: Direction = "LR", + collapse: bool = False, + max_nodes: int = 400, + highlight: Highlight | None = None, + ) -> PipelineDiagram: + """Draw the saved graph with each node's schema and stored-result availability. + + The diagram computes nothing. Display it in a notebook or print it for a + plain-text listing. This interface is provisional, like the read-only view. + + Args: + direction: Lay out the graph from left to right (`"LR"`) or top to + bottom (`"TB"`). + collapse: Fold eligible joins and column operators into their edges. + max_nodes: Above this many nodes, display the text listing. + highlight: Nodes and edges to emphasize, with an optional note. + + Returns: + A diagram of the saved job. + + Raises: + ValueError: If the direction or node limit is invalid, or the highlight + names a node outside the saved graph. + """ + from orcapod.pipeline.diagram import PipelineDiagram + + return PipelineDiagram( + self, + direction=direction, + collapse=collapse, + max_nodes=max_nodes, + highlight=highlight, + ) + + def _repr_mimebundle_( + self, + include: Iterable[str] | None = None, + exclude: Iterable[str] | None = None, + **kwargs: object, + ) -> dict[str, str]: + """Display the saved diagram in a notebook.""" + return self.diagram()._repr_mimebundle_(include, exclude, **kwargs) # pyright: ignore[reportPrivateUsage] # delegate the notebook hook def run(self, *args: object, **kwargs: object) -> Never: """Refuse execution of the saved job.""" diff --git a/tests/test_pipeline/loaded_job/test_source_only_diagram.py b/tests/test_pipeline/loaded_job/test_source_only_diagram.py new file mode 100644 index 000000000..2d9cb3bce --- /dev/null +++ b/tests/test_pipeline/loaded_job/test_source_only_diagram.py @@ -0,0 +1,280 @@ +"""Diagram the saved graph without using the job's original inputs or code.""" + +from __future__ import annotations + +import html +import json +import shutil +import xml.etree.ElementTree as ET +from pathlib import Path +from typing import Any, Never + +import pytest + +from orcapod import PipelineJob, SourceOnlyPipelineJob, function_pod +from orcapod.core.data_function import PythonDataFunction +from orcapod.core.streams.view import StreamView +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import SelectDataColumns, SemiJoin +from orcapod.pipeline import PipelineDiagram +from orcapod.pipeline.diagram import Direction +from orcapod.sources import DerivedSource, DictSource +from orcapod.types import CacheMode +from orcapod.types.provenance import Highlight +from tests.test_pipeline.test_diagram import _run_view + + +@function_pod(output_keys=("total", "difference")) +def summarize(x: int, y: int) -> tuple[int, int]: + """Produce two result columns.""" + return x + y, x - y + + +@pytest.fixture(params=[False, True], ids=["original", "reordered"]) +def saved_job( + request: pytest.FixtureRequest, tmp_path: Path +) -> tuple[Path, InMemoryArrowDatabase]: + """Save a branched job with multiple stored and unavailable outputs.""" + reverse = bool(request.param) + tags = ["unit", "trial"] + measures = {"unit": "a", "trial": 1, "x": 7, "y": 3} + approvals = {"unit": "a", "trial": 1, "approved": True, "note": "checked"} + db = InMemoryArrowDatabase() + job = PipelineJob("report", database=db) + with job: + sources = { + name: DictSource( + [dict(list(row.items())[::-1]) if reverse else row], + source_id=name, + tag_columns=tags[::-1] if reverse else tags, + tag_only_columns=True, + ) + for name, row in ( + [("approvals", approvals), ("measures", measures)] + if reverse + else [("measures", measures), ("approvals", approvals)] + ) + } + 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 / "report.json" + job.save(path) + return path, db + + +def _without_run_facts(model: dict[str, Any]) -> dict[str, Any]: + """Compare diagram content shared by both views of a job.""" + for node in model["nodes"]: + node.pop("status") + node["facts"] = [fact for fact in node["facts"] if fact[0] != "stored results"] + return model + + +def _geometry(diagram: PipelineDiagram) -> list[tuple[str, dict[str, str]]]: + """Read the positioned graph from its public SVG output.""" + root = ET.fromstring(diagram.to_svg()) + attributes = {"transform", "x", "y", "width", "height", "rx", "d"} + return [ + (element.tag, {k: v for k, v in element.attrib.items() if k in attributes}) + for element in root.iter() + if element.tag.endswith(("}path", "}rect")) or "transform" in element.attrib + ] + + +@pytest.mark.parametrize("collapse", [False, True]) +@pytest.mark.parametrize("direction", ["LR", "TB"]) +def test_read_only_diagram_matches_the_loaded_graph( + saved_job: tuple[Path, InMemoryArrowDatabase], + direction: Direction, + collapse: bool, +) -> None: + path, db = saved_job + loaded = PipelineJob.load(path, db) + view = PipelineJob.load(path, db, read_only=True) + highlight = Highlight(nodes=frozenset({"accepted", "accepted_results"})) + actual = view.diagram(direction=direction, collapse=collapse, highlight=highlight) + expected = loaded.diagram( + direction=direction, collapse=collapse, highlight=highlight + ) + model = actual.to_dict() + assert not any(node["status"] for node in model["nodes"]) + assert ( + "accepted_columns" in {node["label"] for node in model["nodes"]} + ) != collapse + assert any(edge.get("constrains") for edge in model["edges"]) + assert _without_run_facts(model) == _without_run_facts(expected.to_dict()) + assert _geometry(actual) == _geometry(expected) + + +def test_read_only_diagram_display_computes_nothing( + saved_job: tuple[Path, InMemoryArrowDatabase], + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + path, db = saved_job + view = PipelineJob.load(path, db, read_only=True) + + def forbidden(*_args: object, **_kwargs: object) -> Never: + raise AssertionError("diagram touched a source, ran code or used the database") + + for name in dir(InMemoryArrowDatabase): + if not name.startswith("_") and callable(getattr(InMemoryArrowDatabase, name)): + monkeypatch.setattr(InMemoryArrowDatabase, name, forbidden) + for cls, names in ( + (DictSource, ("as_table", "iter_data", "check_for_new_data", "from_config")), + (DerivedSource, ("as_table", "iter_data", "check_for_new_data")), + (PythonDataFunction, ("call", "async_call")), + (SelectDataColumns, ("process", "from_config")), + (SemiJoin, ("process", "from_config")), + ): + for name in names: + monkeypatch.setattr(cls, name, forbidden) + + assert isinstance(view, SourceOnlyPipelineJob) + assert not hasattr(view, "bind") + with pytest.raises(RuntimeError, match="cannot run"): + view.run() + diagram = view.diagram() + assert isinstance(diagram, PipelineDiagram) + print(diagram) + listing = capsys.readouterr().out + assert listing == f"{diagram.to_text()}\n" + assert listing.startswith("Job 'report': 7 nodes\n") + assert "accepted_results (function pod) <- accepted_columns" in listing + bundle = view._repr_mimebundle_() + assert bundle["text/plain"] == diagram.to_text() + document = bundle["text/html"] + assert 'class="op-dag-picture"' in document + embedded = document.split('class="op-dag-model">', 1)[1].split("", 1)[0] + model = json.loads(embedded) + assert model == diagram.to_dict() + assert set(view.nodes) == {"chosen", "all_results", "accepted_results"} + assert set(view.labels) == set(view.nodes) | set(view.unavailable) + for node in model["nodes"]: + label = node["label"] + assert node["status"] == "" + assert node["tag_schema"] + assert node["data_schema"] + availability = dict(node["facts"])["stored results"] + if label in view.nodes: + assert availability == "reader configured (matching rows checked on read)" + else: + assert availability == f"no reader ({view.unavailable[label]})" + assert "
" 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

")