From dedf532501e98754074216d5abd17fb22404047f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 17:35:18 -0800 Subject: [PATCH 1/5] feat(view): the preview tells a plain tag from a data-tag (ITL-1304) A StreamView learns which of its tag columns are data-tags (data_tag_columns, from the stream's public keys()) wherever it is built. The display gives a data-tag its own role (developer, November 21, 2026: option A with an underline): bold and underlined in the accent colour in the notebook preview, a "+" prefix in the text preview, with a legend naming only the marks shown. Only the display is marked. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1304.md | 15 + docs/concepts/data-tags.md | 25 +- docs/concepts/notebooks.md | 35 +- docs/concepts/streams.md | 12 +- src/orcapod/core/streams/view.py | 98 ++- .../streams/test_data_tag_preview.py | 607 ++++++++++++++++++ 6 files changed, 757 insertions(+), 35 deletions(-) create mode 100644 changelog.d/ITL-1304.md create mode 100644 tests/test_core/streams/test_data_tag_preview.py diff --git a/changelog.d/ITL-1304.md b/changelog.d/ITL-1304.md new file mode 100644 index 000000000..a4c44dcd1 --- /dev/null +++ b/changelog.d/ITL-1304.md @@ -0,0 +1,15 @@ +### Changed + +- The preview tells a plain tag from a data-tag (ITL-1304). A data-tag (one column that is + both a tag and the data column of the same name) is still shown once, among the tags, in + tag order, but with its own mark: in the notebook (HTML) preview its header is bold and + underlined in the accent colour (a plain tag's stays bold), and in the text preview its name + starts with `+` (a plain tag's with `*`). The legend line names exactly the marks shown: + "bold = tag; bold underlined = data-tag (a tag that is also data)" in a notebook, + "* = tag; + = data-tag (tag and data)" as text, each part only when such a column is + shown. It holds for every view: `head()`, `tail()`, `sort_by_tags()`, `run()`, the + notebook preview and the text form, of a source, a stream, an operator or function pod + result and a job node, loaded jobs included. A `StreamView` has a new field, + `data_tag_columns`, taken from the stream's `keys()`. Only the display is marked: the + view's `table`, `as_table()`, the data frames and every schema, hash and stored form are + unchanged. diff --git a/docs/concepts/data-tags.md b/docs/concepts/data-tags.md index 501a24f58..3a5917d02 100644 --- a/docs/concepts/data-tags.md +++ b/docs/concepts/data-tags.md @@ -37,8 +37,29 @@ not a declared tag is an error. A source built with all its tags plain is exactl source v0.3 built: same columns, same hashes. The column is stored once: `as_table()` shows it once, and every row's tag and data hold -the same value. The notebook preview shows it once, among the tags, marked as a tag -([Working in notebooks](notebooks.md#a-stream-at-the-end-of-a-cell)). +the same value. The preview shows it once, among the tags, marked as a data-tag: in a +notebook its header is bold and underlined (a plain tag's is bold), and as text its name starts +with `+` (a plain tag's with `*`). The legend line names the marks shown +([Working in notebooks](notebooks.md#a-stream-at-the-end-of-a-cell)). Only the display is +marked: the view's table and `as_table()` keep the plain names. + +```python +mixed = op.sources.DictSource( + rows, tag_columns=["unit", "time"], tag_only_columns=["time"], source_id="spikes" +) +print(mixed.head()) +# DictSource[spikes] — all 2 rows +# * = tag; + = data-tag (tag and data) +# shape: (2, 3) +# ┌───────┬───────┬──────┐ +# │ +unit ┆ *time ┆ amp │ +# │ --- ┆ --- ┆ --- │ +# │ i64 ┆ i64 ┆ f64 │ +# ╞═══════╪═══════╪══════╡ +# │ 1 ┆ 10 ┆ 0.5 │ +# │ 2 ┆ 20 ┆ 0.25 │ +# └───────┴───────┴──────┘ +``` Data-tags come first among the data columns, in tag order, then the other data columns in their table order. Every stream, operator result and row follows this order, whatever the diff --git a/docs/concepts/notebooks.md b/docs/concepts/notebooks.md index f44532a04..3ec106ee3 100644 --- a/docs/concepts/notebooks.md +++ b/docs/concepts/notebooks.md @@ -72,8 +72,10 @@ What it shows ([Looking at data](streams.md#looking-at-data) states each rule in 63,349"). - **Tag columns** come first and are marked: in a notebook their headers are bold (in an accent colour), a vertical rule separates them from the data columns and a line under the - header says "bold = tag". A [data-tag](data-tags.md) is one column: the notebook preview - shows it once, among the tags, marked as a tag. + header says "bold = tag". A [data-tag](data-tags.md) is one column: the preview shows + it once, among the tags, with its header bold and underlined, and the line says + "bold underlined = data-tag (a tag that is also data)". The line names only the marks + shown: the tags of `units` are all plain. - **Large cells** are summarised (an array as `ndarray float64 (2, 3)`, bytes as `bytes (300 B)`, long text and long lists shortened); `head().table` keeps the full values. @@ -83,8 +85,9 @@ what is held or stored, or make a bounded table read), never call your code (a f predicate, a side effect) and never write to a database. So a job node shown before the job has run has no rows: its header says `not run`, and the table shows its columns only. -In a terminal, `print(stream.head())` prints the same preview as text. There, each tag -column's name starts with `*` ("* = tag"): +In a terminal, `print(stream.head())` prints the same preview as text. There, each plain tag +column's name starts with `*` ("* = tag"), and each data-tag's with `+` +("+ = data-tag (tag and data)"): ```python print(units.head(3)) @@ -112,6 +115,30 @@ print(job.nodes["rates"].head()) # └─────────────┴──────────┴────────┴───────┴─────────┘ ``` +The same table read with `probe` and `unit` as data-tags (only `subject_id` and `session` +kept plain) marks the two kinds of tag apart: + +```python +units_by_probe = CSVSource( + str(data_dir / "units.csv"), + tag_columns=["subject_id", "session", "probe", "unit"], + tag_only_columns=["subject_id", "session"], + source_id="units", +) +print(units_by_probe.head(2)) +# CSVSource[units] — first 2 of 64 rows +# * = tag; + = data-tag (tag and data) +# shape: (2, 7) +# ┌─────────────┬──────────┬────────┬───────┬────────┬──────────┬──────────┐ +# │ *subject_id ┆ *session ┆ +probe ┆ +unit ┆ region ┆ depth_um ┆ n_spikes │ +# │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ +# │ str ┆ str ┆ str ┆ i64 ┆ str ┆ i64 ┆ i64 │ +# ╞═════════════╪══════════╪════════╪═══════╪════════╪══════════╪══════════╡ +# │ mouse_01 ┆ s1 ┆ imec0 ┆ 0 ┆ V1 ┆ 1580 ┆ 149 │ +# │ mouse_01 ┆ s1 ┆ imec0 ┆ 1 ┆ V1 ┆ 2560 ┆ 326 │ +# └─────────────┴──────────┴────────┴───────┴────────┴──────────┴──────────┘ +``` + (`head()` does not sort, so its header does not say `sorted by tags`; the preview asks for the sorted head.) What each kind of object shows before and after it is computed (a source, a computed stream, a job node, a side-effect node) is the table "What each kind of object diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 7487ae670..6b131351f 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -283,10 +283,14 @@ the stream's results: each row is computed once and every read yields the same r feeds the stream. An upstream finishing its first computation during the read is not a change; a `clear_cache()` upstream between the reads is, and the next read starts again. -The display marks the tag columns, which come first: in a notebook their headers are bold -(in an accent colour), a vertical rule separates them from the data columns and a line under -the header says "bold = tag"; as text, each tag column's name starts with `*` ("* = tag"). -Only the display is marked: the view's table and `as_table()` keep the plain names. +The display marks the tag columns, which come first, in tag order: in a notebook their +headers are bold (in an accent colour), a vertical rule separates them from the data columns +and a line under the header names each mark shown, "bold = tag" for a plain tag and +"bold underlined = data-tag (a tag that is also data)" for a [data-tag](data-tags.md), whose +header is bold and underlined. A data-tag is one column, shown once, among the tags. As text, a +plain tag's name starts with `*` ("* = tag") and a data-tag's with `+` +("+ = data-tag (tag and data)"). Only the display is marked: the view's table and +`as_table()` keep the plain names. In the preview, large cells are summarised (an array as `ndarray float64 (2, 3)`, bytes as `bytes (300 B)`, long text and long lists shortened); `head().table` keeps the full values. diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index 9388afedd..8dbf347a8 100644 --- a/src/orcapod/core/streams/view.py +++ b/src/orcapod/core/streams/view.py @@ -136,30 +136,44 @@ class ColumnRoleMark: html_style: Inline CSS of the column's header cell in the HTML display. text_legend: The legend line of the text display naming this mark, or empty. html_legend: The legend line of the HTML display naming this mark, or empty. + group: The group of columns the role is shown in: the HTML display draws its + rule between two groups, never between two roles of one group. """ text_prefix: str = "" html_style: str = "" text_legend: str = "" html_legend: str = "" + group: str = "" # The one place that says how the display marks each column role (developer, November 13, -# 2026, ITL-1081). Roles today: "tag" and "data". A new role (e.g. a data-tag) gets -# its own entry here; the renderers need no change. The accent colour has a contrast of -# about 4.3:1 on white and on #111; bold carries the meaning without the colour. +# 2026, ITL-1081; the data-tag, ITL-1304). Roles: "tag" (a plain tag), "data-tag" (a tag +# that is also the data column of the same name, shown once) and "data". The renderers +# read only this table. The accent colour has a contrast of about 4.3:1 on white and on +# #111; bold (and the underline of a data-tag) carries the meaning without the colour. The +# legend names the marks shown, in this table's order. COLUMN_ROLE_MARKS: dict[str, ColumnRoleMark] = { "tag": ColumnRoleMark( text_prefix="*", html_style="font-weight:bold;color:#2a7fb8", text_legend="* = tag", html_legend="bold = tag", + group="tags", ), - "data": ColumnRoleMark(), + "data-tag": ColumnRoleMark( + text_prefix="+", + html_style="font-weight:bold;text-decoration:underline;color:#2a7fb8", + text_legend="+ = data-tag (tag and data)", + html_legend="bold underlined = data-tag (a tag that is also data)", + group="tags", + ), + "data": ColumnRoleMark(group="data"), } -# The HTML display draws this rule after the last column of each role, on every row, so -# the table reads "tags | data". It takes the text colour, so it reads on any theme. +# The HTML display draws this rule after the last column of each group of roles, on every +# row, so the table reads "tags | data". It takes the text colour, so it reads on any +# theme. ROLE_BOUNDARY_STYLE = "border-right:2px solid currentColor" @@ -186,6 +200,8 @@ class StreamView: label: The name shown for it: its label, or for a source given no label its source id (``display_name``). Never used as an identity. tag_columns: The columns of ``table`` that are tags. + data_tag_columns: The columns of ``tag_columns`` that are data-tags: each is also + a data column of the stream (``data_tags_of``). Only the display marks them. total_rows: The stream's row count when it is known without computing, else ``None``. For ``PARTIAL``, the number of rows computed so far. total_is_estimate: ``True`` when ``total_rows`` is a recorded estimate. @@ -219,6 +235,7 @@ class StreamView: kind: str label: str tag_columns: tuple[str, ...] = () + data_tag_columns: tuple[str, ...] = () total_rows: int | None = None total_is_estimate: bool = False origin: str = "held" @@ -245,13 +262,15 @@ def of_rows( description: str | None = None, display_all_rows: bool = True, ) -> StreamView: - """Return a view with rows of ``stream``.""" + """Return a view with rows of ``stream``; its data-tags are ``data_tags_of``.""" + tags = tuple(c for c in tag_columns if c in table.column_names) return cls( table=table, status=status, kind=type(stream).__name__, label=display_name(stream), - tag_columns=tuple(c for c in tag_columns if c in table.column_names), + tag_columns=tags, + data_tag_columns=data_tags_of(stream, tags), total_rows=total_rows, total_is_estimate=total_is_estimate, origin=origin, @@ -270,13 +289,16 @@ def without_rows( tag_columns: tuple[str, ...], note: str | None = None, ) -> StreamView: - """Return a head of ``stream`` with no rows: ``table`` holds its columns only.""" + """Return a head of ``stream`` with no rows: ``table`` holds its columns only; + its data-tags are ``data_tags_of``.""" + tags = tuple(c for c in tag_columns if c in table.column_names) return cls( table=table.slice(0, 0), status=status, kind=type(stream).__name__, label=display_name(stream), - tag_columns=tuple(c for c in tag_columns if c in table.column_names), + tag_columns=tags, + data_tag_columns=data_tags_of(stream, tags), note=note, ) @@ -492,20 +514,22 @@ def _describe_rows(self, shown: int) -> str: return f"first {shown:,} of {total:,} {noun}{suffix}" def _display_columns(self) -> list[tuple[str, str]]: - """Return the shown columns in display order, each with its role: tags first.""" + """Return the shown columns in display order, each with its role: the tags first, + in tag order, each a ``"data-tag"`` or a plain ``"tag"``, then the data. A + data-tag is one column and is shown once, among the tags.""" tags = [c for c in self.tag_columns if c in self.table.column_names] - return [(c, "tag") for c in tags] + [ - (c, "data") for c in self.table.column_names if c not in self.tag_columns - ] + return [ + (c, "data-tag" if c in self.data_tag_columns else "tag") for c in tags + ] + [(c, "data") for c in self.table.column_names if c not in self.tag_columns] def _legend(self, text: bool) -> str: - """Return the legend line of the marks the shown columns carry, or empty.""" - roles = dict.fromkeys(role for _, role in self._display_columns()) + """Return the legend line of the marks the shown columns carry, in the order of + ``COLUMN_ROLE_MARKS``, or empty.""" + shown = {role for _, role in self._display_columns()} legends = [ - COLUMN_ROLE_MARKS[role].text_legend - if text - else COLUMN_ROLE_MARKS[role].html_legend - for role in roles + mark.text_legend if text else mark.html_legend + for role, mark in COLUMN_ROLE_MARKS.items() + if role in shown ] return "; ".join(legend for legend in legends if legend) @@ -585,7 +609,8 @@ def _repr_html_(self) -> str: def __str__(self) -> str: """Return the preview as text: header, legend and the rows, each column's - header prefixed by its role's mark (``*`` for a tag).""" + header prefixed by its role's mark (``*`` for a plain tag, ``+`` for a + data-tag).""" lines = [self.header()] legend = self._legend(text=True) if legend: @@ -608,17 +633,20 @@ def _mark_columns(frame_html: str, roles: Sequence[str]) -> str: The cells are found by position, never by name, so a name that HTML escapes is handled as Polars wrote it. The header cell of a column gets its role's - ``html_style``; every cell of the last column of a role followed by another role gets - ``ROLE_BOUNDARY_STYLE``. Everything else is passed on unchanged. + ``html_style``; every cell of the last column of a group of roles followed by another + group gets ``ROLE_BOUNDARY_STYLE``. Everything else is passed on unchanged. Args: frame_html: The HTML of the display frame, one column per entry of ``roles``. roles: The role of each column, in display order. """ header = [COLUMN_ROLE_MARKS[role].html_style for role in roles] + groups = [COLUMN_ROLE_MARKS[role].group for role in roles] boundary = [ - ROLE_BOUNDARY_STYLE if i + 1 < len(roles) and roles[i + 1] != roles[i] else "" - for i in range(len(roles)) + ROLE_BOUNDARY_STYLE + if i + 1 < len(groups) and groups[i + 1] != groups[i] + else "" + for i in range(len(groups)) ] marker = _ColumnMarker(header, boundary) marker.feed(frame_html) @@ -735,6 +763,26 @@ def display_name(stream: Any) -> str: return name +def data_tags_of(stream: Any, tag_columns: Sequence[str]) -> tuple[str, ...]: + """Return the names of ``tag_columns`` that are data-tags of ``stream``. + + A data-tag is one column in both roles: a name among both the tag and the data keys + of the stream's public ``keys()``. A view that shows tag columns has its stream's + schema already, so reading the keys computes, reads and polls nothing; a view with no + tag column (one whose schema would need a poll, ``schema_requires_io``) does not read + them. + + Args: + stream: The stream, source or node whose view is built. + tag_columns: The tag columns the view shows, in display order. + """ + if not tag_columns: + return () + tags, data = stream.keys() + both = set(tags) & set(data) + return tuple(c for c in tag_columns if c in both) + + def preview_html(stream: Any) -> str: """Return the notebook preview of ``stream``: its head with the rows in tag order. diff --git a/tests/test_core/streams/test_data_tag_preview.py b/tests/test_core/streams/test_data_tag_preview.py new file mode 100644 index 000000000..29bf9bcbf --- /dev/null +++ b/tests/test_core/streams/test_data_tag_preview.py @@ -0,0 +1,607 @@ +"""The preview tells a plain tag from a data-tag (ITL-1304). + +A data-tag is one column in both roles: a tag and the data column of the same name. Every +view of a stream knows which of its tag columns are data-tags (``data_tag_columns``, +taken from the stream's public ``keys()``), however the view is built, and only the +display marks them: never ``StreamView.table``, ``as_table()``, ``as_polars_df()`` or a +schema. Building such a view computes nothing, calls no user code and writes nothing. + +The streams here have two plain tags (``session``, ``trial``), two data-tags (``unit``, +``time``) and two data columns (``amp``, ``label``), in several tag orders and table +layouts. +""" + +from __future__ import annotations + +import csv +from html.parser import HTMLParser +from pathlib import Path +from typing import Any +from unittest import mock + +import pyarrow as pa +import pytest + +from orcapod import function_pod +from orcapod.core.operators import Join, SelectDataColumns +from orcapod.core.sources import CSVSource, DerivedSource, DictSource +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.job import PipelineJob +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator +from orcapod.side_effects import SideEffectPod +from orcapod.streams import StreamView, ViewStatus + +PLAIN = ("session", "trial") +DATA_TAGS = ("unit", "time") +DATA = ("amp", "label") + +ROWS = [ + {"session": "s2", "unit": 5, "trial": 2, "time": 31, "amp": 0.125, "label": "n"}, + {"session": "s1", "unit": 3, "trial": 1, "time": 10, "amp": 0.5, "label": "s"}, + {"session": "s2", "unit": 3, "trial": 2, "time": 20, "amp": 0.75, "label": "s"}, + {"session": "s1", "unit": 4, "trial": 1, "time": 12, "amp": 0.25, "label": "b"}, +] + +# Tag orders: plain and data-tags interleaved, data-tags first, and reversed. +TAG_ORDERS = { + "interleaved": ("session", "unit", "trial", "time"), + "data_tags_first": ("time", "unit", "trial", "session"), + "plain_first": ("trial", "session", "unit", "time"), +} +# Table layouts: data before tags, and tags in another order than declared. +LAYOUTS = { + "data_first": ("label", "amp", "time", "trial", "unit", "session"), + "tags_first": ("unit", "session", "time", "trial", "amp", "label"), +} + +ORCHESTRATORS = { + "sync": SyncPipelineOrchestrator, + "async": AsyncPipelineOrchestrator, +} + +CALLS: list[float] = [] + + +@pytest.fixture(autouse=True) +def _reset_calls() -> None: + """Clear the record of function calls before each test.""" + CALLS.clear() + + +@function_pod(output_keys="scaled") +def scale(amp: float) -> float: + """Double ``amp``, recording the call.""" + CALLS.append(amp) + return 2 * amp + + +def _rows(layout: tuple[str, ...]) -> list[dict[str, Any]]: + return [{name: row[name] for name in layout} for row in ROWS] + + +def _source( + tag_order: tuple[str, ...] = TAG_ORDERS["interleaved"], + layout: tuple[str, ...] = LAYOUTS["data_first"], + plain: tuple[str, ...] = PLAIN, +) -> DictSource: + """Four rows with two plain tags, two data-tags and two data columns.""" + return DictSource( + _rows(layout), + tag_columns=list(tag_order), + tag_only_columns=list(plain), + source_id="spikes", + label="spikes", + ) + + +def _expected(tag_order: tuple[str, ...]) -> tuple[str, ...]: + """The data-tags of ``_source(tag_order)``, in tag order.""" + return tuple(c for c in tag_order if c in DATA_TAGS) + + +def _data_tags_of(stream: Any) -> tuple[str, ...]: + """The data-tags ``stream`` declares, in its own tag order; both of ``DATA_TAGS``.""" + tags, data = stream.keys() + found = tuple(c for c in tags if c in data) + assert sorted(found) == sorted(DATA_TAGS) + return found + + +def _in_view_order(view: StreamView) -> tuple[str, ...]: + """``DATA_TAGS`` in the order ``view`` shows its tags (which column order a view + shows is ITL-1305); checks the view shows both.""" + found = tuple(c for c in view.tag_columns if c in DATA_TAGS) + assert sorted(found) == sorted(DATA_TAGS) + return found + + +def _view(view: object) -> StreamView: + """``view`` as the ``StreamView`` every stream's ``head`` and ``run`` return.""" + assert isinstance(view, StreamView) + return view + + +def _views(view: object) -> dict[str, StreamView]: + """Every view a view builds of its own rows, and views of those views.""" + view = _view(view) + return { + "view": view, + "head": view.head(2), + "tail": view.tail(2), + "sorted": view.sort_by_tags(), + "head_of_tail": view.tail(3).head(1), + "sorted_head": view.head(3).sort_by_tags(), + } + + +# --------------------------------------------------------------------------- +# Every way a view is built knows the data-tags +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("layout", list(LAYOUTS)) +@pytest.mark.parametrize("tag_order", list(TAG_ORDERS)) +def test_every_view_of_a_source_knows_its_data_tags( + tag_order: str, layout: str +) -> None: + """head, run and the view's own head, tail and sort all carry the data-tags.""" + source = _source(TAG_ORDERS[tag_order], LAYOUTS[layout]) + expected = _expected(TAG_ORDERS[tag_order]) + for built in ( + source.head(), + source.head(3), + source.head(columns={"sort_by_tags": True}), + source.run(), + ): + for name, view in _views(built).items(): + assert view.tag_columns == TAG_ORDERS[tag_order], name + assert view.data_tag_columns == expected, name + + +def test_a_raw_stream_view_knows_its_data_tags() -> None: + """A raw ``ArrowTableStream`` with ``data_tags`` marks exactly those.""" + table = pa.Table.from_pylist(_rows(LAYOUTS["tags_first"])) + for data_tags in (("unit", "time"), ("time", "unit")): + stream = ArrowTableStream( + table, tag_columns=list(TAG_ORDERS["interleaved"]), data_tags=data_tags + ) + assert stream.head().data_tag_columns == ("unit", "time") + assert stream.run().tail(1).data_tag_columns == ("unit", "time") + plain = ArrowTableStream(table, tag_columns=list(TAG_ORDERS["interleaved"])) + assert plain.head().data_tag_columns == () + + +def test_only_plain_tags_and_only_data_tags() -> None: + """All tags plain: no data-tag; no tag plain: every tag is a data-tag.""" + all_plain = _source(plain=PLAIN + DATA_TAGS) + assert all_plain.head().data_tag_columns == () + assert all_plain.run().sort_by_tags().data_tag_columns == () + none_plain = _source(plain=()) + assert none_plain.head().data_tag_columns == TAG_ORDERS["interleaved"] + assert none_plain.run().tail(2).data_tag_columns == TAG_ORDERS["interleaved"] + + +@pytest.mark.parametrize("tag_order", list(TAG_ORDERS)) +def test_operator_results_know_their_data_tags(tag_order: str) -> None: + """An operator's result, before and after it is computed, carries its data-tags, + for one input and for two inputs in both orders.""" + source = _source(TAG_ORDERS[tag_order]) + expected = _expected(TAG_ORDERS[tag_order]) + other = DictSource( + [{"trial": r["trial"], "session": r["session"], "w": 1.0} for r in ROWS[:2]], + tag_columns=["trial", "session"], + tag_only_columns=True, + source_id="other", + ) + for stream in ( + source.drop_data_columns(["label"]), + source.select_data_columns(["amp", "unit", "time"]), + Join()(source, other), + Join()(other, source), + ): + tags = stream.keys()[0] + expect = tuple(c for c in tags if c in expected) + assert stream.head().status is ViewStatus.NOT_COMPUTED + assert stream.head().data_tag_columns == expect + for name, view in _views(stream.run()).items(): + assert view.data_tag_columns == expect, name + + +def test_dropping_the_data_role_leaves_a_plain_tag() -> None: + """A data-tag whose data role is dropped is shown as a plain tag.""" + source = _source() + with pytest.warns(Warning, match="data-tag"): + stream = source.drop_data_columns(["time"]) + assert stream.run().data_tag_columns == ("unit",) + assert source.drop_tag_columns(["unit"]).run().data_tag_columns == ("time",) + + +def test_function_pod_results_know_their_data_tags() -> None: + """``pod(stream)`` lets data-tags fall through, and the view says so; + ``pod.process`` makes every output tag plain.""" + source = _source() + stream = scale.pod(source) + # The data-tags in the stream's own tag order (which column order a stream shows + # is ITL-1305). + expected = tuple(c for c in stream.keys()[0] if c in DATA_TAGS) + assert sorted(expected) == sorted(DATA_TAGS) + head = _view(stream.head()) + assert CALLS == [] + assert head.status is ViewStatus.NOT_COMPUTED + assert head.data_tag_columns == expected + for name, view in _views(stream.run()).items(): + assert view.data_tag_columns == expected, name + with pytest.warns(Warning, match="data-tag"): + selected = source.select_data_columns(["amp"]) + exact = scale.pod.process(selected) + assert _view(exact.run()).data_tag_columns == () + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_job_nodes_know_their_data_tags(orchestrator: str) -> None: + """Function and operator job nodes, before and after a run on either + orchestrator, and their stored view.""" + job = PipelineJob(name="itl1304", database=InMemoryArrowDatabase()) + with job: + scaled = scale.pod(_source(), label="scaled") + _ = SelectDataColumns(["unit", "time", "scaled"])(scaled, label="sel") + for label in ("scaled", "sel"): + head = job.nodes[label].head() + assert head.status is ViewStatus.NOT_COMPUTED + assert head.data_tag_columns == _data_tags_of(job.nodes[label]), label + assert CALLS == [] + _ = job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + for label in ("scaled", "sel"): + node = job.nodes[label] + for name, view in _views(node.head()).items(): + assert view.data_tag_columns == _in_view_order(view), (label, name) + view = node.run() + assert view.data_tag_columns == _in_view_order(view), label + stored = job.nodes["scaled"].as_source() + assert stored.head().data_tag_columns == _data_tags_of(stored) + + +def test_a_loaded_job_knows_its_data_tags(tmp_path: Path) -> None: + """A loaded job's nodes, before and after a load-only run, and their stored view.""" + path = tmp_path / "spikes.csv" + with path.open("w", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=list(LAYOUTS["data_first"])) + writer.writeheader() + writer.writerows(_rows(LAYOUTS["data_first"])) + source = CSVSource( + str(path), + tag_columns=list(TAG_ORDERS["interleaved"]), + tag_only_columns=list(PLAIN), + source_id="spikes", + ) + job = PipelineJob(name="itl1304", database=DeltaTableDatabase(tmp_path / "store")) + with job: + _ = scale.pod(source, label="scaled") + _ = job.run() + saved = tmp_path / "job.json" + job.save(saved) + CALLS.clear() + + loaded = PipelineJob.load(str(saved)) + node = loaded.nodes["scaled"] + assert node.head().status is ViewStatus.NOT_COMPUTED + assert node.head().data_tag_columns == _data_tags_of(node) + stored = node.as_source().head() + assert stored.data_tag_columns == _in_view_order(stored) + _ = loaded.run(load_only=True) + assert CALLS == [] + for name, view in _views(node.head()).items(): + assert view.status is ViewStatus.LOADED_ONLY, name + assert view.data_tag_columns == _in_view_order(view), name + + +def test_a_derived_source_view_knows_its_data_tags() -> None: + """A derived source over a computed stream keeps the data-tags its keys name.""" + job = PipelineJob(name="itl1304", database=InMemoryArrowDatabase()) + with job: + _ = scale.pod(_source(), label="scaled") + _ = job.run() + derived = job.nodes["scaled"].as_source() + assert isinstance(derived, DerivedSource) + expected = _data_tags_of(derived) + assert derived.run().data_tag_columns == expected + assert derived.head().tail(1).data_tag_columns == expected + + +# --------------------------------------------------------------------------- +# Showing a stream with data-tags computes nothing (ITL-991) +# --------------------------------------------------------------------------- + + +def test_preview_of_a_function_pod_with_data_tags_calls_no_function() -> None: + """Neither head, the preview nor the text form calls the function.""" + stream: Any = scale.pod(_source()) + _ = stream.head() + _ = stream._repr_html_() + _ = str(stream.head()) + assert CALLS == [] + + +def test_preview_of_an_operator_with_data_tags_runs_no_operator() -> None: + """The preview of a join over data-tags never runs the join over rows.""" + other = DictSource( + [{"trial": 1, "session": "s1", "w": 1.0}], + tag_columns=["trial", "session"], + tag_only_columns=True, + source_id="other", + ) + stream = Join()(_source(), other) + original = Join.static_process + with mock.patch.object( + Join, "static_process", autospec=True, side_effect=original + ) as spy: + head = stream.head() + _ = stream._repr_html_() + _ = str(head) + over_rows = sum( + any(s.as_table().num_rows for s in call.args[1:]) + for call in spy.call_args_list + ) + assert over_rows == 0 + assert head.data_tag_columns == _in_view_order(head) + + +def test_preview_of_a_side_effect_with_data_tags_delivers_nothing() -> None: + """Showing a side-effect stream over data-tags delivers nothing.""" + delivered: list[float] = [] + + def deliver(amp: float) -> None: + """Record a delivery.""" + delivered.append(amp) + + # The side effect reads amp only; the data-tags stay tags (plain ones here). + with pytest.warns(Warning, match="data-tag"): + selected = _source().select_data_columns(["amp"]) + stream = SideEffectPod(deliver)(selected) + _ = stream.head() + _ = stream._repr_html_() + assert delivered == [] + + +def test_job_preview_with_data_tags_writes_nothing() -> None: + """Showing the nodes of a job that has not run writes nothing to its database.""" + store = InMemoryArrowDatabase() + job = PipelineJob(name="itl1304", database=store) + with job: + _ = scale.pod(_source(), label="scaled") + with ( + mock.patch.object( + InMemoryArrowDatabase, "add_records", side_effect=AssertionError("write") + ), + mock.patch.object( + InMemoryArrowDatabase, "add_record", side_effect=AssertionError("write") + ), + ): + _ = job.nodes["scaled"]._repr_html_() + _ = str(job.nodes["scaled"].head()) + assert CALLS == [] + + +# --------------------------------------------------------------------------- +# Only the display is marked +# --------------------------------------------------------------------------- + + +def test_only_the_display_is_marked() -> None: + """The view's table, as_table and the data frames carry no mark.""" + source = _source() + view = source.run() + names = list(source.as_table().column_names) + assert view.table.column_names == names + assert view.as_table().column_names == names + assert list(view.as_polars_df().columns) == names + assert source.keys() == ( + TAG_ORDERS["interleaved"], + ("unit", "time", "label", "amp"), + ) + + +class _Cells(HTMLParser): + """Collects every table row of an HTML display: each cell's text and style.""" + + def __init__(self) -> None: + super().__init__() + self.rows: list[list[tuple[str, str]]] = [] + self._cell: list[str] | None = None + self._style = "" + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + if tag == "tr": + self.rows.append([]) + elif tag in ("th", "td"): + self._cell = [] + self._style = dict(attrs).get("style") or "" + + def handle_endtag(self, tag: str) -> None: + if tag in ("th", "td") and self._cell is not None: + self.rows[-1].append(("".join(self._cell), self._style)) + self._cell = None + + def handle_data(self, data: str) -> None: + if self._cell is not None: + self._cell.append(data) + + +def _cells(html_text: str) -> list[list[tuple[str, str]]]: + parser = _Cells() + parser.feed(html_text) + return parser.rows + + +TAG_STYLE = "font-weight:bold" +DATA_TAG_STYLE = "text-decoration:underline" +TEXT_LEGEND = {"tag": "* = tag", "data-tag": "+ = data-tag (tag and data)"} +HTML_LEGEND = { + "tag": "bold = tag", + "data-tag": "bold underlined = data-tag (a tag that is also data)", +} + + +def _check_display(shown: object) -> None: + """Both displays of ``shown`` (a view) mark each plain tag, each data-tag and no data + column, with one rule after the tags, and a legend naming exactly the marks shown.""" + view = _view(shown) + data_tags = set(view.data_tag_columns) + plain = [c for c in view.tag_columns if c not in data_tags] + roles = [*(["tag"] if plain else []), *(["data-tag"] if data_tags else [])] + + html_text = view._repr_html_() + legend = "; ".join(HTML_LEGEND[role] for role in roles) + if legend: + assert f"{legend}" in html_text + else: + assert "bold" not in html_text.split("", 1)[1] + assert "border-right" not in html_text + assert [style for _, style in _cells(view)[0]] == [ + "font-weight:normal;text-decoration:underline" + ] * 2 assert "* = tag" not in str(view) + assert str(view).split("\n")[1].startswith("shape:") def test_text_display_stars_the_tag_columns() -> None: From ec50637da5fba652c5a2be9de0319e75e9bec64c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 18:30:28 -0800 Subject: [PATCH 3/5] fix(view): a raw stream's meta columns stay unmarked in the preview (ITL-1304) A raw ArrowTableStream lists its meta (__) columns among its data keys, so the data role took them and the HTML preview underlined them. Data columns now exclude names with the meta prefix (constants.META_PREFIX); data columns and data-tags keep their marks. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1304.md | 2 +- docs/concepts/notebooks.md | 2 +- docs/concepts/streams.md | 4 +- src/orcapod/core/streams/view.py | 11 +++- .../streams/test_data_tag_preview.py | 53 +++++++++++++++++++ 5 files changed, 66 insertions(+), 6 deletions(-) diff --git a/changelog.d/ITL-1304.md b/changelog.d/ITL-1304.md index 7aa0cd3ae..e55317cd3 100644 --- a/changelog.d/ITL-1304.md +++ b/changelog.d/ITL-1304.md @@ -6,7 +6,7 @@ (developer, November 21, 2026): a tag's header is bold in the accent colour (as before), a data column's header is now underlined (at normal weight), and a data-tag's header has both. The hidden column groups keep their look when shown: system tags are marked as - tags, as before; source-info, context and content-hash columns stay unmarked. In the text preview a data-tag's name starts with `+` (a plain + tags, as before; source-info, context, content-hash and meta (`__`) columns stay unmarked. In the text preview a data-tag's name starts with `+` (a plain tag's with `*`; data columns stay unmarked). The legend line names exactly the marks shown: "bold = tag; underlined = data; bold underlined = data-tag (a tag that is also data)" in a notebook, "* = tag; + = data-tag (tag and data)" as text, each part only when diff --git a/docs/concepts/notebooks.md b/docs/concepts/notebooks.md index 70fc0983b..010af6748 100644 --- a/docs/concepts/notebooks.md +++ b/docs/concepts/notebooks.md @@ -79,7 +79,7 @@ What it shows ([Looking at data](streams.md#looking-at-data) states each rule in "bold underlined = data-tag (a tag that is also data)". The line names only the marks shown: the tags of `units` are all plain. (The pictures were taken before data headers were underlined.) When `columns` asks for the hidden column groups, system tags are - marked as tags and the source-info, context and content-hash columns are left unmarked. + marked as tags and the source-info, context, content-hash and meta columns are left unmarked. - **Large cells** are summarised (an array as `ndarray float64 (2, 3)`, bytes as `bytes (300 B)`, long text and long lists shortened); `head().table` keeps the full values. diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 4553a27b8..d8a5f503a 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -289,8 +289,8 @@ underlined, and a [data-tag](data-tags.md), a tag that is also data, has both; a rule separates the tags from the data columns, and a line under the header names each mark shown ("bold = tag; underlined = data; bold underlined = data-tag (a tag that is also data)"). A data-tag is one column, shown once, among the tags. When `columns` asks for the hidden -column groups, system tags are marked as tags, and the source-info, context and -content-hash columns are left unmarked. As text, a plain tag's name starts with `*` ("* = tag") and a data-tag's +column groups, system tags are marked as tags, and the source-info, context, +content-hash and meta (`__`) columns are left unmarked. As text, a plain tag's name starts with `*` ("* = tag") and a data-tag's with `+` ("+ = data-tag (tag and data)"); a data column's is unmarked. Only the display is marked: the view's table and `as_table()` keep the plain names. diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index 5a911c168..fc40abbfb 100644 --- a/src/orcapod/core/streams/view.py +++ b/src/orcapod/core/streams/view.py @@ -28,6 +28,7 @@ from typing_extensions import override +from orcapod.system_constants import constants from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: @@ -794,7 +795,9 @@ def data_roles_of( The roles are read from the stream's public ``keys()``: a data-tag is one column in both roles, a name among both its tag and its data keys; a data column is a name - among its data keys that is not a tag. A view that shows columns has its stream's + among its data keys that is not a tag and not a meta column (``META_PREFIX``): a raw + ``ArrowTableStream`` lists its meta columns among its data keys, and a meta column + is shown unmarked. A view that shows columns has its stream's schema already, so reading the keys computes, reads and polls nothing; a view with no column (one whose schema would need a poll, ``schema_requires_io``) does not read them. @@ -814,7 +817,11 @@ def data_roles_of( data_names = set(data) data_tags = tuple(c for c in tag_columns if c in data_names and c in set(tags)) data_columns = tuple( - c for c in column_names if c in data_names and c not in tag_columns + c + for c in column_names + if c in data_names + and c not in tag_columns + and not c.startswith(constants.META_PREFIX) ) return data_tags, data_columns diff --git a/tests/test_core/streams/test_data_tag_preview.py b/tests/test_core/streams/test_data_tag_preview.py index 0b0c43e33..1e5eee6e9 100644 --- a/tests/test_core/streams/test_data_tag_preview.py +++ b/tests/test_core/streams/test_data_tag_preview.py @@ -686,3 +686,56 @@ def test_job_nodes_show_the_marks(orchestrator: str) -> None: _check_display(job.nodes["scaled"].as_source().head()) # Only the run called the function, once per row. assert len(CALLS) == len(ROWS) + + +RAW_LAYOUTS = { + "meta_between": ("x", "__debug", "a", "y", "b", "__note"), + "meta_first": ("__note", "__debug", "b", "a", "y", "x"), +} + + +@pytest.mark.parametrize("tag_order", [("a", "b"), ("b", "a")], ids=["ab", "ba"]) +@pytest.mark.parametrize("layout", list(RAW_LAYOUTS)) +def test_meta_columns_of_a_raw_stream_stay_unmarked( + layout: str, tag_order: tuple[str, str] +) -> None: + """A raw stream lists its meta columns among its data keys; the display leaves + them unmarked and the legend counts them as nothing, while its data columns and + its data-tag keep their marks.""" + values = {"a": [1, 2], "b": [3, 4], "x": [5, 6], "y": [7, 8]} + values |= {"__debug": ["d1", "d2"], "__note": ["n1", "n2"]} + table = pa.table({name: values[name] for name in RAW_LAYOUTS[layout]}) + stream = ArrowTableStream(table, tag_columns=list(tag_order), data_tags=["b"]) + assert {"__debug", "__note"} <= set(stream.keys()[1]) + meta = [c for c in RAW_LAYOUTS[layout] if c.startswith("__")] + data = [c for c in RAW_LAYOUTS[layout] if c in ("x", "y")] + for shown in ( + stream.head(), + stream.head(columns={"meta": True}), + stream.run(), + stream.run().tail(1), + ): + view = _view(shown) + assert view.tag_columns == tag_order + assert view.data_tag_columns == ("b",) + assert list(view.data_columns) == data + html_text = view._repr_html_() + header = dict(_cells(html_text)[0]) + for name in meta: + assert header[name] == "", name + for name in data: + assert header[name] == "font-weight:normal;text-decoration:underline" + assert header["a"].startswith("font-weight:bold;color:#2a7fb8") + assert header["b"].startswith( + "font-weight:bold;text-decoration:underline;color:#2a7fb8" + ) + assert ( + "bold = tag; underlined = data; " + "bold underlined = data-tag (a tag that is also data)" + ) in html_text + lines = str(view).split("\n") + assert lines[1] == "* = tag; + = data-tag (tag and data)" + names_line = next(line for line in lines if line.startswith("│")) + names = [cell.strip() for cell in names_line.strip("│").split("┆")] + tags = [("+" if c == "b" else "*") + c for c in tag_order] + assert names == [*tags, *(c for c in RAW_LAYOUTS[layout] if c not in tag_order)] From 35348733f0f509508d064e6d9a01508e9d6e9d02 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 18:38:46 -0800 Subject: [PATCH 4/5] fix(view): mark the columns Polars shows by name; adapted heads get roles (ITL-1304) When Polars truncates a wide table it renders the first and last columns around an ellipsis cell, and the marks were assigned by position over all columns, so shown data columns took another column's role. Each rendered header cell is now matched to its column by name; the ellipsis cell gets no mark (it carries the rule when the tag/data boundary is left out), and a header that cannot be matched leaves every cell unmarked. The text preview was already right: its prefixes are on the names before Polars truncates. head_of adapting a non-StreamView head now reads the columns' roles (tags, data-tags, data) from the stream's keys(), as every other view does; before, such a view had no marks at all. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/streams/view.py | 124 +++++++++++++++--- .../streams/test_data_tag_preview.py | 107 +++++++++++++++ .../streams/test_head_and_preview.py | 70 ++++++++++ 3 files changed, 282 insertions(+), 19 deletions(-) diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index fc40abbfb..8d43e5bde 100644 --- a/src/orcapod/core/streams/view.py +++ b/src/orcapod/core/streams/view.py @@ -628,8 +628,7 @@ def _repr_html_(self) -> str: # Polars shortens strings to its own default length; show up to _MAX_TEXT. with pl.Config(fmt_str_lengths=_MAX_TEXT, tbl_rows=self._display_rows()): frame_html = self._display_frame()._repr_html_() - roles = [role for _, role in self._display_columns()] - parts.append(_mark_columns(frame_html, roles)) + parts.append(_mark_columns(frame_html, self._display_columns())) return "\n".join(parts) def __str__(self) -> str: @@ -653,32 +652,110 @@ def __repr__(self) -> str: ) -def _mark_columns(frame_html: str, roles: Sequence[str]) -> str: +def _mark_columns(frame_html: str, columns: Sequence[tuple[str, str]]) -> str: """Return Polars' HTML table ``frame_html`` with its columns styled by role. - The cells are found by position, never by name, so a name that HTML escapes is - handled as Polars wrote it. The header cell of a column gets its role's - ``html_style``; every cell of the last column of a group of roles followed by another - group gets ``ROLE_BOUNDARY_STYLE``. Everything else is passed on unchanged. + Polars may leave columns out of a wide table, showing the first and the last ones + around an ellipsis cell, so each rendered header cell is matched to its column by + name (``_rendered_roles``), never by its position among all the columns. The header + cell of a column gets its role's ``html_style``; every cell of the last column of a + group of roles followed by another group gets ``ROLE_BOUNDARY_STYLE`` (the ellipsis + cell's when the boundary is among the columns left out). The ellipsis cell gets no + mark, and a header Polars wrote in a form that cannot be matched leaves every cell + unmarked: no mark is better than a wrong one. Everything else is passed on unchanged. Args: - frame_html: The HTML of the display frame, one column per entry of ``roles``. - roles: The role of each column, in display order. + frame_html: The HTML of the display frame, one column per entry of ``columns``. + columns: The name and the role of each column, in display order. """ - header = [COLUMN_ROLE_MARKS[role].html_style for role in roles] - groups = [COLUMN_ROLE_MARKS[role].group for role in roles] - boundary = [ - ROLE_BOUNDARY_STYLE - if i + 1 < len(groups) and groups[i + 1] != groups[i] - else "" - for i in range(len(groups)) + names = _HeaderNames() + names.feed(frame_html) + names.close() + cells = _rendered_columns(names.cells, [name for name, _ in columns]) + roles = [role for _, role in columns] + header = [ + "" if column is None else COLUMN_ROLE_MARKS[roles[column]].html_style + for column in cells ] + boundary = [""] * len(cells) + groups = [COLUMN_ROLE_MARKS[role].group for role in roles] + if cells and any(column is not None for column in cells): + for last in range(len(groups) - 1): + if groups[last] != groups[last + 1]: + # The cell showing the last column of the group, or the ellipsis cell + # when that column is left out. + shown = [i for i, column in enumerate(cells) if column == last] + if not shown: + shown = [i for i, column in enumerate(cells) if column is None] + for i in shown: + boundary[i] = ROLE_BOUNDARY_STYLE marker = _ColumnMarker(header, boundary) marker.feed(frame_html) marker.close() return "".join(marker.out) +_ELLIPSIS = "…" + + +def _rendered_columns(cells: Sequence[str], names: Sequence[str]) -> list[int | None]: + """Return, for each rendered header cell, the index of its column in ``names``, or + ``None`` for the ellipsis cell (and for every cell when they cannot be matched). + + Polars renders either every column, or a first run and a last run of them around one + ellipsis cell; the match is checked by name on both sides of the ellipsis. + + Args: + cells: The text of each cell of the first header row, as rendered. + names: The names of the columns of the display frame, in order. + """ + if list(cells) == list(names): + return list(range(len(names))) + left_out = len(names) - (len(cells) - 1) + if left_out > 0: + for i, cell in enumerate(cells): + if ( + cell == _ELLIPSIS + and list(cells[:i]) == list(names[:i]) + and list(cells[i + 1 :]) == list(names[i + left_out :]) + ): + return [*range(i), None, *range(i + left_out, len(names))] + return [None] * len(cells) + + +class _HeaderNames(HTMLParser): + """Collects the text of each cell of the first header row of an HTML table.""" + + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.cells: list[str] = [] + self._rows: int = 0 + self._in_thead: bool = False + self._cell: list[str] | None = None + + @override + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + if tag == "thead": + self._in_thead = True + elif tag == "tr" and self._in_thead: + self._rows += 1 + elif tag in ("th", "td") and self._in_thead and self._rows == 1: + self._cell = [] + + @override + def handle_endtag(self, tag: str) -> None: + if tag == "thead": + self._in_thead = False + elif tag in ("th", "td") and self._cell is not None: + self.cells.append("".join(self._cell)) + self._cell = None + + @override + def handle_data(self, data: str) -> None: + if self._cell is not None: + self._cell.append(data) + + class _ColumnMarker(HTMLParser): """Copies Polars' HTML table, adding inline styles to cells by column position.""" @@ -850,8 +927,9 @@ def head_of( """Return ``head`` (another stream's) shown as ``stream``. A ``StreamView`` keeps every field. Any other result of ``head`` (a - ``StreamViewProtocol``) is adapted from what that protocol gives: its rows, status - and total. + ``StreamViewProtocol``) is adapted from what that protocol gives (its rows, status + and total), with the columns' roles read from ``stream``'s ``keys()``, as every other + view gets them (``data_roles_of``). Args: head: What another stream's ``head`` returned. @@ -860,11 +938,19 @@ def head_of( note: Another note, if given. """ if not isinstance(head, StreamView): + table: pa.Table = head.table + names = table.column_names + # A table with no column needs no keys (``data_roles_of``). + tags = tuple(c for c in stream.keys()[0] if c in names) if names else () + data_tags, data = data_roles_of(stream, tags, names) head = StreamView( - table=head.table, + table=table, status=ViewStatus(head.status), kind=type(stream).__name__, label=display_name(stream), + tag_columns=tags, + data_tag_columns=data_tags, + data_columns=data, total_rows=head.total_rows, ) return head.for_stream(stream, origin=origin, note=note) diff --git a/tests/test_core/streams/test_data_tag_preview.py b/tests/test_core/streams/test_data_tag_preview.py index 1e5eee6e9..de876cd14 100644 --- a/tests/test_core/streams/test_data_tag_preview.py +++ b/tests/test_core/streams/test_data_tag_preview.py @@ -739,3 +739,110 @@ def test_meta_columns_of_a_raw_stream_stay_unmarked( names = [cell.strip() for cell in names_line.strip("│").split("┆")] tags = [("+" if c == "b" else "*") + c for c in tag_order] assert names == [*tags, *(c for c in RAW_LAYOUTS[layout] if c not in tag_order)] + + +STYLES = { + "tag": "font-weight:bold;color:#2a7fb8", + "data-tag": "font-weight:bold;text-decoration:underline;color:#2a7fb8", + "data": "font-weight:normal;text-decoration:underline", +} +RULE = "border-right:2px solid currentColor" + + +def _header_cells(html_text: str) -> list[tuple[str, str]]: + """The first header row of an HTML display: each cell's text and style.""" + return _cells(html_text)[0] + + +def _check_rendered_roles( + view: StreamView, role_of: dict[str, str], hidden_boundary: bool +) -> list[str]: + """Check every rendered header cell has its own column's mark, the ellipsis none, + and the rule after the last tag (on the ellipsis when that tag is left out). + Return the names of the rendered cells.""" + rows = _cells(view._repr_html_()) + header = rows[0] + names = [name for name, _ in header] + assert "…" in names, "the table is shown truncated" + for name, style in header: + if name == "…": + assert style == (RULE if hidden_boundary else ""), style + else: + expected = STYLES[role_of[name]] + assert style.removesuffix(";" + RULE) == expected, name + ruled = [name for name, style in header if RULE in style] + last_tag = view.tag_columns[-1] + assert ruled == (["…"] if hidden_boundary else [last_tag]) + for row in rows[1:]: + ruled_cells = [i for i, (_, style) in enumerate(row) if RULE in style] + assert ruled_cells == [names.index(ruled[0])] + return names + + +@pytest.mark.parametrize("layout", ["tags_first", "data_first"]) +def test_a_wide_table_marks_the_columns_polars_shows(layout: str) -> None: + """At Polars' default width a 100-column table is shown truncated: every shown + header keeps its own column's mark, never another column's.""" + plain = [f"p{i}" for i in range(5)] + data_tags = [f"t{i}" for i in range(85)] + data = [f"d{i}" for i in range(10)] + tags = plain + data_tags + columns = tags + data if layout == "tags_first" else data[::-1] + tags + source = DictSource( + [{name: i for i, name in enumerate(columns)}], + tag_columns=tags, + tag_only_columns=plain, + source_id="wide", + ) + role_of = { + **dict.fromkeys(plain, "tag"), + **dict.fromkeys(data_tags, "data-tag"), + **dict.fromkeys(data, "data"), + } + view = _view(source.run()) + names = _check_rendered_roles(view, role_of, hidden_boundary=False) + assert names[:5] == plain + assert any(role_of.get(name) == "data" for name in names) + + +@pytest.mark.parametrize("layout", list(LAYOUTS)) +def test_an_explicit_column_limit_marks_the_columns_polars_shows(layout: str) -> None: + """Under ``tbl_cols=4`` the six-column stream shows two columns either side of the + ellipsis: each keeps its own mark, the ellipsis none, and the rule moves onto the + ellipsis when the last tag is left out; the text form marks the same columns.""" + import polars as pl + + source = _source(TAG_ORDERS["interleaved"], LAYOUTS[layout]) + view = _view(source.run()) + role_of = {"session": "tag", "trial": "tag", "unit": "data-tag", "time": "data-tag"} + role_of |= {"amp": "data", "label": "data"} + with pl.Config(tbl_cols=4): + names = _check_rendered_roles(view, role_of, hidden_boundary=True) + text = str(view) + assert names[:2] == ["session", "unit"] + assert names[3:] == list(view.data_columns) + names_line = next(line for line in text.split("\n") if line.startswith("│")) + shown = [cell.strip() for cell in names_line.strip("│").split("┆")] + assert shown == ["*session", "+unit", "…", *view.data_columns] + # Showing more columns than the limit hides none: every mark, by position. + with pl.Config(tbl_cols=20): + header = _header_cells(view._repr_html_()) + assert "…" not in [name for name, _ in header] + for name, style in header: + assert style.removesuffix(";" + RULE) == STYLES[role_of[name]], name + + +def test_an_unmatched_header_marks_nothing() -> None: + """When the rendered header cannot be matched to the columns, no cell is marked.""" + from orcapod.core.streams.view import _mark_columns + + frame = ( + "" + "" + "
ab
i64i64
12
" + ) + marked = _mark_columns(frame, [("x", "tag"), ("y", "data")]) + assert "style=" not in marked + matched = _mark_columns(frame, [("a", "tag"), ("b", "data")]) + assert f'a' in matched + assert f'b' in matched diff --git a/tests/test_core/streams/test_head_and_preview.py b/tests/test_core/streams/test_head_and_preview.py index 5e3b4d76d..c1bc22eda 100644 --- a/tests/test_core/streams/test_head_and_preview.py +++ b/tests/test_core/streams/test_head_and_preview.py @@ -9,6 +9,7 @@ from __future__ import annotations import io +import re from typing import Any from unittest import mock @@ -746,6 +747,75 @@ def _repr_html_(self) -> str: head = head_of(_PlainHead(), source) assert head.status is ViewStatus.ROWS assert head.header() == "ArrowTableSource[readings] — all 2 rows" + # The roles come from the stream, as for every other view (ITL-1304). + assert head.tag_columns == ("id",) + assert head.data_tag_columns == () + assert head.data_columns == ("x",) + assert "bold = tag; underlined = data" in head._repr_html_() + + +def test_head_of_an_adapted_head_marks_plain_tags_data_tags_and_data() -> None: + """A protocol head of a stream with two plain tags, two data-tags and two data + columns, in two table layouts, is shown with every column's mark.""" + from orcapod.core.streams.view import head_of + + class _Wrapped: + """A ``StreamViewProtocol`` result that only wraps another head's rows.""" + + def __init__(self, inner: Any) -> None: + self.table = inner.table + self.status = "rows" + self.total_rows = inner.table.num_rows + + def header(self) -> str: + """Return a fixed header.""" + return "wrapped" + + styles = { + "tag": "font-weight:bold;color:#2a7fb8", + "data-tag": "font-weight:bold;text-decoration:underline;color:#2a7fb8", + "data": "font-weight:normal;text-decoration:underline", + } + for layout in ( + ["amp", "label", "session", "unit", "trial", "time"], + ["time", "trial", "label", "unit", "amp", "session"], + ): + row = { + "session": "s", + "unit": 1, + "trial": 2, + "time": 3, + "amp": 0.5, + "label": "a", + } + source = DictSource( + [{name: row[name] for name in layout}], + tag_columns=["session", "unit", "trial", "time"], + tag_only_columns=["session", "trial"], + source_id="spikes", + ) + head = head_of(_Wrapped(source.head()), source) + assert head.tag_columns == ("session", "unit", "trial", "time") + assert head.data_tag_columns == ("unit", "time") + assert set(head.data_columns) == {"amp", "label"} + html_text = head._repr_html_() + role = { + "session": "tag", + "trial": "tag", + "unit": "data-tag", + "time": "data-tag", + } + first_row = html_text.split("", 1)[1].split("", 1)[0] + header = { + name: style + for style, name in re.findall( + r'([^<]*)', first_row + ) + } + assert list(header) == ["session", "unit", "trial", "time", *head.data_columns] + for name, style in header.items(): + assert style.startswith(styles[role.get(name, "data")]), name + assert "+unit" in str(head) and "*session" in str(head) def test_head_of_n_rows_renders_all_n_rows() -> None: From 1a07f7582b4f3e3ce66a099ca0f7ac774cc49f8b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Fri, 20 Nov 2026 19:08:46 -0800 Subject: [PATCH 5/5] fix(view): the legend names the marks of the rendered columns (ITL-1304) When Polars leaves columns out of a wide table, the legend still named the marks of every column of the view. Each display's legend now names the marks of the columns it rendered, read once by _rendered_columns (the same reading the HTML header marks use): the HTML from its header cells, the text from its header line. _rendered_columns returns None when the cells cannot be matched: the HTML then marks nothing and names no mark; the text, whose marks are part of the names, names every column's. With nothing left out the legend is the full one, as before. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1304.md | 18 +-- src/orcapod/core/streams/view.py | 119 +++++++++++++----- .../streams/test_data_tag_preview.py | 112 ++++++++++++++++- 3 files changed, 205 insertions(+), 44 deletions(-) diff --git a/changelog.d/ITL-1304.md b/changelog.d/ITL-1304.md index e55317cd3..e970e3258 100644 --- a/changelog.d/ITL-1304.md +++ b/changelog.d/ITL-1304.md @@ -6,13 +6,15 @@ (developer, November 21, 2026): a tag's header is bold in the accent colour (as before), a data column's header is now underlined (at normal weight), and a data-tag's header has both. The hidden column groups keep their look when shown: system tags are marked as - tags, as before; source-info, context, content-hash and meta (`__`) columns stay unmarked. In the text preview a data-tag's name starts with `+` (a plain - tag's with `*`; data columns stay unmarked). The legend line names exactly the marks - shown: "bold = tag; underlined = data; bold underlined = data-tag (a tag that is also - data)" in a notebook, "* = tag; + = data-tag (tag and data)" as text, each part only when - such a column is shown. It holds for every view: `head()`, `tail()`, `sort_by_tags()`, - `run()`, the notebook preview and the text form, of a source, a stream, an operator or - function pod result and a job node, loaded jobs included. A `StreamView` has two new - fields, `data_tag_columns` and `data_columns`, taken from the stream's `keys()`. Only the + tags, as before; source-info, context, content-hash and meta (`__`) columns stay + unmarked. In the text preview a data-tag's name starts with `+` (a plain tag's with `*`; + data columns stay unmarked). The legend line names exactly the marks shown (of the + columns Polars renders, when it leaves some out of a wide table): "bold = tag; + underlined = data; bold underlined = data-tag (a tag that is also data)" in a notebook, + "* = tag; + = data-tag (tag and data)" as text, each part only when such a column is + shown. It holds for every view: `head()`, `tail()`, `sort_by_tags()`, `run()`, the + notebook preview and the text form, of a source, a stream, an operator or function pod + result and a job node, loaded jobs included. A `StreamView` has two new fields, + `data_tag_columns` and `data_columns`, taken from the stream's `keys()`. Only the display is marked: the view's `table`, `as_table()`, the data frames and every schema, hash and stored form are unchanged. diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index 8d43e5bde..cde4ba5ee 100644 --- a/src/orcapod/core/streams/view.py +++ b/src/orcapod/core/streams/view.py @@ -20,7 +20,7 @@ import dataclasses import html import importlib -from collections.abc import Sequence +from collections.abc import Iterable, Sequence from dataclasses import dataclass from enum import Enum from html.parser import HTMLParser @@ -547,10 +547,15 @@ def _display_columns(self) -> list[tuple[str, str]]: if c not in self.tag_columns ] - def _legend(self, text: bool) -> str: - """Return the legend line of the marks the shown columns carry, in the order of - ``COLUMN_ROLE_MARKS``, or empty.""" - shown = {role for _, role in self._display_columns()} + def _legend(self, text: bool, roles: Iterable[str]) -> str: + """Return the legend line of the marks of ``roles``, the roles of the columns a + display rendered, in the order of ``COLUMN_ROLE_MARKS``, or empty. + + Args: + text: Whether the legend is the text display's (else the HTML display's). + roles: The role of each rendered column. + """ + shown = set(roles) legends = [ mark.text_legend if text else mark.html_legend for role, mark in COLUMN_ROLE_MARKS.items() @@ -615,33 +620,62 @@ def _display_rows(self) -> int: def _repr_html_(self) -> str: """Return the notebook preview: header, legend and the rows (large cells - summarised), each column's header styled by its role (``COLUMN_ROLE_MARKS``).""" + summarised), each rendered column's header styled by its role + (``COLUMN_ROLE_MARKS``). The legend names the marks of the columns Polars + rendered (``_rendered_columns``): none when the header cannot be matched, since + no cell is then marked, and none when Polars renders no column.""" parts = [ f"
{html.escape(self.header(), quote=False)}
" ] - legend = self._legend(text=False) - if legend: - parts.append( - f"
{html.escape(legend, quote=False)}
" - ) + table_html = "" + roles: list[str] = [] if self.table.num_columns: # Polars shortens strings to its own default length; show up to _MAX_TEXT. with pl.Config(fmt_str_lengths=_MAX_TEXT, tbl_rows=self._display_rows()): frame_html = self._display_frame()._repr_html_() - parts.append(_mark_columns(frame_html, self._display_columns())) + columns = self._display_columns() + names = _HeaderNames() + names.feed(frame_html) + names.close() + rendered = _rendered_columns(names.cells, [name for name, _ in columns]) + table_html = _mark_columns(frame_html, columns, rendered) + if rendered is not None: + roles = [columns[i][1] for i in rendered if i is not None] + legend = self._legend(text=False, roles=roles) + if legend: + parts.append( + f"
{html.escape(legend, quote=False)}
" + ) + if table_html: + parts.append(table_html) return "\n".join(parts) def __str__(self) -> str: """Return the preview as text: header, legend and the rows, each column's header prefixed by its role's mark (``*`` for a plain tag, ``+`` for a - data-tag).""" + data-tag). The legend names the marks of the columns Polars rendered + (``_rendered_columns``); when its header cannot be read, of every column.""" lines = [self.header()] - legend = self._legend(text=True) - if legend: - lines.append(legend) + frame_text = "" + roles: list[str] = [] if self.table.num_columns: with pl.Config(fmt_str_lengths=_MAX_TEXT, tbl_rows=self._display_rows()): - lines.append(str(self._display_frame(text=True))) + frame = self._display_frame(text=True) + frame_text = str(frame) + columns = self._display_columns() + rendered = _rendered_columns(_text_header_cells(frame_text), frame.columns) + if rendered is not None: + roles = [columns[i][1] for i in rendered if i is not None] + else: + # A header that cannot be read (a name Polars wraps over two lines, + # another table style): the marks are part of the names, so every + # column's role is named. + roles = [role for _, role in columns] + legend = self._legend(text=True, roles=roles) + if legend: + lines.append(legend) + if frame_text: + lines.append(frame_text) return "\n".join(lines) def __repr__(self) -> str: @@ -652,26 +686,31 @@ def __repr__(self) -> str: ) -def _mark_columns(frame_html: str, columns: Sequence[tuple[str, str]]) -> str: +def _mark_columns( + frame_html: str, + columns: Sequence[tuple[str, str]], + rendered: Sequence[int | None] | None, +) -> str: """Return Polars' HTML table ``frame_html`` with its columns styled by role. Polars may leave columns out of a wide table, showing the first and the last ones - around an ellipsis cell, so each rendered header cell is matched to its column by - name (``_rendered_roles``), never by its position among all the columns. The header - cell of a column gets its role's ``html_style``; every cell of the last column of a - group of roles followed by another group gets ``ROLE_BOUNDARY_STYLE`` (the ellipsis - cell's when the boundary is among the columns left out). The ellipsis cell gets no - mark, and a header Polars wrote in a form that cannot be matched leaves every cell - unmarked: no mark is better than a wrong one. Everything else is passed on unchanged. + around an ellipsis cell, so each rendered header cell is styled by the column + ``rendered`` matched it to by name (``_rendered_columns``), never by its position + among all the columns. The header cell of a column gets its role's ``html_style``; + every cell of the last column of a group of roles followed by another group gets + ``ROLE_BOUNDARY_STYLE`` (the ellipsis cell's when the boundary is among the columns + left out). The ellipsis cell gets no mark, and a header that could not be matched + leaves every cell unmarked: no mark is better than a wrong one. Everything else is + passed on unchanged. Args: frame_html: The HTML of the display frame, one column per entry of ``columns``. columns: The name and the role of each column, in display order. + rendered: For each rendered header cell, the index of its column in + ``columns``, or ``None`` for the ellipsis cell; ``None`` when the cells + could not be matched (``_rendered_columns``). """ - names = _HeaderNames() - names.feed(frame_html) - names.close() - cells = _rendered_columns(names.cells, [name for name, _ in columns]) + cells = [] if rendered is None else list(rendered) roles = [role for _, role in columns] header = [ "" if column is None else COLUMN_ROLE_MARKS[roles[column]].html_style @@ -698,12 +737,17 @@ def _mark_columns(frame_html: str, columns: Sequence[tuple[str, str]]) -> str: _ELLIPSIS = "…" -def _rendered_columns(cells: Sequence[str], names: Sequence[str]) -> list[int | None]: +def _rendered_columns( + cells: Sequence[str], names: Sequence[str] +) -> list[int | None] | None: """Return, for each rendered header cell, the index of its column in ``names``, or - ``None`` for the ellipsis cell (and for every cell when they cannot be matched). + ``None`` for the ellipsis cell; ``None`` instead of the list when the cells cannot be + matched to the columns. Polars renders either every column, or a first run and a last run of them around one - ellipsis cell; the match is checked by name on both sides of the ellipsis. + ellipsis cell; the match is checked by name on both sides of the ellipsis. The one + reading of which columns a display rendered: the HTML display's header marks and + legend, and the text display's legend, all use it. Args: cells: The text of each cell of the first header row, as rendered. @@ -720,7 +764,16 @@ def _rendered_columns(cells: Sequence[str], names: Sequence[str]) -> list[int | and list(cells[i + 1 :]) == list(names[i + left_out :]) ): return [*range(i), None, *range(i + left_out, len(names))] - return [None] * len(cells) + return None + + +def _text_header_cells(frame_text: str) -> list[str]: + """Return the text of each cell of the first header line of Polars' text table, or + no cell when the table has no such line.""" + for line in frame_text.splitlines(): + if line.startswith("│"): + return [cell.strip() for cell in line.strip().strip("│").split("┆")] + return [] class _HeaderNames(HTMLParser): diff --git a/tests/test_core/streams/test_data_tag_preview.py b/tests/test_core/streams/test_data_tag_preview.py index de876cd14..c733fba64 100644 --- a/tests/test_core/streams/test_data_tag_preview.py +++ b/tests/test_core/streams/test_data_tag_preview.py @@ -834,15 +834,121 @@ def test_an_explicit_column_limit_marks_the_columns_polars_shows(layout: str) -> def test_an_unmatched_header_marks_nothing() -> None: """When the rendered header cannot be matched to the columns, no cell is marked.""" - from orcapod.core.streams.view import _mark_columns + from orcapod.core.streams.view import _mark_columns, _rendered_columns frame = ( "" "" "
ab
i64i64
12
" ) - marked = _mark_columns(frame, [("x", "tag"), ("y", "data")]) + assert _rendered_columns(["a", "b"], ["x", "y"]) is None + marked = _mark_columns(frame, [("x", "tag"), ("y", "data")], None) assert "style=" not in marked - matched = _mark_columns(frame, [("a", "tag"), ("b", "data")]) + columns = [("a", "tag"), ("b", "data")] + matched = _mark_columns(frame, columns, _rendered_columns(["a", "b"], ["a", "b"])) assert f'a' in matched assert f'b' in matched + + +def test_an_unmatched_header_has_no_html_legend_and_a_full_text_legend( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A header that cannot be matched: the HTML marks nothing and so names no mark; + the text display, whose marks are part of the names, names every column's.""" + from orcapod.core.streams import view as view_module + + monkeypatch.setattr(view_module, "_rendered_columns", lambda cells, names: None) + view = _view(_source().run()) + html_text = view._repr_html_() + assert "" not in html_text.split("", 1)[1] + assert str(view).split("\n")[1] == "* = tag; + = data-tag (tag and data)" + + +def _legends(view: StreamView, columns: int | None) -> tuple[str, str]: + """The HTML and text legend lines of ``view`` under ``tbl_cols=columns`` (Polars' + default when ``None``), empty when there is none.""" + import polars as pl + + with pl.Config(tbl_cols=columns) if columns else pl.Config(): + html_text = view._repr_html_() + text = str(view) + html_legend = "" + if "
" in html_text: + html_legend = html_text.split("
", 1)[1].split("", 1)[0] + second = text.split("\n")[1] + return html_legend, "" if second.startswith("shape:") else second + + +TAGS_AND_DATA = "bold = tag; underlined = data" +DATA_AND_DATA_TAGS = ( + "underlined = data; bold underlined = data-tag (a tag that is also data)" +) +FULL = "bold = tag; " + DATA_AND_DATA_TAGS +TEXT_FULL = "* = tag; + = data-tag (tag and data)" + + +@pytest.mark.parametrize("layout", list(LAYOUTS)) +@pytest.mark.parametrize( + ("case", "tag_order", "columns", "html_legend", "text_legend"), + [ + # Plain tags first: tbl_cols=4 shows trial, session, …, two data columns. + ("hides every data-tag", "plain_first", 4, TAGS_AND_DATA, "* = tag"), + # Data-tags first: shows time, unit, …, two data columns. + ( + "hides every plain tag", + "data_tags_first", + 4, + DATA_AND_DATA_TAGS, + "+ = data-tag (tag and data)", + ), + # tbl_cols=1: the text shows one tag and the ellipsis; the HTML no column. + ("hides every data column", "plain_first", 1, "", "* = tag"), + ("hides nothing", "interleaved", 20, FULL, TEXT_FULL), + ("hides nothing by default", "interleaved", None, FULL, TEXT_FULL), + ], + ids=lambda value: value if isinstance(value, str) and " " in value else None, +) +def test_the_legend_names_the_marks_of_the_rendered_columns( + case: str, + tag_order: str, + columns: int | None, + html_legend: str, + text_legend: str, + layout: str, +) -> None: + """Each display's legend names the marks of the columns it rendered: a mark whose + columns Polars left out is not named; with nothing left out, every mark is.""" + view = _view(_source(TAG_ORDERS[tag_order], LAYOUTS[layout]).run()) + assert _legends(view, columns) == (html_legend, text_legend), case + + +@pytest.mark.parametrize("layout", list(LAYOUTS)) +def test_the_legend_follows_hidden_data_columns_with_every_column_group( + layout: str, +) -> None: + """With every column group shown, tbl_cols=4 shows two tags and two source-info + columns: the data columns and data-tags are left out, and no legend names them.""" + view = _view( + _source(TAG_ORDERS["plain_first"], LAYOUTS[layout]).head(all_info=True) + ) + assert _legends(view, 4) == ("bold = tag", "* = tag") + + +def test_the_legend_of_the_wide_table() -> None: + """The 100-column table: the HTML (75 columns by default) shows every kind of + column; the text (8 by default) shows plain tags and data, not a data-tag; under + tbl_cols=6 the HTML shows plain tags and data only.""" + plain = [f"p{i}" for i in range(5)] + data_tags = [f"t{i}" for i in range(85)] + data = [f"d{i}" for i in range(10)] + source = DictSource( + [{name: i for i, name in enumerate(plain + data_tags + data)}], + tag_columns=plain + data_tags, + tag_only_columns=plain, + source_id="wide", + ) + view = _view(source.run()) + assert _legends(view, None) == (FULL, "* = tag") + assert _legends(view, 6) == (TAGS_AND_DATA, "* = tag") + assert _legends(view, 200) == (FULL, TEXT_FULL)