From f22e18d7ce17e3d5ef4a221f6b066e9866b9781a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 17:12:29 -0800 Subject: [PATCH 1/2] feat(sources): mark tags_as_data as provisional --- .zed/rules | 2 + CLAUDE.md | 2 + changelog.d/ITL-1020.md | 10 ++++ docs/concepts/data-tags.md | 5 ++ docs/concepts/identity.md | 4 ++ docs/concepts/operators.md | 5 ++ docs/concepts/sources.md | 17 ++++++- docs/dev/design_issues/ITL-1020-TAD1.md | 14 ++++++ docs/reference/golden-hashes.md | 4 ++ docs/reference/hashing.md | 4 ++ src/orcapod/core/nodes/function_node.py | 3 +- src/orcapod/core/nodes/operator_node.py | 3 +- src/orcapod/core/sources/derived_source.py | 10 +++- src/orcapod/core/sources/provisional.py | 11 +++++ .../core/sources/spiraldb_table_source.py | 7 ++- src/orcapod/errors.py | 9 ++-- src/orcapod/utils/provisional.py | 30 +++++++----- .../test_derived_source_tags_as_data.py | 4 ++ .../sources/test_provisional_sources.py | 33 ++++++++++--- ...test_spiraldb_table_source_tags_as_data.py | 49 ++++++++++++++++++- 20 files changed, 197 insertions(+), 29 deletions(-) create mode 100644 changelog.d/ITL-1020.md create mode 100644 docs/dev/design_issues/ITL-1020-TAD1.md diff --git a/.zed/rules b/.zed/rules index 67395d99a..159357bff 100644 --- a/.zed/rules +++ b/.zed/rules @@ -902,6 +902,8 @@ tokens, ITL-1425), and with the sorted mapping the source id is the source's ide origin enters only through the schema). The config type key stays derived. DerivedSource without tags_as_data (a job node's stored records) keeps its old identity; do not change it (ITL-956). +The tags_as_data argument is provisional and may be removed (ITL-1020), so when in +doubt start with a data-tag, or start with data and promote it to a data-tag if needed. ### Two identity chains diff --git a/CLAUDE.md b/CLAUDE.md index 3b9ba4940..1ebfa7a73 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -922,6 +922,8 @@ tokens, ITL-1425), and with the sorted mapping the source id is the source's ide origin enters only through the schema). The config type key stays `derived`. `DerivedSource` without `tags_as_data` (a job node's stored records) keeps its old identity; do not change it (ITL-956). +The `tags_as_data` argument is provisional and may be removed (ITL-1020), so when in +doubt start with a data-tag, or start with data and promote it to a data-tag if needed. ### Two identity chains diff --git a/changelog.d/ITL-1020.md b/changelog.d/ITL-1020.md new file mode 100644 index 000000000..c6e36a702 --- /dev/null +++ b/changelog.d/ITL-1020.md @@ -0,0 +1,10 @@ +### Changed + +- A non-empty `tags_as_data` mapping now warns once per process across + `DerivedSource`, `node.as_source()` and `SpiralDBTableSource`. + +### Known limitations + +- The `tags_as_data` argument is provisional and may change or be removed. + When in doubt, start with a data-tag, or start with data and promote it to + a data-tag if needed. Promotion from a plain tag is still being designed. diff --git a/docs/concepts/data-tags.md b/docs/concepts/data-tags.md index ec563b6fe..399f2c3be 100644 --- a/docs/concepts/data-tags.md +++ b/docs/concepts/data-tags.md @@ -424,6 +424,11 @@ take it from that column: as in v0.3, the value must also be a data column of it example a copy in the source's data under another name, or `DerivedSource(origin, tags_as_data={...})`. +!!! warning "Provisional" + `tags_as_data` may change or be removed in a later version. When in doubt, start + with a data-tag at the source, or start with data and promote it to a data-tag + if needed. How to promote a plain tag to a data-tag is still being designed. + ## Errors that name a data-tag - `pod.process(stream)` and `pod(stream, strict_columns=True)` are exact: they hand every data diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index c9615c702..9e4c95e95 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -44,6 +44,10 @@ per-row hash is what caching uses. row's content hash is checked against the database. If the hash already exists, the cached result is returned without recomputation. +!!! warning "Provisional" + The [`tags_as_data` argument](sources.md#provisional-sources) may change or + be removed in a later version. + ### `pipeline_hash()` -- schema and topology only The pipeline hash captures the pipeline's **structure** -- schemas, function identities, and diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index b1c743f9a..67094e8c7 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -475,6 +475,11 @@ The output schema follows three rules: `tag_only_columns`), declare it as data at the source, or derive a source that offers the tag as data with `DerivedSource(origin, tags_as_data={...})`. +!!! warning "Provisional" + `tags_as_data` may change or be removed in a later version. When in doubt, start + with a data-tag at the source, or start with data and promote it to a data-tag + if needed. How to promote a plain tag to a data-tag is still being designed. + ```python from orcapod.sources import DerivedSource diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 6da884ab0..fa87a9cee 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -806,6 +806,11 @@ columns, copied as each batch is read (so the source still reads no rows when bu name; you name the copy, which comes after the table's data columns, with the key column's type, never null: +!!! warning "Provisional" + `tags_as_data` may change or be removed in a later version. When in doubt, start + with a data-tag at the source, or start with data and promote it to a data-tag + if needed. How to promote a plain tag to a data-tag is still being designed. + ```python spikes = SpiralDBTableSource( @@ -908,7 +913,8 @@ reads it through its data role, under the same name (see never receives it. When a plain tag's value is also needed as data (a session's start time identifies the session, and it is also what you subtract to get an elapsed time), or you want the value as a data column under another name, pass `tags_as_data` to get a source that keeps -the tag and also offers its value as a data column under a name you choose: +the tag and also offers its value as a data column under a name you choose. +See the [provisional status of `tags_as_data`](#provisional-sources). ```python from datetime import datetime, timezone @@ -1022,6 +1028,15 @@ saved config or by loading a saved job, issues `orcapod.errors.ProvisionalHashWa per source kind per process; filter its class to silence it, as for [provisional operators](operators.md#provisional-operators). +!!! warning "Provisional" + `tags_as_data` may change or be removed in a later version. When in doubt, start + with a data-tag at the source, or start with data and promote it to a data-tag + if needed. How to promote a plain tag to a data-tag is still being designed. + + A non-empty mapping warns once per process across `DerivedSource`, + `node.as_source()` and `SpiralDBTableSource`. This warning covers the argument + itself and is separate from the warning about `DerivedSource` identity. + ## What a source does at a run A job node that has run holds its rows until it is stale, and staleness comes from modified diff --git a/docs/dev/design_issues/ITL-1020-TAD1.md b/docs/dev/design_issues/ITL-1020-TAD1.md new file mode 100644 index 000000000..792e8c904 --- /dev/null +++ b/docs/dev/design_issues/ITL-1020-TAD1.md @@ -0,0 +1,14 @@ +## Sources and tags as data + +### TAD1 — Provisional tag copies after data-tags +**Status:** resolved +**Severity:** medium +**Issue:** ITL-1020 + +Data-tags cover the common case of using a tag's value in a computation. +Removing `tags_as_data` would break existing callers that copy tag values into +data columns. The transition from a plain tag to a data-tag still needs a design. + +**Fix:** Keep `tags_as_data` provisional, with possible future removal, and warn +once per process on the first use of a non-empty mapping. When in doubt, start +with a data-tag or start with data and promote it later. diff --git a/docs/reference/golden-hashes.md b/docs/reference/golden-hashes.md index 8e26952ee..513409da7 100644 --- a/docs/reference/golden-hashes.md +++ b/docs/reference/golden-hashes.md @@ -38,6 +38,10 @@ wanted on purpose starts a new data context version. It never edits a released v the developer's approval of the exact list. So the promise on this page holds for a pipeline only when it contains none of them. See [Provisional files](#provisional-files). +!!! warning "Provisional" + The [`tags_as_data` argument](../concepts/sources.md#provisional-sources) may + change or be removed in a later version. + ## The pieces at a glance The mechanism has five layers. Each one is checked against the layer below it, and the last diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 157986c24..6e3f8834a 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -157,6 +157,10 @@ renaming a label moves every hash it feeds, and with it the paths and keys built ### Default source ids and row identifiers +!!! warning "Provisional" + The [`tags_as_data` argument](../concepts/sources.md#provisional-sources) may + change or be removed in a later version. + A source id is the source's name (rule 7), and every source id is `_v:` (developer, November 23, 2026, ITL-1425). The kind part, `_v`, is the class's `SOURCE_KIND` (also its config type key: one vocabulary) and its `SOURCE_VERSION`, the diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index b863cf5cd..8aad06dec 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3533,7 +3533,8 @@ def as_source( tags_as_data: Maps a tag column of this node to the name of a data column that receives a copy of it. When given, the result is a new root source with its own provenance, which needs a - ``source_id``; see ``DerivedSource``. + ``source_id``. This argument is provisional and may change or + be removed in a later version. source_id: The source's name. Required with ``tags_as_data``, which has no default (ITL-1313). diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 83a1d406c..42e454db8 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -2304,7 +2304,8 @@ def as_source( tags_as_data: Maps a tag column of this node to the name of a data column that receives a copy of it. When given, the result is a new root source with its own provenance, which needs a - ``source_id``; see ``DerivedSource``. + ``source_id``. This argument is provisional and may change or + be removed in a later version. source_id: The source's name. Required with ``tags_as_data``, which has no default (ITL-1313). diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 1b00e7b05..0a9ae1fd8 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -15,7 +15,10 @@ from typing_extensions import override from orcapod.core.sources.base import RootSource -from orcapod.core.sources.provisional import warn_provisional_source +from orcapod.core.sources.provisional import ( + warn_provisional_source, + warn_provisional_tags_as_data, +) from orcapod.core.sources.reload import same_rows from orcapod.core.sources.source_ids import hash_source_name from orcapod.core.sources.stream_builder import ( @@ -170,7 +173,8 @@ class DerivedSource(RootSource): ``:`` of the origin's content hash, so its id is ``derived_v1:semantic_v1:``. tags_as_data: Maps a tag column of the origin to the name of the data - column that receives a copy of it. + column that receives a copy of it. This argument is provisional and + may change or be removed in a later version. record_id_columns: Key columns whose values identify a row in record IDs and provenance tokens, instead of the row position. Only with ``tags_as_data``. @@ -301,6 +305,8 @@ def __init__( # (ITL-1425): ``derived_v1::``. source_id = hash_source_name(origin.content_hash()) super().__init__(source_id=source_id, **kwargs) + if self._tags_as_data: + warn_provisional_tags_as_data() self._origin = origin self._record_id_columns = key_columns self._key_columns = key_columns or () diff --git a/src/orcapod/core/sources/provisional.py b/src/orcapod/core/sources/provisional.py index ee82a75f6..71f821847 100644 --- a/src/orcapod/core/sources/provisional.py +++ b/src/orcapod/core/sources/provisional.py @@ -54,3 +54,14 @@ def warn_provisional_source(name: str) -> None: "docs/concepts/sources.md. To silence: warnings.filterwarnings('ignore', " "category=orcapod.errors.ProvisionalHashWarning).", ) + + +def warn_provisional_tags_as_data() -> None: + """Warn that the tag-copy argument is provisional, independently of source identity.""" + warn_provisional_use( + "tags_as_data", + "tags_as_data is provisional and may change or be removed in a later version. " + "When in doubt, declare the column as a data-tag (or at least as data) at the " + "source.", + record_identity=False, + ) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index dcdd309c5..d310f88a9 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -60,6 +60,7 @@ from orcapod.core.data_tags import TagOnlyColumns, source_data_tags from orcapod.core.sources.source_ids import joined_location, location_source_name from orcapod.core.sources.derived_source import validate_tags_as_data +from orcapod.core.sources.provisional import warn_provisional_tags_as_data from orcapod.core.sources.stream_builder import ( require_custom_system_tags, require_supported_nullable_types, @@ -274,7 +275,9 @@ class SpiralDBTableSource(RootSource): a data-tag: also a data column of the same name (ITL-1023). tags_as_data: Maps a key column that is a tag column of this source to the name of a data column that receives a copy of it, as in - ``DerivedSource``. ``None`` (default) or an empty mapping copies nothing. + ``DerivedSource``. This argument is provisional and may change or be + removed in a later version. ``None`` (default) or an empty mapping + copies nothing. Raises: ValueError: If the table is not found, has no key schema, a tag column or a @@ -365,6 +368,8 @@ def __init__( self._batch_rows = batch_rows self._given_asof = asof self._tags_as_data: dict[str, str] = dict(tags_as_data) if tags_as_data else {} + if self._tags_as_data: + warn_provisional_tags_as_data() location = f"SpiralDB project {project_id!r}, dataset {dataset!r}" try: diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index a748add05..13fdcf660 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -880,7 +880,7 @@ class OrcapodDatabaseContentWarning(UserWarning): class ProvisionalHashWarning(UserWarning): - """A value type or an operator was used whose identity is provisional. + """A provisional identity or feature was used. The library value types (``numpy.ndarray``, ``torch.Tensor``, pandas and polars ``DataFrame`` and ``Series``) are hashed and stored with formats that may still @@ -897,11 +897,14 @@ class ProvisionalHashWarning(UserWarning): downstream of it, which are then computed again. The warning is issued once per operator per process, when the operator is constructed. - A provisional source (``orcapod.sources.PROVISIONAL_SOURCES``, ITL-1314; today - ``PollingSource``) has a default source id and a content hash that are not frozen + A provisional source (``orcapod.sources.PROVISIONAL_SOURCES``, ITL-1314) + has a default source id and a content hash that are not frozen with data context v1. The warning is issued once per source kind per process, when the source is constructed (also from a saved config). + The ``tags_as_data`` argument itself is provisional (ITL-1020). Its warning is + issued once per process on the first use of a non-empty mapping. + To silence it, call ``warnings.filterwarnings("ignore", category=ProvisionalHashWarning)`` after importing Orcapod. Python's ``-W`` option and ``PYTHONWARNINGS`` cannot name this class: they are read before installed diff --git a/src/orcapod/utils/provisional.py b/src/orcapod/utils/provisional.py index 2e1657250..18b3c816c 100644 --- a/src/orcapod/utils/provisional.py +++ b/src/orcapod/utils/provisional.py @@ -1,10 +1,10 @@ -"""Uses of provisional features: the record of which ones a block of code used (ITL-1266). +"""Warnings for provisional features and tracking of provisional identities (ITL-1266). -A provisional feature is one whose identity is not frozen with the current data context: a +A feature whose identity is not frozen with the current data context can be a provisional operator (``core/operators/provisional.py``) or a provisional source -(``core/sources/provisional.py``). Its hashes may change in a later -release, so the golden values that depend on it are kept outside the frozen golden files. -Each provisional feature calls ``note_provisional_use`` with its name whenever it is used, +(``core/sources/provisional.py``). Its hashes may change in a later release, so the golden +values that depend on it are kept outside the frozen golden files. +Each such feature calls ``note_provisional_use`` with its name whenever it is used, before its once-per-process warning; ``recording_provisional_uses`` collects those names for a block of code. The golden hash tool runs each golden case inside one, so a case that uses a provisional feature it does not declare is refused. Recording changes no warning: @@ -79,19 +79,25 @@ def provisional_class_name(cls: type) -> str | None: return None -def warn_provisional_use(name: str, message: str) -> None: - """Note the use of a provisional feature and warn, once per feature per process. +def warn_provisional_use( + name: str, message: str, *, record_identity: bool = True +) -> None: + """Warn once per feature per process and optionally record identity use. - The use is noted every time (``note_provisional_use``). ``ProvisionalHashWarning`` - is issued the first time ``name`` is used in the process, and recorded as issued only - after ``warnings.warn`` returns, so under an error filter every use raises. It is - attributed to the first frame outside Orcapod, the code that used the feature. + With ``record_identity``, the use is noted every time (``note_provisional_use``). + ``ProvisionalHashWarning`` is issued the first time ``name`` is used in the process, + and recorded as issued only after ``warnings.warn`` returns, so under an error filter + every use raises. It is attributed to the first frame outside Orcapod, the code that + used the feature. Args: name: The feature's name, e.g. ``PolarsFilter`` or ``PollingSource``. message: The warning text. + record_identity: Whether golden cases must declare this provisional identity. + Pass false for provisional APIs that do not change the hash freeze. """ - note_provisional_use(name) + if record_identity: + note_provisional_use(name) if name in _issued: return with _lock: diff --git a/tests/test_core/sources/test_derived_source_tags_as_data.py b/tests/test_core/sources/test_derived_source_tags_as_data.py index 61fff09d3..f144d72e8 100644 --- a/tests/test_core/sources/test_derived_source_tags_as_data.py +++ b/tests/test_core/sources/test_derived_source_tags_as_data.py @@ -32,6 +32,10 @@ from ..operators.several_items import MAIN, TAGS_FIRST, Arrangement, make_source +pytestmark = pytest.mark.filterwarnings( + "ignore:tags_as_data is provisional:orcapod.errors.ProvisionalHashWarning" +) + UTC = dt.timezone.utc TS = pa.timestamp("us", tz="UTC") S1 = dt.datetime(2026, 1, 5, 9, 0, tzinfo=UTC) diff --git a/tests/test_core/sources/test_provisional_sources.py b/tests/test_core/sources/test_provisional_sources.py index 8c67b7eb0..acb2fc7e2 100644 --- a/tests/test_core/sources/test_provisional_sources.py +++ b/tests/test_core/sources/test_provisional_sources.py @@ -270,8 +270,9 @@ def test_derived_source_warns_once_for_every_form_and_node_kind() -> None: _ = build(job) _ = build(job) messages = _provisional_warnings(caught) - assert len(messages) == 1, messages + assert len(messages) == 2, messages assert messages[0].startswith("DerivedSource is provisional") + assert messages[1].startswith("tags_as_data is provisional") @pytest.mark.parametrize("form", sorted(DERIVED_FORMS)) @@ -284,12 +285,30 @@ def test_each_derived_form_warns_in_a_new_process(form: str) -> None: warnings.simplefilter("always") with recording_provisional_uses() as used: _ = DERIVED_FORMS[form](job) - assert [m.split(" ", 1)[0] for m in _provisional_warnings(caught)] == [ - "DerivedSource" - ] + _ = DERIVED_FORMS[form](job) + identity, *feature = _provisional_warnings(caught) + assert identity.startswith("DerivedSource is provisional") + if form.startswith("tags_as_data"): + assert feature == [ + "tags_as_data is provisional and may change or be removed in a later " + "version. When in doubt, declare the column as a data-tag (or at least " + "as data) at the source." + ] + else: + assert feature == [] assert used == {"DerivedSource"} +def test_an_empty_mapping_does_not_warn_about_tags_as_data() -> None: + job = _ran_job() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + _ = DerivedSource(_origin(), tags_as_data={}, source_id="empty") + _ = job.nodes["total"].as_source(tags_as_data={}, source_id="empty_node") + (identity,) = _provisional_warnings(caught) + assert identity.startswith("DerivedSource is provisional") + + def _csv_origin(tmp_path: Any) -> Any: """An origin that a config can rebuild: two tags and two data columns.""" from orcapod.sources import CSVSource @@ -313,7 +332,8 @@ def test_derived_source_from_config_warns(tmp_path: Any) -> None: rebuilt = DerivedSource.from_config(config) assert rebuilt.source_id == "derived_v1:copied" assert [m.split(" ", 1)[0] for m in _provisional_warnings(caught)] == [ - "DerivedSource" + "DerivedSource", + "tags_as_data", ] @@ -337,7 +357,8 @@ def test_a_loaded_job_reading_a_derived_source_warns(tmp_path: Any) -> None: loaded = PipelineJob.load(path, database=InMemoryArrowDatabase()) assert isinstance(loaded.sources["copied"], DerivedSource) assert [m.split(" ", 1)[0] for m in _provisional_warnings(caught)] == [ - "DerivedSource" + "DerivedSource", + "tags_as_data", ] diff --git a/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py b/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py index df2e8e7d9..1166bf5eb 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py +++ b/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py @@ -9,6 +9,8 @@ import asyncio import json +import warnings +from collections.abc import Iterator from pathlib import Path from typing import Any, cast @@ -17,12 +19,24 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import DeltaTableDatabase -from orcapod.errors import InputValidationError, SourceTooLargeError +from orcapod.errors import ( + InputValidationError, + ProvisionalHashWarning, + SourceTooLargeError, +) from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.serialization import resolve_source_from_config -from orcapod.sources import SpiralDBTableSource +from orcapod.sources import DerivedSource, SpiralDBTableSource +from orcapod.utils.provisional import ( + recording_provisional_uses, + reset_provisional_use_warnings, +) from tests.test_databases import fake_spiral_sdk +pytestmark = pytest.mark.filterwarnings( + "ignore:tags_as_data is provisional:orcapod.errors.ProvisionalHashWarning" +) + _PROJECT = "edi-sample" _KEYS = pa.schema( [ @@ -77,6 +91,37 @@ def _source(**kwargs: Any) -> SpiralDBTableSource: return SpiralDBTableSource(_PROJECT, "spike", **kwargs) +@pytest.fixture() +def fresh_process() -> Iterator[None]: + """Start with the once-per-process warnings unused.""" + reset_provisional_use_warnings() + yield + reset_provisional_use_warnings() + + +def test_only_nonempty_mappings_warn_once_across_source_types( + project, fresh_process: None +) -> None: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", ProvisionalHashWarning) + origin = _source() + _ = _source(tags_as_data={}) + assert not any(w.category is ProvisionalHashWarning for w in caught) + with recording_provisional_uses() as used: + _ = _source(tags_as_data=_COPY) + _ = _source(tags_as_data={"unit_id": "unit"}) + assert used == set() + _ = DerivedSource(origin, tags_as_data=_COPY, source_id="derived") + + feature, identity = [ + str(w.message) for w in caught if w.category is ProvisionalHashWarning + ] + assert feature.startswith( + "tags_as_data is provisional and may change or be removed in a later version." + ) + assert identity.startswith("DerivedSource is provisional") + + def _column(name: str, table: pa.Table) -> list[Any]: """Return the values of column ``name`` of ``table``.""" return table.column(name).to_pylist() From dc6167ef823935af0990887c6c9b03248e7bfe0f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:02:40 -0800 Subject: [PATCH 2/2] fix(sources): warn for each provisional tag-copy route --- changelog.d/ITL-1020.md | 5 +- docs/concepts/sources.md | 9 ++- docs/dev/design_issues/ITL-1020-TAD1.md | 5 +- src/orcapod/core/nodes/function_node.py | 10 ++- src/orcapod/core/nodes/operator_node.py | 10 ++- src/orcapod/core/operators/group_by.py | 9 ++- src/orcapod/core/sources/derived_source.py | 15 ++++- src/orcapod/core/sources/provisional.py | 14 +++-- .../core/sources/spiraldb_table_source.py | 12 ++-- src/orcapod/errors.py | 8 ++- src/orcapod/pipeline/job.py | 13 ++-- src/orcapod/pipeline/serialization.py | 22 +++++++ .../sources/test_provisional_sources.py | 63 ++++++++++++++----- ...test_spiraldb_table_source_tags_as_data.py | 17 +++-- tests/test_docs/test_site_content.py | 10 +++ 15 files changed, 170 insertions(+), 52 deletions(-) diff --git a/changelog.d/ITL-1020.md b/changelog.d/ITL-1020.md index c6e36a702..e8f764b60 100644 --- a/changelog.d/ITL-1020.md +++ b/changelog.d/ITL-1020.md @@ -1,7 +1,8 @@ ### Changed -- A non-empty `tags_as_data` mapping now warns once per process across - `DerivedSource`, `node.as_source()` and `SpiralDBTableSource`. +- A non-empty `tags_as_data` mapping now warns once per process for each of + `DerivedSource`, `node.as_source()`, and `SpiralDBTableSource`, including when + a saved job is loaded and its source stays unbound. ### Known limitations diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index fa87a9cee..80a5ca7fe 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -1033,9 +1033,12 @@ per source kind per process; filter its class to silence it, as for with a data-tag at the source, or start with data and promote it to a data-tag if needed. How to promote a plain tag to a data-tag is still being designed. - A non-empty mapping warns once per process across `DerivedSource`, - `node.as_source()` and `SpiralDBTableSource`. This warning covers the argument - itself and is separate from the warning about `DerivedSource` identity. + A non-empty mapping warns on first use per process for each of + `DerivedSource`, `node.as_source()` (shared by function and operator nodes), + and `SpiralDBTableSource`. Loading a job with such a mapping also warns for + that route, even if the source stays unbound. Saved node-backed sources use + the `node.as_source()` route. The warning about `DerivedSource` identity is + still issued separately. ## What a source does at a run diff --git a/docs/dev/design_issues/ITL-1020-TAD1.md b/docs/dev/design_issues/ITL-1020-TAD1.md index 792e8c904..5b8f381b2 100644 --- a/docs/dev/design_issues/ITL-1020-TAD1.md +++ b/docs/dev/design_issues/ITL-1020-TAD1.md @@ -10,5 +10,6 @@ Removing `tags_as_data` would break existing callers that copy tag values into data columns. The transition from a plain tag to a data-tag still needs a design. **Fix:** Keep `tags_as_data` provisional, with possible future removal, and warn -once per process on the first use of a non-empty mapping. When in doubt, start -with a data-tag or start with data and promote it later. +once per process per route on the first use of a non-empty mapping, including +when loading a saved job whose source stays unbound. When in doubt, start with +a data-tag or start with data and promote it later. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 573c890cc..adf1339bd 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3548,8 +3548,13 @@ def as_source( tags_as_data: Maps a tag column of this node to the name of a data column that receives a copy of it. When given, the result is a new root source with its own provenance, which needs a - ``source_id``. This argument is provisional and may change or - be removed in a later version. + ``source_id``. + + :::caution[Provisional] + `tags_as_data` may change or be removed in a later version. Start + with a data-tag at the source, or start with data and promote it + to a data-tag if needed. + ::: source_id: The source's name. Required with ``tags_as_data``, which has no default (ITL-1313). @@ -3573,6 +3578,7 @@ def as_source( tags_as_data=tags_as_data, data_context=self.data_context_key, config=self.orcapod_config, + _tags_as_data_route="node.as_source()", ) # ------------------------------------------------------------------ diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index dba16f22a..de0db6f56 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -2346,8 +2346,13 @@ def as_source( tags_as_data: Maps a tag column of this node to the name of a data column that receives a copy of it. When given, the result is a new root source with its own provenance, which needs a - ``source_id``. This argument is provisional and may change or - be removed in a later version. + ``source_id``. + + :::caution[Provisional] + `tags_as_data` may change or be removed in a later version. Start + with a data-tag at the source, or start with data and promote it + to a data-tag if needed. + ::: source_id: The source's name. Required with ``tags_as_data``, which has no default (ITL-1313). @@ -2371,6 +2376,7 @@ def as_source( tags_as_data=tags_as_data, data_context=self.data_context_key, config=self.orcapod_config, + _tags_as_data_route="node.as_source()", ) # ------------------------------------------------------------------ diff --git a/src/orcapod/core/operators/group_by.py b/src/orcapod/core/operators/group_by.py index c544fee70..6e551eb7b 100644 --- a/src/orcapod/core/operators/group_by.py +++ b/src/orcapod/core/operators/group_by.py @@ -233,8 +233,7 @@ class GroupBy(UnaryOperator): the input. The members' values of a dropped plain tag are not carried anywhere. If a downstream step needs to know which member each element came from, make that value a data column before grouping: declare the tag - a data-tag at the source (the default), declare it as data, or use - ``DerivedSource(origin, tags_as_data={...})``. + a data-tag at the source (the default), or declare it as data. Members are sorted by the input's non-group-key tags in name order, each ascending with nulls last, then by the ``record_id`` columns and then the @@ -290,6 +289,12 @@ class GroupBy(UnaryOperator): has no key, so it keeps every tag column, list-valued: those lists are what tells a batch's members apart. + Warning: + ``DerivedSource(origin, tags_as_data={...})`` can copy an existing + plain tag into data before grouping, but ``tags_as_data`` may change or be + removed in a later version. Prefer a data-tag at the source, or start + with data and promote it to a data-tag if needed. + Args: by: Tag column names to group on, in any order (a set too), or one name as a string (a bare string is one name, never its characters). diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index da84566b6..4258be169 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -17,6 +17,7 @@ from orcapod.core.identity_chains import require_bound_identity_origin from orcapod.core.sources.base import RootSource from orcapod.core.sources.provisional import ( + TagsAsDataRoute, warn_provisional_source, warn_provisional_tags_as_data, ) @@ -174,8 +175,13 @@ class DerivedSource(RootSource): ``:`` of the origin's content hash, so its id is ``derived_v1:semantic_v1:``. tags_as_data: Maps a tag column of the origin to the name of the data - column that receives a copy of it. This argument is provisional and - may change or be removed in a later version. + column that receives a copy of it. + + :::caution[Provisional] + `tags_as_data` may change or be removed in a later version. Start + with a data-tag at the source, or start with data and promote it + to a data-tag if needed. + ::: record_id_columns: Key columns whose values identify a row in record IDs and provenance tokens, instead of the row position. Only with ``tags_as_data``. @@ -269,6 +275,9 @@ def __init__( from orcapod.core.nodes.staleness import RunHoldingNode from orcapod.pipeline.source_consistency import require_live_source_bindings + # A direct constructor call can also take a job node. The two as_source + # methods explicitly identify their route. + route: TagsAsDataRoute = kwargs.pop("_tags_as_data_route", "DerivedSource") key_columns = normalize_record_id_columns(record_id_columns) if tags_as_data is None: if isinstance(origin, RootSource): @@ -307,7 +316,7 @@ def __init__( source_id = hash_source_name(origin.content_hash()) super().__init__(source_id=source_id, **kwargs) if self._tags_as_data: - warn_provisional_tags_as_data() + warn_provisional_tags_as_data(route) self._origin = origin self._record_id_columns = key_columns self._key_columns = key_columns or () diff --git a/src/orcapod/core/sources/provisional.py b/src/orcapod/core/sources/provisional.py index 71f821847..fa71d6a60 100644 --- a/src/orcapod/core/sources/provisional.py +++ b/src/orcapod/core/sources/provisional.py @@ -20,6 +20,7 @@ from collections.abc import Mapping from types import MappingProxyType +from typing import Literal, TypeAlias from orcapod.utils.provisional import warn_provisional_use @@ -56,12 +57,17 @@ def warn_provisional_source(name: str) -> None: ) -def warn_provisional_tags_as_data() -> None: - """Warn that the tag-copy argument is provisional, independently of source identity.""" +TagsAsDataRoute: TypeAlias = Literal[ + "DerivedSource", "node.as_source()", "SpiralDBTableSource" +] + + +def warn_provisional_tags_as_data(route: TagsAsDataRoute) -> None: + """Warn once per route for the tag-copy argument, separately from identity.""" warn_provisional_use( - "tags_as_data", + f"tags_as_data:{route}", "tags_as_data is provisional and may change or be removed in a later version. " "When in doubt, declare the column as a data-tag (or at least as data) at the " - "source.", + f"source. Used via {route}.", record_identity=False, ) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index d310f88a9..b674a23a8 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -275,9 +275,13 @@ class SpiralDBTableSource(RootSource): a data-tag: also a data column of the same name (ITL-1023). tags_as_data: Maps a key column that is a tag column of this source to the name of a data column that receives a copy of it, as in - ``DerivedSource``. This argument is provisional and may change or be - removed in a later version. ``None`` (default) or an empty mapping - copies nothing. + ``DerivedSource``. ``None`` (default) or an empty mapping copies nothing. + + :::caution[Provisional] + `tags_as_data` may change or be removed in a later version. Start + with a data-tag at the source, or start with data and promote it + to a data-tag if needed. + ::: Raises: ValueError: If the table is not found, has no key schema, a tag column or a @@ -369,7 +373,7 @@ def __init__( self._given_asof = asof self._tags_as_data: dict[str, str] = dict(tags_as_data) if tags_as_data else {} if self._tags_as_data: - warn_provisional_tags_as_data() + warn_provisional_tags_as_data("SpiralDBTableSource") location = f"SpiralDB project {project_id!r}, dataset {dataset!r}" try: diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 13fdcf660..0fdbf1ab4 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -902,13 +902,15 @@ class ProvisionalHashWarning(UserWarning): with data context v1. The warning is issued once per source kind per process, when the source is constructed (also from a saved config). - The ``tags_as_data`` argument itself is provisional (ITL-1020). Its warning is - issued once per process on the first use of a non-empty mapping. - To silence it, call ``warnings.filterwarnings("ignore", category=ProvisionalHashWarning)`` after importing Orcapod. Python's ``-W`` option and ``PYTHONWARNINGS`` cannot name this class: they are read before installed packages can be imported. + + Warning: + ``tags_as_data`` may change or be removed in a later version (ITL-1020). + A non-empty mapping warns once per route per process. Prefer a data-tag + at the source, or start with data and promote it to a data-tag if needed. """ diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 5b9dbc7ef..975dde168 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1986,6 +1986,7 @@ def load( saved_connector_kind, saved_database_kind, saved_source_kind, + warn_saved_tags_as_data, ) path = _Path(path) @@ -2068,6 +2069,7 @@ def load( except ValueError as exc: raise ValueError(f"{path}: source {spec_name!r}: {exc}") from exc failure: Exception | None = None + source: cp.StreamProtocol | None = None try: # Slots written with the same complete config share one rebuild. config_key = _json.dumps(src_config, sort_keys=True) @@ -2078,9 +2080,15 @@ def load( deepcopy(src_config) ) source = sources_by_config[config_key] + except Warning: + # A warning treated as an error propagates (ITL-1331). + raise except Exception as exc: failure = exc - else: + # A failed rebuild can leave a source or a nested source unbound. + # Check what the saved config uses regardless of what was rebuilt. + warn_saved_tags_as_data(src_config) + if failure is None: if source is None: unresolved_sources[spec_name] = src_config continue @@ -2111,9 +2119,6 @@ def load( spec_name, ) elif isinstance(failure, Warning): - # A warning turned into an error (a ProvisionalHashWarning under an - # error filter) is the caller's request: it propagates, never read as a - # source that could not be rebuilt (ITL-1331). raise failure elif failure is not None: logger.warning( diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 3ea71f25c..f58b4638e 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -2135,6 +2135,28 @@ def saved_fall_through_tags(descriptor: dict[str, Any]) -> tuple[str, ...]: NESTED_SOURCE_CONFIG_KEYS = ("inner_source", "origin") +def warn_saved_tags_as_data(config: dict[str, Any]) -> None: + """Warn from saved source configs, including any source that cannot be rebuilt.""" + from orcapod.core.sources.derived_source import DerivedSource + from orcapod.core.sources.provisional import warn_provisional_tags_as_data + from orcapod.core.sources.spiraldb_table_source import SpiralDBTableSource + + if config.get("tags_as_data"): + kind = config.get("source_type") + if kind == DerivedSource.SOURCE_KIND: + # A node-backed config has no embedded origin and does not distinguish + # as_source() from an explicit DerivedSource over the same node. + warn_provisional_tags_as_data( + "node.as_source()" if config.get("origin") is None else "DerivedSource" + ) + elif kind == SpiralDBTableSource.SOURCE_KIND: + warn_provisional_tags_as_data("SpiralDBTableSource") + for key in NESTED_SOURCE_CONFIG_KEYS: + nested = config.get(key) + if isinstance(nested, dict): + warn_saved_tags_as_data(cast("dict[str, Any]", nested)) + + def check_saved_source_config(config: dict[str, Any]) -> None: """Refuse a saved source config whose own entries are malformed. diff --git a/tests/test_core/sources/test_provisional_sources.py b/tests/test_core/sources/test_provisional_sources.py index acb2fc7e2..9506395c7 100644 --- a/tests/test_core/sources/test_provisional_sources.py +++ b/tests/test_core/sources/test_provisional_sources.py @@ -270,9 +270,10 @@ def test_derived_source_warns_once_for_every_form_and_node_kind() -> None: _ = build(job) _ = build(job) messages = _provisional_warnings(caught) - assert len(messages) == 2, messages + assert len(messages) == 3, messages assert messages[0].startswith("DerivedSource is provisional") - assert messages[1].startswith("tags_as_data is provisional") + assert messages[1].endswith("Used via DerivedSource.") + assert messages[2].endswith("Used via node.as_source().") @pytest.mark.parametrize("form", sorted(DERIVED_FORMS)) @@ -289,11 +290,10 @@ def test_each_derived_form_warns_in_a_new_process(form: str) -> None: identity, *feature = _provisional_warnings(caught) assert identity.startswith("DerivedSource is provisional") if form.startswith("tags_as_data"): - assert feature == [ - "tags_as_data is provisional and may change or be removed in a later " - "version. When in doubt, declare the column as a data-tag (or at least " - "as data) at the source." - ] + (message,) = feature + assert message.startswith("tags_as_data is provisional") + route = "node.as_source()" if " node" in form else "DerivedSource" + assert message.endswith(f"Used via {route}.") else: assert feature == [] assert used == {"DerivedSource"} @@ -473,6 +473,12 @@ def test_reading_a_polling_sources_identity_structure_is_a_use() -> None: NODE_BACKED: dict[str, Any] = { "plain over the function node": lambda job: job.nodes["total"].as_source(), "plain over the operator node": lambda job: job.nodes["picked"].as_source(), + "empty mapping over the function node": lambda job: job.nodes["total"].as_source( + tags_as_data={}, source_id="total_empty" + ), + "tags_as_data over the function node": lambda job: job.nodes["total"].as_source( + tags_as_data=AS_DATA, source_id="total_copied" + ), "tags_as_data over the operator node": lambda job: job.nodes["picked"].as_source( tags_as_data=AS_DATA, source_id="picked_copied" ), @@ -498,26 +504,51 @@ def _consumer_job(tmp_path: Any, build: Any) -> Any: return path -@pytest.mark.parametrize("form", sorted(NODE_BACKED)) -def test_a_loaded_job_over_a_node_backed_derived_source_warns( +@pytest.mark.parametrize("form", ["over an in-memory source", *sorted(NODE_BACKED)]) +def test_a_loaded_job_over_an_unbound_derived_source_warns( tmp_path: Any, form: str ) -> None: - """Its origin cannot be rebuilt, but the load still warns once and notes the use - (Codex review 2 of PR 469).""" + """The saved mapping warns once even though the origin cannot be rebuilt.""" from orcapod import PipelineJob from orcapod.databases import InMemoryArrowDatabase - path = _consumer_job(tmp_path, NODE_BACKED[form]) + build = NODE_BACKED.get(form, DERIVED_FORMS["tags_as_data over a source"]) + path = _consumer_job(tmp_path, build) reset_provisional_use_warnings() with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") with recording_provisional_uses() as used: loaded = PipelineJob.load(path, database=InMemoryArrowDatabase()) - assert [m.split(" ", 1)[0] for m in _provisional_warnings(caught)] == [ - "DerivedSource" - ] - assert "DerivedSource" in used + _ = PipelineJob.load(path, database=InMemoryArrowDatabase()) + identity, *feature = _provisional_warnings(caught) + assert identity.startswith("DerivedSource is provisional") + if form.startswith(("plain", "empty mapping")): + assert feature == [] + else: + (message,) = feature + assert message.startswith("tags_as_data is provisional") + route = "node.as_source()" if "node" in form else "DerivedSource" + assert message.endswith(f"Used via {route}.") + assert used == {"DerivedSource"} assert loaded.sources == {} + assert len(loaded.unbound_sources) == 1 + + +def test_loading_an_unbound_job_honors_the_tags_as_data_error_filter( + tmp_path: Any, +) -> None: + from orcapod import PipelineJob + from orcapod.databases import InMemoryArrowDatabase + + path = _consumer_job(tmp_path, NODE_BACKED["tags_as_data over the function node"]) + reset_provisional_use_warnings() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + warnings.filterwarnings( + "error", "^tags_as_data is provisional", ProvisionalHashWarning + ) + with pytest.raises(ProvisionalHashWarning, match="Used via node.as_source"): + _ = PipelineJob.load(path, database=InMemoryArrowDatabase()) @pytest.mark.parametrize("form", ["over a CSV source", *sorted(NODE_BACKED)]) diff --git a/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py b/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py index 1166bf5eb..cd2a0e8c9 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py +++ b/tests/test_core/sources/test_spiraldb_table_source_tags_as_data.py @@ -31,6 +31,7 @@ recording_provisional_uses, reset_provisional_use_warnings, ) +from tests.test_core.sources.test_provisional_sources import AS_DATA, _ran_job from tests.test_databases import fake_spiral_sdk pytestmark = pytest.mark.filterwarnings( @@ -99,9 +100,10 @@ def fresh_process() -> Iterator[None]: reset_provisional_use_warnings() -def test_only_nonempty_mappings_warn_once_across_source_types( +def test_only_nonempty_mappings_warn_once_per_route( project, fresh_process: None ) -> None: + job = _ran_job() with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always", ProvisionalHashWarning) origin = _source() @@ -112,14 +114,19 @@ def test_only_nonempty_mappings_warn_once_across_source_types( _ = _source(tags_as_data={"unit_id": "unit"}) assert used == set() _ = DerivedSource(origin, tags_as_data=_COPY, source_id="derived") + _ = job.nodes["total"].as_source(tags_as_data=AS_DATA, source_id="total") + _ = job.nodes["picked"].as_source(tags_as_data=AS_DATA, source_id="picked") - feature, identity = [ + spiral_feature, identity, derived_feature, node_feature = [ str(w.message) for w in caught if w.category is ProvisionalHashWarning ] - assert feature.startswith( - "tags_as_data is provisional and may change or be removed in a later version." - ) + assert spiral_feature.startswith("tags_as_data is provisional") + assert spiral_feature.endswith("Used via SpiralDBTableSource.") assert identity.startswith("DerivedSource is provisional") + assert derived_feature.startswith("tags_as_data is provisional") + assert derived_feature.endswith("Used via DerivedSource.") + assert node_feature.startswith("tags_as_data is provisional") + assert node_feature.endswith("Used via node.as_source().") def _column(name: str, table: pa.Table) -> list[Any]: diff --git a/tests/test_docs/test_site_content.py b/tests/test_docs/test_site_content.py index a8fd281f6..9219f9fee 100644 --- a/tests/test_docs/test_site_content.py +++ b/tests/test_docs/test_site_content.py @@ -15,6 +15,7 @@ import json import os +import re import subprocess import sys from pathlib import Path @@ -105,6 +106,15 @@ def test_the_documentation_builds(tmp_path: Path): assert '' in api assert "\n::: " not in api + for page, count in {"sources": 2, "nodes": 2, "operators": 1, "errors": 1}.items(): + api = (out / "api" / f"{page}.md").read_text(encoding="utf-8") + notices = re.findall(r":::caution\[[^\n]*\]\n(.*?)\n *:::", api, re.DOTALL) + notices = [notice for notice in notices if "tags_as_data" in notice] + assert len(notices) == count, page + for notice in notices: + assert "may change or be removed" in " ".join(notice.split()), page + assert "data-tag" in notice, page + def test_the_build_is_deterministic(tmp_path: Path): first, out_a, _ = run_build(REPO_ROOT / "docs", tmp_path / "a", hero=True)