Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog.d/ITL-1454.md
Original file line number Diff line number Diff line change
@@ -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)
11 changes: 11 additions & 0 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions src/orcapod/core/nodes/source_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
4 changes: 4 additions & 0 deletions src/orcapod/core/sources/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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: ``<SOURCE_KIND>_v<SOURCE_VERSION>``."""
Expand Down
200 changes: 200 additions & 0 deletions src/orcapod/core/sources/display_names.py
Original file line number Diff line number Diff line change
@@ -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 (``<kind>_v<N>:<name>``).
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()}
2 changes: 2 additions & 0 deletions src/orcapod/core/sources/spiraldb_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
28 changes: 19 additions & 9 deletions src/orcapod/databases/spiraldb_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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


# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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)


# ---------------------------------------------------------------------------
Expand Down
3 changes: 2 additions & 1 deletion src/orcapod/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""


Expand Down
Loading
Loading