diff --git a/changelog.d/ITL-1432.md b/changelog.d/ITL-1432.md new file mode 100644 index 000000000..f70036ebb --- /dev/null +++ b/changelog.d/ITL-1432.md @@ -0,0 +1,78 @@ +### Added + +- Per-row provenance of a job (ITL-1432). `trace` and `why_missing` are provisional in + 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 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. + - 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`. + - A source is never read. A cached, polling, derived or user-defined source is + `unavailable` only for a step that needs the source's own rows (such as a + `GroupBy` straight over it); a step after it is traced from the tokens its rows + carry. + - Every value is checked against the row it came from, and an ambiguous link is + 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). 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`); + - 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=...)` outlines a `Highlight`'s nodes and edges in the text + 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. + - 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. + +### Fixed + +- A function job node's rows are read in the order its run passed them downstream + (ITL-1441). After a synchronous run over a partly stored history, the node used to + hold the stored results first, so a read of it (`iter_data`, `as_table`, `head`, the + data frames) and a downstream node run on its own (`node.run()`: a `Batch`, its sums + and folded record ids, a load-only aggregate, `GroupBy` members that tie) differed + from what the whole job computed. Now every read gives the input order a synchronous + run passed on, fresh, partly stored, load-only and after `clear_cache()`. An + asynchronous run promises no order (ITL-1437): its rows are read in the order that + run emitted them. + +### Known limitations + +- Provenance (`trace`, `why_missing`) is provisional in 0.4.0 (ITL-1432). Known limits: + - A source is never read. A cached, polling, derived or user-defined source gives + no values for a step that needs its rows: such a step is `unavailable`. Also, the + first step after such a source is never blamed for a missing record. + - Only Orcapod's own operators are followed. A subclass of one, or an operator of + your own, is `unavailable`, for `trace` and for `why_missing` past it. + - Inputs of a commutative `Join` with one pipeline hash (two sources of one schema, + or two upstream joins whose outputs share a pipeline hash) are told apart by their + values. Two such upstream joins holding their sources in opposite orders are + refused rather than guessed. The stored answer (`reached_function`) through tied + inputs is unknown, even when their source ids differ. + - `why_missing` reads the held run: with only stored entries (before a run, or on a + loaded job not yet run) it answers `not_computed`. + - After a fold, the stored answer is known only for the groups the run holds. + - Entries of a recomputed result are told apart only once pipeline entries record + their run id (ITL-1433). + - Job nodes only. 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..62c8b9010 100644 --- a/docs/api/nodes.md +++ b/docs/api/nodes.md @@ -24,3 +24,13 @@ 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. Both are +provisional in 0.4.0: their answers may be refined in a later release; a case they cannot +prove is reported unavailable or refused, never guessed. The known limits are listed on +the [provenance concept page](../concepts/provenance.md#known-limits). + +::: 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/docs/concepts/provenance.md b/docs/concepts/provenance.md new file mode 100644 index 000000000..12b8e538d --- /dev/null +++ b/docs/concepts/provenance.md @@ -0,0 +1,275 @@ +# Provenance: tracing a value + +!!! warning "Provisional" + `trace` and `why_missing` are provisional in 0.4.0. Their answers may be refined in a + later release. A case they cannot prove is reported `unavailable` or refused with + `ProvenanceInconsistencyError`, never guessed. Their known limits are listed under + [Known limits](#known-limits). `diagram(highlight=...)` is in development: its + interface and its look may change in any release. + +A job keeps what it needs to answer "where did this value come from?" for every cell it +holds. `node.trace(row, column)` follows one cell back, step by step, to the source cells it +was made from. `node.why_missing(source, record_id)` says why a source row has no result. Both +only read: they never compute a function, call your code, poll a source or write to the +database. + +```python +from orcapod import PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.sources import DictSource + +trials = DictSource( + [ + {"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}, + ], + tag_columns=["animal", "trial"], + tag_only_columns=True, + source_id="trials", + record_id_columns=["animal", "trial"], +) + + +@function_pod(output_keys=["accuracy", "n"]) +def score(hits: int, misses: int) -> tuple[float, int]: + return hits / (hits + misses), hits + misses + + +@function_pod(output_keys="mean_accuracy") +def average(accuracy: list[float]) -> float: + return sum(accuracy) / len(accuracy) + + +job = PipelineJob(name="behaviour", database=InMemoryArrowDatabase()) +with job: + scores = score.pod(trials, label="scores") + average.pod( + scores.group_by(["animal"]).select_data_columns(["accuracy"]), + label="per_animal", + ) +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, run ..., recorded ... +# GroupBy (animal='a2'): accuracy = [0.8, 0.3] (via SelectDataColumns) +# [0] scores (animal='a2', trial=1): accuracy = 0.8 +# score v0.0 (body function_content_v1:...), reused a stored result, computed ... on local, run ..., recorded ... +# dict_v1:trials {"animal":"a2","trial":1} hits = 8 +# dict_v1:trials {"animal":"a2","trial":1} misses = 2 +# [1] scores (animal='a2', trial=2): accuracy = 0.3 +# score v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# dict_v1:trials {"animal":"a2","trial":2} hits = 3 +# dict_v1:trials {"animal":"a2","trial":2} misses = 7 +``` + +## What a trace reads + +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, + and a function pod, keep them unchanged. A join keeps those of each input, under names + extended with the input's place in the pipeline. So the input row of a row is the row + of the input with the same system tags. +- **A function node's stored records.** For each input row a function node received, its + pipeline record names that row (by its tags and system tags), the result it was served, + and whether this row computed the result or reused one. The stored result says which + function ran: its name, version and body hash, the executor, the Python version and the + time. The trace shows these as a `FunctionRun`, and checks that the input row's content + hash is the one the record stored. +- **The source-info tokens.** Each value carries `::::`, + which names the source cell it came from. A trace ends in `SourceCell`s. + +A `GroupBy` or `Batch` folds its members' system tags into one digest, which cannot be +read backwards. The trace finds the members with the operator's own rule: + +- for `GroupBy`, the input rows with the group's key, in member order; +- for `Batch`, the rows at the batch's position. + +It then folds their system tags again; the result must equal the group's. If it does not, +the trace raises `ProvenanceInconsistencyError` and never guesses. Member `i` fills +position `i` of every list of the grouped row. + +**Equal inputs, one result.** Trial 1 of `a1` and of `a2` have the same hits and misses, so +`score` ran once for the two and stored one result. The trace still follows each row to +its own source record. The `FunctionRun` of trial 1 of `a2` says it reused the stored +result (`computed_here` is `False`); that of `a1` says it computed it. + +`trace.source_cells()` lists the source cells, each once; `trace.function_runs()` lists +every function step's `FunctionRun`. A trace of an operator node or of a source node works +the same way: on a source node it is one cell. + +```python +for cell in trace.source_cells(): + print(cell.text()) +# dict_v1:trials {"animal":"a2","trial":1} hits = 8 +# dict_v1:trials {"animal":"a2","trial":1} misses = 2 +# dict_v1:trials {"animal":"a2","trial":2} hits = 3 +# dict_v1:trials {"animal":"a2","trial":2} misses = 7 +print([(label, run.computed_here) for label, run in trace.function_runs()]) +# [('per_animal', True), ('scores', False), ('scores', True)] +``` + +## When there is nothing to trace + +An operator or function node shows only the rows of its run in this process (see +[Pipelines and Jobs](pipeline-job.md)). Before a run, and on a stale node, there is +nothing to trace, and the trace says so rather than computing. A source node is +different: when its source keeps its rows in memory, a trace of the source node reads +that snapshot, before a run too; any other source is reported `unavailable`. A function +node before a run: + +```python +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 +``` + +A job loaded from its file (`PipelineJob.load`) traces the same once it has run with +`load_only=True`, which reads the stored results and computes nothing. The function steps +then show the same results, with the times they were computed. + +## Why a row is missing + +`why_missing(source, record_id)` takes a source, by its node's label, its name or its full +id as it appears in a source-info token (`dict_v1:trials`), and a record id. The source +argument must name exactly one source: when one source's name is another's id +(`dict_v1:a` names the source `a`, and a source named `dict_v1:a` too), it is refused +with `ValueError` naming both; give the node label or full id that names one. A node +label or source name asks about every id the slot's rows carry, a full id about that id +only; a slot whose label is also one of the several ids it carries is refused for that +string too. It reads the run the job holds: before a run, and on a loaded job not +yet run (`load_only=True`), it answers `not_computed`, even when the store holds entries. +It answers in two steps: + +- **From the rows the nodes hold:** which nodes have a row from it, and which step removed + it. The step is described in the words of `explain()`. For a join, the answer also gives + the key the other input lacks. +- **From the stored records of the first function node on the way:** a stored entry + of that node (this pipeline bound to these sources, in any of its runs) proves that a + row from the record reached the function (`reached_function` is `True`). Entries + stored under another binding of the pipeline are not read. No entry proves nothing: a function that raised on an + input stores no entry for it. So `reached_function` is never `False`; `entry_recorded` + says what the store holds. + +```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) +``` + +The result is an `Absence`. Its fields hold: + +- `missing`: whether the row is missing; +- `reached_function`, `entry_recorded` and `function_node`: the stored-record answer; +- `present_in`: the nodes that hold a row from the record; +- `removed_by`: the step that removed it, a `Step`; +- `because`: the reason, in words. + +Tutorial [Part 8](../tutorial/08-inspecting-and-tracing.md) shows a row removed by a filter +and one removed by a join. + +## On the diagram + +`trace.highlight()` and `answer.highlight()` give a `Highlight`: the nodes and streams on +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; 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 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 +is the job of tutorial [Part 8](../tutorial/08-inspecting-and-tracing.md), first plain, +then with the trace of one firing rate highlighted. Its path stops at `rates`: the grouping +after it is dimmed. That rate reused the result an equal input had computed, so `rates` is +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 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, captioned "highlighted: why record row_48 of units is missing at node imec0_rates: ...": the source units, Filter_2, 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 +`ValueError`. + +## Known limits + +- Job nodes only. A plain stream keeps no stored records, so it cannot be traced this way. +- A source is never read. A source cell is known from the token of the row read from + it, with the value that row holds. Some sources keep their rows in memory: the + in-memory, file and database sources, when their class does not change how they + read. Their rows are also compared with what the run held, and a disagreement raises + `ProvenanceInconsistencyError`. Other sources (cached, polling, derived and your own) + are not read: + - a step that needs their rows is reported with status `unavailable`, such as a + `GroupBy` whose input is the source itself; + - `why_missing` does not blame the first step after them, since it cannot tell + whether the source holds the record. +- A link is never guessed. Two rows that cannot be told apart by their system tags, + tokens and values are refused with `ProvenanceInconsistencyError`. +- Inputs of a commutative `Join` with one pipeline hash are told apart by the values + they hold. Such inputs are two sources of one schema, or two upstream joins whose + outputs share a pipeline hash. When two such upstream joins hold their sources in + opposite orders, no assignment of the values fits, and the trace refuses the link + rather than guess. `why_missing`'s stored answer through such tied inputs is unknown + (`reached_function` is `None`), even when their source ids differ. +- The `row` argument compares values strictly: `False` never selects `0`, and a NaN + key selects the NaN group. +- A node the trace passes must hold its run. After a full run every node does; after + `node.run()` the nodes above it do. +- Only Orcapod's own operators are followed, each by its own rule (which input column + each output column comes from). A subclass of an Orcapod operator, and an operator of + your own, may do anything: `trace` reports their links `unavailable`, and + `why_missing` past one answers `unavailable`. +- `why_missing` reads the run the job holds. With only stored entries (before a run, or + on a loaded job not yet run with `load_only=True`) it answers `not_computed`. +- A `SemiJoin`'s right input only chooses which left rows pass. Its rows never reach the + SemiJoin's output, and `why_missing` says so. +- The stored answer (`reached_function`) after a `GroupBy` or `Batch` is known only for + the groups the run holds now; otherwise it is `None`. +- When a function recomputed a lost result, its stored entries are told apart by the + run id that pipeline entries are to record (ITL-1433); until then the latest entry is + shown. diff --git a/docs/dev/scripts/provenance_diagrams.py b/docs/dev/scripts/provenance_diagrams.py new file mode 100644 index 000000000..b51dd9338 --- /dev/null +++ b/docs/dev/scripts/provenance_diagrams.py @@ -0,0 +1,149 @@ +"""Draw the provenance diagrams shown in the documentation. + +The pictures are drawn by Orcapod itself (``job.diagram(highlight=...)``) from the +tutorial's synthetic dataset (``docs/tutorial/workshop_data.py``), over the pipelines of +tutorial Part 8. Each is the diagram's standalone SVG (the image a notebook shows: on its +own white background, so it reads on a light and a dark page alike). + +Run it to rewrite the pictures after a change to the diagram:: + + uv run python docs/dev/scripts/provenance_diagrams.py + +``tests/test_docs/test_provenance_diagrams.py`` draws them again and compares them with the +committed files, so they never go stale. +""" + +from __future__ import annotations + +import base64 +import re +import sys +import tempfile +import warnings +from pathlib import Path +from typing import Any + +REPOSITORY = Path(__file__).resolve().parents[3] +TUTORIAL = REPOSITORY / "docs" / "tutorial" + +# The committed pictures, by file name (in docs/tutorial/). +PICTURES = ( + "provenance-diagram-plain.svg", + "provenance-diagram-trace.svg", + "provenance-diagram-missing-filter.svg", + "provenance-diagram-missing-join.svg", +) + +_IMAGE = re.compile( + r']* src="data:image/svg\+xml;base64,([^"]+)"' +) + + +def _standalone_svg(diagram: object) -> str: + """The standalone SVG of a diagram: the picture its notebook display shows.""" + html = diagram.to_html() # pyright: ignore[reportAttributeAccessIssue] + match = _IMAGE.search(html) + if match is None: + raise RuntimeError("the diagram's HTML holds no picture") + return base64.b64decode(match.group(1)).decode("utf-8") + "\n" + + +def render() -> dict[str, str]: + """Draw every picture. + + Returns: + The SVG text of each picture, by file name. + """ + sys.path.insert(0, str(TUTORIAL)) + from workshop_data import make_dataset # pyright: ignore[reportMissingImports] + + from orcapod import PipelineJob, function_pod + from orcapod.databases import InMemoryArrowDatabase + from orcapod.sources import CSVSource + from orcapod.types import col + + @function_pod(output_keys="rate_hz") + def firing_rate(n_spikes: int, duration_s: float) -> float: + return n_spikes / duration_s + + @function_pod(output_keys="mean_rate_hz") + def mean_rate(rate_hz: list[float]) -> float: + return sum(rate_hz) / len(rate_hz) + + with tempfile.TemporaryDirectory() as folder, warnings.catch_warnings(): + warnings.simplefilter("ignore") + data_dir = make_dataset(Path(folder)) + database = InMemoryArrowDatabase() + + def units() -> CSVSource: + return CSVSource( + str(data_dir / "units.csv"), + tag_columns=["subject_id", "session", "probe", "unit"], + tag_only_columns=True, + source_id="units", + ) + + def sessions() -> CSVSource: + return CSVSource( + str(data_dir / "sessions.csv"), + tag_columns=["subject_id", "session"], + tag_only_columns=True, + source_id="sessions", + ) + + job = PipelineJob(name="workshop", database=database) + with job: + # As in the tutorial: a stream method (StreamProtocol does not declare it). + rates: Any = firing_rate.pod( + units().select_data_columns(["n_spikes"]), + sessions().select_data_columns(["duration_s"]), + label="rates", + ) + mean_rate.pod( + rates.group_by(["subject_id", "session"]).select_data_columns( + ["rate_hz"] + ), + label="session_means", + ) + _ = job.run() + # One firing rate: its path covers the sources, the Join and rates, not the + # grouping after them; its result was reused (an equal input computed it). + trace = job.nodes["rates"].trace( + {"subject_id": "mouse_02", "session": "s1", "probe": "imec1", "unit": 2}, + "rate_hz", + ) + + imec0 = PipelineJob(name="imec0", database=database) + with imec0: + firing_rate.pod( + units().filter({"probe": "imec0"}).select_data_columns(["n_spikes"]), + sessions() + .filter(col("subject_id") != "mouse_04") + .select_data_columns(["duration_s"]), + label="imec0_rates", + ) + _ = imec0.run() + node = imec0.nodes["imec0_rates"] + return { + "provenance-diagram-plain.svg": _standalone_svg(job.diagram()), + "provenance-diagram-trace.svg": _standalone_svg( + job.diagram(highlight=trace.highlight()) + ), + "provenance-diagram-missing-filter.svg": _standalone_svg( + imec0.diagram(highlight=node.why_missing("units", "row_4").highlight()) + ), + "provenance-diagram-missing-join.svg": _standalone_svg( + imec0.diagram(highlight=node.why_missing("units", "row_48").highlight()) + ), + } + + +def main() -> None: + """Write every picture into docs/tutorial/.""" + for name, svg in render().items(): + (TUTORIAL / name).write_text(svg, encoding="utf-8") + print(f"wrote docs/tutorial/{name}") + + +if __name__ == "__main__": + main() diff --git a/docs/tutorial/08-inspecting-and-tracing.md b/docs/tutorial/08-inspecting-and-tracing.md index d57818836..939ee748b 100644 --- a/docs/tutorial/08-inspecting-and-tracing.md +++ b/docs/tutorial/08-inspecting-and-tracing.md @@ -7,6 +7,7 @@ keeps the answers. This part shows where to find them. You will: - walk backwards from a result to the sources it came from +- trace one value to the source cells it was made from, and find why a row is missing - reveal the provenance columns that every stream carries - read the record Orcapod keeps of each function call - start a second pipeline from the stored results of the first @@ -135,9 +136,8 @@ Two system-tag columns, because two sources feed `rates`; every row depends on o `sessions` and one row of `units`. The column names end in a long hash that identifies the source's position in the pipeline, which is why the sample selects them by prefix. -The companion `_tag_record_id::...` columns identify the individual source row. They hold -compact binary identifiers that Orcapod uses internally to tell rows apart; they are not -meant to be read by eye. +The companion `_tag_record_id::...` columns identify the individual source row, as text: +`row_5` for the sixth row, or the values of the source's key columns when it has some. !!! note "After `group_by`" A grouped row comes from many source rows. Its system tags are folded into a single @@ -200,6 +200,239 @@ They answer different questions. After the "two more units" run of Part 6, a job over the original file, once run, has 64 rows in `as_table()`, while `get_all_records()` has 66. +## Tracing one value to its sources + +The columns above hold every link from a result back to its sources. `trace` follows them +for you, for one cell: give the node, the tags of the row and the column. + +```python +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, run ..., recorded ... +# 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) +# [0] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=0): rate_hz = 4.791666666666667 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_40 n_spikes = 575 (via Join, SelectDataColumns) +# [1] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=1): rate_hz = 5.058333333333334 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_41 n_spikes = 607 (via Join, SelectDataColumns) +# [2] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=2): rate_hz = 7.366666666666666 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_42 n_spikes = 884 (via Join, SelectDataColumns) +# [3] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=3): rate_hz = 4.683333333333334 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_43 n_spikes = 562 (via Join, SelectDataColumns) +# [4] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=0): rate_hz = 5.0 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_44 n_spikes = 600 (via Join, SelectDataColumns) +# [5] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=1): rate_hz = 3.3333333333333335 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_45 n_spikes = 400 (via Join, SelectDataColumns) +# [6] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=2): rate_hz = 6.916666666666667 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_46 n_spikes = 830 (via Join, SelectDataColumns) +# [7] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=3): rate_hz = 3.325 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_47 n_spikes = 399 (via Join, SelectDataColumns) +``` + +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, and the job run that +recorded the entry, with when). 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 +after `via`. + +Each step is found from what the job holds and stores, not guessed: + +- A function's row is matched to its stored record (Part 8, "How was it computed?") by + its system tags, the hidden tags that name the source rows it came from. +- The members of a group are the rows before the grouping with the group's + `subject_id` and `session`, in `probe`, `unit` order (Part 4). Orcapod checks them + against the group's folded system tags and raises an error if they do not agree. +- The last step reads the source-info columns: `csv_v1:units row_40` is row 40 of the + source named `units` (its id names the kind of reader, a CSV file read by version 1, + then its name). + +Nothing is computed: the trace only reads. + +`source_cells()` lists the source cells alone, each once: + +```python +for cell in trace.source_cells(): + print(cell.text()) +# csv_v1:sessions row_5 duration_s = 120.0 +# csv_v1:units row_40 n_spikes = 575 +# csv_v1:units row_41 n_spikes = 607 +# csv_v1:units row_42 n_spikes = 884 +# csv_v1:units row_43 n_spikes = 562 +# csv_v1:units row_44 n_spikes = 600 +# csv_v1:units row_45 n_spikes = 400 +# csv_v1:units row_46 n_spikes = 830 +# csv_v1:units row_47 n_spikes = 399 +``` + +**Computed here, or reused.** In session `s1` of `mouse_02`, two units have the same spike +count, so `firing_rate` received equal inputs twice and ran once (the "63 of 64" above). +The trace still tells the two units apart, and says which of them computed the result and +which reused it: + +```python +shared = means.trace({"subject_id": "mouse_02", "session": "s1"}, "mean_rate_hz") +for step in shared.root.walk(): + if step.node == "rates": + tags = dict(step.tags) + print(tags["probe"], tags["unit"], step.function.computed_here) +# imec0 0 True +# imec0 1 True +# imec0 2 True +# imec0 3 True +# imec1 0 True +# imec1 1 True +# imec1 2 False +# imec1 3 True +``` + +`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 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 mean_rate_hz at node session_means, for subject_id='mouse_03', session='s2': 1 row matches +# * sessions (source · CSVSource) +# * SelectDataColumns_2 (operator) <- sessions +# * units (source · CSVSource) +# * SelectDataColumns_1 (operator) <- units +# * Join (operator) <- SelectDataColumns_2, SelectDataColumns_1 +# * rates (function pod · firing_rate) [computed] <- Join +# * GroupBy (operator) <- rates +# * SelectDataColumns_3 (operator) <- GroupBy +# >* session_means (function pod · mean_rate) [computed] [traced from here] <- SelectDataColumns_3 +``` + +A mean is made through every step of the job, so its path covers the whole diagram. The +trace of one firing rate covers only part of it: the two sources, their column selections, +the join and `rates`. Take the unit that reused a stored result: + +```python +rate = job.nodes["rates"].trace( + {"subject_id": "mouse_02", "session": "s1", "probe": "imec1", "unit": 2}, "rate_hz" +) +print(job.diagram(highlight=rate.highlight())) +# Job 'workshop': 9 nodes +# 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_2 (operator) <- sessions +# * units (source · CSVSource) +# * SelectDataColumns_1 (operator) <- units +# * Join (operator) <- SelectDataColumns_2, SelectDataColumns_1 +# >* rates (function pod · firing_rate) [reused] [traced from here] <- Join +# GroupBy (operator) <- rates +# SelectDataColumns_3 (operator) <- GroupBy +# session_means (function pod · mean_rate) <- SelectDataColumns_3 +``` + +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 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 +`mouse_04`. Neither has a firing rate. `why_missing` says which step removed each: + +```python +from orcapod.types import col + +imec0 = PipelineJob(name="imec0", database=database) +with imec0: + units = CSVSource( + str(data_dir / "units.csv"), + tag_columns=["subject_id", "session", "probe", "unit"], tag_only_columns=True, + source_id="units", + ) + sessions = CSVSource( + str(data_dir / "sessions.csv"), + tag_columns=["subject_id", "session"], tag_only_columns=True, + source_id="sessions", + ) + firing_rate.pod( + units.filter({"probe": "imec0"}).select_data_columns(["n_spikes"]), + sessions.filter(col("subject_id") != "mouse_04").select_data_columns( + ["duration_s"] + ), + label="imec0_rates", + ) +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 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, 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, captioned "highlighted: why record row_4 of units is missing at node imec0_rates: ...": the source units and the node Filter_2 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, captioned "highlighted: why record row_48 of units is missing at node imec0_rates: ...": the source units, Filter_2, 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. + ## Starting a second pipeline from stored results A finished analysis is often the input of the next one. `as_source()` turns the stored @@ -259,6 +492,10 @@ result of the node, including those of earlier runs over other inputs, like values and rows came from; `all_info=True` shows everything. - `get_all_records(columns={"meta": True})` shows how and when each result was computed. - `as_table()` is the output of this job's run; `get_all_records()` is everything stored. +- `node.trace(row, column)` follows one value back to its source cells, and says which + function computed each step and whether it reused a stored result. +- `node.why_missing(source, record_id)` says which step removed a row. +- `job.diagram(highlight=...)` marks a trace's or a missing row's path. - `node.as_source()` starts a new pipeline from stored results. ## Exercises diff --git a/docs/tutorial/provenance-diagram-missing-filter.svg b/docs/tutorial/provenance-diagram-missing-filter.svg new file mode 100644 index 000000000..6244eac8a --- /dev/null +++ b/docs/tutorial/provenance-diagram-missing-filter.svg @@ -0,0 +1,24 @@ +Job 'imec0': why record row_4 of units is missing at node imec0_rates: units row_4 is removed by Filter[Filter_2]: probe='imec0'highlighted: why record row_4 of units is missing at node imec0_rates: units row_4 is removed by Filter…sessions → Filter_1Filter_1 → SelectDataColumns_2SelectDataColumns_2 → Joinunits → Filter_2Filter_2 → SelectDataColumns_1SelectDataColumns_1 → JoinJoin → imec0_ratessessions (source · CSVSource) +tags: subject_id: str, session: str +data: date: date, duration_s: floatsourceCSVSourcesessionsFilter_1 (operator) +tags: subject_id: str, session: str +data: date: date, duration_s: float +inputs: sessionsoperatorFilter_1SelectDataColumns_2 (operator) +tags: subject_id: str, session: str +data: duration_s: float +inputs: Filter_1operatorSelectDataColumns_2units (source · CSVSource) +tags: subject_id: str, session: str, probe: str, unit: int +data: region: str, depth_um: int, n_spikes: intsourceCSVSourceunitsFilter_2 (operator) +tags: subject_id: str, session: str, probe: str, unit: int +data: region: str, depth_um: int, n_spikes: int +inputs: unitsoperatorFilter_2SelectDataColumns_1 (operator) +tags: subject_id: str, session: str, probe: str, unit: int +data: n_spikes: int +inputs: Filter_2operatorSelectDataColumns_1Join (operator) +tags: subject_id: str, session: str, probe: str, unit: int +data: n_spikes: int, duration_s: float +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_rateasked hereimec0_rates diff --git a/docs/tutorial/provenance-diagram-missing-join.svg b/docs/tutorial/provenance-diagram-missing-join.svg new file mode 100644 index 000000000..7b5542b80 --- /dev/null +++ b/docs/tutorial/provenance-diagram-missing-join.svg @@ -0,0 +1,24 @@ +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_1Filter_1 → SelectDataColumns_2SelectDataColumns_2 → Joinunits → Filter_2Filter_2 → SelectDataColumns_1SelectDataColumns_1 → JoinJoin → imec0_ratessessions (source · CSVSource) +tags: subject_id: str, session: str +data: date: date, duration_s: floatsourceCSVSourcesessionsFilter_1 (operator) +tags: subject_id: str, session: str +data: date: date, duration_s: float +inputs: sessionsoperatorFilter_1SelectDataColumns_2 (operator) +tags: subject_id: str, session: str +data: duration_s: float +inputs: Filter_1operatorSelectDataColumns_2units (source · CSVSource) +tags: subject_id: str, session: str, probe: str, unit: int +data: region: str, depth_um: int, n_spikes: intsourceCSVSourceunitsFilter_2 (operator) +tags: subject_id: str, session: str, probe: str, unit: int +data: region: str, depth_um: int, n_spikes: int +inputs: unitsoperatorFilter_2SelectDataColumns_1 (operator) +tags: subject_id: str, session: str, probe: str, unit: int +data: n_spikes: int +inputs: Filter_2operatorSelectDataColumns_1Join (operator) +tags: subject_id: str, session: str, probe: str, unit: int +data: n_spikes: int, duration_s: float +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_rateasked hereimec0_rates diff --git a/docs/tutorial/provenance-diagram-plain.svg b/docs/tutorial/provenance-diagram-plain.svg new file mode 100644 index 000000000..8b82a901e --- /dev/null +++ b/docs/tutorial/provenance-diagram-plain.svg @@ -0,0 +1,28 @@ +Job 'workshop'sessions → SelectDataColumns_2SelectDataColumns_2 → Joinunits → SelectDataColumns_1SelectDataColumns_1 → JoinJoin → ratesrates → GroupByGroupBy → SelectDataColumns_3SelectDataColumns_3 → session_meanssessions (source · CSVSource · bound) +tags: subject_id: str, session: str +data: date: date, duration_s: floatsourceCSVSourceboundsessionsSelectDataColumns_2 (operator · current) +tags: subject_id: str, session: str +data: duration_s: float +inputs: sessionsoperator · currentSelectDataColumns_2units (source · CSVSource · bound) +tags: subject_id: str, session: str, probe: str, unit: int +data: region: str, depth_um: int, n_spikes: intsourceCSVSourceboundunitsSelectDataColumns_1 (operator · current) +tags: subject_id: str, session: str, probe: str, unit: int +data: n_spikes: int +inputs: unitsoperator · currentSelectDataColumns_1Join (operator · current) +tags: subject_id: str, session: str, probe: str, unit: int +data: duration_s: float, n_spikes: int +inputs: SelectDataColumns_2, SelectDataColumns_1operatorcurrentJoinrates (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) +tags: subject_id: str, session: str +data: rate_hz: list[float] +inputs: ratesoperatorcurrentGroupBySelectDataColumns_3 (operator · current) +tags: subject_id: str, session: str +data: rate_hz: list[float] +inputs: GroupByoperator · currentSelectDataColumns_3session_means (function pod · mean_rate · current) +tags: subject_id: str, session: str +data: mean_rate_hz: float +inputs: SelectDataColumns_3 +job's last run: 8 rows, 8 computedfunction podmean_ratecurrentsession_means diff --git a/docs/tutorial/provenance-diagram-trace.svg b/docs/tutorial/provenance-diagram-trace.svg new file mode 100644 index 000000000..f2703a7fd --- /dev/null +++ b/docs/tutorial/provenance-diagram-trace.svg @@ -0,0 +1,28 @@ +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_2SelectDataColumns_2 → Joinunits → SelectDataColumns_1SelectDataColumns_1 → JoinJoin → ratesrates → GroupByGroupBy → SelectDataColumns_3SelectDataColumns_3 → session_meanssessions (source · CSVSource) +tags: subject_id: str, session: str +data: date: date, duration_s: floatsourceCSVSourcesessionsSelectDataColumns_2 (operator) +tags: subject_id: str, session: str +data: duration_s: float +inputs: sessionsoperatorSelectDataColumns_2units (source · CSVSource) +tags: subject_id: str, session: str, probe: str, unit: int +data: region: str, depth_um: int, n_spikes: intsourceCSVSourceunitsSelectDataColumns_1 (operator) +tags: subject_id: str, session: str, probe: str, unit: int +data: n_spikes: int +inputs: unitsoperatorSelectDataColumns_1Join (operator) +tags: subject_id: str, session: str, probe: str, unit: int +data: duration_s: float, n_spikes: int +inputs: SelectDataColumns_2, SelectDataColumns_1operatorJoinrates (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_ratereusedtraced from hereratesGroupBy (operator) +tags: subject_id: str, session: str +data: rate_hz: list[float] +inputs: ratesoperatorGroupBySelectDataColumns_3 (operator) +tags: subject_id: str, session: str +data: rate_hz: list[float] +inputs: GroupByoperatorSelectDataColumns_3session_means (function pod · mean_rate) +tags: subject_id: str, session: str +data: mean_rate_hz: float +inputs: SelectDataColumns_3 +job's last run: 8 rows, 8 computedfunction podmean_ratesession_means diff --git a/site/astro.config.mjs b/site/astro.config.mjs index e8407a005..8a5ac5f1b 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -127,6 +127,7 @@ export default defineConfig({ page('Function Pods', 'concepts/function-pods'), page('Data-tags', 'concepts/data-tags'), page('Pipelines and Jobs', 'concepts/pipeline-job'), + page('Provenance', 'concepts/provenance'), page('Working in Notebooks', 'concepts/notebooks'), page('Your Own Data Types', 'concepts/your-own-data-types'), page('Arrays and Tensors', 'concepts/arrays'), diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index aa717af68..9a0353053 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -24,7 +24,7 @@ import uuid from abc import abstractmethod from collections import Counter -from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from collections.abc import Callable, Iterator, Mapping, Sequence from datetime import datetime, timezone from functools import partial from typing import Any, Literal, NamedTuple, cast @@ -33,6 +33,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, @@ -1400,7 +1401,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 @@ -1429,6 +1430,9 @@ class FunctionJobNode(RunHoldingNode, FunctionNodeBase): # its number of inputs; None when no run completed (ITL-1093). A class default so # nodes rebuilt from a saved descriptor start without a run. _run_entry_counts: Counter[bytes] | None = None + # The same base entry ids in the order the run emitted its rows (ITL-1432): the + # order the rows are held in, so a read gives them as downstream received them. + _run_entry_order: tuple[bytes, ...] = () # Whether the last completed run was load-only, and how many of its inputs had no # stored result (ITL-1095). Class defaults for nodes rebuilt from a descriptor. _run_load_only: bool = False @@ -1466,6 +1470,7 @@ def __init__( self._cached_output_table: "pa.Table | None" = None self._cached_content_hash_column: "pa.Array | None" = None self._run_entry_counts = None + self._run_entry_order = () # DB persistence state (initially None; set via __init__ params or attach_databases) self._pipeline_database: ArrowDatabaseProtocol | None = None @@ -1986,6 +1991,7 @@ def clear_cache(self) -> None: self._cached_output_table = None self._cached_content_hash_column = None self._run_entry_counts = None + self._run_entry_order = () self._run_load_only = False self._run_not_stored = 0 self._run_failed = 0 @@ -2000,20 +2006,23 @@ def _held_pairs(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: cache may hold more (results of other inputs, read from the database), which stay cached for reuse but are not rows of this run (ITL-1093). Without a completed run in this process there are no rows, whatever the cache or the database holds - (ITL-1095). Rows come in the order the cache holds them. An input without output - (an inactive function) is not a row. + (ITL-1095). Rows come in the order the run passed them downstream, a stored + result and a computed one alike, one row per input (a repeated input's row at + each of its places), so every read (``iter_data``, ``as_table``, ``head``, the + data frames, a downstream node's own ``run()``) gives what downstream received + (ITL-1441). A synchronous run passes them in input order, also over a partly + stored history, load-only (the stored inputs) and after ``clear_cache()``. An + asynchronous run promises no order (ITL-1437): its rows are held in the order + that run emitted them. An input without output (an inactive function) is not a + row. """ - counts = self._run_entry_counts - if counts is None: + if self._run_entry_counts is None: return - pairs: Iterable[tuple[TagProtocol, DataProtocol | None]] = ( - pair - for eid, pair in self._cached_output_datas.items() - for _ in range(counts.get(eid, 0)) - ) - for tag, data in pairs: - if data is not None: - yield tag, data + cache = self._cached_output_datas + for eid in self._run_entry_order: + pair = cache.get(eid) + if pair is not None and pair[1] is not None: + yield pair[0], pair[1] def _set_run_rows( self, @@ -2026,12 +2035,14 @@ def _set_run_rows( """Make the inputs of a completed run, by base entry id, the rows this node holds. Args: - entry_ids: The base entry ids of the run's inputs whose rows the node holds. + entry_ids: The base entry ids of the run's inputs whose rows the node holds, + in the order the run emitted them. load_only: Whether the run was load-only (ITL-1095). not_stored: How many inputs of a load-only run had no stored result. failed: How many rows of the run failed (error policy ``"continue"``). """ self._run_entry_counts = Counter(entry_ids) + self._run_entry_order = tuple(entry_ids) self._run_load_only = load_only self._run_not_stored = not_stored self._run_failed = failed @@ -3520,6 +3531,93 @@ def as_source( # Cache-only helpers (PLT-1156) # ------------------------------------------------------------------ + def _stored_provenance( + self, *, results: bool = True + ) -> 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. Each table read is first refreshed to the + store's current version, and only the tables read (``results=False`` touches no + result table). Nothing is computed or written. + + Args: + results: Whether to read the result tables too; ``False`` reads the pipeline + entries only (a question about which inputs reached the function). + + 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 + # A read of what is stored: the store's current version (ITL-1408), of each + # table this read fetches and of no other (entries only: no result table). + self._pipeline_database.refresh_table(self._versioned_pipeline_path) + 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) + if not results: + return entries, None + found: list[pa.Table] = [] + places: list[tuple[ArrowDatabaseProtocol, tuple[str, ...]]] = [ + ( + self._cached_function_pod.result_database, + self._cached_function_pod.record_path, + ) + ] + if self._ephemeral_cached_pod is not None: + places.append( + ( + self._ephemeral_cached_pod.result_database, + self._ephemeral_cached_pod.record_path, + ) + ) + elif self.ephemeral_result_database is not None: + # A loaded node has no pod to build an ephemeral cached pod from; its + # results are at the same path in the ephemeral database. + places.append( + (self.ephemeral_result_database, self._cached_function_pod.record_path) + ) + for database, path in places: + database.refresh_table(path) + stored = database.get_all_records( + path, record_id_column=constants.DATA_RECORD_ID + ) + if stored is not None: + found.append(keep_rows_of_data_context(stored, context_key)) + result_table = ( + None + if not found + else found[0] + if len(found) == 1 + else pa.concat_tables(found, promote_options="default") + ) + return entries, result_table + def _fetch_joined_records( self, base_entry_ids: list[bytes] | None = None, @@ -4492,8 +4590,11 @@ async def route_inputs() -> None: ctx_obs.on_data_end( node_label, tag, data, cached_data, cached=True ) - run_entry_ids.append(base_entry_id) await output.send((cached_tag, cached_data)) + # Recorded once the output took the row, so the held + # order is the order downstream received (a parked + # send can resume after a later one). + run_entry_ids.append(base_entry_id) else: self._preflight_pipeline_write_schema() correlation_key = uuid.uuid4().bytes @@ -4568,8 +4669,9 @@ async def record_and_forward() -> None: # Commits every commit_every_rows rows inside a job (ITL-919); # no await in between, so no other row interleaves. self._row_processed() - run_entry_ids.append(base_entry_id) await output.send((clean_tag, output_data)) + # Recorded once the output took the row (see route_inputs). + run_entry_ids.append(base_entry_id) # Capture outer self so _NodeLabelObserver methods can # update FunctionJobNode state without shadowing with 'self'. diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 03830d22a..b2134184a 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..dee6c1798 --- /dev/null +++ b/src/orcapod/core/nodes/provenance_methods.py @@ -0,0 +1,93 @@ +"""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 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). + + 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 selecting the rows to trace, usually tags: + ``{"subject_id": "mouse_03", "session": "s2"}``. + column: The data column of the cells. + + Returns: + 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. Both are checked against the + rows this node holds: when it holds no run (``not_computed``) there is + nothing to check against, and neither is checked. + 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. + + 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). + + It reads the run the job holds (``not_computed`` without one, even when the + store holds entries). From the rows the nodes hold: the nodes that hold a row + from the record, and the step that removed it, in ``explain()``'s words; for a + join, the key missing from the other input. From the first function node's + stored entries: a stored entry proves the record reached it + (``reached_function``); no entry proves nothing (a function that raised stores + none), so the answer is then unknown, and ``entry_recorded`` says what the store + holds. Past an operator that is not one of Orcapod's own (a subclass, or your + own), the answer is ``unavailable``. + + Args: + source: The source: its node's label, its name or its full id (as in + source-info tokens, ``dict_v1:trials``). It must name one source. + 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. For a source node whose rows are not read, its status is + ``"unavailable"`` and the source id or label is not checked. + + Raises: + ValueError: If no source with that label, name or id feeds this node + (unless this node is a source whose rows are not read), or if it names + several (one's name is another's id): give a node label or full id + that names one. + 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 abb112f5d..e2b83b4e0 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 @@ -1550,7 +1551,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..acce7333c 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -500,6 +500,99 @@ 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]: + """The scalar value of key ``c`` per group: the representative member's.""" + # 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 fold of system-tag column ``c`` per group, over the members in order.""" + # 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 +667,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 2cd0e61dd..e0a6942ee 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1236,3 +1236,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 0e6ee4606..966809d94 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") @@ -385,6 +386,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. @@ -404,17 +406,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..08525ecc9 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,9 @@ class _Node: data_schema: tuple[tuple[str, str], ...] status: str facts: tuple[tuple[str, str], ...] + highlighted: bool = False + mark: str = "" + asked: str = "" @property def kind_line(self) -> str: @@ -97,6 +101,7 @@ class _Edge: source: int target: int folded: tuple[str, ...] = () + highlighted: bool = False # --------------------------------------------------------------------------- @@ -275,7 +280,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 +294,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. @@ -313,6 +324,18 @@ def _build_model( for label, node in by_label.items() if _collapsible(node) and len(succs[label]) == 1 } + if highlight is not None: + # The node the question was asked at is always shown, and so is a + # highlighted node no highlighted edge leaves (where a path ends, such as + # the step that removed a record): folded, its emphasis would be lost. + # The edge decides, not the successor: a highlighted successor reached by + # an edge that is not highlighted does not carry the path on. + folded.discard(highlight.asked) + folded -= { + label + for label in highlight.nodes + if not any((label, s) in highlight.edges for s in succs.get(label, ())) + } shown = [ label for label in _topological_labels(preds, succs) if label not in folded @@ -370,12 +393,47 @@ 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 "", ) ) + + def lit(source: int, target: int, via: tuple[str, ...]) -> bool: + """Whether a displayed edge is emphasized: some highlighted path leads from + its start to its end through the steps folded into it (several folded paths + merge into one displayed edge, so their labels are not one chain).""" + if highlight is None: + return False + start, end = shown[source], shown[target] + if not via: + return (start, end) in highlight.edges + inner = set(via) + frontier, seen = [start], {start} + while frontier: + current = frontier.pop() + for upstream, downstream in highlight.edges: + if upstream != current: + continue + if downstream == end: + return True + if downstream in inner and downstream not in seen: + seen.add(downstream) + frontier.append(downstream) + return False + 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 @@ -426,7 +484,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, node.asked] text = max( len(node.label) * _CHAR_W, max(len(part) for part in parts) * _SMALL_CHAR_W ) @@ -448,6 +506,12 @@ 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) + if node.asked: + # The node the question was asked at ("traced from here"), on its own line. + lines.append(node.asked) return tuple(lines) @@ -672,6 +736,19 @@ 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 = "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]: + """The edges a layout draws.""" + return [edge for edge, _ in layout.edges] + + _KIND_COLOUR: dict[str, str] = { "source": "#2e9e5b", "operator": "#d08a16", @@ -773,6 +850,7 @@ def _svg( layout: _Layout, across: bool, standalone: bool, + caption: str = "", ) -> str: """The SVG picture; complete without any style sheet or script. @@ -786,11 +864,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'' ) + 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 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( '' + f'stroke-opacity="{"0.3" if lit else "0.5"}" stroke-width="1.4">' ) for edge, points in layout.edges: tip = f"{nodes[edge.source].label} → {nodes[edge.target].label}" 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,15 +933,32 @@ 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 = "" + 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" + stroke = _HIGHLIGHT_COLOUR + elif lit and not node.asked: + emphasis = '" opacity="0.4' parts.append( - f'' f"{_escape(_tooltip(node, inputs.get(node.index, ())))}" 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 + 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( @@ -867,7 +992,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) @@ -1026,10 +1151,16 @@ 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()``): 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"``, 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 +1171,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 +1183,38 @@ 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), + *(label for label, _ in highlight.marks), + *((highlight.asked,) if highlight.asked else ()), + } + - 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 +1245,28 @@ 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 + 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 + + 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 +1298,28 @@ def to_text(self) -> str: Returns: A title line, then ``