diff --git a/.zed/rules b/.zed/rules index c46929a35..67395d99a 100644 --- a/.zed/rules +++ b/.zed/rules @@ -987,7 +987,7 @@ generation of hashing; rows of the current data context are the current entries. with the three row ids (developer, November 25, 2026, ITL-1471; below, "Row ids"). A change to the common bookkeeping columns of a table kind moves its layout version, so the table gets a new path. Never add, rename or retype a stored column without it. -- A function result table is at +- A plain function's result table is at //v/python.function.v1/rev1/rdb_v1, three components with three owners (docs/reference/data-function-types.md): - python.function.v1, the data function type and its MAJOR (what a function means and how it @@ -1004,6 +1004,10 @@ generation of hashing; rows of the current data context are the current entries. - Pipeline tables carry no revision (.../python.function.v1/schema:/pdb_v2). A saved job names the type and major only (data_function_type_id); the revision comes from the installed library's declaration (declaration_for(type id)). +- Context-taking result tables start with side_effect_function. They group the output + schema hash, function major and ctx: in one component to preserve the + path depth available to callers (ITL-1559). Live jobs can repeat actions recorded + at the previous paths. Saved jobs can read their original results. - A data function type's declaration (PYTHON_FUNCTION, beside its class in core/data_function.py; the classes in core/data_function_types.py, a leaf module) is the source of truth: type name, major, revision, identity recipe, run rules, and its record diff --git a/CLAUDE.md b/CLAUDE.md index 217bfd081..3b9ba4940 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1016,7 +1016,7 @@ current data context are the current entries. 2026, ITL-1471; below, "Row ids"). A change to the common bookkeeping columns of a table kind moves its layout version, so the table gets a new path. Never add, rename or retype a stored column without it. -- A function result table is at +- A plain function's result table is at `//v/python.function.v1/rev1/rdb_v1`, three components with three owners (`docs/reference/data-function-types.md`): - `python.function.v1`, the data function type and its MAJOR (what a function means and how @@ -1035,6 +1035,10 @@ current data context are the current entries. - Pipeline tables carry no revision (`.../python.function.v1/schema:/pdb_v2`). A saved job names the type and major only (`data_function_type_id`); the revision comes from the installed library's declaration (`declaration_for(type id)`). +- Context-taking result tables start with `side_effect_function`. They group the + output schema hash, function major and `ctx:` in one component to + preserve the path depth available to callers (ITL-1559). Live jobs can repeat + actions recorded at the previous paths. Saved jobs can read their original results. - A data function type's declaration (`PYTHON_FUNCTION`, beside its class in `core/data_function.py`; the classes in `core/data_function_types.py`, a leaf module) is the source of truth: type name, major, revision, identity recipe, run rules, and its record diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md new file mode 100644 index 000000000..20903c136 --- /dev/null +++ b/changelog.d/ITL-1559.md @@ -0,0 +1,23 @@ +### Breaking changes and migration + +- Function pods that receive an invocation context now include the configured parameter + name in their pipeline hash. Their pipeline tables and downstream tables that use the + affected hashes have new `schema:

` paths, and downstream system-tag column names + that incorporate those hashes change. The public idempotency key + `InvocationContext.invocation_hash` also changes for the affected function pods + and for downstream side-effect nodes whose pipeline hashes change. Tables written + by earlier development versions remain at their old paths. There is no migration + for these unreleased layouts. + Result tables for context-taking function pods include `ctx:` in + their paths. Decorator caches also move context-taking results into the + `side_effect_function` namespace. Upgraded live jobs use the new completion + and result paths, so they can repeat actions recorded at the previous paths. + Retain the original stores if saved jobs need to read their results. Use a + separate store for upgraded runs after confirming that repeat deliveries for + previously processed inputs are acceptable. + (ITL-1559) + +### Fixed + +- Loading a saved job restores context-taking function nodes, their stored results, + and their downstream dependencies. (ITL-1559) diff --git a/docs/dev/design_issues/ITL-1559-CXP1.md b/docs/dev/design_issues/ITL-1559-CXP1.md new file mode 100644 index 000000000..eeeb47352 --- /dev/null +++ b/docs/dev/design_issues/ITL-1559-CXP1.md @@ -0,0 +1,17 @@ +## `src/orcapod/core/function_pod.py` — function pod identity + +### CXP1 — Function pod pipeline identity omitted the invocation context parameter +**Status:** resolved +**Severity:** high +**Issue:** ITL-1559 + +A plain function pod and a context-taking pod with the same underlying data function URI +had the same pipeline identity. Under the three-chain design they would become one graph +node over the same slot, even though one receives an invocation context. + +**Fix:** Include the context parameter in the pipeline identity when configured, giving the +pod and its downstream steps distinct pipeline hashes. Plain pods retain the data function's +pipeline identity. Result tables for context-taking pods also include the parameter +name in their paths. An upgraded live job uses the new paths and can deliver again +for an input handled before this change. A saved job restores its context-taking +function nodes and reads their results from the original paths. diff --git a/docs/reference/data-function-types.md b/docs/reference/data-function-types.md index b2ca7bcf8..815dc5e11 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -17,8 +17,21 @@ A function stores each result in its result table, at For a job given a separate result database (`PipelineJob(..., result_database=...)`), the path starts at ``, in that database, with no `/_result`. -The first four components after `_result` are the function's uri. The last three each -have one owner: +A job's default result path for a pod configured with `ctx_arg` is + +```text +/_result/side_effect_function//:v:ctx:/python.function.v1/rev1/rdb_v1 +``` + +With an explicit result database, the path starts at `side_effect_function` in that +database. Standalone pod and decorator caches also use this path relative to +their configured databases. Context-taking paths combine the schema hash, +function major, and context parameter in one component to preserve the store +depth available to callers. Saved jobs record the result path through the type +component. + +For a plain pod the first four components after `_result` are the function's uri. The +last three components of both paths each have one owner: | Component | What it controls | Owner | In a hash | |---|---|---|---| diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 732a8a22a..b99d06705 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -613,7 +613,7 @@ The table below shows what each class returns from `identity_structure()`. | `Data` | Data columns only (raw Arrow table) | Source info columns (`_source_*`) excluded — they are provenance metadata, not data content | | `EmptyData` | Raises `EmptyDataAccessError` | `content_hash()` is overridden to return a stored `cached_content_hash` directly | | `DataFunctionBase` | `self.uri` — `(canonical_function_name, output_schema_hash, major_version, data_function_type_id)` | `output_schema_hash` is site 11; see §5 | -| `FunctionPod` | `self.data_function` (bare object) when no ctx arg; `(self.data_function, self._ctx_arg_name)` when ctx arg present | `ctx_arg_name` is included when present so a ctx-aware pod has a distinct `content_hash` from a plain pod using the same data function | +| `FunctionPod` | `self.data_function` when no context argument is configured, otherwise `(self.data_function, self._ctx_arg_name)` | Both identities include the name of the parameter that receives the invocation context when configured | | `FallThroughPod` (`pod(stream)` over data-tags) | `(plain_pod, ("fall_through_tags", sorted names))` | The data-tags that fall through are a set: sorted by name, so the order of the input's tag columns never moves the pod's hashes or its node's table paths (ITL-1246). The pod's config and a saved job's `fall_through_tags` list them sorted too | | `ArrowTableStream` | `(producer, argument_symmetry(upstreams))` | With no producer (a raw stream), or a producer that is not a `PipelineElementProtocol`: `(class_name, identity table in canonical row order, sorted tag columns)`, plus `("data_tags", sorted names)` when it has any. See "The identity of a raw stream" below | | `RootSource` (`ArrowTableSource`, `ListSource` and every other root source without its own rule) | `(source_id, (hash_schema(tag), hash_schema(data)), record ID key tuple)`, the Arrow schemas of its rows (ITL-640) | `source_id` is `_v:`, the name being the explicit user-supplied value; when not provided it defaults to `::` of the Arrow hash of the raw table (site 4). The class name is not part of it (ITL-1425): the kind part names the kind and implementation version, and the kind enters a datum's identity there only. `PollingSource` is `(source_id, impl.identity(), sorted tag columns, record ID key tuple)` (provisional, ITL-1316). The record ID key tuple lists the columns used to identify rows, in key order (`record_id_columns`, or a database or SpiralDB table's primary key), `()` for the position: two sources that differ only in how they name their rows are two sources (developer decision, November 16, 2026, ITL-1154). Data-inclusive base case of the Merkle chain. A `ListSource` has no rule of its own (developer, November 21, 2026, ITL-1272): its elements and tags enter its identity only through its default source id and its Arrow schema (their types), and with a given `source_id` it is an address like every other source (other elements of the same types leave its content hash unchanged); it used to hold its elements and a hash of its tag function (and took `tag_function_hash_mode`), and with a given `source_id` its content hash did not depend on that id at all. A review of every built-in source's identity is ITL-1311 | @@ -728,13 +728,17 @@ The pipeline hash uses the same `SemanticAwarePythonHasher` with the **`pipeline | `DerivedSource` | `(hash_schema(tag), hash_schema(data))` | Acts as a new root in the pipeline Merkle chain; the Arrow types are its origin's (its typed zero-row table), so they do not change when rows are stored | | `SourceNode`, `SourceJobNode` | `(hash_schema(tag), hash_schema(data))` of the slot's Arrow schemas | A slot made from a stream holds that stream's Arrow types; a slot declared with Python types holds the converter's (one Arrow type per Python type) | | `DataFunctionBase` | `self.uri` (same as `identity_structure()`) | Function identity is already schema-only | -| `FunctionPod` | `self.data_function` **only** (excludes `ctx_arg_name`) | A ctx-aware pod and a plain pod over the same data function share the same `pipeline_hash` value, but have different `uri` values (`ctx_arg_name` is set → `"side_effect_function"` is prepended to the URI) and therefore write to **different** DB table paths | +| `FunctionPod` | `self.data_function` when no context argument is configured, otherwise `(self.data_function, self._ctx_arg_name)` | A context-taking pod has its own pipeline hash. Changing the configured context parameter name changes that hash even when the data function URI is the same | | `FallThroughPod` | `(plain_pod, ("fall_through_tags", sorted names))` | As its content identity: the data-tags are a set of names (ITL-1246) | | `ArrowTableStream` | `(producer, argument_symmetry(upstreams pipeline hashes))` | `pipeline_resolver` routes upstreams through `pipeline_hash()`. Falls back to the Arrow schema identity of the table it holds when producer is absent or not a `PipelineElementProtocol`. | | Operators | `(operator_class_name, argument_symmetry(upstream pipeline hashes))` | Same structure as content identity but using pipeline hashes of upstreams | | `SideEffectPodStream` | `(pod, argument_symmetry(upstreams))` | Same as `identity_structure()` | -> **Note:** `FunctionPod.ctx_arg_name` IS included in `content_hash()` (via `identity_structure()`). It is excluded only from `pipeline_identity_structure()`. A ctx-aware pod receives a system-injected `InvocationContext` argument — a deliberate deviation from the pure data-in / data-out contract — so it is kept distinct from a plain pod at every level: different `content_hash`, different `uri` (prefix `"side_effect_function"`), and different DB table path. The shared `pipeline_hash` value has no practical effect on scoping once the `uri` differs. +A context-taking `FunctionPod` receives a system-injected `InvocationContext` and adds the +`"side_effect_function"` prefix to its pod URI. The pipeline hash also distinguishes it +from a plain pod with the same underlying data function URI. The difference propagates +downstream to the `schema:

` component of stored paths and to system-tag column names +that incorporate the affected pipeline hashes. --- diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index f2f116113..edee43f22 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -23,7 +23,11 @@ data_context_field, require_storable, ) -from orcapod.core.result_cache import ResultCache, pod_timestamp_type +from orcapod.core.result_cache import ( + ResultCache, + context_result_path, + pod_timestamp_type, +) from orcapod.hooks import InvocationStatus from orcapod.protocols.core_protocols import ( FunctionPodProtocol, @@ -43,9 +47,9 @@ class CachedFunctionPod(WrappedFunctionPod): """Pod-level caching wrapper that intercepts ``process_data()``. - Caches at the ``process_data(tag, data)`` level using only the - **input data content hash** as the cache key — the output of a - data function depends solely on the data, not the tag. + Caches at the ``process_data(tag, data)`` level using the input data + content hash. Pods that take an invocation context use a result table + scoped by the configured context parameter. Tag-level provenance tracking (tag + system tags + data hash) is handled separately by ``FunctionNode.add_pipeline_record``. @@ -67,7 +71,7 @@ def __init__( super().__init__(function_pod, **kwargs) self._cache = ResultCache( result_database=result_database, - record_path=self.uri, # no prefix; db is pre-scoped + record_path=context_result_path(self.uri, self.ctx_arg_name), revision=function_pod.data_function.declaration.revision_component, auto_flush=auto_flush, # A pod that takes the invocation context performs an external action. diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 334e57413..2320ed01a 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -29,7 +29,7 @@ default_value_refused, hash_default_value, ) -from orcapod.core.result_cache import ResultCache +from orcapod.core.result_cache import ResultCache, context_result_path from orcapod.errors import ( NoOutputsDeclaredError, OutputContainerTypeError, @@ -1589,16 +1589,23 @@ def __init__( data_function: DataFunctionProtocol, result_database: ArrowDatabaseProtocol, record_path_prefix: tuple[str, ...] = (), + *, + context_parameter: str | None = None, **kwargs, ) -> None: super().__init__(data_function, **kwargs) self._result_database = result_database self._record_path_prefix = record_path_prefix + if context_parameter is not None: + record_path_prefix += ("side_effect_function",) self._cache = ResultCache( result_database=result_database, - record_path=record_path_prefix + self.uri, + record_path=context_result_path( + record_path_prefix + self.uri, context_parameter + ), revision=self.declaration.revision_component, auto_flush=True, + delivers_side_effects=context_parameter is not None, # The first uri component is the function's name; no hash before it. name_path=record_path_prefix + self.uri[:1], ) @@ -1644,9 +1651,9 @@ def call( ``**kwargs`` are forwarded to the wrapped data function's ``call`` so that auto-provided arguments (e.g. ``InvocationContext``) reach - the underlying function. They are intentionally excluded from the - cache key — such arguments are deterministic per row and pod, so the - same input data always produces the same output. + the underlying function. The configured context parameter, when present, + selects a separate result table. Lookup within a table uses the input + data hash. Raises: InputValidationError: If ``data`` is of another data context than this @@ -1665,6 +1672,8 @@ def call( if output_data is not None: module_logger.info(f"Cache hit for {data}!") return output_data + else: + self._cache.check_before_side_effect(self.data_context_key) output_data = self._data_function.call(data, logger=logger, **kwargs) if output_data is not None: if not skip_cache_insert: @@ -1708,6 +1717,8 @@ async def async_call( if output_data is not None: module_logger.info(f"Cache hit for {data}!") return output_data + else: + self._cache.check_before_side_effect(self.data_context_key) output_data = await self._data_function.async_call( data, logger=logger, **kwargs ) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 4b5f82ac0..229f2ecd4 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -186,6 +186,9 @@ def identity_structure(self) -> Any: return self.data_function def pipeline_identity_structure(self) -> Any: + """Include the parameter that receives the invocation context, when set.""" + if self._ctx_arg_name is not None: + return (self.data_function, self._ctx_arg_name) return self.data_function def _build_invocation_context( @@ -1918,6 +1921,8 @@ def function_pod( function_name: Name of the function pod; defaults to ``func.__name__``. version: Version string for the data function. label: Optional label for tracking. + ctx_arg: Name of the invocation context parameter. The pod uses this + name for injection and the decorator cache uses it to scope results. result_database: Optional database for data-level caching (wraps the data function in ``CachedDataFunction``). pod_cache_database: Optional database for pod-level caching @@ -1934,6 +1939,7 @@ def function_pod( """ def decorator(func: Callable) -> CallableWithPodProtocol: + """Build the pod and give its decorator cache the same context parameter.""" if func.__name__ == "": raise ValueError("Lambda functions cannot be used with function_pod") @@ -1952,6 +1958,7 @@ def decorator(func: Callable) -> CallableWithPodProtocol: data_function = CachedDataFunction( data_function, result_database=result_database, + context_parameter=ctx_arg, ) # Create a simple typed function pod diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 6058b1b1c..b863cf5cd 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -1140,12 +1140,7 @@ def from_descriptor( # FunctionNode loaded read-only is always UNAVAILABLE (no DB) node._load_status = LoadStatus.UNAVAILABLE - # Restore node_type from the stored URI prefix - node._node_type = ( - "side_effect_function" - if descriptor.get("node_uri", [""])[0] == "side_effect_function" - else "function" - ) + node._node_type = descriptor["node_type"] return node @@ -1886,19 +1881,26 @@ def from_descriptor( node._stored_pipeline_hash = descriptor.get("pipeline_hash") node._stored_schema = descriptor.get("output_schema", {}) node._stored_node_uri = tuple(descriptor.get("node_uri") or ()) - node._stored_result_record_path = tuple(descriptor.get("node_uri") or ()) + node._node_type = descriptor["node_type"] + # The file records the data function URI. Context-taking pods prefix + # their pipeline paths, and new files also record their result path. + pod_uri = node._stored_node_uri + if node._node_type == "side_effect_function": + pod_uri = ("side_effect_function",) + pod_uri + node._stored_result_record_path = tuple( + descriptor.get("result_record_path", pod_uri) + ) node._descriptor = descriptor node._table_scope = raw_table_scope node._node_identity_path_cache = None - # Compute _stored_pipeline_path from node_uri + pipeline_hash so that + # Compute _stored_pipeline_path from the pod URI + pipeline_hash so that # node_identity_path (used by get_all_records and _load_cached_entries) # resolves to the correct DB path. This mirrors the live computation: # path = function_pod.uri + (f"schema:{pipeline_hash}",) - # Since node_uri == function_pod.uri (same fields), we reconstruct it here. # The descriptor stores hashes as labelled values; a path holds bare digests. pipeline_hash_str = descriptor.get("pipeline_hash", "") - node._stored_pipeline_path = node._stored_node_uri + ( + node._stored_pipeline_path = pod_uri + ( f"schema:{_bare_digest(pipeline_hash_str)}", ) if raw_table_scope != "pipeline_hash": @@ -1943,13 +1945,6 @@ def from_descriptor( result_database=result_db, ) - # Restore node_type from the stored URI prefix - node._node_type = ( - "side_effect_function" - if descriptor.get("node_uri", [""])[0] == "side_effect_function" - else "function" - ) - return node # ------------------------------------------------------------------ diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index 6186c0765..5924d7f97 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -173,6 +173,20 @@ def _with_declared_token_columns( return outputs +def context_result_path( + uri: tuple[str, ...], context_parameter: str | None +) -> tuple[str, ...]: + """Scope context-taking results without adding to the store's required depth.""" + if context_parameter is None: + return uri + *name_path, output_schema_hash, major_version, function_type = uri + return ( + *name_path, + f"{output_schema_hash}:{major_version}:ctx:{context_parameter}", + function_type, + ) + + class ResultCache: """Shared result caching backed by an ``ArrowDatabaseProtocol``. @@ -293,6 +307,11 @@ def stale_tables_accounted_for(self) -> None: """ self._stale_tables_checked = True + def check_before_side_effect(self, data_context_key: str) -> None: + """Apply the stale-table check even when a call bypasses cache lookup.""" + if self._delivers_side_effects: + self._account_for_stale_tables(data_context_key) + def _account_for_stale_tables(self, data_context_key: str) -> None: """Report or refuse, once per cache object, stored results of other generations. diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 6b6eab653..46937b262 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -246,6 +246,15 @@ def save(self, path: str | Path) -> None: case FunctionNode(): if node._function_pod is not None: descriptor["function_config"] = node._function_pod.to_config() + if node._function_pod.ctx_arg_name is not None: + from orcapod.core.result_cache import context_result_path + + descriptor["result_record_path"] = list( + context_result_path( + node._function_pod.uri, + node._function_pod.ctx_arg_name, + ) + ) elif "function_config" in node._descriptor: # A loaded read-only node (its pod not rebuilt, e.g. an output # of an unregistered class) writes its saved config back as it @@ -253,6 +262,13 @@ def save(self, path: str | Path) -> None: descriptor["function_config"] = copy.deepcopy( node._descriptor["function_config"] ) + if ( + node._function_pod is None + and "result_record_path" in node._descriptor + ): + descriptor["result_record_path"] = copy.deepcopy( + node._descriptor["result_record_path"] + ) descriptor["table_scope"] = node._table_scope # Written for every function node, also a plain one (ITL-1019). descriptor[FALL_THROUGH_TAGS_KEY] = list(node.declared_data_tags()) @@ -376,12 +392,13 @@ def load(cls, path: str | Path) -> "Pipeline": deserialize_output_schema, ) + node_type = descriptor.get("node_type") # Every node records its nullability (ITL-1043), and every function node # names its data-tags (ITL-1019). try: validate_descriptor_config(descriptor.get("config")) require_nullability_records(descriptor) - if descriptor.get("node_type") == "function": + if node_type in ("function", "side_effect_function"): descriptor[FALL_THROUGH_TAGS_KEY] = list( saved_fall_through_tags(descriptor) ) @@ -409,7 +426,6 @@ def load(cls, path: str | Path) -> "Pipeline": exc, ) - node_type = descriptor.get("node_type") source_config = descriptor.get("source_config") or {} if node_type == "source": @@ -487,7 +503,7 @@ def load(cls, path: str | Path) -> "Pipeline": ) reconstructed[node_hash] = node - elif node_type == "function": + elif node_type in ("function", "side_effect_function"): up_hashes = upstream_map.get(node_hash, []) upstream_node = reconstructed.get(up_hashes[0]) if up_hashes else None node = FunctionNode.from_descriptor( diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index d64b113dc..d8b3fb44a 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -793,7 +793,8 @@ def _distribute_databases(self) -> None: self._database, self._result_database ) - for node in (self._persistent_node_map or {}).values(): + nodes = (self._persistent_node_map or {}).values() + for node in nodes: if isinstance(node, FunctionJobNode): if self._unresolved_result_database is not None: # Left without a database (see ``load``), never given ``_result``. @@ -808,7 +809,9 @@ def _distribute_databases(self) -> None: cache_mode=node.cache_mode, ) elif isinstance(node, SideEffectJobNode): - node.attach_databases(pipeline_database=pipeline_db) + node.attach_databases( + pipeline_database=pipeline_db, + ) # ------------------------------------------------------------------ # _iter_function_job_nodes() / apply_node_config() diff --git a/tests/test_core/function_pod/test_function_pod_ctx_arg.py b/tests/test_core/function_pod/test_function_pod_ctx_arg.py index 4ab26113a..bb354f7d2 100644 --- a/tests/test_core/function_pod/test_function_pod_ctx_arg.py +++ b/tests/test_core/function_pod/test_function_pod_ctx_arg.py @@ -7,11 +7,20 @@ from __future__ import annotations +import asyncio +import json +from pathlib import Path + import pytest import pyarrow as pa from orcapod.core.streams import ArrowTableStream from orcapod.side_effects import InvocationContext +from orcapod.system_constants import ( + PIPELINE_DB_SCHEMA_VERSION, + RESULT_DB_SCHEMA_VERSION, + TRACKING_DB_SCHEMA_VERSION, +) def _make_stream(n: int = 3) -> ArrowTableStream: @@ -36,6 +45,423 @@ def _make_pipeline_db(): return InMemoryArrowDatabase() +@pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("reverse_columns", [False, True]) +@pytest.mark.filterwarnings( + "ignore:Batch is provisional:orcapod.errors.ProvisionalHashWarning" +) +def test_context_parameter_distinguishes_job_branches( + tmp_path: Path, async_path: bool, reverse_columns: bool +) -> None: + """Two pods sharing a data function URI have separate identities and both run.""" + from orcapod import PipelineJob, function_pod + from orcapod.databases import DeltaTableDatabase + from orcapod.operators import Batch, Join + from orcapod.side_effects import SideEffectPod + from orcapod.sources import DictSource + from orcapod.system_constants import constants + + delivered: list[tuple[int, int]] = [] + + @function_pod(function_name="combine", output_keys=("sum", "difference")) + def plain(x: int, y: int) -> tuple[int, int]: + return x + y, x - y + + @function_pod( + function_name="combine", output_keys=("sum", "difference"), ctx_arg="ctx" + ) + def contextual(x: int, y: int, ctx: InvocationContext) -> tuple[int, int]: + assert isinstance(ctx, InvocationContext) + delivered.append((x, y)) + return x + y + 100, x - y + + tapped: list[tuple[int, int]] = [] + + def tap(sum: int, difference: int, ctx: InvocationContext) -> None: + tapped.append((sum, difference)) + + assert plain.pod.data_function.uri == contextual.pod.data_function.uri + assert plain.pod.pipeline_hash() != contextual.pod.pipeline_hash() + + rows = [ + {"id": 1, "x": 10, "group": "a", "y": 2}, + {"id": 2, "x": 20, "group": "b", "y": 3}, + ] + tags = ["id", "group"] + if reverse_columns: + rows = [dict(reversed(tuple(row.items()))) for row in rows] + tags.reverse() + source = DictSource( + rows, tag_columns=tags, tag_only_columns=True, source_id="input" + ) + right = DictSource( + [ + {"id": row["id"], "group": row["group"], "other": 5, "label": "joined"} + for row in rows + ], + tag_columns=tags, + tag_only_columns=True, + source_id="right", + ) + root = tmp_path / "store" + + def build_job() -> PipelineJob: + with PipelineJob( + name="context_identity", database=DeltaTableDatabase(root) + ) as job: + plain_stream = plain.pod(source, label="plain") + context_stream = contextual.pod(source, label="contextual") + Batch(batch_size=1).process(plain_stream, label="plain_batch") + Batch(batch_size=1).process(context_stream, label="context_batch") + Join()(plain_stream, right, label="plain_join") + Join()(context_stream, right, label="context_join") + SideEffectPod(tap).process(context_stream, label="tap") + return job + + job = build_job() + plain_node = job.nodes["plain"] + context_node = job.nodes["contextual"] + assert plain_node.pipeline_hash() != context_node.pipeline_hash() + assert plain_node.content_hash() != context_node.content_hash() + assert plain_node.node_identity_path[-1] != context_node.node_identity_path[-1] + + summary = asyncio.run(job.run_async()) if async_path else job.run() + assert summary.ok + stored_paths = {path[1:-1] for path in DeltaTableDatabase(root).list_sources()} + assert { + plain_node.node_identity_path, + context_node.node_identity_path, + } <= stored_paths + assert sorted(plain_node.as_table()["sum"].to_pylist()) == [12, 23] + assert sorted(context_node.as_table()["sum"].to_pylist()) == [112, 123] + + plain_batch = job.nodes["plain_batch"] + context_batch = job.nodes["context_batch"] + assert plain_batch.pipeline_hash() != context_batch.pipeline_hash() + plain_columns = { + col + for col in plain_batch.as_table(columns={"system_tags": True}).column_names + if col.startswith(constants.SYSTEM_TAG_PREFIX) + } + context_columns = { + col + for col in context_batch.as_table(columns={"system_tags": True}).column_names + if col.startswith(constants.SYSTEM_TAG_PREFIX) + } + assert len(plain_columns) == len(context_columns) == 2 + assert plain_columns.isdisjoint(context_columns) + + plain_join = job.nodes["plain_join"].as_table(columns={"system_tags": True}) + context_join = job.nodes["context_join"].as_table(columns={"system_tags": True}) + assert sorted(plain_join["sum"].to_pylist()) == [12, 23] + assert sorted(context_join["sum"].to_pylist()) == [112, 123] + plain_tags, contextual_tags = ( + { + name + for name in table.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + } + for table in (plain_join, context_join) + ) + assert len(plain_tags) == len(contextual_tags) == 4 + assert len(plain_tags & contextual_tags) == 2 + + assert sorted(delivered) == [(10, 2), (20, 3)] + assert sorted(tapped) == [(112, 8), (123, 17)] + reopened = build_job() + assert (asyncio.run(reopened.run_async()) if async_path else reopened.run()).ok + assert sorted(delivered) == [(10, 2), (20, 3)] + assert sorted(tapped) == [(112, 8), (123, 17)] + assert sorted(reopened.nodes["contextual"].as_table()["sum"].to_pylist()) == [ + 112, + 123, + ] + + +@pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("tap_only", [False, True], ids=["function", "tap"]) +def test_same_name_completion_logs_for_distinct_schemas( + tmp_path: Path, async_path: bool, tap_only: bool +) -> None: + """Same-name nodes deliver once each, including after reopening their store.""" + from orcapod import PipelineJob, function_pod + from orcapod.databases import DeltaTableDatabase + from orcapod.side_effects import SideEffectPod + from orcapod.sources import DictSource + + delivered: list[int] = [] + + @function_pod(output_keys="result", ctx_arg="ctx") + def contextual(value: int, ctx: InvocationContext) -> int: + delivered.append(value) + return value + + def observe(value: int, ctx: InvocationContext) -> None: + delivered.append(value) + + pod = SideEffectPod(observe) if tap_only else contextual.pod + sources = ( + DictSource( + [{"id": 1, "value": 1}], + tag_columns=["id"], + tag_only_columns=True, + source_id="first", + ), + DictSource( + [{"id": 2, "group": "second", "value": 2}], + tag_columns=["id", "group"], + tag_only_columns=True, + source_id="second", + ), + ) + root = tmp_path / "store" + layout = TRACKING_DB_SCHEMA_VERSION if tap_only else PIPELINE_DB_SCHEMA_VERSION + + for _ in range(2): + with PipelineJob(name="sibling_logs", database=DeltaTableDatabase(root)) as job: + for label, source in zip(("first_step", "second_step"), sources): + pod.process(source, label=label) + summary = asyncio.run(job.run_async()) if async_path else job.run() + assert summary.ok + paths = DeltaTableDatabase(root).list_table_paths() + assert sum(path[-1] == layout for path in paths) == 2 + assert sorted(delivered) == [1, 2] + + +def test_context_parameter_name_enters_pipeline_identity() -> None: + """Renaming the context parameter changes both hashes with the same pod URI.""" + from orcapod import function_pod + + @function_pod(function_name="combine", output_keys="sum", ctx_arg="ctx") + def original(x: int, y: int, ctx: InvocationContext) -> int: + assert isinstance(ctx, InvocationContext) + return x + y + + @function_pod(function_name="combine", output_keys="sum", ctx_arg="invocation") + def renamed(x: int, y: int, invocation: InvocationContext) -> int: + assert isinstance(invocation, InvocationContext) + return x + y + + assert original.pod.uri == renamed.pod.uri + assert original.pod.input_data_schema == renamed.pod.input_data_schema + assert original.pod.pipeline_hash() != renamed.pod.pipeline_hash() + assert original.pod.content_hash() != renamed.pod.content_hash() + + +@pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("cache_kind", ["decorator", "job", "pod"]) +def test_context_parameter_isolates_result_caches( + tmp_path: Path, async_path: bool, cache_kind: str +) -> None: + """A plain result or another context parameter cannot suppress delivery.""" + from orcapod import PipelineJob, function_pod + from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase + from orcapod.sources import DictSource + + shared = InMemoryArrowDatabase() + decorator_db = shared if cache_kind == "decorator" else None + pod_db = shared if cache_kind == "pod" else None + delivered: list[str] = [] + + @function_pod( + function_name="operation", output_keys="result", result_database=decorator_db + ) + def plain(value: int) -> int: + return value + 1 + + @function_pod( + function_name="operation", + output_keys="result", + ctx_arg="ctx", + result_database=decorator_db, + pod_cache_database=pod_db, + ) + def contextual(value: int, ctx: InvocationContext) -> int: + delivered.append("ctx") + return value + 2 + + @function_pod( + function_name="operation", + output_keys="result", + ctx_arg="invocation", + result_database=decorator_db, + pod_cache_database=pod_db, + ) + def renamed(value: int, invocation: InvocationContext) -> int: + delivered.append("invocation") + return value + 3 + + assert plain.pod.data_function.uri == contextual.pod.data_function.uri + assert contextual.pod.data_function.uri == renamed.pod.data_function.uri + source = DictSource( + [{"id": 1, "value": 10}], + tag_columns=["id"], + tag_only_columns=True, + source_id="input", + ) + database = DeltaTableDatabase(tmp_path / "store") + for label, pod, value in ( + ("plain", plain.pod, 11), + ("contextual", contextual.pod, 12), + ("renamed", renamed.pod, 13), + ): + # Separate jobs seed each layer in turn. Give decorator and pod cache + # cases separate outer databases so only the cache under test is shared. + result_database = shared if cache_kind == "job" else InMemoryArrowDatabase() + with PipelineJob( + name=label, database=database, result_database=result_database + ) as job: + pod.process(source, label=label) + assert (asyncio.run(job.run_async()) if async_path else job.run()).ok + assert job.nodes[label].as_table()["result"].to_pylist() == [value] + + assert delivered == ["ctx", "invocation"] + result_suffix = ( + plain.pod.data_function.declaration.revision_component, + RESULT_DB_SCHEMA_VERSION, + ) + expected_paths: set[tuple[str, ...]] = { + ( + *pod.uri[:-3], + f"{pod.uri[-3]}:{pod.uri[-2]}:ctx:{pod.ctx_arg_name}", + pod.uri[-1], + *result_suffix, + ) + for pod in (contextual.pod, renamed.pod) + } + if cache_kind != "pod": + expected_paths.add(plain.pod.uri + result_suffix) + assert set(shared.list_table_paths()) == expected_paths + + +def test_plain_function_subclass_keeps_data_function_pipeline_identity() -> None: + """An override of the plain pod's content identity affects only content.""" + from orcapod import FunctionPod, function_pod + + @function_pod(output_keys="result") + def plain(value: int) -> int: + return value + + class CustomPlainPod(FunctionPod): + def identity_structure(self) -> tuple[object, str]: + return super().identity_structure(), "custom-content" + + custom = CustomPlainPod(plain.pod.data_function) + assert custom.content_hash() != plain.pod.content_hash() + assert custom.pipeline_hash() == plain.pod.pipeline_hash() + + +def test_context_function_subclass_keeps_context_in_pipeline_identity() -> None: + """A content-only override cannot make distinct context parameters collide.""" + from orcapod import FunctionPod, function_pod + + @function_pod(output_keys="result", ctx_arg="ctx") + def action(value: int, ctx: int = 0, invocation: int = 0) -> int: + return value + + class CustomContentPod(FunctionPod): + def identity_structure(self) -> tuple[object, str]: + """Use an application-defined content identity for both instances.""" + return self.data_function, "custom-content" + + first = CustomContentPod(action.pod.data_function, ctx_arg_name="ctx") + renamed = CustomContentPod(action.pod.data_function, ctx_arg_name="invocation") + assert first.pipeline_hash() == action.pod.pipeline_hash() + assert first.pipeline_hash() != renamed.pipeline_hash() + + +@pytest.mark.parametrize("cache_kind", ["decorator", "job", "pod"]) +def test_context_results_fit_existing_database_depth(cache_kind: str) -> None: + """A context-taking function can still use the previous maximum prefix depth.""" + from orcapod import PipelineJob, function_pod + from orcapod.databases import InMemoryArrowDatabase + from orcapod.sources import DictSource + + database = InMemoryArrowDatabase() + prefix = ( + ("one", "two", "three", "four") + if cache_kind == "decorator" + else ( + "one", + "two", + "three", + ) + ) + cache = database.at(*prefix) + deliveries: list[int] = [] + + @function_pod( + output_keys="result", + ctx_arg="ctx", + result_database=cache if cache_kind == "decorator" else None, + pod_cache_database=cache if cache_kind == "pod" else None, + ) + def action(value: int, ctx: InvocationContext) -> int: + deliveries.append(value) + return value + 1 + + source = DictSource( + [{"id": 1, "value": 10}], + tag_columns=["id"], + tag_only_columns=True, + source_id="input", + ) + if cache_kind == "job": + for _ in range(2): + with PipelineJob(name=("one", "two"), database=database) as job: + action.pod(source, label="action") + assert job.run().ok + assert job.nodes["action"].as_table()["result"].to_pylist() == [11] + else: + for _ in range(2): + assert [ + data.as_dict()["result"] for _, data in action.pod(source).iter_data() + ] == [11] + assert deliveries == [10] + + +@pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("audit", [False, True], ids=["removed_sibling", "audit_log"]) +def test_unrelated_tap_log_does_not_block_tracked_completion( + tmp_path: Path, async_path: bool, audit: bool +) -> None: + """Logs of other tap invocations cannot block an unchanged or a new node.""" + from orcapod import PipelineJob + from orcapod.databases import DeltaTableDatabase + from orcapod.side_effects import SideEffectPod, SideEffectPodConfig + from orcapod.sources import DictSource + + delivered: list[int] = [] + + def tap(value: int, ctx: InvocationContext) -> None: + delivered.append(value) + + first = DictSource( + [{"id": 1, "value": 1}], + tag_columns=["id"], + tag_only_columns=True, + source_id="first", + ) + sibling = DictSource( + [{"id": 2, "group": "sibling", "value": 2}], + tag_columns=["id", "group"], + tag_only_columns=True, + source_id="sibling", + ) + root = tmp_path / "store" + for reopening in (False, True): + with PipelineJob(name="tap_logs", database=DeltaTableDatabase(root)) as job: + pod = SideEffectPod( + tap, config=SideEffectPodConfig(track_completion=reopening or not audit) + ) + if reopening or not audit: + pod.process(first, label="first") + if not reopening: + pod.process(sibling, label="sibling") + assert (asyncio.run(job.run_async()) if async_path else job.run()).ok + assert sorted(delivered) == [1, 2] + + class TestCtxArgSchema: """Scenarios 1–2: schema inference and ctx stripping via @function_pod(ctx_arg=...).""" @@ -306,3 +732,394 @@ def my_fn(value: int, ctx: InvocationContext) -> str: # Output values must match for (_, d1), (_, d2) in zip(rows1, rows2): assert d1.as_dict()["result"] == d2.as_dict()["result"] + + +@pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize( + "legacy_case", + ["function_log", "unlisted_function_log", "tap_log", "tap_and_results"], +) +def test_reopening_pre_context_identity_completions( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + async_path: bool, + legacy_case: str, +) -> None: + """Older completion paths are skipped, even when their tables can be listed.""" + from orcapod import FunctionPod, PipelineJob, function_pod + from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase + from orcapod.errors import TableListingNotSupportedError + from orcapod.side_effects import SideEffectPod + from orcapod.sources import DictSource + + delivered: list[tuple[str, int]] = [] + root = tmp_path / "store" + only_downstream_log = legacy_case.startswith("tap") + + def build_job(root: Path) -> PipelineJob: + """Build the same graph against the seed store or its copied tables.""" + + @function_pod(output_keys="result", ctx_arg="ctx") + def contextual(value: int, ctx: InvocationContext) -> int: + delivered.append(("function", value)) + return value + 100 + + def tap(result: int, ctx: InvocationContext) -> None: + delivered.append(("tap", result)) + + with PipelineJob( + name="context_identity", + database=DeltaTableDatabase(root), + # Exercise direct function redelivery when only its pipeline log persists. + result_database=None if only_downstream_log else InMemoryArrowDatabase(), + ) as job: + source = DictSource( + [{"id": 1, "value": 0}], + tag_columns=["id"], + tag_only_columns=True, + source_id="input", + ) + rows = contextual.pod(source, label="contextual") + if only_downstream_log: + SideEffectPod(tap).process(rows, label="tap") + return job + + def run(job: PipelineJob) -> None: + """Run the job using the execution path selected for this case.""" + summary = asyncio.run(job.run_async()) if async_path else job.run() + assert summary.ok + + with monkeypatch.context() as previous: + # Recreate main's pipeline identity while writing real completion records. + previous.setattr( + FunctionPod, "pipeline_identity_structure", lambda pod: pod.data_function + ) + if legacy_case == "tap_and_results": + previous.setattr( + "orcapod.core.cached_function_pod.context_result_path", + lambda uri, _: uri, + ) + run(build_job(root)) + + store = DeltaTableDatabase(root) + table_paths = store.list_table_paths() + (function_log,) = ( + path for path in table_paths if path[-1] == PIPELINE_DB_SCHEMA_VERSION + ) + if only_downstream_log: + # Keep the prior tap log and the result table, without the function log. + # With current results, the run reaches the tap without another delivery. + root = tmp_path / "tap_store" + tap_store = DeltaTableDatabase(root) + for path in table_paths: + if path != function_log: + rows = store.get_all_records(path, record_id_column="__rid") + assert rows is not None + tap_store.add_records(path, rows, record_id_column="__rid") + tap_store.flush() + store = tap_store + (expected_path,) = ( + path for path in table_paths if path[-1] == TRACKING_DB_SCHEMA_VERSION + ) + expected_deliveries = [("function", 0), ("tap", 100)] + if legacy_case == "tap_and_results": + (expected_path,) = ( + path for path in table_paths if path[-1] == RESULT_DB_SCHEMA_VERSION + ) + assert not any(":ctx:" in part for part in expected_path) + else: + expected_path = function_log + expected_deliveries = [("function", 0)] + assert delivered == expected_deliveries + + before = store.get_all_records(expected_path) + assert before is not None and before.num_rows == 1 + with monkeypatch.context() as upgraded: + if legacy_case == "unlisted_function_log": + + def cannot_list(*_args: object, **_kwargs: object) -> list[tuple[str, ...]]: + """Simulate a backend that supports table reads and writes only.""" + raise TableListingNotSupportedError("listing unavailable") + + upgraded.setattr(DeltaTableDatabase, "list_table_paths", cannot_list) + job = build_job(root) + run(job) + run(job) + if legacy_case != "tap_log": + expected_deliveries.append(("function", 0)) + if only_downstream_log: + expected_deliveries.append(("tap", 100)) + assert job.nodes["tap"].as_table()["result"].to_pylist() == [100] + assert delivered == expected_deliveries + assert DeltaTableDatabase(root).get_all_records(expected_path) == before + + +@pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("run_in_job", [False, True], ids=["standalone", "job"]) +@pytest.mark.parametrize("cache_kind", ["decorator", "pod"]) +def test_pre_context_cache_only_results( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + async_path: bool, + run_in_job: bool, + cache_kind: str, +) -> None: + """A pre-context result cache is preserved and the first upgraded run delivers.""" + from orcapod import PipelineJob, function_pod + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import DictSource + + deliveries: list[int] = [] + cache_root = tmp_path / "cache" + + def build_pod(): + """Open the result cache at the decorator or pod layer for this case.""" + cache = DeltaTableDatabase(cache_root) + + @function_pod( + output_keys="result", + ctx_arg="ctx", + result_database=cache if cache_kind == "decorator" else None, + pod_cache_database=cache if cache_kind == "pod" else None, + ) + def action(value: int, ctx: InvocationContext) -> int: + deliveries.append(value) + return value + 100 + + return action.pod + + source = DictSource( + [{"id": 1, "value": 10}], + tag_columns=["id"], + tag_only_columns=True, + source_id="input", + ) + + with monkeypatch.context() as previous: + if cache_kind == "decorator": + previous.setattr( + "orcapod.core.data_function.context_result_path", + lambda uri, _: uri[1:], + ) + else: + previous.setattr( + "orcapod.core.cached_function_pod.context_result_path", + lambda uri, _: uri, + ) + old_rows = list(build_pod().process(source).iter_data()) + assert [data.as_dict()["result"] for _, data in old_rows] == [110] + assert deliveries == [10] + + store = DeltaTableDatabase(cache_root) + (previous_path,) = store.list_table_paths() + assert not any(":ctx:" in part for part in previous_path) + assert (previous_path[0] == "side_effect_function") == (cache_kind == "pod") + before = store.get_all_records(previous_path) + assert before is not None and before.num_rows == 1 + + def run() -> None: + """Check the output through the selected standalone or job entry point.""" + pod = build_pod() + if run_in_job: + with PipelineJob( + name="upgrade", database=DeltaTableDatabase(tmp_path / "job") + ) as job: + pod.process(source, label="action") + summary = asyncio.run(job.run_async()) if async_path else job.run() + assert summary.ok + assert job.nodes["action"].as_table()["result"].to_pylist() == [110] + else: + stream = pod.process(source) + if async_path: + + async def consume() -> None: + assert [ + data.as_dict()["result"] + async for _, data in stream.async_iter_data() + ] == [110] + + asyncio.run(consume()) + else: + assert [data.as_dict()["result"] for _, data in stream.iter_data()] == [ + 110 + ] + + run() + run() + assert deliveries == [10, 10] + reopened = DeltaTableDatabase(cache_root) + assert len(reopened.list_table_paths()) == 2 + assert reopened.get_all_records(previous_path) == before + + +@pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize( + "scenario", ["both", "plain_first", "remove_plain", "remove_plain_with_new_input"] +) +def test_current_sibling_log_is_not_a_previous_context_completion( + tmp_path: Path, async_path: bool, scenario: str +) -> None: + """The plain tap's log remains usable when either branch runs on its own.""" + from orcapod import PipelineJob, function_pod + from orcapod.databases import DeltaTableDatabase + from orcapod.side_effects import SideEffectPod + from orcapod.sources import DictSource + + deliveries: list[tuple[str, int]] = [] + root = tmp_path / "store" + + @function_pod(function_name="step", output_keys="result") + def plain(value: int) -> int: + return value + 100 + + @function_pod(function_name="step", output_keys="result", ctx_arg="ctx") + def contextual(value: int, ctx: InvocationContext) -> int: + deliveries.append(("function", value)) + return value + 200 + + def tap(result: int, ctx: InvocationContext) -> None: + deliveries.append(("tap", result)) + + def build_job( + *, keep_plain: bool = True, keep_contextual: bool = True, value: int = 10 + ) -> PipelineJob: + source = DictSource( + [{"id": 1, "value": value}], + tag_columns=["id"], + tag_only_columns=True, + source_id="input", + ) + with PipelineJob(name="siblings", database=DeltaTableDatabase(root)) as job: + observe = SideEffectPod(tap) + if keep_plain: + observe.process(plain.pod(source, label="plain"), label="plain_tap") + if keep_contextual: + observe.process( + contextual.pod(source, label="contextual"), label="context_tap" + ) + return job + + def run(job: PipelineJob) -> None: + assert (asyncio.run(job.run_async()) if async_path else job.run()).ok + + if scenario == "plain_first": + run(build_job(keep_contextual=False)) + assert deliveries == [("tap", 110)] + + job = build_job() + run(job) + run(job) + reopened = build_job() + run(reopened) + assert reopened.nodes["plain_tap"].as_table()["result"].to_pylist() == [110] + assert reopened.nodes["context_tap"].as_table()["result"].to_pylist() == [210] + assert sorted(deliveries) == [("function", 10), ("tap", 110), ("tap", 210)] + + if scenario.startswith("remove_plain"): + value = 11 if scenario == "remove_plain_with_new_input" else 10 + deliveries.clear() + retained = build_job(keep_plain=False, value=value) + run(retained) + run(retained) + run(build_job(keep_plain=False, value=value)) + assert retained.nodes["context_tap"].as_table()["result"].to_pylist() == [ + value + 200 + ] + expected = [("function", 11), ("tap", 211)] if value == 11 else [] + assert deliveries == expected + run(build_job(value=value)) + if value == 11: + expected.append(("tap", 111)) + assert deliveries == expected + + +@pytest.mark.parametrize( + "previous_identity", [False, True], ids=["current", "previous"] +) +def test_saved_context_function_keeps_its_results_and_downstream_node( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, previous_identity: bool +) -> None: + """Load a saved context-taking function and its downstream side-effect node.""" + from orcapod import FunctionPod, PipelineJob, function_pod + from orcapod.databases import DeltaTableDatabase + from orcapod.side_effects import SideEffectPod + from orcapod.sources import DictSource + + delivered: list[int] = [] + + @function_pod(output_keys="result", ctx_arg="ctx") + def contextual(value: int, ctx: InvocationContext) -> int: + delivered.append(value) + return value + 100 + + def tap(result: int, ctx: InvocationContext) -> None: + delivered.append(result) + + source = DictSource( + [{"id": 1, "value": 0}], + tag_columns=["id"], + tag_only_columns=True, + source_id="input", + ) + saved = tmp_path / "job.json" + + def legacy_result_path( + uri: tuple[str, ...], _context_parameter: str | None + ) -> tuple[str, ...]: + """Keep the pre-context path while using the current saved-job writer.""" + return uri + + with monkeypatch.context() as previous: + if previous_identity: + previous.setattr( + FunctionPod, + "pipeline_identity_structure", + lambda pod: pod.data_function, + ) + previous.setattr( + "orcapod.core.cached_function_pod.context_result_path", + legacy_result_path, + ) + previous.setattr( + "orcapod.core.result_cache.context_result_path", + legacy_result_path, + ) + with PipelineJob( + name="saved_context", database=DeltaTableDatabase(tmp_path / "store") + ) as job: + SideEffectPod(tap).process( + contextual.pod(source, label="contextual"), label="tap" + ) + assert job.run().ok + job.save(saved) + + payload = json.loads(saved.read_text()) + descriptor = next( + node + for node in payload["pipeline"]["nodes"].values() + if node["label"] == "contextual" + ) + if previous_identity: + # Earlier files derived the result path from the URI. + del descriptor["result_record_path"] + saved.write_text(json.dumps(payload)) + + loaded = PipelineJob.load(saved) + contextual_node = loaded.nodes["contextual"] + assert contextual_node.node_type == "side_effect_function" + assert ( + contextual_node.node_identity_path == job.nodes["contextual"].node_identity_path + ) + assert contextual_node.as_source().as_table()["result"].to_pylist() == [100] + loaded.bind(sources={"input": source}) + assert loaded.run(load_only=True).ok + for label in ("contextual", "tap"): + assert loaded.nodes[label].pipeline_hash() == job.nodes[label].pipeline_hash() + assert loaded.nodes[label].content_hash() == job.nodes[label].content_hash() + assert loaded.nodes[label].as_table()["result"].to_pylist() == [100] + assert delivered == [0, 100] + + del descriptor["fall_through_tags"] + saved.write_text(json.dumps(payload)) + with pytest.raises(ValueError, match="saved node 'contextual'.*fall_through_tags"): + PipelineJob.load(saved)