diff --git a/.zed/rules b/.zed/rules index c42e2dddc..4ffbf3a0d 100644 --- a/.zed/rules +++ b/.zed/rules @@ -914,6 +914,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 88233057c..d7369f38e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -934,6 +934,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..e8f764b60 --- /dev/null +++ b/changelog.d/ITL-1020.md @@ -0,0 +1,11 @@ +### Changed + +- 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 + +- 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 a985961f4..ac4d034b1 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 fc99ce262..403031655 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -845,6 +845,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( @@ -947,7 +952,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 @@ -1061,6 +1067,18 @@ 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 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 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..5b8f381b2 --- /dev/null +++ b/docs/dev/design_issues/ITL-1020-TAD1.md @@ -0,0 +1,15 @@ +## 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 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/docs/reference/golden-hashes.md b/docs/reference/golden-hashes.md index 58500fbfa..5bb39f48f 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. + !!! warning "Provisional" In 0.4.0, `SideEffectPod` and its decorators are provisional: the pod's identity, when it delivers, and the layout of its delivery log may change in a later version. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index a6036fb60..dc7c0b13c 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -160,6 +160,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 6bc905919..ee700e532 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -3553,7 +3553,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``; see ``DerivedSource``. + ``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). @@ -3577,6 +3583,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 1bec000ab..de0db6f56 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -2346,7 +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``; see ``DerivedSource``. + ``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). @@ -2370,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 b92d03ffe..4258be169 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -16,7 +16,11 @@ from orcapod.core.identity_chains import require_bound_identity_origin from orcapod.core.sources.base import RootSource -from orcapod.core.sources.provisional import warn_provisional_source +from orcapod.core.sources.provisional import ( + TagsAsDataRoute, + 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 ( @@ -172,6 +176,12 @@ class DerivedSource(RootSource): ``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. + + :::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``. @@ -265,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): @@ -302,6 +315,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(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 ee82a75f6..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 @@ -54,3 +55,19 @@ def warn_provisional_source(name: str) -> None: "docs/concepts/sources.md. To silence: warnings.filterwarnings('ignore', " "category=orcapod.errors.ProvisionalHashWarning).", ) + + +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( + 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 " + 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 dcdd309c5..b674a23a8 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, @@ -276,6 +277,12 @@ class SpiralDBTableSource(RootSource): name of a data column that receives a copy of it, as in ``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 ``where`` column is not in the table, a ``where`` value is ``None``, or @@ -365,6 +372,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("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 c9e6b86f2..bdba06582 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -890,7 +890,7 @@ class OrcapodDatabaseContentWarning(UserWarning): class ProvisionalHashWarning(UserWarning): - """A feature 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 @@ -907,8 +907,8 @@ 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). @@ -923,6 +923,11 @@ class ProvisionalHashWarning(UserWarning): 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 63c332a4e..cd745867a 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -2042,6 +2042,7 @@ def load( saved_connector_kind, saved_database_kind, saved_source_kind, + warn_saved_tags_as_data, ) path = _Path(path) @@ -2124,6 +2125,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) @@ -2134,9 +2136,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 @@ -2167,9 +2175,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/src/orcapod/utils/provisional.py b/src/orcapod/utils/provisional.py index 09bb1ca75..857ab002b 100644 --- a/src/orcapod/utils/provisional.py +++ b/src/orcapod/utils/provisional.py @@ -1,11 +1,11 @@ -"""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``), a provisional source (``core/sources/provisional.py``) or a provisional pod (``core/provisional_pods.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, +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: @@ -80,19 +80,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..9506395c7 100644 --- a/tests/test_core/sources/test_provisional_sources.py +++ b/tests/test_core/sources/test_provisional_sources.py @@ -270,8 +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) == 1, messages + assert len(messages) == 3, messages assert messages[0].startswith("DerivedSource 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)) @@ -284,12 +286,29 @@ 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"): + (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"} +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", ] @@ -452,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" ), @@ -477,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 df2e8e7d9..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 @@ -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,25 @@ 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_core.sources.test_provisional_sources import AS_DATA, _ran_job 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 +92,43 @@ 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_per_route( + project, fresh_process: None +) -> None: + job = _ran_job() + 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") + _ = 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") + + spiral_feature, identity, derived_feature, node_feature = [ + str(w.message) for w in caught if w.category is ProvisionalHashWarning + ] + 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]: """Return the values of column ``name`` of ``table``.""" return table.column(name).to_pylist() 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)