"
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"]