diff --git a/changelog.d/ITL-1454.md b/changelog.d/ITL-1454.md new file mode 100644 index 000000000..51a265fd4 --- /dev/null +++ b/changelog.d/ITL-1454.md @@ -0,0 +1,7 @@ +### 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 `RestrictedAggregationWarning` name it by that label instead of its slot's name; the diagram's details and the warning give the full source id. 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) + +### Fixed + +- **`UnrecordedTableSchemaWarning` holds no lock while it warns.** A warning hook may wait for another thread that reads an unrecorded SpiralDB table, or read the table itself. The warning is usually shown once per table and process: threads reading a table at the same time may each show it, and once shown it is not shown again. Turned into an error, it is raised by every reader. (ITL-1454) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 499cbd724..10c01b935 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -429,6 +429,17 @@ 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 +`RestrictedAggregationWarning` by that label; the diagram's details (`source id`) and the +warning give its full source id. `explain()` and `trace()` name it by its id. 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. A single node's preview shows the label +alone. This is display only: the slot +keeps its name, the one `job.nodes[...]` and `bind` take. In a diagram, 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/docs/concepts/sources.md b/docs/concepts/sources.md index 4ed1897b1..de39979ad 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -695,7 +695,8 @@ every depth and metadata. The name is reserved, and listings leave it out. - **A table that is not recorded** (its dataset has no `__orcapod_schemas__`, or no row for it) reads as SpiralDB reports it: every column has the type `T | None` and no metadata, and a function pod must accept `None` (`x: float | None`). `UnrecordedTableSchemaWarning` says - so, once per table and process. + so, usually once per table and process (threads reading it at the same time may each + show it; once shown, it is not shown again). - **A record that is not complete** is refused: the last row written says for which project and dataset, how many tables, and a digest of their rows. When it is missing or does not fit, every read that opens a table of the dataset raises `TableSchemaError`, and so does a 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..07221924c 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -127,6 +127,10 @@ class RootSource(StreamBase): values, other Arrow types, another record id): a new version is a new source id. """ + # 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]] = ("", "") + @classmethod def kind_part(cls) -> str: """The kind part of this class's source ids: ``_v``.""" diff --git a/src/orcapod/core/sources/display_names.py b/src/orcapod/core/sources/display_names.py new file mode 100644 index 000000000..5d10e7c3d --- /dev/null +++ b/src/orcapod/core/sources/display_names.py @@ -0,0 +1,200 @@ +"""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 types import GetSetDescriptorType +from typing import Any + + +@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, ...] + + +# The slots of ``type`` itself: an attribute or property a metaclass defines under the +# same name is not read. +_TYPE_MRO: Any = type.__dict__["__mro__"] +_TYPE_DICT: Any = type.__dict__["__dict__"] + + +def _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)] + + +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))) + + +def _stored(source: object) -> Mapping[str, Any]: + """Return an object's instance dictionary, read past any hook its class defines.""" + for namespace in _class_dicts(type(source)): + found = namespace.get("__dict__") + if type(found) is GetSetDescriptorType: + return found.__get__(source) + return {} + + +def _class_value(source: object, name: str) -> Any: + """Return what the class of ``source`` or its nearest base declares as ``name``.""" + return next(d[name] for d in _class_dicts(type(source)) if name in d) + + +_LINE_BREAKS = "\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029" + + +def _stored_text(source: object, name: str) -> str: + """Return the text stored under ``name``, as a plain ``str``; ``""`` for none.""" + value = _stored(source).get(name) + return str.__str__(value) if isinstance(value, str) else "" + + +def _one_line(text: str) -> str: + """Return ``text`` with its line breaks written as escapes.""" + return "".join(ascii(c)[1:-1] if c in _LINE_BREAKS else c for c in text) + + +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. Never raises: a source whose label cannot + be read is shown as one without a label. + + Args: + stream: The source, or any stream bound to a slot. + """ + try: + return _labelled_source(stream) + except Exception: # noqa: BLE001 # a display never changes an outcome + return None + + +def _labelled_source(stream: Any) -> LabelledSource | None: + 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 _is_a(stream, RootSource) or _is_a(stream, SourceProxy): + return None + label = _one_line(_stored_text(stream, "_label")) + if not label: + return None + source: Any = stream + while type(source) is CachedSource: + source = _stored(source).get("_source") + # A cache accepts any source-like object; only a root source holds a name to show. + if not _is_a(source, RootSource) or _is_a(source, SourceProxy): + return None + name = _stored_text(source, "_source_name") + if not name: + return None + source_id = build_source_id( + _class_value(source, "SOURCE_KIND"), + _class_value(source, "SOURCE_VERSION"), + name, + ) + declared = _class_value(source, "DISPLAY_PARTS") + # Only a plain tuple of two plain names is used, so reading it runs no code. + if ( + type(declared) is not tuple + or len(declared) != 2 + or not all(type(part) is str for part in declared) + ): + declared = ("", "") + near, far = declared + dataset, project = _stored_text(source, near), _stored_text(source, far) + both = f"{project}.{dataset}" if dataset and project else "" + parts = (dataset, project, both, name, source_id) + return LabelledSource(label, source_id, tuple(_one_line(p) for p in parts)) + + +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 5dd3d41a1..6312a677f 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -291,6 +291,8 @@ class SpiralDBTableSource(RootSource): """Config type key and the kind in the source id's kind part (one vocabulary).""" SOURCE_VERSION: ClassVar[int] = 1 """The version of this kind's implementation, in the kind part (ITL-1425).""" + + DISPLAY_PARTS: ClassVar[tuple[str, str]] = ("_dataset", "_project_id") TABLE_IS_ROWS: ClassVar[bool] = True TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = True diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 768c698a6..bd72e28fe 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -27,7 +27,7 @@ from collections.abc import Iterator, Mapping from contextlib import contextmanager from copy import copy -from threading import RLock +from threading import local from typing import TYPE_CHECKING, Any, cast import pyarrow as pa @@ -75,7 +75,7 @@ ) # Tables a warning was issued for in this process (``UnrecordedTableSchemaWarning``). _warned_unrecorded: set[tuple[str, str]] = set() -_warned_lock = RLock() # a warning hook may read a table itself +_warning_here = local() # ``keys``: what this thread is warning about right now # --------------------------------------------------------------------------- @@ -187,23 +187,33 @@ def _warn_unrecorded(table: str, table_id: str) -> None: def _warn_once(about: tuple[str, str], message: str) -> None: - """Issue an ``UnrecordedTableSchemaWarning`` once per ``about`` and process. + """Issue an ``UnrecordedTableSchemaWarning``, usually once per ``about`` and process. + + Once it has been shown it is not shown again. Threads reading one table at the same + time may each show it: no lock is held while warning, since a warning hook may wait + for another thread that reads an unrecorded table. A warning turned into an error is + not recorded as shown, so every reader raises it. A hook that reads the table itself + is not warned again about it. Args: about: What the warning is about. message: The warning. """ - # Held over the check, the warning and the record: while one thread's warning is - # turned into an error, another does not pass as if it had been shown. - with _warned_lock: - if about in _warned_unrecorded: - return + warning_now: set[tuple[str, str]] | None = getattr(_warning_here, "keys", None) + if warning_now is None: + warning_now = _warning_here.keys = set() + if about in _warned_unrecorded or about in warning_now: + return + warning_now.add(about) + try: warnings.warn( message, UnrecordedTableSchemaWarning, stacklevel=outside_orcapod_stacklevel(), ) - _warned_unrecorded.add(about) + finally: + warning_now.discard(about) + _warned_unrecorded.add(about) # --------------------------------------------------------------------------- diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index a12be0ae7..7720e7980 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -619,7 +619,8 @@ class UnrecordedTableSchemaWarning(UserWarning): nullable, with no Arrow metadata. A table written by an Orcapod release on pyspiral reads this way until its dataset is migrated (``scripts/migrate_spiral_schemas.py``), so its schema and its hashes differ from - what they were. Issued once per table and process. + what they were. Usually issued once per table and process: threads reading the + table at the same time may each issue it. """ 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 ``