From b7480b078678adcfe5f0aa57d1d6cdb3606ee1de Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 11:24:39 -0800 Subject: [PATCH 01/33] feat(pipeline): node.trace(), node.why_missing() and diagram highlight (ITL-1432) The workshop subset of the provenance showcase (ITL-1421, round two): - R: FunctionJobNode._stored_provenance reads the node's own pipeline entries and results with every column (entry id, base entry id, __node_content_hash, __computed), current data context only. get_all_records() is unchanged. - A: node.trace(row, column) on job nodes: output row system tags -> pipeline entry -> result (function, version, body hash, executor, time, computed here or reused) -> input row by system tags (content hash = __input_data_hash) -> GroupBy/Batch members by the operator's own rule (fold_members), checked by refolding their system tags -> source cells from the tokens. Exact on a shared memoized result; the same on a loaded job after run(load_only=True). Shows the pipeline entry's run id and time when stored (ITL-1433). - B: job.diagram(highlight=Highlight(...)); Trace and Absence offer theirs. - C: node.why_missing(source, record_id) -> Absence: the first function node's stored entries first, then the first step that removed the record, in explain()'s words; for a join, the key missing from the other input. Read-only: nothing is computed, no user code runs, nothing is polled or written. GroupBy's member order moves into one helper (no value changes; golden --check clean). Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1432.md | 25 + docs/api/index.md | 2 +- docs/api/nodes.md | 7 + docs/api/types.md | 12 + src/orcapod/core/nodes/function_node.py | 59 +- src/orcapod/core/nodes/operator_node.py | 3 +- src/orcapod/core/nodes/provenance_methods.py | 75 ++ src/orcapod/core/nodes/source_node.py | 3 +- src/orcapod/core/operators/batch.py | 29 + src/orcapod/core/operators/group_by.py | 177 +++-- src/orcapod/errors.py | 11 + src/orcapod/pipeline/base.py | 12 +- src/orcapod/pipeline/diagram.py | 112 ++- src/orcapod/pipeline/provenance.py | 791 +++++++++++++++++++ src/orcapod/types/__init__.py | 11 + src/orcapod/types/provenance.py | 377 +++++++++ tests/test_pipeline/test_provenance.py | 376 +++++++++ 17 files changed, 2005 insertions(+), 77 deletions(-) create mode 100644 changelog.d/ITL-1432.md create mode 100644 src/orcapod/core/nodes/provenance_methods.py create mode 100644 src/orcapod/pipeline/provenance.py create mode 100644 src/orcapod/types/provenance.py create mode 100644 tests/test_pipeline/test_provenance.py diff --git a/changelog.d/ITL-1432.md b/changelog.d/ITL-1432.md new file mode 100644 index 000000000..d2dcbe667 --- /dev/null +++ b/changelog.d/ITL-1432.md @@ -0,0 +1,25 @@ +### Added + +- Per-row provenance of a job (ITL-1432), in development: these interfaces may change. + - `node.trace(row, column)` on a job node traces one cell back to the source cells it + was made from. It returns a `Trace` of `TraceStep`s, with `SourceCell` leaves. + - Each function step has a `FunctionRun`: the function's name, version and body + hash, the executor and the time it computed, and whether this row's entry computed + the result or reused one stored for equal inputs. + - A `GroupBy` or `Batch` step lists its members, found by the operator's own rule and + checked by folding their system tags (`ProvenanceInconsistencyError` if they + disagree). + - The trace is exact on a result shared by two input rows, and works the same on a + loaded job after `run(load_only=True)`. + - Where a node holds no run, the trace says `not_computed`. + - `node.why_missing(source, record_id)` returns an `Absence`: + - whether the record ever reached the first function node, from its stored pipeline + entries; + - the nodes holding a row from it; + - the step that removed it, as a `Step` in `explain()`'s words; + - for a join, the key missing from the other input. + - `job.diagram(highlight=...)` emphasizes a `Highlight`'s nodes and edges and shows + its note. `Trace.highlight()` and `Absence.highlight()` give the trace's or the + missing row's path. + - The new types are in `orcapod.types`. None of these reads computes, calls user code, + polls or writes, and no hash, stored path or stored column changes. diff --git a/docs/api/index.md b/docs/api/index.md index 4cd9f9556..c76985a60 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -25,4 +25,4 @@ Everything else lives in subpackages: | [`orcapod.databases`](databases.md) | Persistent storage backends for computation results | | [`orcapod.nodes`](nodes.md) | Pipeline graph elements, including the DB-backed job nodes | | [`orcapod.streams`](streams.md) | Immutable (Tag, Data) sequences backed by PyArrow tables | -| [`orcapod.types`](types.md) | Core type definitions: `Schema`, `ColumnConfig`, `ContentHash`, `Condition`, `col`, `Explanation` | +| [`orcapod.types`](types.md) | Core type definitions: `Schema`, `ColumnConfig`, `ContentHash`, `Condition`, `col`, `Explanation`, `Trace`, `Absence`, `Highlight` | diff --git a/docs/api/nodes.md b/docs/api/nodes.md index 1b46f76d7..e39dd4b51 100644 --- a/docs/api/nodes.md +++ b/docs/api/nodes.md @@ -24,3 +24,10 @@ The database-backed nodes a `PipelineJob` builds; these are what `job.nodes[labe ::: orcapod.core.nodes.OperatorJobNode ::: orcapod.core.nodes.SourceJobNode + +## Provenance of a job's rows + +Every job node above (function, operator and source) has these two methods: they trace a +cell to its source cells, and say why a source record does not reach a node. + +::: orcapod.core.nodes.provenance_methods.ProvenanceMethods diff --git a/docs/api/types.md b/docs/api/types.md index aef3f1e7a..2403cc7df 100644 --- a/docs/api/types.md +++ b/docs/api/types.md @@ -25,3 +25,15 @@ Core type definitions used throughout Orcapod. ::: orcapod.types.SourceReading ::: orcapod.types.Step + +::: orcapod.types.Trace + +::: orcapod.types.TraceStep + +::: orcapod.types.FunctionRun + +::: orcapod.types.SourceCell + +::: orcapod.types.Absence + +::: orcapod.types.Highlight diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 2465e89d5..0cee62a4a 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -31,6 +31,7 @@ import pyarrow as pa from orcapod import contexts +from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.function_pod import ( fall_through_tags, function_input, @@ -1388,7 +1389,7 @@ def _joined_from_stored( return pa.Table.from_arrays(columns, names=names) -class FunctionJobNode(RunHoldingNode, FunctionNodeBase): +class FunctionJobNode(ProvenanceMethods, RunHoldingNode, FunctionNodeBase): """DB-backed execution node for function pod invocations. Created by ``PipelineJob`` at run time; never recorded inside a plain @@ -3395,6 +3396,62 @@ def as_source( # Cache-only helpers (PLT-1156) # ------------------------------------------------------------------ + def _stored_provenance(self) -> tuple[pa.Table | None, pa.Table | None]: + """Read this node's stored pipeline entries and results with every column. + + The provenance reader (ITL-1432). Unlike ``get_all_records``, nothing is joined + and nothing is dropped: the pipeline entries keep their key + (``__pipeline_entry_id``), ``__pipeline_base_entry_id``, the recomputation + index, ``__node_content_hash`` and ``__computed``; the results keep their key + as ``__data_id``, the column the pipeline entries name it by. Only this node's + entries are kept (``__node_content_hash``, when the table is shared by the + nodes of one pipeline hash), and only rows of the current data context, of + both tables. Results are read from the persistent result database and, when + one is attached, the ephemeral one. Nothing is computed or written. + + Returns: + The pipeline entries and the results, each ``None`` when nothing is + stored or no database is attached. + """ + if self._pipeline_database is None or self._cached_function_pod is None: + return None, None + context_key = self._stored_data_context_key + entries = self._pipeline_database.get_all_records( + self._versioned_pipeline_path, + record_id_column=_PIPELINE_ENTRY_ID_COL, + ) + if entries is not None: + entries = keep_rows_of_data_context(entries, context_key) + if self._table_scope == "pipeline_hash": + own_hash = self.content_hash().to_prefixed_digest() + mask = pa.array( + [ + value == own_hash + for value in entries.column( + constants.NODE_CONTENT_HASH_COL + ).to_pylist() + ], + pa.bool_(), + ) + entries = entries.filter(mask) + found: list[pa.Table] = [] + for cached_pod in (self._cached_function_pod, self._ephemeral_cached_pod): + if cached_pod is None: + continue + stored = cached_pod.result_database.get_all_records( + cached_pod.record_path, record_id_column=constants.DATA_RECORD_ID + ) + if stored is not None: + found.append(keep_rows_of_data_context(stored, context_key)) + results = ( + None + if not found + else found[0] + if len(found) == 1 + else pa.concat_tables(found, promote_options="default") + ) + return entries, results + def _fetch_joined_records( self, base_entry_ids: list[bytes] | None = None, diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 8db4ba400..9ef402e7a 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -28,6 +28,7 @@ import pyarrow.compute as pc from orcapod import contexts +from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.data_tags import ( mark_data_tags, data_tag_names, @@ -803,7 +804,7 @@ def as_node(self) -> OperatorNode: # --------------------------------------------------------------------------- -class OperatorJobNode(RunHoldingNode, OperatorNodeBase): +class OperatorJobNode(ProvenanceMethods, RunHoldingNode, OperatorNodeBase): """DB-backed execution node for operator pod invocations. Stream node representing an operator invocation with optional DB persistence. diff --git a/src/orcapod/core/nodes/provenance_methods.py b/src/orcapod/core/nodes/provenance_methods.py new file mode 100644 index 000000000..5fc127b90 --- /dev/null +++ b/src/orcapod/core/nodes/provenance_methods.py @@ -0,0 +1,75 @@ +"""The provenance methods of job nodes: ``trace`` and ``why_missing`` (ITL-1432).""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from orcapod.types.provenance import Absence, Trace + + +class ProvenanceMethods: + """Mixin of the job nodes (source, operator, function) that can be traced. + + Both methods read only what the job's nodes hold and what their databases store: + they never compute, call user code, poll or write. + """ + + def trace(self, row: Mapping[str, Any], column: str) -> Trace: + """Trace one cell of this node back to the source cells it was made from. + + In development: this interface may change. + + Each step names the node, the cell's value there and its row's tags. A function + step says which function produced the value, with its version, body hash, + executor and time, and whether this row's entry computed the result or reused + one stored for equal inputs. A ``GroupBy`` or ``Batch`` step lists its members, + found by the operator's own rule and checked: their system tags must fold to + the group's. The leaves are source cells. A loaded job traces the same once it + has run with ``load_only=True``. + + Args: + row: Column values that select exactly one row this node holds, usually + its tags: ``{"subject_id": "mouse_03", "session": "s2"}``. + column: The data column of the cell. + + Returns: + The trace; its root's status is ``"not_computed"`` when this node holds no + run (``run()`` the job first). + + Raises: + ValueError: If ``column`` is not a data column of this node, or ``row`` + names a column this node does not have or does not select one row. + ProvenanceInconsistencyError: If a link cannot be proven from what the job + holds and stores (a group whose members do not fold to its values). + """ + from orcapod.pipeline.provenance import trace + + return trace(self, row, column) + + def why_missing(self, source: str, record_id: str) -> Absence: + """Say whether rows from one source record reach this node, and if not, why. + + In development: this interface may change. + + First, from the first function node's stored pipeline entries: whether the + record ever reached it, in any run. Then, from the rows the nodes hold: the + nodes that hold a row from the record, and the first step that removed it, + in ``explain()``'s words; for a join, the key missing from the other input. + + Args: + source: The source id (as in source-info tokens). + record_id: The record id (``row_``, or the key columns as JSON). + + Returns: + The answer; its status is ``"not_computed"`` when a node on the way holds no + run. + + Raises: + ValueError: If no source with that id feeds this node. + ProvenanceInconsistencyError: If a group's members cannot be proven. + """ + from orcapod.pipeline.provenance import why_missing + + return why_missing(self, source, record_id) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 4359027fd..48fc50f04 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -21,6 +21,7 @@ import pyarrow as pa from orcapod import contexts +from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag @@ -1547,7 +1548,7 @@ def from_stream( return node -class SourceJobNode(SourceNodeBase): +class SourceJobNode(ProvenanceMethods, SourceNodeBase): """Execution-ready source node wrapping an optional concrete stream. Used inside ``PipelineJob._persistent_node_map``. The ``_concrete`` diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 5c621afce..e7a1969f8 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -101,6 +101,35 @@ def _batch_sizes(self, row_count: int) -> list[int]: sizes.append(rest) return sizes + fold_label: ClassVar[str] = BATCH_FOLD_LABEL + """The label of this operator's folds of the system tags.""" + + def fold_members( + self, table: pa.Table, tag_columns: Sequence[str] + ) -> list[list[int]]: + """Return the members of each batch of ``table``, as row numbers in member order. + + Reads only the given table, with the rule batching uses: consecutive rows, + ``batch_size`` each (``_batch_sizes``). The caller checks a batch by folding + its members' system tags (``fold_system_tag_values`` with ``fold_label``), + which must give the batch's folded values: the rows must be in the order the + batch read them. + + Args: + table: The input rows, in the order the batch read them. + tag_columns: The input's user tag columns (unused: a batch has no key). + + Returns: + One list of row numbers per batch. + """ + del tag_columns # a batch is decided by position alone + out: list[list[int]] = [] + start = 0 + for size in self._batch_sizes(table.num_rows): + out.append(list(range(start, start + size))) + start += size + return out + def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: """Group rows into fixed-size batches, list-wrapping their values. diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index b78a0553c..33ff7d6fe 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -500,6 +500,97 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: # names a row within its source only (ITL-1154), so the source-id columns # come last: two members with equal record ids from different sources still # have one order. + groups, order, offsets, bit_names = self._member_layout( + table, non_key_tags, system_tag_columns + ) + + def emitted(c: str) -> pa.Array[Any]: + # Every member of a group holds the same key value except a float's + # bits, so a non-float key is the first member's. + rows = groups[bit_names.get(c, "first")].to_arrow().cast(pa.int64()) + return table.column(c).take(rows).combine_chunks() + + def folded(c: str) -> pa.Array[Any]: + # The members' text values in member order, folded per group; text loses + # nothing in Python. + values = cast(list[Any], table.column(c).take(order).to_pylist()) + bounds = cast(list[int], offsets.to_pylist()) + return pa.array( + [ + arrow_utils.fold_system_tag_values( + values[start:end], label=GROUP_BY_FOLD_LABEL + ) + for start, end in zip(bounds[:-1], bounds[1:]) + ], + table.schema.field(c).type, + ) + + # Every stream has a data context; StreamProtocol does not declare it. + type_converter = stream.data_context.type_converter # pyright: ignore[reportAttributeAccessIssue] + fields: list[pa.Field[Any]] = [] + arrays: list[pa.Array[Any]] = [] + # The input's columns in its order, without the dropped tags: a key and a + # folded column keep their field, a member column becomes a list. + for field in table.drop_columns(list(dropped_columns)).schema: + c = field.name + if c in member_columns: + list_type = arrow_utils.aggregated_list_type( + field.type, type_converter, column=c + ) + fields.append(pa.field(c, list_type, nullable=False)) + arrays.append( + arrow_utils.aggregated_list_array( + table.column(c).take(order), offsets, list_type + ) + ) + else: + fields.append(field) + arrays.append(emitted(c) if c in self.by else folded(c)) + grouped_table = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) + + n_char = self.orcapod_config.hashing.system_tag_n_char + grouped_table = arrow_utils.append_to_system_tags( + grouped_table, stream.pipeline_hash().to_hex(n_char) + ) + + # The keys, in the input's tag order rather than the order of `by`. A + # data-tag key stays a data-tag: scalar in both roles (specification + # section 8.1); a data-tag non-key is now a plain (list) data column. + # The keys lead the table, as in a table built from rows (ITL-1131): a + # data-tag non-key declared before them keeps its data column, which + # must not come first. + keys = [c for c in tag_columns if c in self.by] + grouped_table = grouped_table.select( + [*keys, *(c for c in grouped_table.column_names if c not in keys)] + ) + return ArrowTableStream( + grouped_table, + tag_columns=keys, + data_context=stream.data_context, + data_tags=[c for c in data_tags if c in self.by], + ) + + def _member_layout( + self, + table: pa.Table, + non_key_tags: Sequence[str], + system_tag_columns: Sequence[str], + ) -> tuple[pl.DataFrame, pa.Array[Any], pa.Int64Array, dict[str, str]]: + """Decide the groups of ``table`` and the order of each group's members. + + The one place the member order is decided: the grouping itself and + ``fold_members`` both use it. + + Args: + table: The input table, with its system-tag columns. + non_key_tags: The input's user tags that are not keys. + system_tag_columns: The input's system-tag columns. + + Returns: + The groups (Polars frame: ``size``, ``first`` and the float key bit + columns), the input row numbers in member order, group by group, the + offsets of each group in that order, and the bit column of each float key. + """ named = self.member_order or () sort_columns = named + tuple(sorted(c for c in non_key_tags if c not in named)) for prefix in ( @@ -574,72 +665,38 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: pa.int64(), ), ) + return groups, order, offsets, bit_names - def emitted(c: str) -> pa.Array[Any]: - # Every member of a group holds the same key value except a float's - # bits, so a non-float key is the first member's. - rows = groups[bit_names.get(c, "first")].to_arrow().cast(pa.int64()) - return table.column(c).take(rows).combine_chunks() + def fold_members( + self, table: pa.Table, tag_columns: Sequence[str] + ) -> list[list[int]]: + """Return the members of each group of ``table``, as row numbers in member order. - def folded(c: str) -> pa.Array[Any]: - # The members' text values in member order, folded per group; text loses - # nothing in Python. - values = cast(list[Any], table.column(c).take(order).to_pylist()) - bounds = cast(list[int], offsets.to_pylist()) - return pa.array( - [ - arrow_utils.fold_system_tag_values( - values[start:end], label=GROUP_BY_FOLD_LABEL - ) - for start, end in zip(bounds[:-1], bounds[1:]) - ], - table.schema.field(c).type, - ) + Reads only the given table, with the rule the grouping uses: the row numbers of + the members of each output row, groups in output order. The caller checks a + group by folding its members' system tags (``fold_system_tag_values`` with + ``fold_label``), which must give the group's folded values. - # Every stream has a data context; StreamProtocol does not declare it. - type_converter = stream.data_context.type_converter # pyright: ignore[reportAttributeAccessIssue] - fields: list[pa.Field[Any]] = [] - arrays: list[pa.Array[Any]] = [] - # The input's columns in its order, without the dropped tags: a key and a - # folded column keep their field, a member column becomes a list. - for field in table.drop_columns(list(dropped_columns)).schema: - c = field.name - if c in member_columns: - list_type = arrow_utils.aggregated_list_type( - field.type, type_converter, column=c - ) - fields.append(pa.field(c, list_type, nullable=False)) - arrays.append( - arrow_utils.aggregated_list_array( - table.column(c).take(order), offsets, list_type - ) - ) - else: - fields.append(field) - arrays.append(emitted(c) if c in self.by else folded(c)) - grouped_table = pa.Table.from_arrays(arrays, schema=pa.schema(fields)) - - n_char = self.orcapod_config.hashing.system_tag_n_char - grouped_table = arrow_utils.append_to_system_tags( - grouped_table, stream.pipeline_hash().to_hex(n_char) - ) + Args: + table: The input rows, with their system-tag columns. + tag_columns: The input's user tag columns. - # The keys, in the input's tag order rather than the order of `by`. A - # data-tag key stays a data-tag: scalar in both roles (specification - # section 8.1); a data-tag non-key is now a plain (list) data column. - # The keys lead the table, as in a table built from rows (ITL-1131): a - # data-tag non-key declared before them keeps its data column, which - # must not come first. - keys = [c for c in tag_columns if c in self.by] - grouped_table = grouped_table.select( - [*keys, *(c for c in grouped_table.column_names if c not in keys)] + Returns: + One list of row numbers per group. + """ + system_tag_columns = tuple( + c for c in table.column_names if c.startswith(constants.SYSTEM_TAG_PREFIX) ) - return ArrowTableStream( - grouped_table, - tag_columns=keys, - data_context=stream.data_context, - data_tags=[c for c in data_tags if c in self.by], + non_key_tags = tuple(c for c in tag_columns if c not in self.by) + _, order, offsets, _ = self._member_layout( + table, non_key_tags, system_tag_columns ) + rows = cast(list[int], order.to_pylist()) + bounds = cast(list[int], offsets.to_pylist()) + return [rows[start:end] for start, end in zip(bounds[:-1], bounds[1:])] + + fold_label: ClassVar[str] = GROUP_BY_FOLD_LABEL + """The label of this operator's folds of the system tags.""" # ------------------------------------------------------------------ # Schema prediction diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 3b7a93fb7..b007562e3 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1184,3 +1184,14 @@ def __str__(self) -> str: "completions, so on it the node performs every side effect again: use " "one only when a repeated delivery is acceptable." ) + + +class ProvenanceInconsistencyError(ValueError): + """What a job holds and what its databases store disagree about a row's provenance. + + Raised by ``node.trace`` and ``node.why_missing`` (ITL-1432) when a link they follow + cannot be proven: a group's or batch's members whose system tags do not fold to the + group's folded values, a row with no stored pipeline entry while the node has a + database, or a stored entry whose input is not the row the node holds. The tools never + guess a link; the message names the node and what disagreed. + """ diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index fead4fab3..eac6fbbc5 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -24,6 +24,7 @@ if TYPE_CHECKING: import networkx as nx from orcapod.pipeline.diagram import PipelineDiagram + from orcapod.types.provenance import Highlight from orcapod.protocols.database_protocols import ArrowDatabaseProtocol else: nx = LazyModule("networkx") @@ -342,6 +343,7 @@ def diagram( direction: Literal["LR", "TB"] = "LR", collapse: bool = False, max_nodes: int = 400, + highlight: Highlight | None = None, ) -> PipelineDiagram: """A diagram of the DAG, drawn in a notebook without Graphviz. @@ -361,17 +363,25 @@ def diagram( feed exactly one node into the edges they lie on. max_nodes: Above this many nodes, show the text listing instead of the picture. + highlight: Nodes and edges to emphasize, with a note: a trace's path + (``node.trace(...).highlight()``) or a missing row's + (``node.why_missing(...).highlight()``). Returns: The diagram. Raises: RuntimeError: If the pipeline has not been compiled yet. + ValueError: If ``highlight`` names a node the pipeline does not have. """ from orcapod.pipeline.diagram import PipelineDiagram return PipelineDiagram( - self, direction=direction, collapse=collapse, max_nodes=max_nodes + self, + direction=direction, + collapse=collapse, + max_nodes=max_nodes, + highlight=highlight, ) def _repr_mimebundle_( diff --git a/src/orcapod/pipeline/diagram.py b/src/orcapod/pipeline/diagram.py index fd5800d6e..7b5ab7694 100644 --- a/src/orcapod/pipeline/diagram.py +++ b/src/orcapod/pipeline/diagram.py @@ -39,6 +39,7 @@ from typing_extensions import override +from orcapod.types.provenance import Highlight from orcapod.utils.in_development import warn_in_development if TYPE_CHECKING: @@ -82,6 +83,7 @@ class _Node: data_schema: tuple[tuple[str, str], ...] status: str facts: tuple[tuple[str, str], ...] + highlighted: bool = False @property def kind_line(self) -> str: @@ -97,6 +99,7 @@ class _Edge: source: int target: int folded: tuple[str, ...] = () + highlighted: bool = False # --------------------------------------------------------------------------- @@ -275,7 +278,11 @@ def _is_job(pipeline: _Drawable) -> bool: def _build_model( - pipeline: _Drawable, *, is_job: bool, collapse: bool + pipeline: _Drawable, + *, + is_job: bool, + collapse: bool, + highlight: Highlight | None = None, ) -> tuple[list[_Node], list[_Edge]]: """Read a compiled pipeline or job into the model's nodes and edges. @@ -285,6 +292,8 @@ def _build_model( job's ``last_run`` gives row counts. collapse: Whether to fold the column-choosing, renaming and join operators that feed exactly one node into the edges they lie on. + highlight: The nodes and edges to emphasize, by label. A folded edge is + emphasized when its ends and every step folded into it are. Returns: The nodes in topological order (ties by label) and the edges, sorted. @@ -372,10 +381,26 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: data_schema=_schema_pairs(data_schema), status=statuses.get(label, ""), facts=facts, + highlighted=highlight is not None and label in highlight.nodes, ) ) + + def lit(source: int, target: int, via: tuple[str, ...]) -> bool: + if highlight is None: + return False + ends = (shown[source], shown[target]) + if not via: + return ends in highlight.edges + chain = (ends[0], *via, ends[1]) + return all(pair in highlight.edges for pair in zip(chain, chain[1:])) + edge_list = [ - _Edge(source=source, target=target, folded=via) + _Edge( + source=source, + target=target, + folded=via, + highlighted=lit(source, target, via), + ) for (source, target), via in sorted(edges.items()) ] return nodes, edge_list @@ -672,6 +697,15 @@ def node_end(key: int, leaving: bool) -> tuple[float, float]: # A solid stroke and a 14 % fill of each kind's colour read on light and dark notebook # themes alike; text and edges use ``currentColor``, the notebook's own text colour. +_HIGHLIGHT_COLOUR = "#d9480f" +"""The colour of a highlight's nodes and edges (``diagram(highlight=...)``).""" + + +def _layout_edges(layout: _Layout) -> list[_Edge]: + """The edges a layout draws.""" + return [edge for edge, _ in layout.edges] + + _KIND_COLOUR: dict[str, str] = { "source": "#2e9e5b", "operator": "#d08a16", @@ -808,16 +842,28 @@ def _svg( '' ) + # A highlight (``diagram(highlight=...)``) draws its edges in its colour and dims + # the nodes outside it. + lit = any(node.highlighted for node in nodes) or any( + edge.highlighted for edge in _layout_edges(layout) + ) for edge, points in layout.edges: tip = f"{nodes[edge.source].label} → {nodes[edge.target].label}" if edge.folded: tip += f" (through {', '.join(edge.folded)})" dash = ' stroke-dasharray="5 3"' if edge.folded else "" + accent = ( + f' class="op-dag-highlight" stroke="{_HIGHLIGHT_COLOUR}" ' + 'stroke-opacity="1" stroke-width="2.6"' + if edge.highlighted + else "" + ) + head_fill = _HIGHLIGHT_COLOUR if edge.highlighted else "currentColor" parts.append( - f'' + f'' f"{_escape(tip)}" f'' - f'' ) parts.append('') @@ -834,8 +880,15 @@ 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}" + emphasis = "" + if node.highlighted: + emphasis = " op-dag-highlight" + stroke_width = "3.2" + colour = _HIGHLIGHT_COLOUR + elif lit: + emphasis = '" opacity="0.4' parts.append( - f'' f"{_escape(_tooltip(node, inputs.get(node.index, ())))}" @@ -1026,10 +1079,13 @@ class PipelineDiagram: details of the node it leads to. max_nodes: Above this many nodes (after folding), the notebook shows the plain-text listing instead of the picture. + highlight: Nodes and edges to emphasize, by label, with a note + (``Trace.highlight()``, ``Absence.highlight()``): drawn in an accent colour, + the other nodes dimmed; the listing marks them with ``*``. Raises: - ValueError: If ``direction`` is not ``"LR"`` or ``"TB"``, or ``max_nodes`` is not - positive. + ValueError: If ``direction`` is not ``"LR"`` or ``"TB"``, ``max_nodes`` is not + positive, or ``highlight`` names a node the pipeline does not have. RuntimeError: If the pipeline has not been compiled. """ @@ -1040,6 +1096,7 @@ def __init__( direction: Direction = "LR", collapse: bool = False, max_nodes: int = 400, + highlight: Highlight | None = None, ) -> None: if direction not in ("LR", "TB"): raise ValueError(f"direction must be 'LR' or 'TB', not {direction!r}") @@ -1051,19 +1108,33 @@ def __init__( "PipelineDiagram and the notebook display of a pipeline or job) is in " "development: its interface and appearance may change in any release.", ) + if highlight is not None: + labels = {node.label for node in pipeline.dag.nodes()} + unknown = sorted( + {*highlight.nodes, *(end for edge in highlight.edges for end in edge)} + - labels + ) + if unknown: + raise ValueError( + f"highlight names {unknown[0]!r}, which is not a node of this " + "pipeline" + ) + self._highlight: Highlight | None = highlight is_job = _is_job(pipeline) self._kind: str = "job" if is_job else "pipeline" self._name: str = ".".join(pipeline.name) self._direction: Direction = direction self._max_nodes: int = max_nodes self._collapse: bool = collapse - nodes, edges = _build_model(pipeline, is_job=is_job, collapse=collapse) + nodes, edges = _build_model( + pipeline, is_job=is_job, collapse=collapse, highlight=highlight + ) self._nodes: list[_Node] = nodes self._edges: list[_Edge] = edges # The other layout, for the notebook's collapse checkbox: kept only when folding # changes something. Built from the same read of the graph, computing nothing. other_nodes, other_edges = _build_model( - pipeline, is_job=is_job, collapse=not collapse + pipeline, is_job=is_job, collapse=not collapse, highlight=highlight ) self._other: tuple[list[_Node], list[_Edge]] | None = ( None if len(other_nodes) == len(nodes) else (other_nodes, other_edges) @@ -1094,12 +1165,24 @@ def to_dict(self) -> dict[str, Any]: ``status`` (``""`` for a pipeline), ``tag_schema`` and ``data_schema`` (lists of ``[column, type text]``) and ``facts`` (lists of ``[name, text]``); each edge has ``source`` and ``target`` (node indices) and ``folded`` - (the labels of the steps folded into it). + (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``. """ return self._model(self._nodes, self._edges) def _model(self, nodes: list[_Node], edges: list[_Edge]) -> dict[str, Any]: """The model of one layout: the given nodes and edges.""" + model = self._plain_model(nodes, edges) + if self._highlight is not None: + model["note"] = self._highlight.note + for entry, node in zip(model["nodes"], nodes): + entry["highlighted"] = node.highlighted + for entry, edge in zip(model["edges"], edges): + entry["highlighted"] = edge.highlighted + return model + + def _plain_model(self, nodes: list[_Node], edges: list[_Edge]) -> dict[str, Any]: + """The model of one layout without a highlight.""" return { "kind": self._kind, "name": self._name, @@ -1131,12 +1214,17 @@ def to_text(self) -> str: Returns: A title line, then `` diff --git a/docs/tutorial/provenance-diagram-missing-join.svg b/docs/tutorial/provenance-diagram-missing-join.svg index eefc959a5..2df84e44c 100644 --- a/docs/tutorial/provenance-diagram-missing-join.svg +++ b/docs/tutorial/provenance-diagram-missing-join.svg @@ -1,4 +1,4 @@ -Job 'imec0': units row_48 is removed by Join: rows without a match in 'sessions' are droppedsessions → Filter_2Filter_2 → SelectDataColumns_2SelectDataColumns_2 → Joinunits → Filter_1Filter_1 → SelectDataColumns_1SelectDataColumns_1 → JoinJoin → imec0_ratessessions (source · CSVSource · bound) +Job 'imec0': units row_48 is removed by Join: rows without a match in 'sessions' are droppedhighlighted: units row_48 is removed by Join: rows without a match in 'sessions' are droppedsessions → Filter_2Filter_2 → SelectDataColumns_2SelectDataColumns_2 → Joinunits → Filter_1Filter_1 → SelectDataColumns_1SelectDataColumns_1 → JoinJoin → imec0_ratessessions (source · CSVSource · bound) tags: subject_id: str, session: str data: date: date, duration_s: floatsourceCSVSourceboundsessionsFilter_2 (operator · current) tags: subject_id: str, session: str @@ -8,17 +8,17 @@ tags: subject_id: str, session: str data: duration_s: float inputs: Filter_2operator · currentSelectDataColumns_2units (source · CSVSource · bound) tags: subject_id: str, session: str, probe: str, unit: int -data: region: str, depth_um: int, n_spikes: intsourceCSVSourceboundunitsFilter_1 (operator · current) +data: region: str, depth_um: int, n_spikes: intsourceCSVSourceboundunitsFilter_1 (operator · current) tags: subject_id: str, session: str, probe: str, unit: int data: region: str, depth_um: int, n_spikes: int -inputs: unitsoperatorcurrentFilter_1SelectDataColumns_1 (operator · current) +inputs: unitsoperatorcurrentFilter_1SelectDataColumns_1 (operator · current) tags: subject_id: str, session: str, probe: str, unit: int data: n_spikes: int -inputs: Filter_1operator · currentSelectDataColumns_1Join (operator · current) +inputs: Filter_1operator · currentSelectDataColumns_1Join (operator · current) tags: subject_id: str, session: str, probe: str, unit: int data: n_spikes: int, duration_s: float -inputs: SelectDataColumns_2, SelectDataColumns_1operatorcurrentJoinimec0_rates (function pod · firing_rate · current) +inputs: SelectDataColumns_2, SelectDataColumns_1operatorcurrentJoinimec0_rates (function pod · firing_rate · current) tags: subject_id: str, session: str, probe: str, unit: int data: rate_hz: float inputs: Join -job's last run: 24 rows, 24 computedfunction podfiring_ratecurrentimec0_rates +job's last run: 24 rows, 24 computedfunction podfiring_ratecurrentimec0_rates diff --git a/docs/tutorial/provenance-diagram-trace.svg b/docs/tutorial/provenance-diagram-trace.svg index 65903e182..40a26b672 100644 --- a/docs/tutorial/provenance-diagram-trace.svg +++ b/docs/tutorial/provenance-diagram-trace.svg @@ -1,28 +1,28 @@ -Job 'workshop': trace of session_means.mean_rate_hzsessions → SelectDataColumns_1SelectDataColumns_1 → Joinunits → SelectDataColumns_3SelectDataColumns_3 → JoinJoin → ratesrates → GroupByGroupBy → SelectDataColumns_2SelectDataColumns_2 → session_meanssessions (source · CSVSource · bound) +Job 'workshop': trace of rates.rate_hz subject_id='mouse_02', session='s1', probe='imec1', unit=2highlighted: trace of rates.rate_hz subject_id='mouse_02', session='s1', probe='imec1', unit=2sessions → SelectDataColumns_1SelectDataColumns_1 → Joinunits → SelectDataColumns_3SelectDataColumns_3 → JoinJoin → ratesrates → GroupByGroupBy → SelectDataColumns_2SelectDataColumns_2 → session_meanssessions (source · CSVSource · bound) tags: subject_id: str, session: str -data: date: date, duration_s: floatsourceCSVSourceboundsessionsSelectDataColumns_1 (operator · current) +data: date: date, duration_s: floatsourceCSVSourceboundsessionsSelectDataColumns_1 (operator · current) tags: subject_id: str, session: str data: duration_s: float -inputs: sessionsoperator · currentSelectDataColumns_1units (source · CSVSource · bound) +inputs: sessionsoperator · currentSelectDataColumns_1units (source · CSVSource · bound) tags: subject_id: str, session: str, probe: str, unit: int -data: region: str, depth_um: int, n_spikes: intsourceCSVSourceboundunitsSelectDataColumns_3 (operator · current) +data: region: str, depth_um: int, n_spikes: intsourceCSVSourceboundunitsSelectDataColumns_3 (operator · current) tags: subject_id: str, session: str, probe: str, unit: int data: n_spikes: int -inputs: unitsoperator · currentSelectDataColumns_3Join (operator · current) +inputs: unitsoperator · currentSelectDataColumns_3Join (operator · current) tags: subject_id: str, session: str, probe: str, unit: int data: duration_s: float, n_spikes: int -inputs: SelectDataColumns_1, SelectDataColumns_3operatorcurrentJoinrates (function pod · firing_rate · current) +inputs: SelectDataColumns_1, SelectDataColumns_3operatorcurrentJoinrates (function pod · firing_rate · current) tags: subject_id: str, session: str, probe: str, unit: int data: rate_hz: float inputs: Join -job's last run: 64 rows, 63 computed, 1 reusedfunction podfiring_ratecurrentratesGroupBy (operator · current) +job's last run: 64 rows, 63 computed, 1 reusedfunction podfiring_ratecurrentreusedratesGroupBy (operator · current) tags: subject_id: str, session: str data: rate_hz: list[float] -inputs: ratesoperatorcurrentGroupBySelectDataColumns_2 (operator · current) +inputs: ratesoperatorcurrentGroupBySelectDataColumns_2 (operator · current) tags: subject_id: str, session: str data: rate_hz: list[float] -inputs: GroupByoperator · currentSelectDataColumns_2session_means (function pod · mean_rate · current) +inputs: GroupByoperator · currentSelectDataColumns_2session_means (function pod · mean_rate · current) tags: subject_id: str, session: str data: mean_rate_hz: float inputs: SelectDataColumns_2 -job's last run: 8 rows, 8 computedfunction podmean_ratecurrentsession_means +job's last run: 8 rows, 8 computedfunction podmean_ratecurrentsession_means diff --git a/src/orcapod/pipeline/diagram.py b/src/orcapod/pipeline/diagram.py index a2e72d712..d50c0ddfd 100644 --- a/src/orcapod/pipeline/diagram.py +++ b/src/orcapod/pipeline/diagram.py @@ -84,6 +84,7 @@ class _Node: status: str facts: tuple[tuple[str, str], ...] highlighted: bool = False + mark: str = "" @property def kind_line(self) -> str: @@ -382,6 +383,7 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: status=statuses.get(label, ""), facts=facts, highlighted=highlight is not None and label in highlight.nodes, + mark="" if highlight is None else highlight.mark(label), ) ) @@ -465,7 +467,7 @@ class _Layout: def _text_room(node: _Node) -> float: """The width of a node's text: its label or the widest part of its kind line (the kind, the detail, the status), within the node width limits (ITL-1232).""" - parts = node.kind_line.split(" · ") + parts = [*node.kind_line.split(" · "), node.mark] text = max( len(node.label) * _CHAR_W, max(len(part) for part in parts) * _SMALL_CHAR_W ) @@ -487,6 +489,9 @@ def _kind_lines(node: _Node) -> tuple[str, ...]: lines[-1] = joined else: lines.append(part) + if node.mark: + # A highlight's mark (a trace's computed / reused) on a line of its own. + lines.append(node.mark) return tuple(lines) @@ -711,8 +716,12 @@ def node_end(key: int, leaving: bool) -> tuple[float, float]: # A solid stroke and a 14 % fill of each kind's colour read on light and dark notebook # themes alike; text and edges use ``currentColor``, the notebook's own text colour. -_HIGHLIGHT_COLOUR = "#d9480f" -"""The colour of a highlight's nodes and edges (``diagram(highlight=...)``).""" +_HIGHLIGHT_COLOUR = "currentColor" +"""The colour of a highlight's nodes and edges (``diagram(highlight=...)``): the text +colour, which no kind or status uses (red and amber mean failed and stale), dark on a +light page and light on a dark one.""" +_CAPTION_H = 24.0 +"""The height of the caption line a highlight with a note adds above the picture.""" def _layout_edges(layout: _Layout) -> list[_Edge]: @@ -821,6 +830,7 @@ def _svg( layout: _Layout, across: bool, standalone: bool, + caption: str = "", ) -> str: """The SVG picture; complete without any style sheet or script. @@ -834,11 +844,13 @@ def _svg( text colour, since an image does not take the page's colours. Otherwise the text and edges take the page's text colour and the background is transparent. + caption: A line drawn above the picture (a highlight's note), or ``""``. Returns: The ```` element. """ - width, height = _num(layout.width), _num(layout.height) + top = _CAPTION_H if caption else 0.0 + width, height = _num(layout.width), _num(layout.height + top) colour = ' color="#1f1f1f"' if standalone else ' style="max-width:100%;height:auto"' parts = [ f'' ) - parts.append( - '' - ) + if caption: + parts.append( + f'' + f"{_escape(_clip(caption, layout.width - 2 * _MARGIN, _CHAR_W))}" + f'' + ) # A highlight (``diagram(highlight=...)``) draws its edges in its colour and dims - # the nodes outside it. + # the other edges and the nodes outside it. lit = any(node.highlighted for node in nodes) or any( edge.highlighted for edge in _layout_edges(layout) ) + parts.append( + '' + ) for edge, points in layout.edges: tip = f"{nodes[edge.source].label} → {nodes[edge.target].label}" if edge.folded: @@ -895,10 +914,12 @@ def _svg( dash = ' stroke-dasharray="4 3"' if node.status in _DASHED_STATUSES else "" label = f"{node.label}, {node.kind_line}" emphasis = "" + stroke = colour if node.highlighted: + # The kind's fill is kept; the outline is the highlight's. emphasis = " op-dag-highlight" stroke_width = "3.2" - colour = _HIGHLIGHT_COLOUR + stroke = _HIGHLIGHT_COLOUR elif lit: emphasis = '" opacity="0.4' parts.append( @@ -907,7 +928,7 @@ def _svg( f'transform="translate({_num(x)},{_num(y)})">' f"{_escape(_tooltip(node, inputs.get(node.index, ())))}" f'' ) if node.kind in ("side_effect", "side_effect_function"): @@ -923,10 +944,17 @@ def _svg( ) kind_lines = _kind_lines(node) for line_number, line in enumerate(kind_lines): + # A highlight's mark (the last line) is drawn in bold at full strength. + is_mark = bool(node.mark) and line_number == len(kind_lines) - 1 + weight = ( + ' font-weight="600" class="op-dag-mark"' + if is_mark + else ' fill-opacity="0.75"' + ) parts.append( f'{_escape(_clip(line, w, _SMALL_CHAR_W))}' + f'text-anchor="middle" font-size="{_SMALL_PX}" fill="currentColor"' + f"{weight}>{_escape(_clip(line, w, _SMALL_CHAR_W))}" ) label_y = 34 + _LINE_H * (len(kind_lines) - 1) parts.append( @@ -934,7 +962,7 @@ def _svg( f'font-size="{_FONT_PX}" font-weight="600" fill="currentColor">' f"{_escape(_clip(node.label, w, _CHAR_W))}" ) - parts.append("") + parts.append("" if caption else "") return "".join(parts) @@ -1094,8 +1122,11 @@ class PipelineDiagram: max_nodes: Above this many nodes (after folding), the notebook shows the plain-text listing instead of the picture. highlight: Nodes and edges to emphasize, by label, with a note - (``Trace.highlight()``, ``Absence.highlight()``): drawn in an accent colour, - the other nodes dimmed; the listing marks them with ``*``. + (``Trace.highlight()``, ``Absence.highlight()``): outlined in the text + colour (no status uses it), the other nodes and edges dimmed, the note as + a caption above the picture, and a node's mark (a trace's ``computed`` / + ``reused``) on a line of its own; the listing marks them with ``*`` and + ``[mark]``. Raises: ValueError: If ``direction`` is not ``"LR"`` or ``"TB"``, ``max_nodes`` is not @@ -1125,7 +1156,11 @@ def __init__( if highlight is not None: labels = {node.label for node in pipeline.dag.nodes()} unknown = sorted( - {*highlight.nodes, *(end for edge in highlight.edges for end in edge)} + { + *highlight.nodes, + *(end for edge in highlight.edges for end in edge), + *(label for label, _ in highlight.marks), + } - labels ) if unknown: @@ -1191,6 +1226,8 @@ def _model(self, nodes: list[_Node], edges: list[_Edge]) -> dict[str, Any]: model["note"] = self._highlight.note for entry, node in zip(model["nodes"], nodes): entry["highlighted"] = node.highlighted + if node.mark: + entry["mark"] = node.mark for entry, edge in zip(model["edges"], edges): entry["highlighted"] = edge.highlighted return model @@ -1239,6 +1276,8 @@ def to_text(self) -> str: for node in self._nodes: mark = "* " if node.highlighted else " " line = f"{mark}{node.label} ({node.kind_line})" + if node.mark: + line += f" [{node.mark}]" if node.index in inputs: line += " <- " + ", ".join(inputs[node.index]) lines.append(line) @@ -1268,9 +1307,21 @@ def _svg( layout = _layout(nodes, edges, direction) inputs = _inputs(nodes, edges) return _svg( - self._picture_title(), nodes, inputs, layout, direction == "LR", standalone + self._picture_title(), + nodes, + inputs, + layout, + direction == "LR", + standalone, + self._caption(), ) + def _caption(self) -> str: + """The line drawn above the picture: what the highlight shows, or ``""``.""" + if self._highlight is not None and self._highlight.note: + return f"highlighted: {self._highlight.note}" + return "" + def _picture_title(self) -> str: """The picture's title: the diagram's, with the highlight's note.""" if self._highlight is not None and self._highlight.note: @@ -1339,12 +1390,14 @@ def _picture(self) -> str: layout, self._direction == "LR", standalone=True, + caption=self._caption(), ) encoded = base64.b64encode(svg.encode("utf-8")).decode("ascii") alt = f"Diagram of {self.title}: {len(self._nodes)} nodes" return ( f'{_escape(alt)}' diff --git a/src/orcapod/pipeline/diagram_assets/diagram.js b/src/orcapod/pipeline/diagram_assets/diagram.js index 072ca0caf..235ec91e7 100644 --- a/src/orcapod/pipeline/diagram_assets/diagram.js +++ b/src/orcapod/pipeline/diagram_assets/diagram.js @@ -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 (n.mark) row(dl, 'highlight', n.mark); n.facts.forEach(function (f) { row(dl, f[0], f[1]); }); panel.appendChild(dl); panel.classList.add('op-dag-open'); diff --git a/src/orcapod/types/provenance.py b/src/orcapod/types/provenance.py index 052e0a43d..e0a1b3c72 100644 --- a/src/orcapod/types/provenance.py +++ b/src/orcapod/types/provenance.py @@ -78,12 +78,22 @@ class Highlight: Attributes: nodes: The labels of the nodes to emphasize. edges: The streams to emphasize, as ``(upstream label, downstream label)``. - note: A line shown with the diagram (its listing and its picture's title). + note: A line shown with the diagram (its listing, and its picture's caption and + title). + marks: A word shown on a node, as ``(label, mark)``: for a trace, each + function node on the path is marked ``"computed"`` (its rows on the path + computed their results), ``"reused"`` (they reused results stored for + equal inputs) or ``"computed + reused"`` (some did each). """ nodes: frozenset[str] = frozenset() edges: frozenset[tuple[str, str]] = frozenset() note: str = "" + marks: frozenset[tuple[str, str]] = frozenset() + + def mark(self, label: str) -> str: + """Return the mark of the node ``label``, or ``""`` when it has none.""" + return next((mark for node, mark in self.marks if node == label), "") @dataclass(frozen=True) @@ -331,11 +341,31 @@ def nodes(self) -> tuple[str, ...]: return tuple(sorted({step.node for step in self.root.walk()})) def highlight(self) -> Highlight: - """Return the trace's path, for ``job.diagram(highlight=...)``.""" + """Return the trace's path, for ``job.diagram(highlight=...)``. + + Each function node on the path is marked with how its rows on the path got + their results: ``"computed"``, ``"reused"`` or ``"computed + reused"``. + """ + how: dict[str, set[bool]] = {} + for node, run in self.function_runs(): + how.setdefault(node, set()).add(run.computed_here) + marks = frozenset( + ( + node, + "computed + reused" + if len(seen) > 1 + else "computed" + if True in seen + else "reused", + ) + for node, seen in how.items() + ) + row = f" {_tags_text(self.root.tags)}" if self.root.tags else "" return Highlight( nodes=frozenset(self.nodes()), edges=frozenset(self.edges), - note=f"trace of {self.root.node}.{self.root.column}", + note=f"trace of {self.root.node}.{self.root.column}{row}", + marks=marks, ) def text(self) -> str: diff --git a/tests/test_pipeline/test_provenance_review.py b/tests/test_pipeline/test_provenance_review.py index 8cd29e8d6..9979e770c 100644 --- a/tests/test_pipeline/test_provenance_review.py +++ b/tests/test_pipeline/test_provenance_review.py @@ -2120,3 +2120,151 @@ def make(y: int, load_only: bool) -> Any: assert answer.reached_function is True and answer.entry_recorded is True else: assert answer.reached_function is None + + +# --------------------------------------------------------------------------- +# Developer feedback on the trace picture: computed or reused on the diagram +# --------------------------------------------------------------------------- + + +@function_pod(output_keys="score") +def hit_rate(hits: int, misses: int) -> float: + """The fraction of hits; a1 trial 1 and a2 trial 1 are equal inputs (one run).""" + return hits / (hits + misses) + + +@function_pod(output_keys="mean") +def mean_score(score: list[float]) -> float: + """The mean of an animal's scores.""" + return sum(score) / len(score) + + +TRIALS = [ + {"animal": "a1", "trial": 1, "hits": 8, "misses": 2}, + {"animal": "a1", "trial": 2, "hits": 6, "misses": 4}, + {"animal": "a2", "trial": 1, "hits": 8, "misses": 2}, + {"animal": "a2", "trial": 2, "hits": 3, "misses": 7}, +] + + +def _trials_job(database: Any, rows: list[dict[str, Any]] = TRIALS) -> PipelineJob: + trials = DictSource( + rows, + tag_columns=["animal", "trial"], + tag_only_columns=True, + source_id="trials", + ) + job = PipelineJob(name="marks", database=database) + with job: + scores = hit_rate.pod(trials, label="scores") + mean_score.pod( + SelectDataColumns(["score"])(GroupBy(["animal"])(scores)), label="means" + ) + return job + + +def _marks(job: PipelineJob) -> dict[str, dict[str, str]]: + scores, means = job.nodes["scores"], job.nodes["means"] + which = { + "a1 trial 1": scores.trace({"animal": "a1", "trial": 1}, "score"), + "a2 trial 1": scores.trace({"animal": "a2", "trial": 1}, "score"), + "a2": means.trace({"animal": "a2"}, "mean"), + } + return {name: dict(t.highlight().marks) for name, t in which.items()} + + +EXPECTED_MARKS = { + "a1 trial 1": {"scores": "computed"}, + "a2 trial 1": {"scores": "reused"}, + "a2": {"scores": "computed + reused", "means": "computed"}, +} + + +def _run_after_a1(database: Any, mode: str) -> PipelineJob: + """A first run stores a1's scores; the job over every trial then runs in ``mode``, + so a2 trial 1 (a1 trial 1's input) reuses a stored result on either orchestrator + (the async one runs equal inputs of one run concurrently: both compute).""" + _ = _trials_job(database, TRIALS[:2]).run() + job = _trials_job(database) + run(job, mode) + return job + + +@pytest.mark.parametrize("mode", ["sync", "async"]) +def test_a_trace_highlight_marks_each_function_node(mode: str) -> None: + assert _marks(_run_after_a1(InMemoryArrowDatabase(), mode)) == EXPECTED_MARKS + + +def test_equal_inputs_computed_at_once_are_both_marked_computed() -> None: + """In one async run equal inputs are computed concurrently, and the mark says so.""" + job = _trials_job(InMemoryArrowDatabase()) + run(job, "async") + assert _marks(job)["a2 trial 1"] == {"scores": "computed"} + + +def test_a_trace_highlight_marks_on_a_loaded_job(tmp_path: Path) -> None: + job = _run_after_a1(DeltaTableDatabase(tmp_path / "store"), "sync") + job.save(tmp_path / "job.json") + loaded = PipelineJob.load( + tmp_path / "job.json", database=DeltaTableDatabase(tmp_path / "store") + ) + loaded.bind( + sources={ + "trials": DictSource( + TRIALS, + tag_columns=["animal", "trial"], + tag_only_columns=True, + source_id="trials", + ) + } + ) + loaded.run(load_only=True) + assert _marks(loaded) == EXPECTED_MARKS + + +def test_the_diagram_shows_the_marks_and_the_caption() -> None: + job = _trials_job(InMemoryArrowDatabase()) + job.run() + trace = job.nodes["means"].trace({"animal": "a2"}, "mean") + diagram = job.diagram(highlight=trace.highlight()) + listing = str(diagram) + assert "* scores (function pod · hit_rate · current) [computed + reused]" in listing + assert "* means (function pod · mean_score · current) [computed]" in listing + svg = diagram.to_svg() + assert 'computed + reused' in svg + assert 'class="op-dag-mark">computed' in svg + model = diagram.to_dict() + assert {n["label"]: n.get("mark") for n in model["nodes"]}["scores"] == ( + "computed + reused" + ) + + +def test_a_mark_on_an_unknown_node_is_refused() -> None: + from orcapod.types import Highlight + + job = _trials_job(InMemoryArrowDatabase()) + with pytest.raises(ValueError, match="nowhere"): + job.diagram(highlight=Highlight(marks=frozenset({("nowhere", "computed")}))) + + +def test_the_highlight_colour_is_no_status_or_kind_colour() -> None: + """Highlighted must not read as failed or stale: the highlight is drawn in the text + colour, which no status and no kind uses.""" + from orcapod.pipeline import diagram + + colour = diagram._HIGHLIGHT_COLOUR + assert colour == "currentColor" + assert colour not in diagram._STATUS_COLOUR.values() + assert colour not in diagram._KIND_COLOUR.values() + job = _trials_job(InMemoryArrowDatabase()) + job.run() + svg = job.diagram( + highlight=job.nodes["scores"] + .trace({"animal": "a1", "trial": 1}, "score") + .highlight() + ).to_svg() + for status_colour in {"#d63c3c", "#d08a16"}: + assert f'stroke="{status_colour}" stroke-width="3.2"' not in svg + assert 'class="op-dag-highlight" stroke="currentColor"' in svg From 37cc4100e9666680ce54798312e3729262ca4e7e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 17:13:12 -0800 Subject: [PATCH 21/33] feat(provenance): the asked node, written-out questions, several rows per trace (ITL-1432) Developer feedback on 85448829: 1. The node a question was asked at is marked apart from the path: Highlight.asked and asked_text ("traced from here", "asked here"); the listing marks it ">" and "[traced from here]", the picture gives it a second outline in the text colour and a bold line, never dimmed; the notebook panel shows it. 2. A highlight shows the provenance question only: no node status (word, dot or dashed outline) in its listing or picture; the plain diagram keeps them. 3. Questions are written out, in one wording for the text header, the listing, the caption and the docs: "trace of rate_hz at node rates, for subject_id=...: 1 row matches"; "why record row_4 of units is missing at node imec0_rates" (the first line of Absence.text()). 4. trace's selector matches any number of held rows ({} for every row): one root per matching row in tag order (Trace.roots; Trace.root when exactly one), the header says how many match, source_cells(), function_runs() and the highlight cover them all (marks merged per node). No match is a Trace with status no_match; a column the node does not have is still ValueError. Pictures regenerated; Part 8 shows several rows; concept page and changelog updated. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1432.md | 15 +- docs/concepts/provenance.md | 42 ++-- docs/tutorial/08-inspecting-and-tracing.md | 95 +++++---- .../provenance-diagram-missing-filter.svg | 18 +- .../provenance-diagram-missing-join.svg | 18 +- docs/tutorial/provenance-diagram-trace.svg | 20 +- src/orcapod/core/nodes/provenance_methods.py | 30 +-- src/orcapod/pipeline/diagram.py | 46 ++++- .../pipeline/diagram_assets/diagram.js | 1 + src/orcapod/pipeline/provenance.py | 85 +++++--- src/orcapod/types/provenance.py | 114 ++++++++-- tests/test_pipeline/test_provenance.py | 21 +- tests/test_pipeline/test_provenance_review.py | 195 +++++++++++++++++- 13 files changed, 534 insertions(+), 166 deletions(-) diff --git a/changelog.d/ITL-1432.md b/changelog.d/ITL-1432.md index 44b806905..7c23f5241 100644 --- a/changelog.d/ITL-1432.md +++ b/changelog.d/ITL-1432.md @@ -4,8 +4,12 @@ 0.4.0: their answers may be refined; a case they cannot prove is reported unavailable or refused (`ProvenanceInconsistencyError`), never guessed. `diagram(highlight=...)` is in development. - - `node.trace(row, column)` on a job node traces one cell back to the source cells it - was made from. It returns a `Trace` of `TraceStep`s, with `SourceCell` leaves. + - `node.trace(row, column)` on a job node traces cells back to the source cells they + were made from: every held row whose columns equal `row`'s values (any number; `{}` + traces every row; none matching gives status `no_match`). It returns a `Trace` + whose text starts with the question written out (`trace of rate_hz at node rates, + for ...: 2 rows match`), with one tree of `TraceStep`s per row (`roots`) and + `SourceCell` leaves. - Each function step has a `FunctionRun`: the function's name, version and body hash, the executor and the time it computed, and whether this row's entry computed the result or reused one stored for equal inputs. @@ -23,7 +27,8 @@ refused. - `node.why_missing(source, record_id)` returns an `Absence`. `source` is a source id (as in source-info tokens) or a source node's label. It reads the held run - (`not_computed` without one). It gives: + (`not_computed` without one). Its text starts with the question (`why record row_4 + of units is missing at node imec0_rates`). It gives: - whether a stored entry of the first function node proves the record reached it (`reached_function`; never "did not reach": a function that raised stores no entry), and what the store records (`entry_recorded`); @@ -31,7 +36,9 @@ - the step that removed it, as a `Step` in `explain()`'s words; - for a join, the key missing from the other input. - `job.diagram(highlight=...)` outlines a `Highlight`'s nodes and edges in the text - colour (no node status uses it), dims the rest and shows its note as a caption. + colour (no node status uses it), dims the rest, shows its note (the question + written out) as a caption, leaves out the nodes' run status, and marks the node the + question was asked at ("traced from here", "asked here"; `>` in the listing). `Trace.highlight()` and `Absence.highlight()` give the trace's or the missing row's path; a trace's highlight also marks each function node on it `computed`, `reused` or `computed + reused` (`Highlight.marks`), on the node and in the text listing. diff --git a/docs/concepts/provenance.md b/docs/concepts/provenance.md index 2feaa359e..fcd62905b 100644 --- a/docs/concepts/provenance.md +++ b/docs/concepts/provenance.md @@ -53,6 +53,7 @@ job.run() trace = job.nodes["per_animal"].trace({"animal": "a2"}, "mean_accuracy") print(trace) +# trace of mean_accuracy at node per_animal, for animal='a2': 1 row matches # per_animal (animal='a2'): mean_accuracy = 0.55 # average v0.0 (body function_content_v1:...), computed here, computed ... on local # GroupBy (animal='a2'): accuracy = [0.8, 0.3] (via SelectDataColumns) @@ -68,9 +69,15 @@ print(trace) ## What a trace reads -The `row` argument selects one row the node holds, by its tags (all of them, or enough to -pick one row). The `column` is one of its data columns. Each step of the trace is a -`TraceStep`; it is found from three records the job keeps. +The `row` argument selects the held rows to trace, by column values (usually tags): every +row of the node whose columns equal them is traced, any number, and `{}` traces every +row. The `column` is one of its data columns. The trace's first line repeats the question +and says how many rows match (`trace of mean_accuracy at node per_animal, for +animal='a2': 1 row matches`). `trace.roots` holds one tree per matching row, in tag +order; `trace.root` is the one tree when exactly one row matches. A selector that matches +no held row gives a trace with status `no_match`; one that names a column the node does +not have raises `ValueError`. Each step of the trace is a `TraceStep`; it is found from +three records the job keeps. - **The system tags of each row.** Every row carries hidden tags naming the source rows it came from (`as_table(columns={"system_tags": True})`). An operator that works row by row, @@ -130,6 +137,7 @@ fresh = PipelineJob(name="behaviour", database=InMemoryArrowDatabase()) with fresh: fresh_scores = score.pod(trials, label="scores") print(fresh.nodes["scores"].trace({"animal": "a1", "trial": 1}, "accuracy")) +# trace of accuracy at node scores, for animal='a1', trial=1: the node holds no rows to trace here # scores: accuracy = None # not computed: run() the job first ``` @@ -159,6 +167,7 @@ It answers in two steps: ```python answer = job.nodes["per_animal"].why_missing("trials", '{"animal":"a3","trial":1}') print(answer) +# why record {"animal":"a3","trial":1} of trials is missing at node per_animal # trials {"animal":"a3","trial":1} does not reach per_animal: source 'trials' holds no record '{"animal":"a3","trial":1}' # no successful entry of function node 'scores' is stored for it (the function raised on it, or never received it) ``` @@ -177,23 +186,28 @@ and one removed by a join. ## On the diagram `trace.highlight()` and `answer.highlight()` give a `Highlight`: the nodes and streams on -the path, with a note. `job.diagram(highlight=...)` outlines them in the text colour (which -no node status uses: red means failed), dims the rest, and shows the note as a caption. +the path (for several rows, the union of their paths), with a note, the question written +out. `job.diagram(highlight=...)` outlines them in the text colour (which no node status +uses: red means failed), dims the rest, shows the note as a caption, and leaves out every +node's run status: it shows the provenance question only. The node the question was asked +at (`Highlight.asked`) gets a second outline and the line "traced from here" or "asked +here"; in the listing it is marked `>`. A trace's highlight also marks each function node on the path with how its rows on the path got their results (`Highlight.marks`): `computed`, `reused` (a result stored for equal inputs) or `computed + reused` (some rows each). Its text listing marks the highlighted -nodes with `*` and a function node's mark in brackets. Here `scores` computed the score of +nodes with `*` and a function node's mark in brackets; a mark of several rows is merged +per node. Here `scores` computed the score of trial 2 of `a2` and reused the one stored for trial 1 (above): ```python print(job.diagram(highlight=trace.highlight())) # Job 'behaviour': 5 nodes -# highlight (*): trace of per_animal.mean_accuracy animal='a2' -# * trials (source · DictSource · bound) -# * scores (function pod · score · current) [computed + reused] <- trials -# * GroupBy (operator · current) <- scores -# * SelectDataColumns (operator · current) <- GroupBy -# * per_animal (function pod · average · current) [computed] <- SelectDataColumns +# highlight (*): trace of mean_accuracy at node per_animal, for animal='a2': 1 row matches +# * trials (source · DictSource) +# * scores (function pod · score) [computed + reused] <- trials +# * GroupBy (operator) <- scores +# * SelectDataColumns (operator) <- GroupBy +# >* per_animal (function pod · average) [computed] [traced from here] <- SelectDataColumns ``` In a notebook the diagram is drawn as a picture, the mark as a bold line on its node. Here @@ -204,13 +218,13 @@ marked `reused`: ![The diagram of the tutorial's workshop job: the sources sessions and units on the left, through column selections and a Join into the function pod rates, then GroupBy, a selection and the function pod session_means on the right](../tutorial/provenance-diagram-plain.svg) -![The same diagram captioned "highlighted: trace of rates.rate_hz subject_id='mouse_02', session='s1', probe='imec1', unit=2": the sources, their column selections, the Join and rates outlined in a dark line, rates with the bold line "reused"; GroupBy, its selection and session_means dimmed](../tutorial/provenance-diagram-trace.svg) +![The same diagram captioned "highlighted: trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches": the sources, their column selections, the Join and rates outlined in a dark line; rates has a second outline and the bold lines "reused" and "traced from here"; GroupBy, its selection and session_means dimmed](../tutorial/provenance-diagram-trace.svg) A missing row's highlight ends at the step that removed it, and dims the rest. In the tutorial's second job, a unit of `mouse_04` passes the filter on `probe` and is removed by the Join, which has no session of `mouse_04` to match it with: -![The diagram of the tutorial's imec0 job with the path of units row_48 highlighted: the source units, Filter_1, SelectDataColumns_1 and the Join outlined in a dark line; the sessions branch and the function pod imec0_rates dimmed](../tutorial/provenance-diagram-missing-join.svg) +![The diagram of the tutorial's imec0 job, captioned "highlighted: why record row_48 of units is missing at node imec0_rates: ...": the source units, Filter_1, SelectDataColumns_1 and the Join outlined in a dark line; the sessions branch dimmed; the function pod imec0_rates with a second outline and the bold line "asked here"](../tutorial/provenance-diagram-missing-join.svg) A `Highlight` can also be made by hand, from node labels, `(upstream, downstream)` label pairs and `(label, mark)` pairs. A label the job does not have is refused with diff --git a/docs/tutorial/08-inspecting-and-tracing.md b/docs/tutorial/08-inspecting-and-tracing.md index 7d22f960d..bd4972969 100644 --- a/docs/tutorial/08-inspecting-and-tracing.md +++ b/docs/tutorial/08-inspecting-and-tracing.md @@ -206,6 +206,7 @@ for you, for one cell: give the node, the tags of the row and the column. means = job.nodes["session_means"] trace = means.trace({"subject_id": "mouse_03", "session": "s2"}, "mean_rate_hz") print(trace) +# trace of mean_rate_hz at node session_means, for subject_id='mouse_03', session='s2': 1 row matches # session_means (subject_id='mouse_03', session='s2'): mean_rate_hz = 5.059375 # mean_rate v0.0 (body function_content_v1:...), computed here, computed ... on local # GroupBy (subject_id='mouse_03', session='s2'): rate_hz = [4.791666666666667, 5.058333333333334, 7.366666666666666, 4.683333333333334, 5.0, 3.3333333333333335, 6.916666666666667, 3.325] (via SelectDataColumns) @@ -243,7 +244,9 @@ print(trace) # units row_47 n_spikes = 399 (via Join, SelectDataColumns) ``` -Read it from the top. The mean of `mouse_03`, session `s2`, was computed by `mean_rate` +The first line repeats the question: the column traced, the node it was asked at and the +row selector, and how many held rows match it. Read the rest from the top. The mean of +`mouse_03`, session `s2`, was computed by `mean_rate` (its version, the hash of its body, when and where it ran). Its input was the grouped row of eight rates. Each rate was computed by `firing_rate` from one row of `units.csv` and the one row of `sessions.csv` for that session; the operators it passed through are listed @@ -301,24 +304,42 @@ for step in shared.root.walk(): `imec1` unit 2 reused the result that `imec0` unit 0 computed: one stored result, two rows, both traced to their own row of `units.csv`. +**Several rows at once.** The selector need not pick one row: every held row whose columns +equal the values given is traced, and `{}` traces every row. Each matching row has its own +tree, in `trace.roots`, in tag order; `source_cells()` and the highlight cover them all: + +```python +both = means.trace({"subject_id": "mouse_02"}, "mean_rate_hz") +print(both.header()) +# trace of mean_rate_hz at node session_means, for subject_id='mouse_02': 2 rows match +print([dict(root.tags) for root in both.roots]) +# [{'subject_id': 'mouse_02', 'session': 's1'}, {'subject_id': 'mouse_02', 'session': 's2'}] +print(len(both.source_cells())) +# 18 +``` + +A selector that matches no held row gives a trace that says so (`no held row matches`, +status `no_match`); one that names a column the node does not have is an error. + **On the diagram.** `trace.highlight()` marks the trace's path on the job's diagram. The -listing marks the nodes on the path with `*`, and each function node on it with how its -rows on the path got their results: `[computed]`, `[reused]` (a result stored for equal -inputs), or `[computed + reused]` (some rows each): +listing shows the provenance question only, with no run status. It marks the nodes on the +path with `*`, the node the trace was asked at with `>` and `[traced from here]`, and each +function node on the path with how its rows on the path got their results: `[computed]`, +`[reused]` (a result stored for equal inputs), or `[computed + reused]` (some rows each): ```python print(job.diagram(highlight=trace.highlight())) # Job 'workshop': 9 nodes -# highlight (*): trace of session_means.mean_rate_hz subject_id='mouse_03', session='s2' -# * sessions (source · CSVSource · bound) -# * SelectDataColumns_1 (operator · current) <- sessions -# * units (source · CSVSource · bound) -# * SelectDataColumns_3 (operator · current) <- units -# * Join (operator · current) <- SelectDataColumns_1, SelectDataColumns_3 -# * rates (function pod · firing_rate · current) [computed] <- Join -# * GroupBy (operator · current) <- rates -# * SelectDataColumns_2 (operator · current) <- GroupBy -# * session_means (function pod · mean_rate · current) [computed] <- SelectDataColumns_2 +# highlight (*): trace of mean_rate_hz at node session_means, for subject_id='mouse_03', session='s2': 1 row matches +# * sessions (source · CSVSource) +# * SelectDataColumns_1 (operator) <- sessions +# * units (source · CSVSource) +# * SelectDataColumns_3 (operator) <- units +# * Join (operator) <- SelectDataColumns_1, SelectDataColumns_3 +# * rates (function pod · firing_rate) [computed] <- Join +# * GroupBy (operator) <- rates +# * SelectDataColumns_2 (operator) <- GroupBy +# >* session_means (function pod · mean_rate) [computed] [traced from here] <- SelectDataColumns_2 ``` A mean is made through every step of the job, so its path covers the whole diagram. The @@ -331,23 +352,24 @@ rate = job.nodes["rates"].trace( ) print(job.diagram(highlight=rate.highlight())) # Job 'workshop': 9 nodes -# highlight (*): trace of rates.rate_hz subject_id='mouse_02', session='s1', probe='imec1', unit=2 -# * sessions (source · CSVSource · bound) -# * SelectDataColumns_1 (operator · current) <- sessions -# * units (source · CSVSource · bound) -# * SelectDataColumns_3 (operator · current) <- units -# * Join (operator · current) <- SelectDataColumns_1, SelectDataColumns_3 -# * rates (function pod · firing_rate · current) [reused] <- Join -# GroupBy (operator · current) <- rates -# SelectDataColumns_2 (operator · current) <- GroupBy -# session_means (function pod · mean_rate · current) <- SelectDataColumns_2 +# highlight (*): trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches +# * sessions (source · CSVSource) +# * SelectDataColumns_1 (operator) <- sessions +# * units (source · CSVSource) +# * SelectDataColumns_3 (operator) <- units +# * Join (operator) <- SelectDataColumns_1, SelectDataColumns_3 +# >* rates (function pod · firing_rate) [reused] [traced from here] <- Join +# GroupBy (operator) <- rates +# SelectDataColumns_2 (operator) <- GroupBy +# session_means (function pod · mean_rate) <- SelectDataColumns_2 ``` -In a notebook the same call draws the picture. The caption says what is highlighted; the -path is outlined in the text colour and the rest is dimmed (no status of a node is shown -in that colour: red is kept for failed). The mark is the bold line on `rates`: +In a notebook the same call draws the picture. The caption is the question; the path is +outlined in the text colour and the rest is dimmed (no status of a node is shown in that +colour: red is kept for failed). The node it was asked at has a second outline and the +bold line "traced from here"; the mark is the bold line "reused": -![The diagram of the workshop job, captioned "highlighted: trace of rates.rate_hz subject_id='mouse_02', session='s1', probe='imec1', unit=2": the sources sessions and units, their column selections, the Join and the function pod rates outlined in a dark line, rates with the bold line "reused"; GroupBy, its selection and the function pod session_means dimmed](provenance-diagram-trace.svg) +![The diagram of the workshop job, captioned "highlighted: trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches": the sources sessions and units, their column selections, the Join and the function pod rates outlined in a dark line; rates has a second outline and the bold lines "reused" and "traced from here"; GroupBy, its selection and the function pod session_means dimmed](provenance-diagram-trace.svg) **Why is a row missing?** A second job keeps only the `imec0` probe and leaves out the sessions of `mouse_04`. Row 4 of `units.csv` is an `imec1` unit, and row 48 is a unit of @@ -377,29 +399,32 @@ with imec0: ) imec0.run() print(imec0.nodes["imec0_rates"].why_missing("units", "row_4")) +# why record row_4 of units is missing at node imec0_rates # units row_4 is removed by Filter[...]: probe='imec0' # no successful entry of function node 'imec0_rates' is stored for it (the function raised on it, or never received it) # present in: units print(imec0.nodes["imec0_rates"].why_missing("units", "row_48")) +# why record row_48 of units is missing at node imec0_rates # units row_48 is removed by Join: rows without a match in 'sessions' are dropped # no successful entry of function node 'imec0_rates' is stored for it (the function raised on it, or never received it) # present in: units, ... # because: no row with session='s1', subject_id='mouse_04' in ... (reads sessions) ``` -The first line answers the question: which step removed the row. The second is read from -the stored records of `imec0_rates`: no run of this job stored a result for the row. On -its own that does not prove the function never saw it (a function that raised on a row -stores no result for it); the first line says why it did not. +The first line repeats the question. The second answers it: which step removed the row. +The third is read from the stored records of `imec0_rates`: no run of this job stored a +result for the row. On its own that does not prove the function never saw it (a function +that raised on a row stores no result for it); the second line says why it did not. `why_missing(...).highlight()` marks the path up to the step that removed the row; the -other nodes are dimmed. For `units row_4`, the path ends at the filter on `probe`: +other nodes are dimmed, except the node asked at, marked "asked here". For `units row_4`, +the path ends at the filter on `probe`: -![The diagram of the imec0 job with the path of units row_4 highlighted: the source units and the node Filter_1 outlined in a dark line; the sessions branch, the Join and the function pod imec0_rates dimmed](provenance-diagram-missing-filter.svg) +![The diagram of the imec0 job, captioned "highlighted: why record row_4 of units is missing at node imec0_rates: ...": the source units and the node Filter_1 outlined in a dark line; the sessions branch and the Join dimmed; the function pod imec0_rates with a second outline and the bold line "asked here"](provenance-diagram-missing-filter.svg) For `units row_48`, the row passes the filter and its column selection and ends at the Join, which has no session `s1` of `mouse_04` to match it with: -![The diagram of the imec0 job with the path of units row_48 highlighted: the source units, Filter_1, SelectDataColumns_1 and the Join outlined in a dark line; the sessions branch and the function pod imec0_rates dimmed](provenance-diagram-missing-join.svg) +![The diagram of the imec0 job, captioned "highlighted: why record row_48 of units is missing at node imec0_rates: ...": the source units, Filter_1, SelectDataColumns_1 and the Join outlined in a dark line; the sessions branch dimmed; the function pod imec0_rates with a second outline and the bold line "asked here"](provenance-diagram-missing-join.svg) The pictures are drawn by `job.diagram(...)` itself, from the job above. diff --git a/docs/tutorial/provenance-diagram-missing-filter.svg b/docs/tutorial/provenance-diagram-missing-filter.svg index 3ff8f50be..1418b793d 100644 --- a/docs/tutorial/provenance-diagram-missing-filter.svg +++ b/docs/tutorial/provenance-diagram-missing-filter.svg @@ -1,24 +1,24 @@ -Job 'imec0': units row_4 is removed by Filter[Filter_1]: probe='imec0'highlighted: units row_4 is removed by Filter[Filter_1]: probe='imec0'sessions → Filter_2Filter_2 → SelectDataColumns_2SelectDataColumns_2 → Joinunits → Filter_1Filter_1 → SelectDataColumns_1SelectDataColumns_1 → JoinJoin → imec0_ratessessions (source · CSVSource · bound) +Job 'imec0': why record row_4 of units is missing at node imec0_rates: units row_4 is removed by Filter[Filter_1]: probe='imec0'highlighted: why record row_4 of units is missing at node imec0_rates: units row_4 is removed by Filter…sessions → Filter_2Filter_2 → SelectDataColumns_2SelectDataColumns_2 → Joinunits → Filter_1Filter_1 → SelectDataColumns_1SelectDataColumns_1 → JoinJoin → imec0_ratessessions (source · CSVSource) tags: subject_id: str, session: str -data: date: date, duration_s: floatsourceCSVSourceboundsessionsFilter_2 (operator · current) +data: date: date, duration_s: floatsourceCSVSourcesessionsFilter_2 (operator) tags: subject_id: str, session: str data: date: date, duration_s: float -inputs: sessionsoperatorcurrentFilter_2SelectDataColumns_2 (operator · current) +inputs: sessionsoperatorFilter_2SelectDataColumns_2 (operator) tags: subject_id: str, session: str data: duration_s: float -inputs: Filter_2operator · currentSelectDataColumns_2units (source · CSVSource · bound) +inputs: Filter_2operatorSelectDataColumns_2units (source · CSVSource) tags: subject_id: str, session: str, probe: str, unit: int -data: region: str, depth_um: int, n_spikes: intsourceCSVSourceboundunitsFilter_1 (operator · current) +data: region: str, depth_um: int, n_spikes: intsourceCSVSourceunitsFilter_1 (operator) tags: subject_id: str, session: str, probe: str, unit: int data: region: str, depth_um: int, n_spikes: int -inputs: unitsoperatorcurrentFilter_1SelectDataColumns_1 (operator · current) +inputs: unitsoperatorFilter_1SelectDataColumns_1 (operator) tags: subject_id: str, session: str, probe: str, unit: int data: n_spikes: int -inputs: Filter_1operator · currentSelectDataColumns_1Join (operator · current) +inputs: Filter_1operatorSelectDataColumns_1Join (operator) tags: subject_id: str, session: str, probe: str, unit: int data: n_spikes: int, duration_s: float -inputs: SelectDataColumns_2, SelectDataColumns_1operatorcurrentJoinimec0_rates (function pod · firing_rate · current) +inputs: SelectDataColumns_2, SelectDataColumns_1operatorJoinimec0_rates (function pod · firing_rate) tags: subject_id: str, session: str, probe: str, unit: int data: rate_hz: float inputs: Join -job's last run: 24 rows, 24 computedfunction podfiring_ratecurrentimec0_rates +job's last run: 24 rows, 24 computedfunction podfiring_rateasked hereimec0_rates diff --git a/docs/tutorial/provenance-diagram-missing-join.svg b/docs/tutorial/provenance-diagram-missing-join.svg index 2df84e44c..7c087271e 100644 --- a/docs/tutorial/provenance-diagram-missing-join.svg +++ b/docs/tutorial/provenance-diagram-missing-join.svg @@ -1,24 +1,24 @@ -Job 'imec0': units row_48 is removed by Join: rows without a match in 'sessions' are droppedhighlighted: units row_48 is removed by Join: rows without a match in 'sessions' are droppedsessions → Filter_2Filter_2 → SelectDataColumns_2SelectDataColumns_2 → Joinunits → Filter_1Filter_1 → SelectDataColumns_1SelectDataColumns_1 → JoinJoin → imec0_ratessessions (source · CSVSource · bound) +Job 'imec0': why record row_48 of units is missing at node imec0_rates: units row_48 is removed by Join: rows without a match in 'sessions' are droppedhighlighted: why record row_48 of units is missing at node imec0_rates: units row_48 is removed by Join…sessions → Filter_2Filter_2 → SelectDataColumns_2SelectDataColumns_2 → Joinunits → Filter_1Filter_1 → SelectDataColumns_1SelectDataColumns_1 → JoinJoin → imec0_ratessessions (source · CSVSource) tags: subject_id: str, session: str -data: date: date, duration_s: floatsourceCSVSourceboundsessionsFilter_2 (operator · current) +data: date: date, duration_s: floatsourceCSVSourcesessionsFilter_2 (operator) tags: subject_id: str, session: str data: date: date, duration_s: float -inputs: sessionsoperatorcurrentFilter_2SelectDataColumns_2 (operator · current) +inputs: sessionsoperatorFilter_2SelectDataColumns_2 (operator) tags: subject_id: str, session: str data: duration_s: float -inputs: Filter_2operator · currentSelectDataColumns_2units (source · CSVSource · bound) +inputs: Filter_2operatorSelectDataColumns_2units (source · CSVSource) tags: subject_id: str, session: str, probe: str, unit: int -data: region: str, depth_um: int, n_spikes: intsourceCSVSourceboundunitsFilter_1 (operator · current) +data: region: str, depth_um: int, n_spikes: intsourceCSVSourceunitsFilter_1 (operator) tags: subject_id: str, session: str, probe: str, unit: int data: region: str, depth_um: int, n_spikes: int -inputs: unitsoperatorcurrentFilter_1SelectDataColumns_1 (operator · current) +inputs: unitsoperatorFilter_1SelectDataColumns_1 (operator) tags: subject_id: str, session: str, probe: str, unit: int data: n_spikes: int -inputs: Filter_1operator · currentSelectDataColumns_1Join (operator · current) +inputs: Filter_1operatorSelectDataColumns_1Join (operator) tags: subject_id: str, session: str, probe: str, unit: int data: n_spikes: int, duration_s: float -inputs: SelectDataColumns_2, SelectDataColumns_1operatorcurrentJoinimec0_rates (function pod · firing_rate · current) +inputs: SelectDataColumns_2, SelectDataColumns_1operatorJoinimec0_rates (function pod · firing_rate) tags: subject_id: str, session: str, probe: str, unit: int data: rate_hz: float inputs: Join -job's last run: 24 rows, 24 computedfunction podfiring_ratecurrentimec0_rates +job's last run: 24 rows, 24 computedfunction podfiring_rateasked hereimec0_rates diff --git a/docs/tutorial/provenance-diagram-trace.svg b/docs/tutorial/provenance-diagram-trace.svg index 40a26b672..c5dd98253 100644 --- a/docs/tutorial/provenance-diagram-trace.svg +++ b/docs/tutorial/provenance-diagram-trace.svg @@ -1,28 +1,28 @@ -Job 'workshop': trace of rates.rate_hz subject_id='mouse_02', session='s1', probe='imec1', unit=2highlighted: trace of rates.rate_hz subject_id='mouse_02', session='s1', probe='imec1', unit=2sessions → SelectDataColumns_1SelectDataColumns_1 → Joinunits → SelectDataColumns_3SelectDataColumns_3 → JoinJoin → ratesrates → GroupByGroupBy → SelectDataColumns_2SelectDataColumns_2 → session_meanssessions (source · CSVSource · bound) +Job 'workshop': trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matcheshighlighted: trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matchessessions → SelectDataColumns_1SelectDataColumns_1 → Joinunits → SelectDataColumns_3SelectDataColumns_3 → JoinJoin → ratesrates → GroupByGroupBy → SelectDataColumns_2SelectDataColumns_2 → session_meanssessions (source · CSVSource) tags: subject_id: str, session: str -data: date: date, duration_s: floatsourceCSVSourceboundsessionsSelectDataColumns_1 (operator · current) +data: date: date, duration_s: floatsourceCSVSourcesessionsSelectDataColumns_1 (operator) tags: subject_id: str, session: str data: duration_s: float -inputs: sessionsoperator · currentSelectDataColumns_1units (source · CSVSource · bound) +inputs: sessionsoperatorSelectDataColumns_1units (source · CSVSource) tags: subject_id: str, session: str, probe: str, unit: int -data: region: str, depth_um: int, n_spikes: intsourceCSVSourceboundunitsSelectDataColumns_3 (operator · current) +data: region: str, depth_um: int, n_spikes: intsourceCSVSourceunitsSelectDataColumns_3 (operator) tags: subject_id: str, session: str, probe: str, unit: int data: n_spikes: int -inputs: unitsoperator · currentSelectDataColumns_3Join (operator · current) +inputs: unitsoperatorSelectDataColumns_3Join (operator) tags: subject_id: str, session: str, probe: str, unit: int data: duration_s: float, n_spikes: int -inputs: SelectDataColumns_1, SelectDataColumns_3operatorcurrentJoinrates (function pod · firing_rate · current) +inputs: SelectDataColumns_1, SelectDataColumns_3operatorJoinrates (function pod · firing_rate) tags: subject_id: str, session: str, probe: str, unit: int data: rate_hz: float inputs: Join -job's last run: 64 rows, 63 computed, 1 reusedfunction podfiring_ratecurrentreusedratesGroupBy (operator · current) +job's last run: 64 rows, 63 computed, 1 reusedfunction podfiring_ratereusedtraced from hereratesGroupBy (operator) tags: subject_id: str, session: str data: rate_hz: list[float] -inputs: ratesoperatorcurrentGroupBySelectDataColumns_2 (operator · current) +inputs: ratesoperatorGroupBySelectDataColumns_2 (operator) tags: subject_id: str, session: str data: rate_hz: list[float] -inputs: GroupByoperator · currentSelectDataColumns_2session_means (function pod · mean_rate · current) +inputs: GroupByoperatorSelectDataColumns_2session_means (function pod · mean_rate) tags: subject_id: str, session: str data: mean_rate_hz: float inputs: SelectDataColumns_2 -job's last run: 8 rows, 8 computedfunction podmean_ratecurrentsession_means +job's last run: 8 rows, 8 computedfunction podmean_ratesession_means diff --git a/src/orcapod/core/nodes/provenance_methods.py b/src/orcapod/core/nodes/provenance_methods.py index e1cb715f3..08d28c15b 100644 --- a/src/orcapod/core/nodes/provenance_methods.py +++ b/src/orcapod/core/nodes/provenance_methods.py @@ -17,32 +17,34 @@ class ProvenanceMethods: """ def trace(self, row: Mapping[str, Any], column: str) -> Trace: - """Trace one cell of this node back to the source cells it was made from. + """Trace cells of this node back to the source cells they were made from. Provisional in 0.4.0: answers may be refined; a case that cannot be proven is reported unavailable or refused (the known limits are in the provenance concept page). - Each step names the node, the cell's value there and its row's tags. A function - step says which function produced the value, with its version, body hash, - executor and time, and whether this row's entry computed the result or reused - one stored for equal inputs. A ``GroupBy`` or ``Batch`` step lists its members, - found by the operator's own rule and checked: their system tags must fold to - the group's. The leaves are source cells. A loaded job traces the same once it - has run with ``load_only=True``. + Every row this node holds whose columns equal ``row``'s values is traced (any + number; ``{}`` traces every row). Each step names the node, the cell's value + there and its row's tags. A function step says which function produced the + value, with its version, body hash, executor and time, and whether this row's + entry computed the result or reused one stored for equal inputs. A ``GroupBy`` + or ``Batch`` step lists its members, found by the operator's own rule and + checked: their system tags must fold to the group's. The leaves are source + cells. A loaded job traces the same once it has run with ``load_only=True``. Args: - row: Column values that select exactly one row this node holds, usually - its tags: ``{"subject_id": "mouse_03", "session": "s2"}``. - column: The data column of the cell. + row: Column values selecting the rows to trace, usually tags: + ``{"subject_id": "mouse_03", "session": "s2"}``. + column: The data column of the cells. Returns: - The trace; its root's status is ``"not_computed"`` when this node holds no - run (``run()`` the job first). + The trace: one root per matching row, its header saying how many match + (status ``"no_match"`` when none does); its one root's status is + ``"not_computed"`` when this node holds no run (``run()`` the job first). Raises: ValueError: If ``column`` is not a data column of this node, or ``row`` - names a column this node does not have or does not select one row. + names a column this node does not have. ProvenanceInconsistencyError: If a link cannot be proven from what the job holds and stores (a group whose members do not fold to its values). """ diff --git a/src/orcapod/pipeline/diagram.py b/src/orcapod/pipeline/diagram.py index d50c0ddfd..4bdbd7ec5 100644 --- a/src/orcapod/pipeline/diagram.py +++ b/src/orcapod/pipeline/diagram.py @@ -85,6 +85,7 @@ class _Node: facts: tuple[tuple[str, str], ...] highlighted: bool = False mark: str = "" + asked: str = "" @property def kind_line(self) -> str: @@ -380,10 +381,14 @@ def ends(label: str, via: tuple[str, ...]) -> list[tuple[str, tuple[str, ...]]]: detail=_node_detail(node), tag_schema=_schema_pairs(tag_schema), data_schema=_schema_pairs(data_schema), - status=statuses.get(label, ""), + # A highlight shows the provenance question only: no run status. + status="" if highlight is not None else statuses.get(label, ""), facts=facts, 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" + if highlight is not None and highlight.asked == label + else "", ) ) @@ -467,7 +472,7 @@ class _Layout: def _text_room(node: _Node) -> float: """The width of a node's text: its label or the widest part of its kind line (the kind, the detail, the status), within the node width limits (ITL-1232).""" - parts = [*node.kind_line.split(" · "), node.mark] + 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 ) @@ -492,6 +497,9 @@ def _kind_lines(node: _Node) -> tuple[str, ...]: if node.mark: # A highlight's mark (a trace's computed / reused) on a line of its own. lines.append(node.mark) + if node.asked: + # The node the question was asked at ("traced from here"), on its own line. + lines.append(node.asked) return tuple(lines) @@ -920,7 +928,7 @@ def _svg( emphasis = " op-dag-highlight" stroke_width = "3.2" stroke = _HIGHLIGHT_COLOUR - elif lit: + elif lit and not node.asked: emphasis = '" opacity="0.4' parts.append( f'' ) + if node.asked: + # The node the question was asked at: a second outline around it, in the + # text colour (readable on a light and a dark page). + parts.append( + f'' + ) if node.kind in ("side_effect", "side_effect_function"): parts.append( f'= len(kind_lines) - emphasized weight = ( ' font-weight="600" class="op-dag-mark"' if is_mark @@ -1160,6 +1178,7 @@ def __init__( *highlight.nodes, *(end for edge in highlight.edges for end in edge), *(label for label, _ in highlight.marks), + *((highlight.asked,) if highlight.asked else ()), } - labels ) @@ -1228,6 +1247,8 @@ def _model(self, nodes: list[_Node], edges: list[_Edge]) -> dict[str, Any]: entry["highlighted"] = node.highlighted if node.mark: entry["mark"] = node.mark + if node.asked: + entry["asked"] = node.asked for entry, edge in zip(model["edges"], edges): entry["highlighted"] = edge.highlighted return model @@ -1266,18 +1287,27 @@ def to_text(self) -> str: Returns: A title line, then ``