From 4d7ef60fb98979724cbf50961606cbcd2997ed7a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 15:43:07 -0800 Subject: [PATCH 01/11] feat(pipeline): show a source by its assigned label (ITL-1454) Display only: the diagram, node preview, explain(), trace() and RestrictedAggregationWarning. No name, hash, id or stored path changes. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1454.md | 3 + docs/concepts/pipeline-job.md | 10 + src/orcapod/core/nodes/source_node.py | 10 + src/orcapod/core/sources/base.py | 4 + src/orcapod/core/sources/display_names.py | 130 ++++++++ .../core/sources/spiraldb_table_source.py | 1 + src/orcapod/core/streams/explain.py | 51 ++- src/orcapod/pipeline/diagram.py | 41 ++- .../pipeline/diagram_assets/diagram.js | 4 +- src/orcapod/pipeline/provenance.py | 18 +- src/orcapod/pipeline/restrictions.py | 12 +- src/orcapod/types/explanation.py | 7 +- src/orcapod/types/provenance.py | 7 +- .../test_source_display_names.py | 292 ++++++++++++++++++ 14 files changed, 564 insertions(+), 26 deletions(-) create mode 100644 changelog.d/ITL-1454.md create mode 100644 src/orcapod/core/sources/display_names.py create mode 100644 tests/test_pipeline/test_source_display_names.py diff --git a/changelog.d/ITL-1454.md b/changelog.d/ITL-1454.md new file mode 100644 index 000000000..50a49cec6 --- /dev/null +++ b/changelog.d/ITL-1454.md @@ -0,0 +1,3 @@ +### Changed + +- **A job shows a source by its own label.** Where the source bound to a slot has an assigned label, the job's diagram, the node's preview, and the text of `explain()`, `trace()` and `RestrictedAggregationWarning` name it by that label instead of its slot's name or source id; the diagram's details and the texts give the full source id once. Sources sharing a label, or a label that is another node's name, are shown as `label (part)`, with the shortest part that tells them apart (a SpiralDB table's dataset, then its project, then the source's name). Display only: slot names, node labels, the keys of `job.nodes`, saved files, hashes, ids and stored paths are unchanged, and so is the text of a source without a label and of a loaded job. (ITL-1454) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 83bf7acf3..c4d39ddd3 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -431,6 +431,16 @@ function of a function pod, the class of a bound source), and for a job its stat A selected node also shows the row counts of the job's last run (`job.last_run`). +A source bound with a label (`DictSource(..., label="mice")`, `SpiralDBTableSource(..., +label="units")`) is shown in a job's diagram, in its node's preview, and in the text of +`explain()`, `trace()` and `RestrictedAggregationWarning` by that label; the diagram's +details (`source id`) and the texts give its full source id once. Two sources with one +label, or a label that is another node's name, are shown as `label (part)`: a SpiralDB +table's dataset, else its project, else the source's name. This is display only: the slot +keeps its name, the one `job.nodes[...]` and `bind` take. A source without a label is shown +by its slot's name, as is every source of a `Pipeline` (which binds none) and of a loaded +job (a source's label is not saved). + The options: - `direction="TB"` lays the graph out top to bottom instead of left to right. diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index e2b83b4e0..b6b8bc0f6 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1948,6 +1948,16 @@ def _typed_zero_row_table(self) -> "pa.Table | None": return table return self._declared_form.apply(table) + def _display_name(self) -> str: + """The name a preview header shows: the bound source's assigned label, else the + node's own. The node's label and the slot's name are not changed (ITL-1454).""" + from orcapod.core.sources.display_names import labelled_source + + source = labelled_source(self._bound_source) + if source is None or self.has_assigned_label: + return self.label + return source.label + def _schema_requires_io(self, config: ColumnConfig) -> bool: """Whether reading the schema with ``config`` would poll: as for the bound source.""" return self._bound_source is not None and schema_requires_io( diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index b719c6315..decb53b9f 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -121,6 +121,10 @@ class RootSource(StreamBase): """The source's kind: its config type key and the first part of its source id.""" SOURCE_VERSION: ClassVar[int] + + # The attributes holding what tells two sources of one label apart in a display, + # nearest first (``core/sources/display_names.py``); ``""`` for a kind without them. + DISPLAY_PARTS: ClassVar[tuple[str, str]] = ("", "") """The version of the kind's implementation, in the source id's kind part (ITL-1425). Bump it when a row read before a change could read differently after it (other diff --git a/src/orcapod/core/sources/display_names.py b/src/orcapod/core/sources/display_names.py new file mode 100644 index 000000000..c8f126274 --- /dev/null +++ b/src/orcapod/core/sources/display_names.py @@ -0,0 +1,130 @@ +"""How a source is named where a pipeline is shown (ITL-1454): by its assigned label. + +Display only: a slot's name, a node's label, every hash, id and stored path are what they +are without it. Everything is read from what a source stores; no method or property of a +source is called, so showing a pipeline runs no user code. +""" + +from __future__ import annotations + +from collections.abc import Collection, Iterable, Mapping +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from orcapod.core.sources.base import RootSource + + +@dataclass(frozen=True) +class LabelledSource: + """A source with an assigned label, as a display names it. + + Attributes: + label: The assigned label. + source_id: The full source id (``_v:``). + parts: What tells it apart from a source of the same label, shortest first + (a SpiralDB table's dataset, its project, both, then any source's name and + id); ``""`` for a part its kind lacks. + """ + + label: str + source_id: str + parts: tuple[str, ...] + + +def labelled_source(stream: Any) -> LabelledSource | None: + """Return the source as a display names it, or ``None`` when it has no label. + + ``None`` for a stream that is no source, a source with no assigned label and a + proxy of a source that could not be rebuilt. A ``CachedSource`` is named by its own + label and the id of the source it wraps. + + Args: + stream: The source, or any stream bound to a slot. + """ + from orcapod.core.sources.base import RootSource + from orcapod.core.sources.cached_source import CachedSource + from orcapod.core.sources.source_ids import build_source_id + from orcapod.core.sources.source_proxy import SourceProxy + + if not isinstance(stream, RootSource) or isinstance(stream, SourceProxy): + return None + label = vars(stream).get("_label") + source: RootSource = stream + while type(source) is CachedSource: + source = vars(source)["_source"] + name = vars(source).get("_source_name") + if not isinstance(label, str) or not label or not isinstance(name, str): + return None + if isinstance(source, SourceProxy): + return None + kind, version = type(source).SOURCE_KIND, type(source).SOURCE_VERSION + near, far = type(source).DISPLAY_PARTS + dataset, project = (str(vars(source).get(p) or "") for p in (near, far)) + both = f"{project}.{dataset}" if dataset and project else "" + source_id = build_source_id(kind, version, name) + return LabelledSource(label, source_id, (dataset, project, both, name, source_id)) + + +def display_names( + sources: Mapping[str, LabelledSource], names: Collection[str] +) -> dict[str, str]: + """Return the text each labelled source is shown by: its label when that is enough. + + Sources sharing a label, and a source whose label is another shown name, are shown + as ``label (part)`` with the shortest part that tells all of them apart. A source no + part tells apart keeps its own name, so no two texts are ever equal. The order of + the sources changes nothing. + + Args: + sources: The labelled sources, by the name each is shown by without a label. + names: Every name the display shows (the nodes' labels), these included. + + Returns: + The text, by the same keys as ``sources``. + """ + groups: dict[str, list[str]] = {} + for name, source in sources.items(): + groups.setdefault(source.label, []).append(name) + texts: dict[str, str] = {} + for label, members in groups.items(): + taken = set(names) - set(members) + if len(members) == 1 and label not in taken: + texts[members[0]] = label + continue + taken.update(groups) + for level in zip(*(sources[m].parts for m in members), strict=True): + shown = [f"{label} ({part})" for part in level] + if all(level) and len(set(shown)) == len(shown) and not taken & set(shown): + texts.update(zip(members, shown)) + break + else: + texts.update({m: f"{label} ({m})" for m in members}) + used = list(texts.values()) + return { + n: t if used.count(t) == 1 and t not in set(names) - {n} else n + for n, t in texts.items() + } + + +def node_display_names(nodes: Iterable[Any]) -> dict[str, tuple[str, str]]: + """Return the text and full source id of each source node shown by its source's label. + + Args: + nodes: The nodes of one pipeline or job. + + Returns: + ``(text, source id)`` by node label, for the nodes whose bound source has an + assigned label; a node given a label of its own, an unbound slot and every other + node is not listed (it is shown by its own label). + """ + all_nodes = list(nodes) + found: dict[str, LabelledSource] = {} + for node in all_nodes: + if node.node_type != "source" or node.has_assigned_label: + continue + source = labelled_source(getattr(node, "bound_source", None)) + if source is not None: + found[node.label] = source + texts = display_names(found, {node.label for node in all_nodes}) + return {name: (text, found[name].source_id) for name, text in texts.items()} diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index a139dc2f4..83bb7068a 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -286,6 +286,7 @@ class SpiralDBTableSource(RootSource): SOURCE_KIND: ClassVar[str] = "spiraldb_table" """Config type key and the kind in the source id's kind part (one vocabulary).""" SOURCE_VERSION: ClassVar[int] = 1 + DISPLAY_PARTS: ClassVar[tuple[str, str]] = ("_dataset", "_project_id") """The version of this kind's implementation, in the kind part (ITL-1425).""" TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True diff --git a/src/orcapod/core/streams/explain.py b/src/orcapod/core/streams/explain.py index 2669a52d2..e18e7c7a4 100644 --- a/src/orcapod/core/streams/explain.py +++ b/src/orcapod/core/streams/explain.py @@ -14,7 +14,7 @@ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING from orcapod.types.condition import Condition @@ -129,7 +129,40 @@ def _sort_key(key: _ReadingKey) -> tuple[str, str, bool, bool, str, int]: ] -def _reach(stream: StreamProtocol, memo: dict[int, _Reach]) -> _Reach: +def _shown_names(stream: StreamProtocol) -> dict[str, str]: + """Return the text each labelled source ``stream`` reads is shown by, by source id. + + A source read under two labels (or with and without one) is shown by its id. + """ + from orcapod.core.sources.display_names import ( + LabelledSource, + display_names, + labelled_source, + ) + + found: dict[str, set[LabelledSource | None]] = {} + seen: set[int] = set() + pending = [stream] + while pending: + current = pending.pop() + if id(current) in seen: + continue + seen.add(id(current)) + _, beneath = _beneath(current) + if isinstance(beneath, SourceReading): + found.setdefault(beneath.name, set()).add(labelled_source(current)) + else: + pending.extend(beneath) + one = {name: next(iter(found[name])) for name in found if len(found[name]) == 1} + return display_names( + {name: source for name, source in one.items() if source is not None}, + set(found), + ) + + +def _reach( + stream: StreamProtocol, memo: dict[int, _Reach], shown: Mapping[str, str] +) -> _Reach: """Return the sources ``stream`` reads and the steps above each, once per node. Each node is expanded once (``memo``), so a graph whose nodes share inputs costs one @@ -148,11 +181,11 @@ def _reach(stream: StreamProtocol, memo: dict[int, _Reach]) -> _Reach: memo[id(stream)] = result return result inputs = found - reaches = [_reach(upstream, memo) for upstream in inputs] + reaches = [_reach(upstream, memo, shown) for upstream in inputs] producer = stream.producer if kind == "inputs" else None result = {} for position, reach in enumerate(reaches): - step = _step_of(stream, producer, position, inputs, reaches) + step = _step_of(stream, producer, position, inputs, reaches, shown) chooses_only = isinstance(producer, SemiJoin) and position == 1 for key, (reading, distance, steps) in reach.items(): here = None if distance is None else distance + 1 @@ -180,6 +213,7 @@ def _step_of( position: int, inputs: Sequence[StreamProtocol], reaches: Sequence[_Reach], + shown: Mapping[str, str], ) -> Step | None: """Return the step ``stream``'s operator takes on its input at ``position``; the other inputs are named by the sources they read (sorted, joined).""" @@ -188,7 +222,10 @@ def _step_of( if not isinstance(producer, StaticOutputOperatorPod): return None others = sorted( - ", ".join(sorted({reading.name for reading, _, _ in reach.values()})) + ", ".join( + shown.get(name, name) + for name in sorted({reading.name for reading, _, _ in reach.values()}) + ) for i, reach in enumerate(reaches) if i != position ) @@ -207,7 +244,8 @@ def explain(stream: StreamProtocol) -> Explanation: Returns: The explanation; nothing is computed, read, polled or written. """ - reach = _reach(stream, {}) + shown = _shown_names(stream) + reach = _reach(stream, {}, shown) sources = [] for key in sorted(reach, key=_sort_key): reading, _, steps = reach[key] @@ -225,6 +263,7 @@ def explain(stream: StreamProtocol) -> Explanation: condition=reading.condition, limit=reading.limit, steps=tuple(step for _, step in ordered), + shown=shown.get(reading.name, ""), ) ) return Explanation(stream=stream_name(stream), sources=tuple(sources)) diff --git a/src/orcapod/pipeline/diagram.py b/src/orcapod/pipeline/diagram.py index 08525ecc9..613955179 100644 --- a/src/orcapod/pipeline/diagram.py +++ b/src/orcapod/pipeline/diagram.py @@ -39,6 +39,7 @@ from typing_extensions import override +from orcapod.core.sources.display_names import node_display_names from orcapod.types.provenance import Highlight from orcapod.utils.in_development import warn_in_development @@ -86,6 +87,13 @@ class _Node: highlighted: bool = False mark: str = "" asked: str = "" + shown: str = "" + + @property + def text(self) -> str: + """The name drawn: the bound source's assigned label (``shown``), else the + node's label.""" + return self.shown or self.label @property def kind_line(self) -> str: @@ -369,11 +377,15 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: by_label[label], (statuses[upstream] for upstream in preds[label]) ) + source_names = node_display_names(by_label.values()) nodes: list[_Node] = [] for label in shown: node = by_label[label] summary = summaries.get(label) facts = _run_facts(summary) if is_job else () + 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: @@ -396,6 +408,7 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: # 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, 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" @@ -486,7 +499,7 @@ def _text_room(node: _Node) -> float: kind, the detail, the status), within the node width limits (ITL-1232).""" parts = [*node.kind_line.split(" · "), node.mark, node.asked] text = max( - len(node.label) * _CHAR_W, max(len(part) for part in parts) * _SMALL_CHAR_W + len(node.text) * _CHAR_W, max(len(part) for part in parts) * _SMALL_CHAR_W ) return max(_MIN_W - 2 * _PAD, min(_MAX_W - 2 * _PAD, text)) @@ -834,7 +847,7 @@ def _schema_text(pairs: Sequence[tuple[str, str]]) -> str: def _tooltip(node: _Node, inputs: Sequence[str]) -> str: """The node's details as plain text, shown on hover over the inline picture.""" - lines = [f"{node.label} ({node.kind_line})"] + lines = [f"{node.text} ({node.kind_line})"] lines.append(f"tags: {_schema_text(node.tag_schema)}") lines.append(f"data: {_schema_text(node.data_schema)}") if inputs: @@ -901,7 +914,7 @@ def _svg( f'stroke-opacity="{"0.3" if lit else "0.5"}" stroke-width="1.4">' ) for edge, points in layout.edges: - tip = f"{nodes[edge.source].label} → {nodes[edge.target].label}" + tip = f"{nodes[edge.source].text} → {nodes[edge.target].text}" if edge.folded: tip += f" (through {', '.join(edge.folded)})" dash = ' stroke-dasharray="5 3"' if edge.folded else "" @@ -932,7 +945,7 @@ def _svg( ) stroke_width = "1.4" if node.kind == "operator" else "2.2" dash = ' stroke-dasharray="4 3"' if node.status in _DASHED_STATUSES else "" - label = f"{node.label}, {node.kind_line}" + label = f"{node.text}, {node.kind_line}" emphasis = "" stroke = colour if node.highlighted: @@ -990,7 +1003,7 @@ def _svg( parts.append( f'' - f"{_escape(_clip(node.label, w, _CHAR_W))}" + f"{_escape(_clip(node.text, w, _CHAR_W))}" ) parts.append("" if caption else "") return "".join(parts) @@ -1000,7 +1013,7 @@ def _table(nodes: Sequence[_Node], inputs: Mapping[int, Sequence[str]]) -> str: """Every node with its inputs, schema and run facts: shown where scripts do not run.""" rows = "".join( "" - f"{_escape(node.label)}" + f"{_escape(node.text)}" f"{_escape(node.kind_line)}" f"{_escape(', '.join(inputs.get(node.index, ())))}" f"{_escape(_schema_text(node.tag_schema))}" @@ -1078,10 +1091,10 @@ def _asset(name: str) -> str: def _inputs(nodes: Sequence[_Node], edges: Sequence[_Edge]) -> dict[int, list[str]]: - """The labels of each node's inputs, by node index, in edge order.""" + """The drawn names of each node's inputs, by node index, in edge order.""" inputs: dict[int, list[str]] = {} for edge in edges: - inputs.setdefault(edge.target, []).append(nodes[edge.source].label) + inputs.setdefault(edge.target, []).append(nodes[edge.source].text) return inputs @@ -1244,6 +1257,8 @@ def to_dict(self) -> dict[str, Any]: ``label``, ``kind`` (its ``node_type``), ``kind_text``, ``detail``, ``status`` (``""`` for a pipeline), ``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``; each edge has ``source`` and ``target`` (node indices) and ``folded`` (the labels of the steps folded into it). With a highlight, every node and edge also has ``highlighted``, and the model has the highlight's ``note``. @@ -1282,6 +1297,8 @@ def _plain_model(self, nodes: list[_Node], edges: list[_Edge]) -> dict[str, Any] "tag_schema": [list(pair) for pair in node.tag_schema], "data_schema": [list(pair) for pair in node.data_schema], "facts": [list(fact) for fact in node.facts], + # Only where a source's assigned label is drawn (ITL-1454). + **({"text": node.shown} if node.shown else {}), } for node in nodes ], @@ -1297,8 +1314,10 @@ def to_text(self) -> str: In development: this interface may change. Returns: - A title line, then ``