diff --git a/changelog.d/ITL-1455.md b/changelog.d/ITL-1455.md new file mode 100644 index 000000000..0d7dff6de --- /dev/null +++ b/changelog.d/ITL-1455.md @@ -0,0 +1,3 @@ +### Changed + +- **The pipeline diagram draws an input that only constrains apart.** The right input of a `SemiJoin` decides which rows of the left input pass and passes none on: the diagram draws it as a dashed edge entering the box from the side, its details say which tags the rows match on, and the text form says `<- a; constrained by b`. Folding (`collapse=True`) keeps it. An operator declares such inputs in `CONSTRAINING_INPUTS`. Display only: no hash, id, stored path, node label or saved file changes, and a diagram without such an input is drawn as before. (ITL-1455) diff --git a/docs/concepts/notebooks.md b/docs/concepts/notebooks.md index 010af6748..4cc4f72ef 100644 --- a/docs/concepts/notebooks.md +++ b/docs/concepts/notebooks.md @@ -256,6 +256,8 @@ laid out left to right. Here is `job` as the last line of a cell, after its run, - **A node's details.** Click a node (or focus it and press Enter) to see its schema: its tag and data columns, the nodes it reads from and, for a job, its run status and the row counts of the job's last run. +- **Constraining inputs.** The right input of a `SemiJoin` only decides which rows pass: a + dashed edge entering from the side of the box. - **Statuses.** Each node of a job shows one: `not run`, `current`, `stale`, `failed`, `loaded only`, `partial`, or `bound` or `unbound` for a source slot. Before `job.run()` every node but the sources says `not run`. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 10c01b935..a8f19817a 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -456,6 +456,13 @@ shown first, and the one shown where scripts do not run. A selected node stays s when it is in the new layout. The checkboxes appear for graphs of up to 100 nodes: a larger diagram carries only the layout its arguments ask for, which keeps a notebook small. +An input that only decides which rows of another input pass (the right input of a +`SemiJoin`) is drawn as a dashed edge that enters the box from the side (from above or below +when the graph runs left to right); the data input enters as every other edge does. The node's +details give the tags the rows match on, and the text form lists such an input after the +others: `<- spikes; constrained by units`. `collapse=True` never hides it: folded steps on its +way are drawn dash-dotted. + In each node, the kind line under the name (kind, what it is, status) is wrapped onto short lines, so a node is about as wide as its name. diff --git a/docs/dev/specs/itl-1455-constraining-inputs/after-LR-collapsed.svg b/docs/dev/specs/itl-1455-constraining-inputs/after-LR-collapsed.svg new file mode 100644 index 000000000..1e3692caa --- /dev/null +++ b/docs/dev/specs/itl-1455-constraining-inputs/after-LR-collapsed.svg @@ -0,0 +1,32 @@ +Job 'workshop'approved_sessions → SemiJoin_1: only decides which rows pass +keeps the rows that match on: sessionsessions → SemiJoin_1SemiJoin_1 → SemiJoin_2: only decides which rows pass +keeps the rows that match on: sessionSemiJoin_1 → rates (through Join)spikes → SemiJoin_3units → SemiJoin_2SemiJoin_2 → SemiJoin_3 (through SelectDataColumns): only decides which rows pass +keeps the rows that match on: session, unitSemiJoin_2 → qualitySemiJoin_3 → rates (through Join)approved_sessions (source · DictSource · bound) +tags: session: str +data: note: strsource · DictSourceboundapproved_sessionssessions (source · DictSource · bound) +tags: session: str +data: duration: floatsourceDictSourceboundsessionsSemiJoin_1 (operator · not run) +tags: session: str +data: duration: float +inputs: sessions; constrained by approved_sessions +keeps the rows that match on: sessionoperatornot runSemiJoin_1spikes (source · DictSource · bound) +tags: session: str, unit: str +data: spikes: list[float]sourceDictSourceboundspikesunits (source · DictSource · bound) +tags: session: str, unit: str +data: snr: floatsourceDictSourceboundunitsSemiJoin_2 (operator · not run) +tags: session: str, unit: str +data: snr: float +inputs: units; constrained by SemiJoin_1 +keeps the rows that match on: sessionoperatornot runSemiJoin_2SemiJoin_3 (operator · not run) +tags: session: str, unit: str +data: spikes: list[float] +inputs: spikes; constrained by SemiJoin_2 +keeps the rows that match on: session, unit +folded steps: SelectDataColumnsoperatornot runSemiJoin_3quality (function pod · not run) +tags: session: str, unit: str +data: n: int +inputs: SemiJoin_2function podnot runqualityrates (function pod · mean_rate · not run) +tags: session: str, unit: str +data: rate: float +inputs: SemiJoin_1, SemiJoin_3 +folded steps: Joinfunction podmean_ratenot runrates \ No newline at end of file diff --git a/docs/dev/specs/itl-1455-constraining-inputs/after-LR.svg b/docs/dev/specs/itl-1455-constraining-inputs/after-LR.svg new file mode 100644 index 000000000..f127f64d2 --- /dev/null +++ b/docs/dev/specs/itl-1455-constraining-inputs/after-LR.svg @@ -0,0 +1,36 @@ +Job 'workshop'approved_sessions → SemiJoin_1: only decides which rows pass +keeps the rows that match on: sessionsessions → SemiJoin_1SemiJoin_1 → SemiJoin_2: only decides which rows pass +keeps the rows that match on: sessionSemiJoin_1 → Joinspikes → SemiJoin_3units → SemiJoin_2SemiJoin_2 → SelectDataColumnsSemiJoin_2 → qualitySelectDataColumns → SemiJoin_3: only decides which rows pass +keeps the rows that match on: session, unitSemiJoin_3 → JoinJoin → ratesapproved_sessions (source · DictSource · bound) +tags: session: str +data: note: strsource · DictSourceboundapproved_sessionssessions (source · DictSource · bound) +tags: session: str +data: duration: floatsourceDictSourceboundsessionsSemiJoin_1 (operator · not run) +tags: session: str +data: duration: float +inputs: sessions; constrained by approved_sessions +keeps the rows that match on: sessionoperatornot runSemiJoin_1spikes (source · DictSource · bound) +tags: session: str, unit: str +data: spikes: list[float]sourceDictSourceboundspikesunits (source · DictSource · bound) +tags: session: str, unit: str +data: snr: floatsourceDictSourceboundunitsSemiJoin_2 (operator · not run) +tags: session: str, unit: str +data: snr: float +inputs: units; constrained by SemiJoin_1 +keeps the rows that match on: sessionoperatornot runSemiJoin_2SelectDataColumns (operator · not run) +tags: session: str, unit: str +data: snr: float +inputs: SemiJoin_2operator · not runSelectDataColumnsSemiJoin_3 (operator · not run) +tags: session: str, unit: str +data: spikes: list[float] +inputs: spikes; constrained by SelectDataColumns +keeps the rows that match on: session, unitoperatornot runSemiJoin_3Join (operator · not run) +tags: session: str, unit: str +data: spikes: list[float], duration: float +inputs: SemiJoin_1, SemiJoin_3operatornot runJoinquality (function pod · not run) +tags: session: str, unit: str +data: n: int +inputs: SemiJoin_2function podnot runqualityrates (function pod · mean_rate · not run) +tags: session: str, unit: str +data: rate: float +inputs: Joinfunction podmean_ratenot runrates \ No newline at end of file diff --git a/docs/dev/specs/itl-1455-constraining-inputs/after-TB.svg b/docs/dev/specs/itl-1455-constraining-inputs/after-TB.svg new file mode 100644 index 000000000..93c9a1b42 --- /dev/null +++ b/docs/dev/specs/itl-1455-constraining-inputs/after-TB.svg @@ -0,0 +1,36 @@ +Job 'workshop'approved_sessions → SemiJoin_1: only decides which rows pass +keeps the rows that match on: sessionsessions → SemiJoin_1SemiJoin_1 → SemiJoin_2: only decides which rows pass +keeps the rows that match on: sessionSemiJoin_1 → Joinspikes → SemiJoin_3units → SemiJoin_2SemiJoin_2 → SelectDataColumnsSemiJoin_2 → qualitySelectDataColumns → SemiJoin_3: only decides which rows pass +keeps the rows that match on: session, unitSemiJoin_3 → JoinJoin → ratesapproved_sessions (source · DictSource · bound) +tags: session: str +data: note: strsource · DictSourceboundapproved_sessionssessions (source · DictSource · bound) +tags: session: str +data: duration: floatsourceDictSourceboundsessionsSemiJoin_1 (operator · not run) +tags: session: str +data: duration: float +inputs: sessions; constrained by approved_sessions +keeps the rows that match on: sessionoperatornot runSemiJoin_1spikes (source · DictSource · bound) +tags: session: str, unit: str +data: spikes: list[float]sourceDictSourceboundspikesunits (source · DictSource · bound) +tags: session: str, unit: str +data: snr: floatsourceDictSourceboundunitsSemiJoin_2 (operator · not run) +tags: session: str, unit: str +data: snr: float +inputs: units; constrained by SemiJoin_1 +keeps the rows that match on: sessionoperatornot runSemiJoin_2SelectDataColumns (operator · not run) +tags: session: str, unit: str +data: snr: float +inputs: SemiJoin_2operator · not runSelectDataColumnsSemiJoin_3 (operator · not run) +tags: session: str, unit: str +data: spikes: list[float] +inputs: spikes; constrained by SelectDataColumns +keeps the rows that match on: session, unitoperatornot runSemiJoin_3Join (operator · not run) +tags: session: str, unit: str +data: spikes: list[float], duration: float +inputs: SemiJoin_1, SemiJoin_3operatornot runJoinquality (function pod · not run) +tags: session: str, unit: str +data: n: int +inputs: SemiJoin_2function podnot runqualityrates (function pod · mean_rate · not run) +tags: session: str, unit: str +data: rate: float +inputs: Joinfunction podmean_ratenot runrates \ No newline at end of file diff --git a/docs/dev/specs/itl-1455-constraining-inputs/before-LR.svg b/docs/dev/specs/itl-1455-constraining-inputs/before-LR.svg new file mode 100644 index 000000000..74747022e --- /dev/null +++ b/docs/dev/specs/itl-1455-constraining-inputs/before-LR.svg @@ -0,0 +1,30 @@ +Job 'workshop'approved_sessions → SemiJoin_1sessions → SemiJoin_1SemiJoin_1 → SemiJoin_2SemiJoin_1 → Joinspikes → SemiJoin_3units → SemiJoin_2SemiJoin_2 → SelectDataColumnsSemiJoin_2 → qualitySelectDataColumns → SemiJoin_3SemiJoin_3 → JoinJoin → ratesapproved_sessions (source · DictSource · bound) +tags: session: str +data: note: strsource · DictSourceboundapproved_sessionssessions (source · DictSource · bound) +tags: session: str +data: duration: floatsourceDictSourceboundsessionsSemiJoin_1 (operator · not run) +tags: session: str +data: duration: float +inputs: approved_sessions, sessionsoperatornot runSemiJoin_1spikes (source · DictSource · bound) +tags: session: str, unit: str +data: spikes: list[float]sourceDictSourceboundspikesunits (source · DictSource · bound) +tags: session: str, unit: str +data: snr: floatsourceDictSourceboundunitsSemiJoin_2 (operator · not run) +tags: session: str, unit: str +data: snr: float +inputs: SemiJoin_1, unitsoperatornot runSemiJoin_2SelectDataColumns (operator · not run) +tags: session: str, unit: str +data: snr: float +inputs: SemiJoin_2operator · not runSelectDataColumnsSemiJoin_3 (operator · not run) +tags: session: str, unit: str +data: spikes: list[float] +inputs: spikes, SelectDataColumnsoperatornot runSemiJoin_3Join (operator · not run) +tags: session: str, unit: str +data: spikes: list[float], duration: float +inputs: SemiJoin_1, SemiJoin_3operatornot runJoinquality (function pod · not run) +tags: session: str, unit: str +data: n: int +inputs: SemiJoin_2function podnot runqualityrates (function pod · mean_rate · not run) +tags: session: str, unit: str +data: rate: float +inputs: Joinfunction podmean_ratenot runrates \ No newline at end of file diff --git a/docs/dev/specs/itl-1455-constraining-inputs/before-TB.svg b/docs/dev/specs/itl-1455-constraining-inputs/before-TB.svg new file mode 100644 index 000000000..80bdf8855 --- /dev/null +++ b/docs/dev/specs/itl-1455-constraining-inputs/before-TB.svg @@ -0,0 +1,30 @@ +Job 'workshop'approved_sessions → SemiJoin_1sessions → SemiJoin_1SemiJoin_1 → SemiJoin_2SemiJoin_1 → Joinspikes → SemiJoin_3units → SemiJoin_2SemiJoin_2 → SelectDataColumnsSemiJoin_2 → qualitySelectDataColumns → SemiJoin_3SemiJoin_3 → JoinJoin → ratesapproved_sessions (source · DictSource · bound) +tags: session: str +data: note: strsource · DictSourceboundapproved_sessionssessions (source · DictSource · bound) +tags: session: str +data: duration: floatsourceDictSourceboundsessionsSemiJoin_1 (operator · not run) +tags: session: str +data: duration: float +inputs: approved_sessions, sessionsoperatornot runSemiJoin_1spikes (source · DictSource · bound) +tags: session: str, unit: str +data: spikes: list[float]sourceDictSourceboundspikesunits (source · DictSource · bound) +tags: session: str, unit: str +data: snr: floatsourceDictSourceboundunitsSemiJoin_2 (operator · not run) +tags: session: str, unit: str +data: snr: float +inputs: SemiJoin_1, unitsoperatornot runSemiJoin_2SelectDataColumns (operator · not run) +tags: session: str, unit: str +data: snr: float +inputs: SemiJoin_2operator · not runSelectDataColumnsSemiJoin_3 (operator · not run) +tags: session: str, unit: str +data: spikes: list[float] +inputs: spikes, SelectDataColumnsoperatornot runSemiJoin_3Join (operator · not run) +tags: session: str, unit: str +data: spikes: list[float], duration: float +inputs: SemiJoin_1, SemiJoin_3operatornot runJoinquality (function pod · not run) +tags: session: str, unit: str +data: n: int +inputs: SemiJoin_2function podnot runqualityrates (function pod · mean_rate · not run) +tags: session: str, unit: str +data: rate: float +inputs: Joinfunction podmean_ratenot runrates \ No newline at end of file diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index 58d54ddeb..d2a379f50 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -76,6 +76,9 @@ class SemiJoin(BinaryOperator): (a null key matches nothing) and keeps the left input's type (ITL-829). """ + CONSTRAINING_INPUTS: ClassVar[tuple[int, ...]] = (1,) + CONSTRAINT_MATCHES_SHARED_TAGS: ClassVar[bool] = True + @staticmethod def _match_keys( left_tag_keys: Collection[str], right_tag_keys: Collection[str] diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index dd34a82ec..f829d44a5 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -134,6 +134,20 @@ class StaticOutputOperatorPod(TraceableBase): and its input's head is never asked for. """ + CONSTRAINING_INPUTS: ClassVar[tuple[int, ...]] = () + """The input positions whose rows only decide which rows of the other inputs pass. + + No row of such an input flows on (``SemiJoin``'s right input). Display only: the + pipeline diagram draws these inputs apart (ITL-1455); it enters no identity. Only a + plain tuple of plain integers within the inputs counts; anything else is none. + """ + + CONSTRAINT_MATCHES_SHARED_TAGS: ClassVar[bool] = False + """Whether the constraining inputs match on the tag columns every input has. + + Display only: the diagram then names those tags. + """ + PROVISIONAL: ClassVar[bool] = False """Whether the operator is provisional: its identity is not frozen (ITL-1266). diff --git a/src/orcapod/core/sources/display_names.py b/src/orcapod/core/sources/display_names.py index 5d10e7c3d..f7f3d1a1d 100644 --- a/src/orcapod/core/sources/display_names.py +++ b/src/orcapod/core/sources/display_names.py @@ -41,7 +41,7 @@ def _mro(cls: type) -> tuple[type, ...]: return _TYPE_MRO.__get__(cls) -def _class_dicts(cls: type) -> list[Mapping[str, Any]]: +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)] @@ -53,7 +53,7 @@ def _is_a(source: object, cls: type) -> bool: 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)): + for namespace in class_dicts(type(source)): found = namespace.get("__dict__") if type(found) is GetSetDescriptorType: return found.__get__(source) @@ -62,7 +62,7 @@ def _stored(source: object) -> Mapping[str, Any]: 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) + 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" diff --git a/src/orcapod/pipeline/diagram.py b/src/orcapod/pipeline/diagram.py index 613955179..28b73c2c7 100644 --- a/src/orcapod/pipeline/diagram.py +++ b/src/orcapod/pipeline/diagram.py @@ -39,7 +39,7 @@ from typing_extensions import override -from orcapod.core.sources.display_names import node_display_names +from orcapod.core.sources.display_names import class_dicts, node_display_names from orcapod.types.provenance import Highlight from orcapod.utils.in_development import warn_in_development @@ -88,6 +88,7 @@ class _Node: mark: str = "" asked: str = "" shown: str = "" + keeps: tuple[str, ...] = () @property def text(self) -> str: @@ -110,6 +111,13 @@ class _Edge: target: int folded: tuple[str, ...] = () highlighted: bool = False + # The stream only decides which rows of the target's other inputs pass (ITL-1455). + constrains: bool = False + + @property + def key(self) -> tuple[int, int, bool]: + """What tells the edge apart: one stream can be both kinds of input.""" + return (self.source, self.target, self.constrains) # --------------------------------------------------------------------------- @@ -195,6 +203,73 @@ def _collapsible(node: Any) -> bool: ) +def _upstream_labels(node: Any, label_of: Mapping[int, str]) -> list[str | None]: + """The label of each of an operator node's inputs, in argument order. + + Args: + node: The node. + label_of: The label of each node of the graph, by the node's ``id()``. + + Returns: + One label per input; ``None`` for an input that is not a node of the graph. + """ + return [label_of.get(id(stream)) for stream in node.upstreams] + + +def _declared(producer: Any, name: str) -> Any: + """What an operator's class declares, read without running any code of the class. + + Args: + producer: The operator, or ``None``. + 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)): + if name in namespace: + return namespace[name] + return None + + +def _input_roles( + node: Any, upstream_labels: Sequence[str], label_of: Mapping[int, str] +) -> list[tuple[str, bool]]: + """A node's inputs, each with whether it only constrains the others (ITL-1455). + + Which input positions constrain is declared by the operator's class + (``CONSTRAINING_INPUTS``). A stream that is both kinds of input is listed twice. + + Args: + 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()``. + + 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": + return plain + producer = getattr(node, "producer", None) + positions = _declared(producer, "CONSTRAINING_INPUTS") + if type(positions) is not tuple or not positions: + return plain + ordered = _upstream_labels(node, label_of) + if not all(type(i) is int and 0 <= i < len(ordered) for i in positions): + return plain + if set(ordered) != set(upstream_labels): + # An input is missing (a loaded graph that lost a node): positions say nothing. + return plain + roles = {(label, i in positions) for i, label in enumerate(ordered)} + return [ + (label, constrains) + for label in upstream_labels + for constrains in (False, True) + if (label, constrains) in roles + ] + + def _run_facts(summary: NodeRunSummary | None) -> tuple[tuple[str, str], ...]: """What the job's last run did with a node's rows, from its ``NodeRunSummary``.""" if summary is None: @@ -259,6 +334,37 @@ def _failed_rows(node: Any) -> int: return _last_run_failed(node) if isinstance(node, FunctionJobNode) else 0 +def _constraint_fact( + node: Any, label_of: Mapping[int, str], by_label: Mapping[str, Any] +) -> tuple[str, str] | None: + """What a node's constraining inputs do, from its inputs' predicted tag columns. + + Args: + 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. + + 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: + return None + try: + tag_keys = [ + tuple(by_label[label].output_schema()[0]) + for label in _upstream_labels(node, label_of) + if label is not None + ] + except ValueError: + return None + shared = set(tag_keys[0]).intersection(*tag_keys[1:]) + if not shared: + return ("keeps every row", "the inputs share no tag column") + return ("keeps the rows that match on", ", ".join(sorted(shared))) + + def _topological_labels( preds: Mapping[str, Sequence[str]], succs: Mapping[str, Sequence[str]] ) -> list[str]: @@ -325,12 +431,22 @@ def _build_model( for names in (*preds.values(), *succs.values()): names.sort() + label_of = {id(node): label for label, node in by_label.items()} + roles = { + label: _input_roles(node, preds[label], label_of) + for label, node in by_label.items() + } + folded: set[str] = set() if collapse: + # A step with a constraining input is never folded: the constraint would be + # drawn as data. folded = { label for label, node in by_label.items() - if _collapsible(node) and len(succs[label]) == 1 + if _collapsible(node) + and len(succs[label]) == 1 + and not any(constrains for _, constrains in roles[label]) } if highlight is not None: # The node the question was asked at is always shown, and so is a @@ -359,12 +475,15 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: found.extend(ends(upstream, (label, *via))) return found - edges: dict[tuple[int, int], tuple[str, ...]] = {} + edges: dict[tuple[int, int, bool], tuple[str, ...]] = {} + direct: set[tuple[int, int, bool]] = set() folded_into: dict[str, list[str]] = {} for label in shown: - for upstream in preds[label]: + for upstream, constrains in roles[label]: for end, via in ends(upstream, ()): - key = (index[end], index[label]) + key = (index[end], index[label], constrains) + if not via: + direct.add(key) edges[key] = tuple(dict.fromkeys((*edges.get(key, ()), *via))) folded_into.setdefault(label, []).extend(via) @@ -394,6 +513,11 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: # draws the graph and says why the columns are missing. tag_schema, data_schema = {}, {} facts = (*facts, ("schema", f"not available: {error}")) + keeps: tuple[str, str] | None = None + if any(constrains for _, constrains in roles[label]): + keeps = _constraint_fact(node, label_of, by_label) + if keeps is not None: + facts = (*facts, keeps) steps = list(dict.fromkeys(folded_into.get(label, []))) if steps: facts = (*facts, ("folded steps", ", ".join(steps))) @@ -409,6 +533,7 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: status="" if highlight is not None else statuses.get(label, ""), facts=facts, shown=source_text, + keeps=keeps or (), 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" @@ -417,13 +542,13 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: ) ) - def lit(source: int, target: int, via: tuple[str, ...]) -> bool: + def lit(key: tuple[int, int, bool], via: tuple[str, ...]) -> bool: """Whether a displayed edge is emphasized: some highlighted path leads from its start to its end through the steps folded into it (several folded paths merge into one displayed edge, so their labels are not one chain).""" if highlight is None: return False - start, end = shown[source], shown[target] + start, end = shown[key[0]], shown[key[1]] if not via: return (start, end) in highlight.edges inner = set(via) @@ -433,7 +558,7 @@ def lit(source: int, target: int, via: tuple[str, ...]) -> bool: for upstream, downstream in highlight.edges: if upstream != current: continue - if downstream == end: + if downstream == end and (current != start or key in direct): return True if downstream in inner and downstream not in seen: seen.add(downstream) @@ -445,9 +570,10 @@ def lit(source: int, target: int, via: tuple[str, ...]) -> bool: source=source, target=target, folded=via, - highlighted=lit(source, target, via), + highlighted=lit((source, target, constrains), via), + constrains=constrains, ) - for (source, target), via in sorted(edges.items()) + for (source, target, constrains), via in sorted(edges.items()) ] return nodes, edge_list @@ -468,6 +594,9 @@ def lit(source: int, target: int, via: tuple[str, ...]) -> bool: _LAYER_GAP = 56.0 _NODE_GAP = 22.0 _DUMMY_GAP = 10.0 +# The free lane kept beside a box on the side where a constraining edge enters it. +_LANE = 20.0 +_LANE_TURN = 12.0 # how far before the box's middle the edge turns towards it _MARGIN = 12.0 _SWEEPS = 12 _PLACEMENT_ROUNDS = 8 @@ -590,7 +719,7 @@ def _layout( for node in nodes: width, height = _node_size(node) boxes[node.index] = _Box(node.index, layer[node.index], width, height) - chains: dict[tuple[int, int], list[int]] = {} + chains: dict[tuple[int, int, bool], list[int]] = {} links: dict[int, list[int]] = {} back: dict[int, list[int]] = {} dummy = -1 @@ -601,7 +730,7 @@ def _layout( chain.append(dummy) dummy -= 1 chain.append(edge.target) - chains[(edge.source, edge.target)] = chain + chains[edge.key] = chain for upper, lower in zip(chain, chain[1:]): links.setdefault(upper, []).append(lower) back.setdefault(lower, []).append(upper) @@ -641,13 +770,38 @@ def barycenter(item: tuple[int, _Box]) -> tuple[float, int]: best, best_count = [list(row) for row in layers], count layers = best + # The side of each box a constraining edge enters it from (-1.0 or 1.0): where its + # last point lies among the other inputs' in the layer before, so that it does not + # cross them; after them when it does not differ. The lane beside the box is kept + # free there. + sides: dict[int, float] = {} + if any(edge.constrains for edge in edges): + order = {box.key: j for row in layers for j, box in enumerate(row)} + arriving: dict[int, dict[bool, list[int]]] = {} + for edge in edges: + arriving.setdefault(edge.target, {False: [], True: []})[ + edge.constrains + ].append(order[chains[edge.key][-2]]) + for target, by_role in arriving.items(): + if by_role[True]: + data, limits = by_role[False], by_role[True] + before = bool(data) and sum(limits) / len(limits) < sum(data) / len( + data + ) + sides[target] = -1.0 if before else 1.0 + + def lane(box: _Box, side: float) -> float: + """The room kept free beside a box, on the given side.""" + return _LANE if sides.get(box.key) == side else 0.0 + def extent(box: _Box) -> float: return (box.height if across else box.width) if box.key >= 0 else 0.0 def separation(row: Sequence[_Box], j: int) -> float: both_nodes = row[j - 1].key >= 0 and row[j].key >= 0 gap = _NODE_GAP if both_nodes else _DUMMY_GAP - return (extent(row[j - 1]) + extent(row[j])) / 2 + gap + lanes = lane(row[j - 1], 1.0) + lane(row[j], -1.0) + return (extent(row[j - 1]) + extent(row[j])) / 2 + gap + lanes for row in layers: cursor = 0.0 @@ -682,10 +836,16 @@ def place(row: Sequence[_Box], wanted: Sequence[float]) -> None: wanted.append(sum(found) / len(found) if found else box.pos) place(layers[i], wanted) - lowest = min((box.pos - extent(box) / 2 for box in boxes.values()), default=0.0) + lowest = min( + (box.pos - extent(box) / 2 - lane(box, -1.0) for box in boxes.values()), + default=0.0, + ) for box in boxes.values(): box.pos -= lowest - breadth = max((box.pos + extent(box) / 2 for box in boxes.values()), default=0.0) + breadth = max( + (box.pos + extent(box) / 2 + lane(box, 1.0) for box in boxes.values()), + default=0.0, + ) depth = [ max( @@ -725,7 +885,7 @@ def node_end(key: int, leaving: bool) -> tuple[float, float]: routed: list[tuple[_Edge, list[tuple[float, float]]]] = [] for edge in edges: - chain = chains[(edge.source, edge.target)] + chain = chains[edge.key] points = [node_end(edge.source, leaving=True)] for key in chain[1:-1]: box = boxes[key] @@ -733,7 +893,17 @@ def node_end(key: int, leaving: bool) -> tuple[float, float]: points.extend( [point(start, box.pos), point(start + depth[box.layer], box.pos)] ) - points.append(node_end(edge.target, leaving=False)) + if edge.constrains: + # Down the lane beside the box, to the corner where it turns, then in. + box = boxes[edge.target] + side = sides[edge.target] + middle = starts[box.layer] + depth[box.layer] / 2 + edge_of_box = box.pos + side * extent(box) / 2 + points.append(point(starts[box.layer], edge_of_box + side * _LANE * 0.8)) + points.append(point(middle, edge_of_box + side * _LANE * 0.8)) + points.append(point(middle, edge_of_box)) + else: + points.append(node_end(edge.target, leaving=False)) routed.append((edge, points)) breadth_total = breadth + 2 * _MARGIN @@ -824,6 +994,34 @@ def _edge_path(points: Sequence[tuple[float, float]], across: bool) -> str: return " ".join(out) +def _side_path(points: Sequence[tuple[float, float]], across: bool) -> str: + """The path of a constraining edge: to the lane beside its box, along it, and in. + + Its last three points are the lane's start, the corner and the box's side. + """ + (cx, cy), (x, y) = points[-2:] + turn = (cx - _LANE_TURN, cy) if across else (cx, cy - _LANE_TURN) + return ( + f"{_edge_path(points[:-2], across)} L{_num(turn[0])},{_num(turn[1])} " + f"Q{_num(cx)},{_num(cy)} {_num(x)},{_num(y)}" + ) + + +def _side_arrow_head( + corner: tuple[float, float], end: tuple[float, float], across: bool +) -> str: + """A filled triangle pointing from ``corner`` to ``end``, its tip at ``end``.""" + x, y = end + half = _ARROW / 2 + if across: + back = y + (_ARROW if corner[1] > y else -_ARROW) + corners = [(x - half, back), (x, y), (x + half, back)] + else: + back = x + (_ARROW if corner[0] > x else -_ARROW) + corners = [(back, y - half), (x, y), (back, y + half)] + return "M" + " L".join(f"{_num(a)},{_num(b)}" for a, b in corners) + " Z" + + def _arrow_head(end: tuple[float, float], across: bool) -> str: """A filled triangle pointing along the layer axis, its tip at ``end``.""" x, y = end @@ -841,17 +1039,22 @@ def _clip(text: str, width: float, char_width: float) -> str: return text if len(text) <= room else text[: max(room - 1, 1)] + "…" +def _keeps(node: _Node) -> str: + """What the node's constraining inputs keep, or ``""``.""" + return ": ".join(node.keeps) + + def _schema_text(pairs: Sequence[tuple[str, str]]) -> str: return ", ".join(f"{name}: {tp}" for name, tp in pairs) or "none" -def _tooltip(node: _Node, inputs: Sequence[str]) -> str: +def _tooltip(node: _Node, inputs: str) -> str: """The node's details as plain text, shown on hover over the inline picture.""" 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: - lines.append(f"inputs: {', '.join(inputs)}") + lines.append(f"inputs: {inputs}") lines.extend(f"{name}: {text}" for name, text in node.facts) return "\n".join(lines) @@ -859,7 +1062,7 @@ def _tooltip(node: _Node, inputs: Sequence[str]) -> str: def _svg( title: str, nodes: Sequence[_Node], - inputs: Mapping[int, Sequence[str]], + inputs: Mapping[int, str], layout: _Layout, across: bool, standalone: bool, @@ -870,7 +1073,7 @@ def _svg( Args: title: The diagram's title, the picture's accessible name. nodes: The nodes. - inputs: The labels of each node's inputs, by node index. + inputs: Each node's inputs as text, by node index. layout: Where the nodes and edges are drawn. across: Whether the layers advance left to right. standalone: Draw it for an image of its own: on a light background, in a fixed @@ -918,6 +1121,19 @@ def _svg( if edge.folded: tip += f" (through {', '.join(edge.folded)})" dash = ' stroke-dasharray="5 3"' if edge.folded else "" + if edge.constrains: + tip += ": only decides which rows pass" + note = _keeps(nodes[edge.target]) + if note: + tip += f"\n{note}" + # Told from a folded data edge by the pattern too; folded, by both. + pattern = "8 3 2 3" if edge.folded else "3 3" + dash = f' class="op-dag-constraint" stroke-dasharray="{pattern}"' + path = _side_path(points, across) + head = _side_arrow_head(points[-2], points[-1], across) + else: + path = _edge_path(points, across) + head = _arrow_head(points[-1], across) accent = ( f' class="op-dag-highlight" stroke="{_HIGHLIGHT_COLOUR}" ' 'stroke-opacity="1" stroke-width="2.6"' @@ -928,8 +1144,8 @@ def _svg( parts.append( f'' f"{_escape(tip)}" - f'' - f'' + f'' ) parts.append('') @@ -959,7 +1175,7 @@ def _svg( f'' - f"{_escape(_tooltip(node, inputs.get(node.index, ())))}" + f"{_escape(_tooltip(node, inputs.get(node.index, '')))}" f'' @@ -1009,13 +1225,13 @@ def _svg( return "".join(parts) -def _table(nodes: Sequence[_Node], inputs: Mapping[int, Sequence[str]]) -> str: +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.""" rows = "".join( "" f"{_escape(node.text)}" f"{_escape(node.kind_line)}" - f"{_escape(', '.join(inputs.get(node.index, ())))}" + f"{_escape(inputs.get(node.index, ''))}" f"{_escape(_schema_text(node.tag_schema))}" f"{_escape(_schema_text(node.data_schema))}" f"{_escape('; '.join(f'{n}: {t}' for n, t in node.facts))}" @@ -1090,11 +1306,24 @@ def _asset(name: str) -> str: return _compact(text, css=name.endswith(".css")) -def _inputs(nodes: Sequence[_Node], edges: Sequence[_Edge]) -> dict[int, list[str]]: - """The drawn names of each node's inputs, by node index, in edge order.""" - inputs: dict[int, list[str]] = {} +def _inputs(nodes: Sequence[_Node], edges: Sequence[_Edge]) -> dict[int, str]: + """Each node's inputs as text, by node index: drawn names in edge order. + + The inputs that only constrain follow the others: ``a; constrained by b``. + """ + data: dict[int, list[str]] = {} + limits: dict[int, list[str]] = {} for edge in edges: - inputs.setdefault(edge.target, []).append(nodes[edge.source].text) + names = limits if edge.constrains else data + names.setdefault(edge.target, []).append(nodes[edge.source].text) + inputs: dict[int, str] = {} + for target in dict.fromkeys(edge.target for edge in edges): + parts: list[str] = [] + if target in data: + parts.append(", ".join(data[target])) + if target in limits: + parts.append(f"constrained by {', '.join(limits[target])}") + inputs[target] = "; ".join(parts) return inputs @@ -1241,8 +1470,8 @@ def title(self) -> str: """ return f"{self._kind.capitalize()} {self._name!r}" - def _inputs(self) -> dict[int, list[str]]: - """The labels of each node's inputs, in edge order.""" + def _inputs(self) -> dict[int, str]: + """Each node's inputs as text, by node index.""" return _inputs(self._nodes, self._edges) def to_dict(self) -> dict[str, Any]: @@ -1260,7 +1489,10 @@ def to_dict(self) -> dict[str, Any]: 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 + (the labels of the steps folded into it), and ``constrains`` (``True``) when + the stream only decides which rows of the other inputs pass (``SemiJoin``'s + right input); a stream that is both kinds of input of a node has two edges. + With a highlight, every node and edge also has ``highlighted``, and the model has the highlight's ``note``. """ return self._model(self._nodes, self._edges) @@ -1303,7 +1535,13 @@ def _plain_model(self, nodes: list[_Node], edges: list[_Edge]) -> dict[str, Any] for node in nodes ], "edges": [ - {"source": e.source, "target": e.target, "folded": list(e.folded)} + { + "source": e.source, + "target": e.target, + "folded": list(e.folded), + # Only where the stream constrains the other inputs (ITL-1455). + **({"constrains": True} if e.constrains else {}), + } for e in edges ], } @@ -1317,7 +1555,8 @@ def to_text(self) -> str: A title line, then `` ( · · ) <- `` per node, in topological order with ties broken by label; the name is the bound source's assigned label for a source that has one, else the node's - label. With a + label. Inputs that only constrain the others follow them + (``<- a; constrained by b``). With a highlight, a line with its note follows the title, no status is shown, each highlighted node's line starts with ``*`` and the node the question was asked at with ``>`` (and ends with ``[traced from here]`` or @@ -1340,7 +1579,7 @@ def to_text(self) -> str: if node.asked: line += f" [{node.asked}]" if node.index in inputs: - line += " <- " + ", ".join(inputs[node.index]) + line += " <- " + inputs[node.index] lines.append(line) # A lone surrogate cannot be printed or saved as UTF-8: shown as U+FFFD. return _SURROGATE.sub("\ufffd", "\n".join(lines)) diff --git a/src/orcapod/pipeline/diagram_assets/diagram.js b/src/orcapod/pipeline/diagram_assets/diagram.js index ab0e4bec9..ce42c67bd 100644 --- a/src/orcapod/pipeline/diagram_assets/diagram.js +++ b/src/orcapod/pipeline/diagram_assets/diagram.js @@ -307,10 +307,10 @@ dl.appendChild(dd); } function select(i) { - var n = model.nodes[i], inputs = []; + var n = model.nodes[i], inputs = [], limits = []; selected = n.label; model.edges.forEach(function (e) { - if (e.target === i) inputs.push(model.nodes[e.source].text || model.nodes[e.source].label); + if (e.target === i) (e.constrains ? limits : inputs).push(model.nodes[e.source].text || model.nodes[e.source].label); }); svg.querySelectorAll('.op-dag-node').forEach(function (g) { g.classList.toggle('op-dag-selected', +g.getAttribute('data-index') === i); @@ -328,6 +328,7 @@ row(dl, 'tags', schema(n.tag_schema)); row(dl, 'data', schema(n.data_schema)); row(dl, 'inputs', inputs.join(', ') || 'none'); + if (limits.length) row(dl, 'constrained by', limits.join(', ')); if (n.asked) row(dl, 'question', n.asked); if (n.mark) row(dl, 'highlight', n.mark); n.facts.forEach(function (f) { row(dl, f[0], f[1]); }); diff --git a/tests/test_pipeline/diagram_harness.js b/tests/test_pipeline/diagram_harness.js index b3d12f171..2dec84d8f 100644 --- a/tests/test_pipeline/diagram_harness.js +++ b/tests/test_pipeline/diagram_harness.js @@ -172,6 +172,7 @@ function observe() { .filter((g) => g.classList.contains('op-dag-selected')) .map((g) => g.getAttribute('aria-label').split(', ')[0]) : [], panel: root.querySelector('.op-dag-panel').classList.contains('op-dag-open'), + panelText: root.querySelector('.op-dag-panel').textContent, count: root.querySelector('.op-dag-count').textContent, controls: Object.fromEntries(['direction', 'collapse'] .filter((name) => root.querySelector('.op-dag-' + name)) diff --git a/tests/test_pipeline/test_diagram_constraints.py b/tests/test_pipeline/test_diagram_constraints.py new file mode 100644 index 000000000..afb3099f2 --- /dev/null +++ b/tests/test_pipeline/test_diagram_constraints.py @@ -0,0 +1,441 @@ +"""The diagram draws an input that only constrains the others apart (ITL-1455).""" + +from __future__ import annotations + +import re +import shutil +import warnings +import xml.etree.ElementTree as ET +from pathlib import Path +from typing import Any, cast + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import SemiJoinIgnoredColumnWarning +from orcapod.operators import Join, MergeJoin, SemiJoin +from orcapod.pipeline import PipelineDiagram +from orcapod.pipeline.diagram import _Edge, _layout, _Node +from orcapod.sources import DictSource +from orcapod.types.provenance import Highlight + +from ..test_core.operators.several_items import ( + MAIN, + P, + Q, + Arrangement, + arrangements, + make_source, +) +from .test_diagram import _run_view + +CALLS: list[str] = [] + + +@function_pod(output_keys="rate") +def rate(x: int) -> float: + """Return the value as a float.""" + CALLS.append("rate") + return float(x) + + +def _source(name: str, tags: list[str], *data: str) -> DictSource: + return DictSource( + [{**dict.fromkeys(tags, f"t{i}"), **dict.fromkeys(data, i)} for i in range(3)], + tag_columns=tags, + tag_only_columns=True, + source_id=name, + ) + + +def _job(*, reverse: bool = False) -> PipelineJob: + """Nested semi joins, recorded in either order of the sources.""" + job = PipelineJob(name="nested", database=InMemoryArrowDatabase()) + made = { + name: _source(name, tags, *data) + for name, tags, data in ( + ("spikes", ["session", "unit"], ("x",)), + ("units", ["unit", "session"], ("snr", "depth")), + ("approved", ["session"], ("note",)), + )[:: -1 if reverse else 1] + } + with job: + kept = made["units"].semi_join(made["approved"], label="kept_units") + chosen = kept.select_data_columns(["snr"]) + rate.pod(made["spikes"].semi_join(chosen, label="kept"), label="rates") + return job + + +def _edges(diagram: PipelineDiagram) -> set[tuple[str, str, bool, tuple[str, ...]]]: + model = diagram.to_dict() + label = [node["label"] for node in model["nodes"]] + return { + ( + label[e["source"]], + label[e["target"]], + e.get("constrains", False), + tuple(e["folded"]), + ) + for e in model["edges"] + } + + +def _facts(diagram: PipelineDiagram, label: str) -> dict[str, str]: + (node,) = [n for n in diagram.to_dict()["nodes"] if n["label"] == label] + return dict(node["facts"]) + + +def test_only_semi_join_declares_a_constraining_input() -> None: + assert SemiJoin.CONSTRAINING_INPUTS == (1,) + assert Join.CONSTRAINING_INPUTS == MergeJoin.CONSTRAINING_INPUTS == () + + +@pytest.mark.parametrize("blueprint", [False, True]) +def test_the_right_input_constrains_in_model_text_and_details(blueprint: bool) -> None: + job = _job() + diagram = (job.pipeline if blueprint else job).diagram() + assert _edges(diagram) == { + ("units", "kept_units", False, ()), + ("approved", "kept_units", True, ()), + ("kept_units", "SelectDataColumns", False, ()), + ("spikes", "kept", False, ()), + ("SelectDataColumns", "kept", True, ()), + ("kept", "rates", False, ()), + } + # The key is in the model only where it applies. + assert {e.get("constrains", True) for e in diagram.to_dict()["edges"]} == {True} + text = diagram.to_text() + assert "<- units; constrained by approved" in text + assert "<- spikes; constrained by SelectDataColumns" in text + assert _facts(diagram, "kept_units")["keeps the rows that match on"] == "session" + assert _facts(diagram, "kept")["keeps the rows that match on"] == "session, unit" + + +def test_folding_keeps_the_constraint() -> None: + diagram = _job().diagram(collapse=True) + assert ("kept_units", "kept", True, ("SelectDataColumns",)) in _edges(diagram) + assert "<- spikes; constrained by kept_units" in diagram.to_text() + assert 'stroke-dasharray="8 3 2 3"' in diagram.to_svg() + + +def test_a_folded_join_beneath_a_constraint_constrains_from_each_of_its_inputs() -> ( + None +): + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + limits = _source("b", ["k"], "y").join(_source("c", ["k"], "z")) + rate.pod(_source("a", ["k"], "x").semi_join(limits, label="s"), label="r") + edges = _edges(job.diagram(collapse=True)) + assert {e for e in edges if e[1] == "s"} == { + ("a", "s", False, ()), + ("b", "s", True, ("Join",)), + ("c", "s", True, ("Join",)), + } + + +class _ConstrainedJoin(Join): + CONSTRAINING_INPUTS = (1,) + + +def test_a_foldable_step_with_a_constraining_input_is_not_folded() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + joined = _ConstrainedJoin(label="limited")( + _source("a", ["k"], "x"), _source("b", ["k"], "y") + ) + rate.pod(joined.select_data_columns(["x"]), label="r") + edges = _edges(job.diagram(collapse=True)) + assert {e for e in edges if e[1] == "limited"} == { + ("a", "limited", False, ()), + ("b", "limited", True, ()), + } + + +class _Tuple(tuple[int, ...]): + pass + + +class _Int(int): + pass + + +class _Raises: + def __get__(self, *args: Any) -> Any: + raise RuntimeError("read through a hook") + + +def _custom_job(operator: type[Join]) -> PipelineJob: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + operator(label="limited")(_source("a", ["k"], "x"), _source("b", ["k"], "y")) + return job + + +@pytest.mark.parametrize( + "declared", + [1, None, "1", [1], {1}, frozenset({1}), (True,), (1.0,), ("1",), (2,), (-1,)] + + [(1, 2), (1, None), _Tuple((1,)), (_Int(1),), _Raises()], + # Not the repr, which can hold an address: every xdist worker must collect one name. + ids=lambda value: type(value).__name__, +) +def test_a_malformed_declaration_counts_as_none(declared: Any) -> None: + class Custom(Join): + CONSTRAINING_INPUTS = declared + + class Plain(Join): + pass + + Plain.__name__ = "Custom" + for collapse in (False, True): + drawn, plain = ( + _custom_job(operator).diagram(collapse=collapse) + for operator in (Custom, Plain) + ) + assert drawn.to_dict() == plain.to_dict() + assert drawn.to_text() == plain.to_text() + assert drawn.to_svg() == plain.to_svg() + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +@pytest.mark.parametrize("positions", [(1, 2), (2, 1), (0, 2), (2, 0), (0, 1)], ids=str) +def test_several_constraining_positions_in_any_order( + arrangement: Arrangement, positions: tuple[int, ...] +) -> None: + class Custom(Join): + CONSTRAINING_INPUTS = positions + CONSTRAINT_MATCHES_SHARED_TAGS = True + + partners = [ + make_source(spec, Arrangement(spec.tags, arrangement.layout, arrangement.roles)) + for spec in (P, Q) + ] + sources = [make_source(MAIN, arrangement), *partners] + names = [MAIN.source_id, P.source_id, Q.source_id] + shared = sorted(set(MAIN.tags) & set(P.tags) & set(Q.tags)) + # The positions are argument positions, in either order of the arguments. + for order in ((0, 1, 2), (2, 1, 0)): + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + Custom(label="limited")(*(sources[i] for i in order)) + diagram = job.diagram() + assert _edges(diagram) == { + (names[i], "limited", position in positions, ()) + for position, i in enumerate(order) + } + facts = _facts(diagram, "limited") + if shared: + assert facts["keeps the rows that match on"] == ", ".join(shared) + else: + assert "keeps every row" in facts + + +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +def test_a_semi_join_s_keys_are_listed_whatever_the_arrangement( + arrangement: Arrangement, +) -> None: + other = make_source(P, Arrangement(P.tags, arrangement.layout, arrangement.roles)) + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job, warnings.catch_warnings(): + warnings.simplefilter("ignore", SemiJoinIgnoredColumnWarning) + SemiJoin(label="limited")(make_source(MAIN, arrangement), other) + shared = ", ".join(sorted(set(MAIN.tags) & set(P.tags))) + assert _facts(job.diagram(), "limited")["keeps the rows that match on"] == shared + + +def test_drawing_calls_nothing_of_a_users_operator() -> None: + class Meta(type(Join)): + drawing = False + + def __getattribute__(cls, name: str) -> Any: + if name.startswith("CONSTRAIN") and Meta.drawing: + raise RuntimeError("metaclass hook ran") + return super().__getattribute__(name) + + class Custom(Join, metaclass=Meta): + CONSTRAINING_INPUTS = (1,) + CONSTRAINT_MATCHES_SHARED_TAGS = cast(Any, _Raises()) + + def __getattribute__(self, name: str) -> Any: + if name.startswith("CONSTRAIN"): + raise RuntimeError("instance hook ran") + return super().__getattribute__(name) + + def constraint_fact(self, tag_keys: Any) -> Any: + raise RuntimeError("user callback ran") + + job = _custom_job(Custom) + Meta.drawing = True + diagram = job.diagram() + assert "constrained by b" in diagram.to_text() + assert not any("keeps" in name for name in _facts(diagram, "limited")) + + +def test_a_users_operator_may_declare_that_it_matches_on_the_shared_tags() -> None: + class Custom(Join): + CONSTRAINING_INPUTS = (1,) + CONSTRAINT_MATCHES_SHARED_TAGS = True + + facts = _facts(_custom_job(Custom).diagram(), "limited") + assert facts["keeps the rows that match on"] == "k" + + +def test_one_stream_as_both_inputs_has_two_edges() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + a = _source("a", ["k"], "x") + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SemiJoinIgnoredColumnWarning) + rate.pod(a.semi_join(a, label="s"), label="r") + diagram = job.diagram() + assert {e for e in _edges(diagram) if e[1] == "s"} == { + ("a", "s", False, ()), + ("a", "s", True, ()), + } + assert "s (operator · SemiJoin · not run) <- a; constrained by a" in ( + diagram.to_text() + ) + + +def test_no_shared_tag_column_is_stated() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + s = _source("a", ["k"], "x").semi_join(_source("b", ["m"], "y"), label="s") + rate.pod(s, label="r") + facts = _facts(job.diagram(), "s") + assert facts["keeps every row"] == "the inputs share no tag column" + + +def test_a_diagram_without_a_constraint_has_no_new_key_or_drawing() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + joined = _source("a", ["k"], "x").join(_source("b", ["k"], "y")) + rate.pod(joined, label="r") + diagram = job.diagram() + assert all( + set(e) == {"source", "target", "folded"} for e in diagram.to_dict()["edges"] + ) + assert "constrain" not in diagram.to_svg() + diagram.to_text() + + +def test_making_the_diagram_calls_no_function_and_moves_no_identity() -> None: + job = _job() + before = {label: node.content_hash() for label, node in job.nodes.items()} + CALLS.clear() + for collapse in (False, True): + job.diagram(collapse=collapse).to_html() + assert CALLS == [] + assert {label: n.content_hash() for label, n in job.nodes.items()} == before + + +def test_a_loaded_job_keeps_the_roles(tmp_path: Any) -> None: + job = _job() + job.run() + path = tmp_path / "job.json" + job.save(str(path)) + loaded = PipelineJob.load(str(path)) + assert _edges(loaded.diagram()) == _edges(job.diagram()) + + +@pytest.mark.parametrize("direction", ["LR", "TB"]) +def test_the_drawing_does_not_depend_on_the_recording_order(direction: Any) -> None: + pictures = { + _job(reverse=reverse).diagram(direction=direction).to_svg() + for reverse in (False, True) + } + assert len(pictures) == 1 + + +def test_a_highlight_lights_a_constraining_edge_by_its_own_path() -> None: + highlight = Highlight( + nodes=frozenset({"approved", "kept_units"}), + edges=frozenset({("approved", "kept_units")}), + ) + svg = _job().diagram(highlight=highlight).to_svg() + lit = [g for g in _edge_groups(svg) if "op-dag-highlight" in g] + assert len(lit) == 1 and "op-dag-constraint" in lit[0] + + +def test_a_folded_constraint_is_not_lit_by_the_data_edge_beside_it() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + a = _source("a", ["k"], "x") + rate.pod(a.semi_join(a.map_data({"x": "z"}), label="s"), label="r") + highlight = Highlight(nodes=frozenset({"a", "s"}), edges=frozenset({("a", "s")})) + svg = job.diagram(collapse=True, highlight=highlight).to_svg() + lit = [g for g in _edge_groups(svg) if "op-dag-highlight" in g] + assert len(lit) == 1 and "op-dag-constraint" not in lit[0] + + +def _edge_groups(svg: str) -> list[str]: + return re.findall(r"", svg, re.DOTALL) + + +def test_the_edge_tooltip_says_what_is_kept_and_labels_are_escaped() -> None: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + b = rate.pod(_source("b", ["k"], "x"), label="" + "long" * 40) + rate.pod(_source("a", ["k"], "x").semi_join(b, label="s"), label="r") + root = ET.fromstring(job.diagram().to_svg()) + titles = [t.text or "" for t in root.iter("{http://www.w3.org/2000/svg}title")] + assert any( + t.startswith("long") + and t.endswith("only decides which rows pass\nkeeps the rows that match on: k") + for t in titles + ) + + +# --------------------------------------------------------------------------- +# The layout +# --------------------------------------------------------------------------- + + +def _node(index: int, label: str) -> _Node: + return _Node(index, label, "operator", "", (), (), "", ()) + + +@pytest.mark.parametrize("direction", ["LR", "TB"]) +def test_a_constraint_enters_from_the_side_and_crosses_no_box_of_its_layer( + direction: Any, +) -> None: + labels = ["a", "b" * 30, "c", "s" * 20, "t", "u"] + nodes = [_node(i, label) for i, label in enumerate(labels)] + for flags in range(2**6): + pairs = [(0, 3), (1, 3), (1, 4), (2, 4), (2, 5), (0, 5)] + edges = [ + _Edge(s, t, constrains=bool(flags >> n & 1)) + for n, (s, t) in enumerate(pairs) + ] + layout = _layout(nodes, sorted(edges, key=lambda e: e.key), direction) + for edge, points in layout.edges: + if not edge.constrains: + continue + x, y, w, h = layout.boxes[edge.target] + (cx, cy), (ex, ey) = points[-2:] + if direction == "TB": + assert ey == cy == pytest.approx(y + h / 2) + assert any(ex == pytest.approx(side) for side in (x, x + w)) + assert not x <= cx <= x + w + else: + assert ex == cx == pytest.approx(x + w / 2) + assert any(ey == pytest.approx(side) for side in (y, y + h)) + assert not y <= cy <= y + h + for px, py in points[-3:-1]: + assert 0 <= px <= layout.width and 0 <= py <= layout.height + for bx, by, bw, bh in layout.boxes.values(): + assert not (bx <= px <= bx + bw and by <= py <= by + bh) + + +@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is not on PATH") +def test_the_details_panel_lists_constraining_inputs_apart(tmp_path: Path) -> None: + (seen,) = _run_view( + _job().diagram().to_html(), + [ + {"op": "run", "width": 400}, + {"op": "select", "label": "kept"}, + {"op": "observe"}, + ], + tmp_path, + ) + assert "inputsspikesconstrained bySelectDataColumns" in seen["panelText"] + assert "keeps the rows that match onsession, unit" in seen["panelText"]