From 8347a2181493db6dbe670b31e04ffc18f20d2115 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 02:37:36 -0800 Subject: [PATCH 1/7] fix(function_pod)!: a context-taking pod has its own pipeline hash --- changelog.d/ITL-1559.md | 8 ++ docs/dev/design_issues/ITL-1559-CXP1.md | 14 +++ docs/reference/hashing.md | 10 +- src/orcapod/core/function_pod.py | 3 +- .../function_pod/test_function_pod_ctx_arg.py | 101 ++++++++++++++++++ 5 files changed, 132 insertions(+), 4 deletions(-) create mode 100644 changelog.d/ITL-1559.md create mode 100644 docs/dev/design_issues/ITL-1559-CXP1.md diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md new file mode 100644 index 000000000..4b51c592a --- /dev/null +++ b/changelog.d/ITL-1559.md @@ -0,0 +1,8 @@ +### 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. Tables written by earlier development versions + remain at their old paths. There is no migration for these unreleased layouts. + (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..df17778ad --- /dev/null +++ b/docs/dev/design_issues/ITL-1559-CXP1.md @@ -0,0 +1,14 @@ +## `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:** Use the same structure for the pod's content and pipeline identities. Include +the context parameter name when configured so the pod and its downstream steps have +distinct pipeline hashes. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 4c9a4af72..92af40943 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -611,7 +611,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)), key_columns)`, 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, key_columns)` (provisional, ITL-1316). `key_columns` is the resolved tuple of record-id key columns 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 | @@ -726,13 +726,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` | Same as `identity_structure()` | 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/function_pod.py b/src/orcapod/core/function_pod.py index 1d0f7d9ce..fc30664e7 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -181,7 +181,8 @@ def identity_structure(self) -> Any: return self.data_function def pipeline_identity_structure(self) -> Any: - return self.data_function + """Include the parameter that receives the invocation context, when set.""" + return self.identity_structure() def _build_invocation_context( self, 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..c07b7a2f0 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,6 +7,8 @@ from __future__ import annotations +import asyncio + import pytest import pyarrow as pa @@ -36,6 +38,105 @@ 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( + 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.operators import Batch + from orcapod.sources import DictSource + from orcapod.system_constants import constants + + @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) + return x + y + 100, x - y + + 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" + ) + db = _make_pipeline_db() + with PipelineJob(name="context_identity", database=db) 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") + + 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 db.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) + + +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() + + class TestCtxArgSchema: """Scenarios 1–2: schema inference and ctx stripping via @function_pod(ctx_arg=...).""" From 2b5a048a1ddcfcd68776f089914e0f378f726dab Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 03:02:46 -0800 Subject: [PATCH 2/7] fix(pipeline): guard context-taking completions and restore saved nodes --- .zed/rules | 5 +- CLAUDE.md | 7 +- changelog.d/ITL-1559.md | 7 + docs/dev/design_issues/ITL-1559-CXP1.md | 4 +- src/orcapod/contexts/stored.py | 69 ++--- src/orcapod/core/nodes/function_node.py | 38 ++- src/orcapod/errors.py | 29 ++- src/orcapod/pipeline/graph.py | 6 +- src/orcapod/side_effects.py | 18 +- .../function_pod/test_function_pod_ctx_arg.py | 245 +++++++++++++++++- 10 files changed, 340 insertions(+), 88 deletions(-) diff --git a/.zed/rules b/.zed/rules index beb76d466..73df4ad3e 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1019,7 +1019,8 @@ generation of hashing; rows of the current data context are the current entries. every read or lookup keeps rows of the current data context only (keep_rows_of_data_context, or a lookup constraint on the column). - A table at an older layout is never read as current and never modified. What a node does - about such tables, and about rows of another data context, is decided in one place, + about such tables, rows of another data context, and completion tables at another path + under the same name is decided in one place, contexts/stored.account_for_stale_tables: count and report, or, for a node that delivers side effects (a SideEffectPod node, or a function node whose pod takes the invocation context, ctx_arg), raise SideEffectLogDataContextError before any delivery. A new kind of @@ -1030,6 +1031,8 @@ generation of hashing; rows of the current data context are the current entries. , side_effect_function/, side_effects/, relative to the node's database; /source for a cached source) and every table there whose last component is not in contexts/stored.CURRENT_LAYOUTS is of another layout (tables_of_another_layout). + For a node that tracks completions, the same listing finds a current-layout completion + table at a path other than the node's own (completion_path, ITL-1559). A new layout constant must be added to CURRENT_LAYOUTS. A store that cannot list raises TableListingNotSupportedError: side-effecting nodes then warn and proceed (developer, November 11, 2026). Every database class implements list_table_paths. Stores of the diff --git a/CLAUDE.md b/CLAUDE.md index 23d483749..caf22ef4f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1050,7 +1050,8 @@ current data context are the current entries. and every read or lookup keeps rows of the current data context only (`keep_rows_of_data_context`, or a lookup constraint on the column). - A table at an older layout is never read as current and never modified. What a node does - about such tables, and about rows of another data context, is decided in one place, + about such tables, rows of another data context, and completion tables at another path + under the same name is decided in one place, `contexts/stored.account_for_stale_tables`: count and report, or, for a node that delivers side effects (a `SideEffectPod` node, or a function node whose pod takes the invocation context, `ctx_arg`), raise `SideEffectLogDataContextError` before any delivery. A new kind @@ -1061,7 +1062,9 @@ current data context are the current entries. ``, `side_effect_function/`, `side_effects/`, relative to the node's database; `/source` for a cached source) and every table there whose last component is not in `contexts/stored.CURRENT_LAYOUTS` is of another layout - (`tables_of_another_layout`). A new layout constant must be added to `CURRENT_LAYOUTS`. A + (`tables_of_another_layout`). For a node that tracks completions, the same listing + finds a current-layout completion table at a path other than the node's own + (`completion_path`, ITL-1559). A new layout constant must be added to `CURRENT_LAYOUTS`. A store that cannot list raises `TableListingNotSupportedError`: side-effecting nodes then warn and proceed (developer, November 11, 2026). Every database class implements `list_table_paths`. Stores of the versions before 0.4 are not looked for otherwise (no diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index 4b51c592a..6ee7a00a6 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -5,4 +5,11 @@ affected hashes have new `schema:

` paths, and downstream system-tag column names that incorporate those hashes change. Tables written by earlier development versions remain at their old paths. There is no migration for these unreleased layouts. + Side-effecting function nodes and tracked side-effect pods refuse to run when + completion tables exist at another path under the same name. (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 index df17778ad..09bd1b3b2 100644 --- a/docs/dev/design_issues/ITL-1559-CXP1.md +++ b/docs/dev/design_issues/ITL-1559-CXP1.md @@ -11,4 +11,6 @@ node over the same slot, even though one receives an invocation context. **Fix:** Use the same structure for the pod's content and pipeline identities. Include the context parameter name when configured so the pod and its downstream steps have -distinct pipeline hashes. +distinct pipeline hashes. When an existing completion table is at a different path under +the same name, the stale-table check refuses delivery. A saved job restores its +context-taking function nodes and reads their results using its recorded identities. diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index 3369233a3..db51b38d3 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -17,8 +17,8 @@ not looked for at a computed path. The beginning of the path, up to the name of the function or pod, holds no hash: the tables under it are listed (``list_table_paths``), and a table whose last path component is not one of the current layouts is of another layout -(ITL-954). Tables of the versions before 0.4 are not looked for otherwise: nobody has such -a store, and their layouts had the names the first release uses (ITL-1259). +(ITL-954). This listing also finds completion tables at the current layout under a +different path, which can happen when a pipeline hash changes (ITL-1559). Example: To list the data contexts a stored table holds, call @@ -373,10 +373,13 @@ class StaleTables: tables: The tables found, each once. unlisted: The places that could not be searched because the database cannot list its tables. + other_completion_paths: Current-layout completion tables at another path + under the same function or pod name. """ tables: list[StaleTable] = field(default_factory=list) unlisted: list[UnlistedTables] = field(default_factory=list) + other_completion_paths: list[tuple[str, ...]] = field(default_factory=list) def include(self, other: "StaleTables") -> None: """Add what another search found, leaving out tables already known. @@ -391,38 +394,34 @@ def include(self, other: "StaleTables") -> None: if (table.record_path, table.old_layout) not in known ) self.unlisted.extend(other.unlisted) + for path in other.other_completion_paths: + if path not in self.other_completion_paths: + self.other_completion_paths.append(path) def tables_of_another_layout( - database: object, - name_path: tuple[str, ...], + paths: list[tuple[str, ...]], result_revision: str | None = None, ) -> list[tuple[str, ...]]: - """List the tables under ``name_path`` that are at another layout than this build's. + """Select the listed tables with another layout than this build's. Another layout and the current ones are told apart by path components, never by a hash: every table this version writes ends in one of ``CURRENT_LAYOUTS``, and a function result table has its data function type's revision just before its layout - (``.../rev1/rdb_v1``, ITL-1259). ``name_path`` is expected to end with the name of one - function or pod, so that every table under it belongs to a node of that name. + (``.../rev1/rdb_v1``, ITL-1259). Args: - database: The database to list. - name_path: Leading path components, relative to the database's ``base_path``. + paths: The database's table paths under the function or pod name. result_revision: The revision component of the result tables the caller reads (``rev1``). A result table under ``name_path`` with another revision is then of another layout too. ``None`` checks the last component only. Returns: - The paths, relative to the database's ``base_path``, of the tables under - ``name_path`` that are not at a current layout, sorted. - - Raises: - TableListingNotSupportedError: If the database cannot list its tables. + The paths of tables that are not at a current layout, in listing order. """ return [ path - for path in _list_table_paths(database, name_path) + for path in paths if path[-1] not in CURRENT_LAYOUTS or ( result_revision is not None @@ -454,13 +453,15 @@ def find_stale_tables( current: tuple[tuple[str, ...], str] | None = None, name_path: tuple[str, ...] | None = None, result_revision: str | None = None, + completion_path: tuple[str, ...] | None = None, ) -> StaleTables: """Find the stored rows of other generations that belong to one table of a node. Two searches, neither of which writes anything: - under ``name_path``, by listing the database, for tables of another layout - wherever their hashes put them (ITL-954; not read, so not counted); + wherever their hashes put them (ITL-954), and for completion tables with + the current layout whose paths differ from ``completion_path``; - in the current table, for rows of another data context. Args: @@ -473,20 +474,24 @@ def find_stale_tables( result_revision: For a result cache, the revision of its data function type's record: a result table under ``name_path`` at another revision is listed too (``tables_of_another_layout``). + completion_path: The expected path of a side-effect completion log. A table + under ``name_path`` with the same layout at another path may hold + completions this node cannot match (ITL-1559). Returns: The tables of another layout found, then one entry per other data context - found in the current table (in key order); and ``name_path`` under - ``unlisted`` if the database could not list its tables. + found in the current table (in key order), the alternate completion paths, + and ``name_path`` under ``unlisted`` if the database could not list its tables. """ found = StaleTables() if name_path is not None: under = database.base_path + name_path try: - listed = tables_of_another_layout(database, name_path, result_revision) + paths = _list_table_paths(database, name_path) except TableListingNotSupportedError as exc: found.unlisted.append(UnlistedTables(under, str(exc))) else: + other_layouts = tables_of_another_layout(paths, result_revision) found.include( StaleTables( [ @@ -497,10 +502,16 @@ def find_stale_tables( True, under, ) - for path in listed + for path in other_layouts ] ) ) + if completion_path is not None: + found.other_completion_paths = [ + database.base_path + path + for path in paths + if path[-1] == completion_path[-1] and path != completion_path + ] if current is not None: current_path, current_context = current for key, rows in sorted(stored_data_contexts(database, current_path).items()): @@ -522,12 +533,11 @@ def account_for_stale_tables( nodes) reports each table with its number of rows and moves on. - A node whose run is an external action (a side-effect pod, or a function pod that takes the invocation context) must not act again for inputs it already - handled, and those completions cannot be matched under the current data - context. It fails before doing anything. Every old-layout table under the - node's name counts, so a table of another function or pod with the same name - in the job, or of another node of the same function, fails it too: the error - names the tables. Where the database cannot list its tables, the node warns and - proceeds (developer, November 11, 2026). + handled when those completions cannot be matched at the current path or under + the current data context. It fails before doing anything. Every old-layout table + and every differently scoped completion table under the node's name counts. + The error names the tables. Where the database cannot list its tables, the + node warns and proceeds (developer, November 11, 2026). Args: found: What ``find_stale_tables`` found for the node's tables. @@ -539,10 +549,11 @@ def account_for_stale_tables( found. The caller adds the node label. """ if delivers_side_effects: - if found.tables: + if found.tables or found.other_completion_paths: raise SideEffectLogDataContextError( - tuple(table.record_path for table in found.tables), - found.tables[0].data_context, + tuple(table.record_path for table in found.tables) + + tuple(found.other_completion_paths), + found.tables[0].data_context if found.tables else None, current_context, ) if found.unlisted: diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9809760af..d00cc75ca 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -83,7 +83,6 @@ UnstorableColumnError, ) from orcapod.contexts.stored import ( - StaleTables, keep_rows_of_data_context, require_same_data_context, account_for_stale_tables, @@ -1140,12 +1139,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 @@ -1598,10 +1592,9 @@ def _account_for_stale_tables(self) -> None: unchanged, and their number is reported (ITL-944). Such tables are looked for at this node's own path and, because the hashes in a path can differ between versions, anywhere under the function's name in the database (ITL-954). A node - that delivers side effects fails instead, and for it the result tables and - rows of another data context in the current tables count too: none of them - can be matched with current inputs, so every side effect would be delivered - again. + that delivers side effects fails instead. Alternate paths at the current + pipeline layout, stale result tables, and rows of another data context in + the current tables also count because their completions cannot be matched. Raises: SideEffectLogDataContextError: If this node delivers side effects and @@ -1617,6 +1610,7 @@ def _account_for_stale_tables(self) -> None: if delivers and not self._current_tables_checked else None, name_path=self.node_name_path or None, + completion_path=self._versioned_pipeline_path if delivers else None, ) if delivers: for cached_pod in (self._cached_function_pod, self._ephemeral_cached_pod): @@ -1630,7 +1624,7 @@ def _account_for_stale_tables(self) -> None: # That the database cannot list its tables is reported once per node # object and attached database, not at every run. if self._unlisted_store_reported: - found = StaleTables(tables=found.tables) + found.unlisted.clear() self._unlisted_store_reported = True try: account_for_stale_tables( @@ -1892,19 +1886,24 @@ 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. Its pod uses the side-effect + # prefix for both pipeline and result tables when it takes a context. + 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 = 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": @@ -1949,13 +1948,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/errors.py b/src/orcapod/errors.py index eda66139c..ac5016c88 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1282,7 +1282,7 @@ def __str__(self) -> str: class SideEffectLogDataContextError(OrcapodDatabaseError): - """Raised when a side-effecting node finds completions logged under another data context. + """Raised when a side-effecting node finds incompatible stored completions. A node whose run is an external action finds what it already did by keys hashed under its data context: a side-effect pod in its invocation log, a function pod @@ -1296,11 +1296,11 @@ class SideEffectLogDataContextError(OrcapodDatabaseError): operator and source tables do not fail this way: there, such rows are reported, skipped and computed again. - Tables written by Orcapod up to v0.2 are found by name: every table at an older - layout stored under the node's function or pod name in the job counts, - whatever hashes its path holds (ITL-954). A table of another function or pod - with the same name in the same job, or of another node of the same function, - therefore raises this error too; ``record_paths`` names every table found. + The search lists tables under the node's function or pod name (ITL-954). + A table at an older layout or a current-layout completion table at another + path counts. The latter can occur when a pipeline hash changes (ITL-1559). + A table belonging to another node of the same name can therefore raise this + error too. ``record_paths`` names every table found. A fresh database is not a safe way around this error: it holds no completions, so on it the node performs every side effect again. Run the node on a fresh database only @@ -1312,7 +1312,8 @@ class SideEffectLogDataContextError(OrcapodDatabaseError): record_paths: Paths, from the root of the database, of the tables holding such completions. record_path: The first of ``record_paths``. - found_context: Data context key of the completions that do not match. + found_context: Data context key of the completions that do not match, or + ``None`` when only alternate current-layout paths were found. current_context: Data context key of the node. node_label: Label of the node. """ @@ -1320,7 +1321,7 @@ class SideEffectLogDataContextError(OrcapodDatabaseError): def __init__( self, record_paths: tuple[tuple[str, ...], ...], - found_context: str, + found_context: str | None, current_context: str, node_label: str | None = None, ) -> None: @@ -1328,7 +1329,7 @@ def __init__( Args: record_paths: Paths of the tables holding completions that do not match. - found_context: Data context key of those completions. + found_context: Data context key of those completions, if known. current_context: Data context key of the node. node_label: Label of the node, if known. """ @@ -1336,7 +1337,7 @@ def __init__( tuple(path) for path in record_paths ) self.record_path: tuple[str, ...] = self.record_paths[0] - self.found_context: str = found_context + self.found_context = found_context self.current_context: str = current_context super().__init__( self.record_paths, found_context, current_context, node_label=node_label @@ -1346,6 +1347,14 @@ def __str__(self) -> str: """Describe the tables, both data contexts and the remedy.""" node = f"Node {self.node_label!r}" if self.node_label else "This node" tables = ", ".join(repr("/".join(path)) for path in self.record_paths) + if self.found_context is None: + return ( + f"{node} performs side effects, and stored completions exist at " + f"different paths under the same name ({tables}). They cannot be " + "matched with current inputs, so nothing was delivered or written by " + "this node. Reopen the job with the version and pipeline that wrote " + "these tables to reuse the completions." + ) return ( f"{node} performs side effects, and its stored completions were logged " f"under the data context {self.found_context!r} (in {tables}), but the " diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 0b58b8f37..8de7745ea 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -384,11 +384,12 @@ 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: 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) ) @@ -416,7 +417,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": @@ -494,7 +494,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/side_effects.py b/src/orcapod/side_effects.py index dd691c62d..9edd56643 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -45,7 +45,6 @@ UnstorableColumnError, ) from orcapod.contexts.stored import ( - StaleTables, account_for_stale_tables, data_context_field, find_stale_tables, @@ -1114,16 +1113,14 @@ def clear_cache(self) -> None: self._set_modified_time(None) def _refuse_log_of_another_data_context(self) -> None: - """Refuse an invocation log holding deliveries of another data context. + """Refuse invocation logs holding deliveries this run cannot match. A delivery already made is found by a record id hashed under this node's data context, so deliveries logged under another one would not be found and - every side effect would be delivered again (ITL-944). Two cases: a log at an - older table layout (written by Orcapod up to v0.2), and rows of another data - context in the current log. An older log is looked for at this node's own - path and, because the hash in the path can differ between versions, anywhere - under the pod's name in the database (ITL-954). Checked at the start of every - run, so a log that appears between two runs of one node object is found too. + every side effect would be delivered again (ITL-944). The search looks under + the pod's name for older layouts and, when tracking completions, logs at a + different path under the current layout (ITL-954, ITL-1559). Checked at the + start of every run, so a log that appears between runs is found too. The current log is read and counted by data context the first time only; the later runs list the database, which reads no table. @@ -1139,12 +1136,15 @@ def _refuse_log_of_another_data_context(self) -> None: current=None if self._current_log_checked else (self._table_path, current), # ("side_effects", ): the part of the path that holds no hash. name_path=self.node_uri, + completion_path=self._table_path + if self._pod.pod_config.track_completion + else None, ) if found.unlisted: # The check runs before every run; that the database cannot list its tables # is reported once per node object and attached database. if self._unlisted_store_reported: - found = StaleTables(tables=found.tables) + found.unlisted.clear() self._unlisted_store_reported = True try: account_for_stale_tables( 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 c07b7a2f0..b5e3f2214 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 @@ -8,12 +8,18 @@ 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, + TRACKING_DB_SCHEMA_VERSION, +) def _make_stream(n: int = 3) -> ArrowTableStream: @@ -44,14 +50,18 @@ def _make_pipeline_db(): "ignore:Batch is provisional:orcapod.errors.ProvisionalHashWarning" ) def test_context_parameter_distinguishes_job_branches( - async_path: bool, reverse_columns: bool + 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.operators import Batch + 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 @@ -61,8 +71,14 @@ def plain(x: int, y: int) -> tuple[int, int]: ) 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() @@ -77,13 +93,31 @@ def contextual(x: int, y: int, ctx: InvocationContext) -> tuple[int, int]: source = DictSource( rows, tag_columns=tags, tag_only_columns=True, source_id="input" ) - db = _make_pipeline_db() - with PipelineJob(name="context_identity", database=db) 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") - + 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() @@ -92,7 +126,7 @@ def contextual(x: int, y: int, ctx: InvocationContext) -> tuple[int, int]: summary = asyncio.run(job.run_async()) if async_path else job.run() assert summary.ok - stored_paths = {path[1:-1] for path in db.list_sources()} + stored_paths = {path[1:-1] for path in DeltaTableDatabase(root).list_sources()} assert { plain_node.node_identity_path, context_node.node_identity_path, @@ -116,6 +150,32 @@ def contextual(x: int, y: int, ctx: InvocationContext) -> tuple[int, int]: 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, + ] + def test_context_parameter_name_enters_pipeline_identity() -> None: """Renaming the context parameter changes both hashes with the same pod URI.""" @@ -407,3 +467,168 @@ 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("only_downstream_log", [False, True], ids=["function", "tap"]) +def test_reopening_pre_context_identity_completions_refuses_delivery( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + async_path: bool, + only_downstream_log: bool, +) -> None: + """Completions at the previous schema path refuse a run before redelivery.""" + from orcapod import FunctionPod, PipelineJob, function_pod + from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase + from orcapod.errors import SideEffectLogDataContextError + from orcapod.side_effects import SideEffectPod + from orcapod.sources import DictSource + + delivered: list[tuple[str, int]] = [] + root = tmp_path / "store" + + def build_job(root: Path) -> PipelineJob: + @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: + 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 + ) + 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 shared result cache and the prior tap log. This lets the run + # reach the tap, even though the function would otherwise refuse first. + 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_label = "tap" + expected_deliveries = [("function", 0), ("tap", 100)] + else: + expected_path = function_log + expected_label = "contextual" + 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 pytest.raises(SideEffectLogDataContextError) as info: + run(build_job(root)) + assert info.value.node_label == expected_label + assert expected_path in info.value.record_paths + assert delivered == expected_deliveries + assert DeltaTableDatabase(root).get_all_records(expected_path) == before + + +@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" + with monkeypatch.context() as previous: + if previous_identity: + previous.setattr( + FunctionPod, + "pipeline_identity_structure", + lambda pod: pod.data_function, + ) + 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) + + 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] + + malformed = json.loads(saved.read_text()) + descriptor = next( + node + for node in malformed["pipeline"]["nodes"].values() + if node["label"] == "contextual" + ) + del descriptor["fall_through_tags"] + saved.write_text(json.dumps(malformed)) + with pytest.raises(ValueError, match="saved node 'contextual'.*fall_through_tags"): + PipelineJob.load(saved) From 147048b9bceb8303369876d7400897816817add5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 03:43:16 -0800 Subject: [PATCH 3/7] fix(pipeline): recognize sibling completion logs --- .zed/rules | 9 ++-- CLAUDE.md | 9 ++-- changelog.d/ITL-1559.md | 9 ++-- docs/dev/design_issues/ITL-1559-CXP1.md | 4 +- src/orcapod/contexts/stored.py | 18 ++++--- src/orcapod/core/nodes/function_node.py | 22 ++++++-- src/orcapod/errors.py | 8 +-- src/orcapod/pipeline/job.py | 16 +++++- src/orcapod/side_effects.py | 18 +++++-- .../function_pod/test_function_pod_ctx_arg.py | 50 +++++++++++++++++++ 10 files changed, 130 insertions(+), 33 deletions(-) diff --git a/.zed/rules b/.zed/rules index caa7331b0..bc23a7cf7 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1019,8 +1019,8 @@ generation of hashing; rows of the current data context are the current entries. every read or lookup keeps rows of the current data context only (keep_rows_of_data_context, or a lookup constraint on the column). - A table at an older layout is never read as current and never modified. What a node does - about such tables, rows of another data context, and completion tables at another path - under the same name is decided in one place, + about such tables, rows of another data context, and completion tables under the same name + outside the current job's completion paths is decided in one place, contexts/stored.account_for_stale_tables: count and report, or, for a node that delivers side effects (a SideEffectPod node, or a function node whose pod takes the invocation context, ctx_arg), raise SideEffectLogDataContextError before any delivery. A new kind of @@ -1031,8 +1031,9 @@ generation of hashing; rows of the current data context are the current entries. , side_effect_function/, side_effects/, relative to the node's database; /source for a cached source) and every table there whose last component is not in contexts/stored.CURRENT_LAYOUTS is of another layout (tables_of_another_layout). - For a node that tracks completions, the same listing finds a current-layout completion - table at a path other than the node's own (completion_path, ITL-1559). + For a node that tracks completions, the same listing finds current-layout completion + tables outside the node's own path and those of its job (completion_path and + job_completion_paths, ITL-1559). A new layout constant must be added to CURRENT_LAYOUTS. A store that cannot list raises TableListingNotSupportedError: side-effecting nodes then warn and proceed (developer, November 11, 2026). Every database class implements list_table_paths. Stores of the diff --git a/CLAUDE.md b/CLAUDE.md index 9c0a5d11c..bd47524fd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1050,8 +1050,8 @@ current data context are the current entries. and every read or lookup keeps rows of the current data context only (`keep_rows_of_data_context`, or a lookup constraint on the column). - A table at an older layout is never read as current and never modified. What a node does - about such tables, rows of another data context, and completion tables at another path - under the same name is decided in one place, + about such tables, rows of another data context, and completion tables under the same name + outside the current job's completion paths is decided in one place, `contexts/stored.account_for_stale_tables`: count and report, or, for a node that delivers side effects (a `SideEffectPod` node, or a function node whose pod takes the invocation context, `ctx_arg`), raise `SideEffectLogDataContextError` before any delivery. A new kind @@ -1063,8 +1063,9 @@ current data context are the current entries. node's database; `/source` for a cached source) and every table there whose last component is not in `contexts/stored.CURRENT_LAYOUTS` is of another layout (`tables_of_another_layout`). For a node that tracks completions, the same listing - finds a current-layout completion table at a path other than the node's own - (`completion_path`, ITL-1559). A new layout constant must be added to `CURRENT_LAYOUTS`. A + finds current-layout completion tables outside the node's own path and those of its job + (`completion_path` and `job_completion_paths`, ITL-1559). + A new layout constant must be added to `CURRENT_LAYOUTS`. A store that cannot list raises `TableListingNotSupportedError`: side-effecting nodes then warn and proceed (developer, November 11, 2026). Every database class implements `list_table_paths`. Stores of the versions before 0.4 are not looked for otherwise (no diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index 6ee7a00a6..f855f45db 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -3,10 +3,13 @@ - 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. Tables written by earlier development versions - remain at their old paths. There is no migration for these unreleased layouts. + 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. Side-effecting function nodes and tracked side-effect pods refuse to run when - completion tables exist at another path under the same name. + completion tables under the same name exist outside the current job's completion paths. (ITL-1559) ### Fixed diff --git a/docs/dev/design_issues/ITL-1559-CXP1.md b/docs/dev/design_issues/ITL-1559-CXP1.md index 09bd1b3b2..a5dbd6b36 100644 --- a/docs/dev/design_issues/ITL-1559-CXP1.md +++ b/docs/dev/design_issues/ITL-1559-CXP1.md @@ -11,6 +11,6 @@ node over the same slot, even though one receives an invocation context. **Fix:** Use the same structure for the pod's content and pipeline identities. Include the context parameter name when configured so the pod and its downstream steps have -distinct pipeline hashes. When an existing completion table is at a different path under -the same name, the stale-table check refuses delivery. A saved job restores its +distinct pipeline hashes. The stale-table check refuses delivery when a completion table +under the same name is outside the current job's completion paths. A saved job restores its context-taking function nodes and reads their results using its recorded identities. diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index db51b38d3..58f65973a 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -17,8 +17,8 @@ not looked for at a computed path. The beginning of the path, up to the name of the function or pod, holds no hash: the tables under it are listed (``list_table_paths``), and a table whose last path component is not one of the current layouts is of another layout -(ITL-954). This listing also finds completion tables at the current layout under a -different path, which can happen when a pipeline hash changes (ITL-1559). +(ITL-954). This listing also finds current-layout completion tables that the +current job does not address, which can happen when a pipeline hash changes (ITL-1559). Example: To list the data contexts a stored table holds, call @@ -30,7 +30,7 @@ import logging import warnings -from collections.abc import Collection +from collections.abc import Collection, Set from dataclasses import dataclass, field from typing import Any, NamedTuple, Protocol, cast @@ -454,6 +454,7 @@ def find_stale_tables( name_path: tuple[str, ...] | None = None, result_revision: str | None = None, completion_path: tuple[str, ...] | None = None, + job_completion_paths: Set[tuple[str, ...]] = frozenset(), ) -> StaleTables: """Find the stored rows of other generations that belong to one table of a node. @@ -461,7 +462,7 @@ def find_stale_tables( - under ``name_path``, by listing the database, for tables of another layout wherever their hashes put them (ITL-954), and for completion tables with - the current layout whose paths differ from ``completion_path``; + the current layout outside the set of paths addressed by the current job; - in the current table, for rows of another data context. Args: @@ -477,6 +478,8 @@ def find_stale_tables( completion_path: The expected path of a side-effect completion log. A table under ``name_path`` with the same layout at another path may hold completions this node cannot match (ITL-1559). + job_completion_paths: Completion paths relative to this database for the + compiled job. Logs belonging to another node of this job are current. Returns: The tables of another layout found, then one entry per other data context @@ -510,7 +513,9 @@ def find_stale_tables( found.other_completion_paths = [ database.base_path + path for path in paths - if path[-1] == completion_path[-1] and path != completion_path + if path[-1] == completion_path[-1] + and path != completion_path + and path not in job_completion_paths ] if current is not None: current_path, current_context = current @@ -535,7 +540,8 @@ def account_for_stale_tables( that takes the invocation context) must not act again for inputs it already handled when those completions cannot be matched at the current path or under the current data context. It fails before doing anything. Every old-layout table - and every differently scoped completion table under the node's name counts. + and every completion table under the node's name outside the current job's + completion paths counts. The error names the tables. Where the database cannot list its tables, the node warns and proceeds (developer, November 11, 2026). diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index d00cc75ca..0d085ffc0 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -24,7 +24,7 @@ import uuid from abc import abstractmethod from collections import Counter -from collections.abc import Callable, Iterator, Mapping, Sequence +from collections.abc import Callable, Iterator, Mapping, Sequence, Set from datetime import datetime, timezone from functools import partial from typing import Any, Literal, NamedTuple, cast @@ -1400,6 +1400,7 @@ class FunctionJobNode(ProvenanceMethods, RunHoldingNode, FunctionNodeBase): _token_column_types: "dict[str, pa.DataType] | None" = None # Set once a database that cannot list its tables was reported. _unlisted_store_reported: bool = False + _job_completion_paths: Set[tuple[str, ...]] = frozenset() # Instance ids of the inputs of the last completed run in this process, each with # its number of inputs; None when no run completed (ITL-1093). A class default so # nodes rebuilt from a saved descriptor start without a run. @@ -1522,6 +1523,11 @@ def _delivers_side_effects(self) -> bool: and self._function_pod.ctx_arg_name is not None ) + @property + def completion_log_path(self) -> tuple[str, ...] | None: + """The pipeline table storing this live context-taking node's completions.""" + return self._versioned_pipeline_path if self._delivers_side_effects else None + def _begin_run(self) -> None: """Reset schema preflight and refresh the stored tables for this run. @@ -1592,9 +1598,9 @@ def _account_for_stale_tables(self) -> None: unchanged, and their number is reported (ITL-944). Such tables are looked for at this node's own path and, because the hashes in a path can differ between versions, anywhere under the function's name in the database (ITL-954). A node - that delivers side effects fails instead. Alternate paths at the current - pipeline layout, stale result tables, and rows of another data context in - the current tables also count because their completions cannot be matched. + that delivers side effects fails instead. Completion paths outside the + current job, stale result tables, and rows of another data context in the + current tables also count because their completions cannot be matched. Raises: SideEffectLogDataContextError: If this node delivers side effects and @@ -1610,7 +1616,8 @@ def _account_for_stale_tables(self) -> None: if delivers and not self._current_tables_checked else None, name_path=self.node_name_path or None, - completion_path=self._versioned_pipeline_path if delivers else None, + completion_path=self.completion_log_path, + job_completion_paths=self._job_completion_paths, ) if delivers: for cached_pod in (self._cached_function_pod, self._ephemeral_cached_pod): @@ -1688,6 +1695,8 @@ def attach_databases( pipeline_database: ArrowDatabaseProtocol | None = None, result_database: ArrowDatabaseProtocol | None = None, ephemeral_database: ArrowDatabaseProtocol | None = None, + *, + job_completion_paths: Set[tuple[str, ...]] = frozenset(), ) -> None: """Attach databases for persistent caching and pipeline records. @@ -1718,6 +1727,8 @@ def attach_databases( via ``set_ephemeral_database()``. Equivalent to calling ``set_ephemeral_database(ephemeral_database)`` after ``attach_databases()``. + job_completion_paths: Current completion log paths in the job's + pipeline database. """ if pipeline_database is not None: # A database that cannot store this node's tables refuses them now, @@ -1726,6 +1737,7 @@ def attach_databases( if ephemeral_database is not None: self.require_storable_results(ephemeral_database) # Another database has its own tables of other generations to account for. + self._job_completion_paths = job_completion_paths self._stale_tables_checked = False self._current_tables_checked = False self._pipeline_preflight_checked = False diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index ac5016c88..192f0a8ba 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1297,10 +1297,10 @@ class SideEffectLogDataContextError(OrcapodDatabaseError): skipped and computed again. The search lists tables under the node's function or pod name (ITL-954). - A table at an older layout or a current-layout completion table at another - path counts. The latter can occur when a pipeline hash changes (ITL-1559). - A table belonging to another node of the same name can therefore raise this - error too. ``record_paths`` names every table found. + A table at an older layout or a current-layout completion table under the + same name outside the current job's completion paths counts. The latter can + occur when a pipeline hash changes (ITL-1559). ``record_paths`` names every + table found. A fresh database is not a safe way around this error: it holds no completions, so on it the node performs every side effect again. Run the node on a fresh database only diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 82f59257c..fc39403dd 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -651,7 +651,9 @@ 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() + job_completion_paths: set[tuple[str, ...]] = set() + 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``. @@ -659,6 +661,7 @@ def _distribute_databases(self) -> None: node.attach_databases( pipeline_database=pipeline_db, result_database=result_db, + job_completion_paths=job_completion_paths, ) elif isinstance(node, OperatorJobNode): node.attach_databases( @@ -666,7 +669,16 @@ 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, + job_completion_paths=job_completion_paths, + ) + + # Collect the paths after attachment, when every node addresses its job table. + for node in nodes: + if isinstance(node, (FunctionJobNode, SideEffectJobNode)): + if (path := node.completion_log_path) is not None: + job_completion_paths.add(path) # ------------------------------------------------------------------ # _iter_function_job_nodes() / apply_node_config() diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 9edd56643..d8bede286 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -12,7 +12,7 @@ import dataclasses import datetime import logging -from collections.abc import Callable, Collection, Iterator, Sequence +from collections.abc import Callable, Collection, Iterator, Sequence, Set from typing import TYPE_CHECKING, Any, Literal, cast import pyarrow as pa @@ -1084,6 +1084,7 @@ def __init__( ) self._pipeline_database: ArrowDatabaseProtocol | None = None self._table_path: tuple[str, ...] | None = None + self._job_completion_paths: Set[tuple[str, ...]] = frozenset() self._unlisted_store_reported = False self._current_log_checked = False # The rows the last completed run passed on, in the order it passed them; @@ -1112,14 +1113,19 @@ def clear_cache(self) -> None: self._run_load_only = False self._set_modified_time(None) + @property + def completion_log_path(self) -> tuple[str, ...] | None: + """The attached invocation log path, including logs that only audit delivery.""" + return self._table_path + def _refuse_log_of_another_data_context(self) -> None: """Refuse invocation logs holding deliveries this run cannot match. A delivery already made is found by a record id hashed under this node's data context, so deliveries logged under another one would not be found and every side effect would be delivered again (ITL-944). The search looks under - the pod's name for older layouts and, when tracking completions, logs at a - different path under the current layout (ITL-954, ITL-1559). Checked at the + the pod's name for older layouts and, when tracking completions, logs outside + the current job's completion paths (ITL-954, ITL-1559). Checked at the start of every run, so a log that appears between runs is found too. The current log is read and counted by data context the first time only; the later runs list the database, which reads no table. @@ -1139,6 +1145,7 @@ def _refuse_log_of_another_data_context(self) -> None: completion_path=self._table_path if self._pod.pod_config.track_completion else None, + job_completion_paths=self._job_completion_paths, ) if found.unlisted: # The check runs before every run; that the database cannot list its tables @@ -1180,6 +1187,8 @@ def require_storable_tables(self, pipeline_database: ArrowDatabaseProtocol) -> N def attach_databases( self, pipeline_database: ArrowDatabaseProtocol | None = None, + *, + job_completion_paths: Set[tuple[str, ...]] = frozenset(), ) -> None: """Attach or detach the pipeline database. @@ -1190,12 +1199,15 @@ def attach_databases( Args: pipeline_database: Pre-scoped pipeline DB (at pipeline root), or ``None`` to detach. + job_completion_paths: Current completion log paths in the job's + pipeline database. """ if pipeline_database is not None: # A database that cannot store the invocation log refuses it now, # before anything is delivered or changes (ITL-1162). self.require_storable_tables(pipeline_database) self._pipeline_database = pipeline_database + self._job_completion_paths = job_completion_paths self._unlisted_store_reported = False self._current_log_checked = False if pipeline_database is not None: 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 b5e3f2214..f73d34efa 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 @@ -177,6 +177,56 @@ def build_job() -> PipelineJob: ] +@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 From 22ac14336ea3d36b4312dde42fa62d80bf877692 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:18:33 -0800 Subject: [PATCH 4/7] fix(pipeline): isolate invocation-context results and completion checks --- .zed/rules | 14 +- CLAUDE.md | 12 +- changelog.d/ITL-1559.md | 5 +- docs/dev/design_issues/ITL-1559-CXP1.md | 11 +- docs/reference/data-function-types.md | 9 +- docs/reference/hashing.md | 1 + src/orcapod/contexts/stored.py | 42 ++--- src/orcapod/core/cached_function_pod.py | 14 +- src/orcapod/core/data_function.py | 17 +- src/orcapod/core/function_pod.py | 45 ++++- src/orcapod/core/nodes/function_node.py | 42 +++-- src/orcapod/core/result_cache.py | 9 + src/orcapod/errors.py | 9 +- src/orcapod/pipeline/graph.py | 16 ++ src/orcapod/pipeline/job.py | 9 - src/orcapod/side_effects.py | 30 +-- .../function_pod/test_function_pod_ctx_arg.py | 174 +++++++++++++++++- tests/test_databases/test_list_table_paths.py | 6 +- 18 files changed, 359 insertions(+), 106 deletions(-) diff --git a/.zed/rules b/.zed/rules index bc23a7cf7..80b65794b 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,8 @@ 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 and add a ctx: + component immediately before the data function type (ITL-1559). - 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 @@ -1019,8 +1021,8 @@ generation of hashing; rows of the current data context are the current entries. every read or lookup keeps rows of the current data context only (keep_rows_of_data_context, or a lookup constraint on the column). - A table at an older layout is never read as current and never modified. What a node does - about such tables, rows of another data context, and completion tables under the same name - outside the current job's completion paths is decided in one place, + about such tables, rows of another data context, and completion tables at a node's + previous pipeline identity is decided in one place, contexts/stored.account_for_stale_tables: count and report, or, for a node that delivers side effects (a SideEffectPod node, or a function node whose pod takes the invocation context, ctx_arg), raise SideEffectLogDataContextError before any delivery. A new kind of @@ -1031,9 +1033,9 @@ generation of hashing; rows of the current data context are the current entries. , side_effect_function/, side_effects/, relative to the node's database; /source for a cached source) and every table there whose last component is not in contexts/stored.CURRENT_LAYOUTS is of another layout (tables_of_another_layout). - For a node that tracks completions, the same listing finds current-layout completion - tables outside the node's own path and those of its job (completion_path and - job_completion_paths, ITL-1559). + For a node that tracks completions, the same listing checks the exact current-layout path + computed from that node's pipeline identity before the context parameter entered the hash + (previous_completion_path, ITL-1559). A new layout constant must be added to CURRENT_LAYOUTS. A store that cannot list raises TableListingNotSupportedError: side-effecting nodes then warn and proceed (developer, November 11, 2026). Every database class implements list_table_paths. Stores of the diff --git a/CLAUDE.md b/CLAUDE.md index bd47524fd..92f3557bf 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,8 @@ 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` and add a + `ctx:` component immediately before the data function type (ITL-1559). - 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 @@ -1050,8 +1052,8 @@ current data context are the current entries. and every read or lookup keeps rows of the current data context only (`keep_rows_of_data_context`, or a lookup constraint on the column). - A table at an older layout is never read as current and never modified. What a node does - about such tables, rows of another data context, and completion tables under the same name - outside the current job's completion paths is decided in one place, + about such tables, rows of another data context, and completion tables at a node's + previous pipeline identity is decided in one place, `contexts/stored.account_for_stale_tables`: count and report, or, for a node that delivers side effects (a `SideEffectPod` node, or a function node whose pod takes the invocation context, `ctx_arg`), raise `SideEffectLogDataContextError` before any delivery. A new kind @@ -1063,8 +1065,8 @@ current data context are the current entries. node's database; `/source` for a cached source) and every table there whose last component is not in `contexts/stored.CURRENT_LAYOUTS` is of another layout (`tables_of_another_layout`). For a node that tracks completions, the same listing - finds current-layout completion tables outside the node's own path and those of its job - (`completion_path` and `job_completion_paths`, ITL-1559). + checks the exact current-layout path computed from that node's pipeline identity + before the context parameter entered the hash (`previous_completion_path`, ITL-1559). A new layout constant must be added to `CURRENT_LAYOUTS`. A store that cannot list raises `TableListingNotSupportedError`: side-effecting nodes then warn and proceed (developer, November 11, 2026). Every database class implements diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index f855f45db..fd8153bc2 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -9,7 +9,10 @@ by earlier development versions remain at their old paths. There is no migration for these unreleased layouts. Side-effecting function nodes and tracked side-effect pods refuse to run when - completion tables under the same name exist outside the current job's completion paths. + a completion table exists at that node's exact previous pipeline path. + Result tables for context-taking function pods have a new `ctx:` + path component so results from a plain pod or a different context parameter + cannot prevent delivery. Saved jobs continue reading their original result tables. (ITL-1559) ### Fixed diff --git a/docs/dev/design_issues/ITL-1559-CXP1.md b/docs/dev/design_issues/ITL-1559-CXP1.md index a5dbd6b36..d13127e0e 100644 --- a/docs/dev/design_issues/ITL-1559-CXP1.md +++ b/docs/dev/design_issues/ITL-1559-CXP1.md @@ -9,8 +9,9 @@ A plain function pod and a context-taking pod with the same underlying data func 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:** Use the same structure for the pod's content and pipeline identities. Include -the context parameter name when configured so the pod and its downstream steps have -distinct pipeline hashes. The stale-table check refuses delivery when a completion table -under the same name is outside the current job's completion paths. A saved job restores its -context-taking function nodes and reads their results using its recorded identities. +**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. The stale-table check refuses delivery when a completion table exists at the +node's exact previous pipeline path. A saved job restores its context-taking function nodes +and reads their results from the original result paths. diff --git a/docs/reference/data-function-types.md b/docs/reference/data-function-types.md index 51c09f494..66e5965f0 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -17,8 +17,13 @@ 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 pod configured with `ctx_arg` uses +`side_effect_function///v/ctx:/python.function.v1/rev1/rdb_v1` +relative to its result database. Saved jobs record that 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 bb65be4c4..5b8e27f39 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -376,6 +376,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | function `uri` (output-schema digest) | `core/data_function.py:DataFunctionBase.output_data_schema_hash` | | operator `uri` | `core/operators/static_output_pod.py:StaticOutputOperatorPod.uri` | | `schema:` / `instance:` / `node:` path components | `core/nodes/function_node.py:FunctionNodeBase.node_identity_path`, `core/nodes/operator_node.py:OperatorNodeBase.node_identity_path`, `side_effects.py:SideEffectJobNode.attach_databases`, `core/sources/cached_source.py:CachedSource._unversioned_cache_path` | +| Previous completion table path (ITL-1559) | `core/function_pod.py:pipeline_hash_before_context_parameter..resolve`, `core/nodes/function_node.py:FunctionJobNode._previous_completion_path`, `side_effects.py:SideEffectJobNode._previous_completion_path` | | source-node slot names | `core/nodes/source_node.py:SourceNode.from_stream`, `core/nodes/source_node.py:SourceJobNode.from_stream` | | source system-tag column name (schema digest) | `utils/schema_utils.py:compute_schema_hash` | | system-tag suffixes of `Join`, `MergeJoin`, `Batch`, `GroupBy` | `core/operators/join.py:Join._compute_system_tag_suffixes`, `core/operators/join.py:Join._predict_system_tag_schema`, `core/operators/join.py:Join.static_process`, `core/operators/merge_join.py:MergeJoin._system_tag_suffix`, `core/operators/batch.py:Batch.unary_output_schema`, `core/operators/batch.py:Batch.unary_static_process`, `core/operators/group_by.py:GroupBy.unary_output_schema`, `core/operators/group_by.py:GroupBy.unary_static_process` | diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index 58f65973a..686ecf0fb 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -30,7 +30,7 @@ import logging import warnings -from collections.abc import Collection, Set +from collections.abc import Collection from dataclasses import dataclass, field from typing import Any, NamedTuple, Protocol, cast @@ -373,8 +373,8 @@ class StaleTables: tables: The tables found, each once. unlisted: The places that could not be searched because the database cannot list its tables. - other_completion_paths: Current-layout completion tables at another path - under the same function or pod name. + other_completion_paths: Current-layout completion tables at the caller's + previous pipeline identity. """ tables: list[StaleTable] = field(default_factory=list) @@ -413,8 +413,8 @@ def tables_of_another_layout( Args: paths: The database's table paths under the function or pod name. result_revision: The revision component of the result tables the caller reads - (``rev1``). A result table under ``name_path`` with another revision is then - of another layout too. ``None`` checks the last component only. + (``rev1``). A listed result table with another revision is of another + layout too. ``None`` checks the last component only. Returns: The paths of tables that are not at a current layout, in listing order. @@ -453,16 +453,15 @@ def find_stale_tables( current: tuple[tuple[str, ...], str] | None = None, name_path: tuple[str, ...] | None = None, result_revision: str | None = None, - completion_path: tuple[str, ...] | None = None, - job_completion_paths: Set[tuple[str, ...]] = frozenset(), + previous_completion_path: tuple[str, ...] | None = None, ) -> StaleTables: """Find the stored rows of other generations that belong to one table of a node. Two searches, neither of which writes anything: - under ``name_path``, by listing the database, for tables of another layout - wherever their hashes put them (ITL-954), and for completion tables with - the current layout outside the set of paths addressed by the current job; + wherever their hashes put them (ITL-954), and for the completion table of + this node's previous pipeline identity (ITL-1559); - in the current table, for rows of another data context. Args: @@ -475,11 +474,8 @@ def find_stale_tables( result_revision: For a result cache, the revision of its data function type's record: a result table under ``name_path`` at another revision is listed too (``tables_of_another_layout``). - completion_path: The expected path of a side-effect completion log. A table - under ``name_path`` with the same layout at another path may hold - completions this node cannot match (ITL-1559). - job_completion_paths: Completion paths relative to this database for the - compiled job. Logs belonging to another node of this job are current. + previous_completion_path: The exact path of this node's completion table + before its pipeline identity changed, relative to this database. Returns: The tables of another layout found, then one entry per other data context @@ -509,14 +505,13 @@ def find_stale_tables( ] ) ) - if completion_path is not None: - found.other_completion_paths = [ - database.base_path + path - for path in paths - if path[-1] == completion_path[-1] - and path != completion_path - and path not in job_completion_paths - ] + if ( + previous_completion_path is not None + and previous_completion_path in paths + ): + found.other_completion_paths.append( + database.base_path + previous_completion_path + ) if current is not None: current_path, current_context = current for key, rows in sorted(stored_data_contexts(database, current_path).items()): @@ -540,8 +535,7 @@ def account_for_stale_tables( that takes the invocation context) must not act again for inputs it already handled when those completions cannot be matched at the current path or under the current data context. It fails before doing anything. Every old-layout table - and every completion table under the node's name outside the current job's - completion paths counts. + and a completion table at the node's previous pipeline identity count. The error names the tables. Where the database cannot list its tables, the node warns and proceeds (developer, November 11, 2026). 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 7fd1200b0..ed50547b2 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -27,7 +27,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, @@ -1540,16 +1540,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], ) @@ -1595,9 +1602,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 diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index fc30664e7..cfb40cdd0 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -51,11 +51,13 @@ TrackerManagerProtocol, ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.protocols.hashing_protocols import PipelineElementProtocol from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.system_constants import constants from orcapod.types import ( ColumnConfig, + ContentHash, PipelineConfig, PodConfig, Schema, @@ -88,6 +90,44 @@ def _executor_supports_concurrent( return executor is not None and executor.supports_concurrent_execution +def pipeline_hash_before_context_parameter(stream: StreamBase) -> ContentHash: + """Recompute a stream's pipeline hash using the pre-ITL-1559 pod identity. + + Only the pipeline identity of a context-taking function changed. Reuse the + current identities of the sources and other leaves, and resolve the former + pod identity through the existing identity structures of its descendants. + """ + hasher = stream.data_context.semantic_hasher + hashes: dict[int, ContentHash] = {} + + def resolve(obj: Any) -> ContentHash: + if not isinstance(obj, PipelineElementProtocol): + return obj.content_hash(hasher) + key = id(obj) + if key not in hashes: + if isinstance(obj, _FunctionPodBase) and obj.ctx_arg_name is not None: + structure = ( + obj.data_function + if type(obj).pipeline_identity_structure + is _FunctionPodBase.pipeline_identity_structure + else obj.pipeline_identity_structure() + ) + hashes[key] = hasher.hash_object(structure, resolver=resolve) + elif ( + isinstance(obj, StreamBase) + and obj.producer is not None + and obj.upstreams + ): + hashes[key] = hasher.hash_object( + obj.pipeline_identity_structure(), resolver=resolve + ) + else: + hashes[key] = obj.pipeline_hash(hasher) + return hashes[key] + + return resolve(stream) + + class _FunctionPodBase(TraceableBase): """Base pod that applies a data function to each input data.""" @@ -182,7 +222,9 @@ def identity_structure(self) -> Any: def pipeline_identity_structure(self) -> Any: """Include the parameter that receives the invocation context, when set.""" - return self.identity_structure() + if self._ctx_arg_name is not None: + return self.identity_structure() + return self.data_function def _build_invocation_context( self, @@ -1871,6 +1913,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 0d085ffc0..5898b9d98 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -24,7 +24,7 @@ import uuid from abc import abstractmethod from collections import Counter -from collections.abc import Callable, Iterator, Mapping, Sequence, Set +from collections.abc import Callable, Iterator, Mapping, Sequence from datetime import datetime, timezone from functools import partial from typing import Any, Literal, NamedTuple, cast @@ -38,6 +38,7 @@ fall_through_tags, function_input, function_input_schema, + pipeline_hash_before_context_parameter, result_data_schema, result_pod, with_fall_through, @@ -1400,7 +1401,6 @@ class FunctionJobNode(ProvenanceMethods, RunHoldingNode, FunctionNodeBase): _token_column_types: "dict[str, pa.DataType] | None" = None # Set once a database that cannot list its tables was reported. _unlisted_store_reported: bool = False - _job_completion_paths: Set[tuple[str, ...]] = frozenset() # Instance ids of the inputs of the last completed run in this process, each with # its number of inputs; None when no run completed (ITL-1093). A class default so # nodes rebuilt from a saved descriptor start without a run. @@ -1528,6 +1528,21 @@ def completion_log_path(self) -> tuple[str, ...] | None: """The pipeline table storing this live context-taking node's completions.""" return self._versioned_pipeline_path if self._delivers_side_effects else None + def _previous_completion_path(self) -> tuple[str, ...] | None: + path = self.completion_log_path + if path is None: + return None + previous = pipeline_hash_before_context_parameter(self) + if previous == self.pipeline_hash(): + return None + # The layout is last, with an instance component only at content scope. + schema_index = -2 if self._table_scope == "pipeline_hash" else -3 + return ( + *path[:schema_index], + f"schema:{previous.to_hex()}", + *path[schema_index + 1 :], + ) + def _begin_run(self) -> None: """Reset schema preflight and refresh the stored tables for this run. @@ -1598,9 +1613,10 @@ def _account_for_stale_tables(self) -> None: unchanged, and their number is reported (ITL-944). Such tables are looked for at this node's own path and, because the hashes in a path can differ between versions, anywhere under the function's name in the database (ITL-954). A node - that delivers side effects fails instead. Completion paths outside the - current job, stale result tables, and rows of another data context in the - current tables also count because their completions cannot be matched. + that delivers side effects fails instead. A completion table at the node's + previous pipeline identity, stale result tables, and rows of another data + context in the current tables also count because their completions cannot + be matched. Raises: SideEffectLogDataContextError: If this node delivers side effects and @@ -1616,8 +1632,7 @@ def _account_for_stale_tables(self) -> None: if delivers and not self._current_tables_checked else None, name_path=self.node_name_path or None, - completion_path=self.completion_log_path, - job_completion_paths=self._job_completion_paths, + previous_completion_path=self._previous_completion_path(), ) if delivers: for cached_pod in (self._cached_function_pod, self._ephemeral_cached_pod): @@ -1695,8 +1710,6 @@ def attach_databases( pipeline_database: ArrowDatabaseProtocol | None = None, result_database: ArrowDatabaseProtocol | None = None, ephemeral_database: ArrowDatabaseProtocol | None = None, - *, - job_completion_paths: Set[tuple[str, ...]] = frozenset(), ) -> None: """Attach databases for persistent caching and pipeline records. @@ -1727,8 +1740,6 @@ def attach_databases( via ``set_ephemeral_database()``. Equivalent to calling ``set_ephemeral_database(ephemeral_database)`` after ``attach_databases()``. - job_completion_paths: Current completion log paths in the job's - pipeline database. """ if pipeline_database is not None: # A database that cannot store this node's tables refuses them now, @@ -1737,7 +1748,6 @@ def attach_databases( if ephemeral_database is not None: self.require_storable_results(ephemeral_database) # Another database has its own tables of other generations to account for. - self._job_completion_paths = job_completion_paths self._stale_tables_checked = False self._current_tables_checked = False self._pipeline_preflight_checked = False @@ -1899,12 +1909,14 @@ def from_descriptor( node._stored_schema = descriptor.get("output_schema", {}) node._stored_node_uri = tuple(descriptor.get("node_uri") or ()) node._node_type = descriptor["node_type"] - # The file records the data function URI. Its pod uses the side-effect - # prefix for both pipeline and result tables when it takes a context. + # 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 = 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 diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index e341983bf..4a82c33a3 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -173,6 +173,15 @@ def _with_declared_token_columns( return outputs +def context_result_path( + uri: tuple[str, ...], context_parameter: str | None +) -> tuple[str, ...]: + """Scope context-taking result tables by the configured parameter name.""" + if context_parameter is None: + return uri + return (*uri[:-1], f"ctx:{context_parameter}", uri[-1]) + + class ResultCache: """Shared result caching backed by an ``ArrowDatabaseProtocol``. diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 192f0a8ba..f619b598e 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1297,10 +1297,9 @@ class SideEffectLogDataContextError(OrcapodDatabaseError): skipped and computed again. The search lists tables under the node's function or pod name (ITL-954). - A table at an older layout or a current-layout completion table under the - same name outside the current job's completion paths counts. The latter can - occur when a pipeline hash changes (ITL-1559). ``record_paths`` names every - table found. + A table at an older layout or a current-layout completion table at the + node's previous pipeline identity (ITL-1559) counts. ``record_paths`` + names every table found. A fresh database is not a safe way around this error: it holds no completions, so on it the node performs every side effect again. Run the node on a fresh database only @@ -1350,7 +1349,7 @@ def __str__(self) -> str: if self.found_context is None: return ( f"{node} performs side effects, and stored completions exist at " - f"different paths under the same name ({tables}). They cannot be " + f"its previous pipeline identity ({tables}). They cannot be " "matched with current inputs, so nothing was delivered or written by " "this node. Reopen the job with the version and pipeline that wrote " "these tables to reuse the completions." diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 8de7745ea..ababc041e 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -254,6 +254,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 @@ -261,6 +270,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()) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index fc39403dd..011cbb588 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -652,7 +652,6 @@ def _distribute_databases(self) -> None: ) nodes = (self._persistent_node_map or {}).values() - job_completion_paths: set[tuple[str, ...]] = set() for node in nodes: if isinstance(node, FunctionJobNode): if self._unresolved_result_database is not None: @@ -661,7 +660,6 @@ def _distribute_databases(self) -> None: node.attach_databases( pipeline_database=pipeline_db, result_database=result_db, - job_completion_paths=job_completion_paths, ) elif isinstance(node, OperatorJobNode): node.attach_databases( @@ -671,15 +669,8 @@ def _distribute_databases(self) -> None: elif isinstance(node, SideEffectJobNode): node.attach_databases( pipeline_database=pipeline_db, - job_completion_paths=job_completion_paths, ) - # Collect the paths after attachment, when every node addresses its job table. - for node in nodes: - if isinstance(node, (FunctionJobNode, SideEffectJobNode)): - if (path := node.completion_log_path) is not None: - job_completion_paths.add(path) - # ------------------------------------------------------------------ # _iter_function_job_nodes() / apply_node_config() # ------------------------------------------------------------------ diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index d8bede286..8f6c1a517 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -12,7 +12,7 @@ import dataclasses import datetime import logging -from collections.abc import Callable, Collection, Iterator, Sequence, Set +from collections.abc import Callable, Collection, Iterator, Sequence from typing import TYPE_CHECKING, Any, Literal, cast import pyarrow as pa @@ -1084,7 +1084,6 @@ def __init__( ) self._pipeline_database: ArrowDatabaseProtocol | None = None self._table_path: tuple[str, ...] | None = None - self._job_completion_paths: Set[tuple[str, ...]] = frozenset() self._unlisted_store_reported = False self._current_log_checked = False # The rows the last completed run passed on, in the order it passed them; @@ -1118,14 +1117,27 @@ def completion_log_path(self) -> tuple[str, ...] | None: """The attached invocation log path, including logs that only audit delivery.""" return self._table_path + def _previous_completion_path(self) -> tuple[str, ...] | None: + from orcapod.core.function_pod import pipeline_hash_before_context_parameter + + if not self._pod.pod_config.track_completion: + return None + previous = pipeline_hash_before_context_parameter(self) + if previous == self.pipeline_hash(): + return None + return self.node_uri + ( + f"schema:{previous.to_hex()}", + TRACKING_DB_SCHEMA_VERSION, + ) + def _refuse_log_of_another_data_context(self) -> None: """Refuse invocation logs holding deliveries this run cannot match. A delivery already made is found by a record id hashed under this node's data context, so deliveries logged under another one would not be found and every side effect would be delivered again (ITL-944). The search looks under - the pod's name for older layouts and, when tracking completions, logs outside - the current job's completion paths (ITL-954, ITL-1559). Checked at the + the pod's name for older layouts and, when tracking completions, the log at + this node's previous pipeline identity (ITL-954, ITL-1559). Checked at the start of every run, so a log that appears between runs is found too. The current log is read and counted by data context the first time only; the later runs list the database, which reads no table. @@ -1142,10 +1154,7 @@ def _refuse_log_of_another_data_context(self) -> None: current=None if self._current_log_checked else (self._table_path, current), # ("side_effects", ): the part of the path that holds no hash. name_path=self.node_uri, - completion_path=self._table_path - if self._pod.pod_config.track_completion - else None, - job_completion_paths=self._job_completion_paths, + previous_completion_path=self._previous_completion_path(), ) if found.unlisted: # The check runs before every run; that the database cannot list its tables @@ -1187,8 +1196,6 @@ def require_storable_tables(self, pipeline_database: ArrowDatabaseProtocol) -> N def attach_databases( self, pipeline_database: ArrowDatabaseProtocol | None = None, - *, - job_completion_paths: Set[tuple[str, ...]] = frozenset(), ) -> None: """Attach or detach the pipeline database. @@ -1199,15 +1206,12 @@ def attach_databases( Args: pipeline_database: Pre-scoped pipeline DB (at pipeline root), or ``None`` to detach. - job_completion_paths: Current completion log paths in the job's - pipeline database. """ if pipeline_database is not None: # A database that cannot store the invocation log refuses it now, # before anything is delivered or changes (ITL-1162). self.require_storable_tables(pipeline_database) self._pipeline_database = pipeline_database - self._job_completion_paths = job_completion_paths self._unlisted_store_reported = False self._current_log_checked = False if pipeline_database is not None: 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 f73d34efa..3a168ba9b 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 @@ -18,6 +18,7 @@ from orcapod.side_effects import InvocationContext from orcapod.system_constants import ( PIPELINE_DB_SCHEMA_VERSION, + RESULT_DB_SCHEMA_VERSION, TRACKING_DB_SCHEMA_VERSION, ) @@ -247,6 +248,146 @@ def renamed(x: int, y: int, invocation: InvocationContext) -> int: 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[:-1], f"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() + + +@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=...).""" @@ -641,6 +782,12 @@ def tap(result: int, ctx: InvocationContext) -> None: source_id="input", ) saved = tmp_path / "job.json" + + def legacy_result_path( + uri: tuple[str, ...], _context_parameter: str | None + ) -> tuple[str, ...]: + return uri + with monkeypatch.context() as previous: if previous_identity: previous.setattr( @@ -648,6 +795,14 @@ def tap(result: int, ctx: InvocationContext) -> None: "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: @@ -657,6 +812,17 @@ def tap(result: int, ctx: InvocationContext) -> None: 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" @@ -672,13 +838,7 @@ def tap(result: int, ctx: InvocationContext) -> None: assert loaded.nodes[label].as_table()["result"].to_pylist() == [100] assert delivered == [0, 100] - malformed = json.loads(saved.read_text()) - descriptor = next( - node - for node in malformed["pipeline"]["nodes"].values() - if node["label"] == "contextual" - ) del descriptor["fall_through_tags"] - saved.write_text(json.dumps(malformed)) + saved.write_text(json.dumps(payload)) with pytest.raises(ValueError, match="saved node 'contextual'.*fall_through_tags"): PipelineJob.load(saved) diff --git a/tests/test_databases/test_list_table_paths.py b/tests/test_databases/test_list_table_paths.py index 8e2e5cad0..1171f1416 100644 --- a/tests/test_databases/test_list_table_paths.py +++ b/tests/test_databases/test_list_table_paths.py @@ -366,9 +366,9 @@ def test_stale_lookup_uses_layout_and_revision_after_a_long_name( current = name + ("new_hash", "rev1", "rdb_v1") other = (name[0][:-1] + "-", "old_hash", "rev0", "rdb_v0") _fill(store, [old_layout, old_revision, current, other]) - assert tables_of_another_layout(store, name, "rev1") == sorted( - [old_layout, old_revision] - ) + assert tables_of_another_layout( + store.list_table_paths(name), "rev1" + ) == sorted([old_layout, old_revision]) def test_the_last_component_is_the_layout(self, tmp_path: Path): """The last listed component is the original layout component.""" From 07d3651d8d641d1279c4894cb68c2154e6ae4c6a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:40:20 -0800 Subject: [PATCH 5/7] fix(pipeline): guard legacy context caches and reopen sibling taps --- changelog.d/ITL-1559.md | 13 +- docs/dev/design_issues/ITL-1559-CXP1.md | 8 +- docs/reference/data-function-types.md | 12 +- src/orcapod/contexts/stored.py | 31 +++- src/orcapod/core/cached_function_pod.py | 1 + src/orcapod/core/data_function.py | 20 +++ src/orcapod/core/result_cache.py | 20 +++ src/orcapod/errors.py | 6 +- src/orcapod/pipeline/job.py | 10 ++ src/orcapod/side_effects.py | 11 +- .../function_pod/test_function_pod_ctx_arg.py | 170 +++++++++++++++++- 11 files changed, 279 insertions(+), 23 deletions(-) diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index fd8153bc2..e3b2b03d7 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -9,10 +9,17 @@ by earlier development versions remain at their old paths. There is no migration for these unreleased layouts. Side-effecting function nodes and tracked side-effect pods refuse to run when - a completion table exists at that node's exact previous pipeline path. + a completion table exists at that node's exact previous pipeline path. A + tracked tap can reopen alongside a live sibling that owns the tap's former path. Result tables for context-taking function pods have a new `ctx:` - path component so results from a plain pod or a different context parameter - cannot prevent delivery. Saved jobs continue reading their original result tables. + path component. Decorator caches also move context-taking results into the + `side_effect_function` namespace. The pod and job caches refuse delivery if + their exact previous result table exists. For a decorator cache, the old path + was shared with plain calls. The check refuses delivery when a row there + matches the configured function's signature hash. A different or missing hash + cannot identify a legacy contextual result, and a plain result with the same + hash cannot be distinguished from one. Saved jobs continue reading their + original result tables. (ITL-1559) ### Fixed diff --git a/docs/dev/design_issues/ITL-1559-CXP1.md b/docs/dev/design_issues/ITL-1559-CXP1.md index d13127e0e..c2deb0acd 100644 --- a/docs/dev/design_issues/ITL-1559-CXP1.md +++ b/docs/dev/design_issues/ITL-1559-CXP1.md @@ -12,6 +12,8 @@ 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. The stale-table check refuses delivery when a completion table exists at the -node's exact previous pipeline path. A saved job restores its context-taking function nodes -and reads their results from the original result paths. +their paths. The stale-table check looks at the exact previous pipeline and result +paths. A live tap that owns a path keeps it available to that tap. A decorator +cache's previous path was shared with plain calls, so the check uses the stored +function signature to recognize previously completed calls. 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 66e5965f0..449081c96 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -17,9 +17,15 @@ 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`. -A pod configured with `ctx_arg` uses -`side_effect_function///v/ctx:/python.function.v1/rev1/rdb_v1` -relative to its result database. Saved jobs record that result path through the type +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. 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 diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index 686ecf0fb..b1151c891 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -373,8 +373,8 @@ class StaleTables: tables: The tables found, each once. unlisted: The places that could not be searched because the database cannot list its tables. - other_completion_paths: Current-layout completion tables at the caller's - previous pipeline identity. + other_completion_paths: Current-layout tables recording completions at + the caller's previous pipeline or result cache path. """ tables: list[StaleTable] = field(default_factory=list) @@ -454,15 +454,15 @@ def find_stale_tables( name_path: tuple[str, ...] | None = None, result_revision: str | None = None, previous_completion_path: tuple[str, ...] | None = None, + previous_result: tuple[tuple[str, ...], tuple[str, bytes] | None] | None = None, ) -> StaleTables: """Find the stored rows of other generations that belong to one table of a node. - Two searches, neither of which writes anything: - - under ``name_path``, by listing the database, for tables of another layout wherever their hashes put them (ITL-954), and for the completion table of this node's previous pipeline identity (ITL-1559); - - in the current table, for rows of another data context. + - in the current table, for rows of another data context; + - at the exact previous result path, for evidence of completed calls (ITL-1559). Args: database: The database the paths belong to. @@ -476,6 +476,8 @@ def find_stale_tables( (``tables_of_another_layout``). previous_completion_path: The exact path of this node's completion table before its pipeline identity changed, relative to this database. + previous_result: The exact previous result table path and optional + column/value pair identifying a result in a shared legacy namespace. Returns: The tables of another layout found, then one entry per other data context @@ -512,6 +514,23 @@ def find_stale_tables( found.other_completion_paths.append( database.base_path + previous_completion_path ) + if previous_result is not None: + path, match = previous_result + if match is None: + completed = database.table_exists(path) + else: + column, value = match + rows = database.get_all_records(path) + completed = ( + rows is not None + and column in rows.column_names + and pc.any( + pc.equal(rows[column], pa.scalar(value, type=pa.large_binary())) + ).as_py() + is True + ) + if completed: + found.other_completion_paths.append(database.base_path + path) if current is not None: current_path, current_context = current for key, rows in sorted(stored_data_contexts(database, current_path).items()): @@ -535,7 +554,7 @@ def account_for_stale_tables( that takes the invocation context) must not act again for inputs it already handled when those completions cannot be matched at the current path or under the current data context. It fails before doing anything. Every old-layout table - and a completion table at the node's previous pipeline identity count. + and a completion table at the node's previous pipeline or result path count. The error names the tables. Where the database cannot list its tables, the node warns and proceeds (developer, November 11, 2026). diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index edee43f22..2a85bcd81 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -79,6 +79,7 @@ def __init__( # The uri holds no hash up to the function's name, which comes after # "side_effect_function" for a pod that takes the invocation context. name_path=self.uri[: 2 if function_pod.ctx_arg_name is not None else 1], + previous_record_path=self.uri if self.ctx_arg_name is not None else None, ) def require_storable_results(self) -> None: diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index ed50547b2..6a581b5e3 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -45,6 +45,7 @@ check_conformance, normalize_output_numbers, ) +from orcapod.system_constants import constants from orcapod.types import ContentHash, DataValue, Schema, SchemaLike from orcapod.utils import schema_utils from orcapod.utils.canonical_type_names import stabilize_type_names @@ -1547,7 +1548,20 @@ def __init__( super().__init__(data_function, **kwargs) self._result_database = result_database self._record_path_prefix = record_path_prefix + previous_record_path = None + previous_result_match = None if context_parameter is not None: + # Decorator caches used the plain namespace. The stored signature + # lets us recognize results from the same declared interface. + signature = self.get_function_variation_data().get( + "function_signature_hash" + ) + if isinstance(signature, bytes): + previous_record_path = record_path_prefix + self.uri + previous_result_match = ( + f"{constants.PF_VARIATION_PREFIX}function_signature_hash", + signature, + ) record_path_prefix += ("side_effect_function",) self._cache = ResultCache( result_database=result_database, @@ -1559,6 +1573,8 @@ def __init__( 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], + previous_record_path=previous_record_path, + previous_result_match=previous_result_match, ) @property @@ -1623,6 +1639,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: @@ -1666,6 +1684,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/result_cache.py b/src/orcapod/core/result_cache.py index 4a82c33a3..7d8a20a16 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -211,6 +211,8 @@ def __init__( auto_flush: bool = True, delivers_side_effects: bool = False, name_path: tuple[str, ...] | None = None, + previous_record_path: tuple[str, ...] | None = None, + previous_result_match: tuple[str, bytes] | None = None, ) -> None: """Create a result cache over one result table. @@ -230,6 +232,10 @@ def __init__( the part that holds no hash. Result tables written before v0.3 are looked for under it, whatever hashes their paths hold (ITL-954). ``None`` looks at the paths computed from ``record_path`` only. + previous_record_path: Result path through the type component before + context-taking results moved to their own path (ITL-1559). + previous_result_match: The stored column and value that identify the + function's results if the previous path is shared with plain calls. """ self._result_database = result_database self._record_path = record_path @@ -237,6 +243,14 @@ def __init__( self._auto_flush = auto_flush self._delivers_side_effects = delivers_side_effects self._name_path = name_path + self._previous_result = ( + ( + previous_record_path + (revision, RESULT_DB_SCHEMA_VERSION), + previous_result_match, + ) + if previous_record_path is not None and previous_record_path != record_path + else None + ) # Set once a read has reported the stored rows it skipped. self._skipped_rows_reported = False # Set once stored results of other generations have been accounted for. @@ -291,6 +305,7 @@ def stale_tables( else None, name_path=self._name_path, result_revision=self._revision, + previous_result=self._previous_result, ) def stale_tables_accounted_for(self) -> None: @@ -302,6 +317,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/errors.py b/src/orcapod/errors.py index f619b598e..cb421e7ab 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1297,8 +1297,8 @@ class SideEffectLogDataContextError(OrcapodDatabaseError): skipped and computed again. The search lists tables under the node's function or pod name (ITL-954). - A table at an older layout or a current-layout completion table at the - node's previous pipeline identity (ITL-1559) counts. ``record_paths`` + A table at an older layout or evidence of completion at the node's previous + pipeline or result cache path (ITL-1559) counts. ``record_paths`` names every table found. A fresh database is not a safe way around this error: it holds no completions, so on @@ -1349,7 +1349,7 @@ def __str__(self) -> str: if self.found_context is None: return ( f"{node} performs side effects, and stored completions exist at " - f"its previous pipeline identity ({tables}). They cannot be " + f"a previous pipeline or result cache path ({tables}). They cannot be " "matched with current inputs, so nothing was delivered or written by " "this node. Reopen the job with the version and pipeline that wrote " "these tables to reuse the completions." diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 011cbb588..e73d01066 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -652,6 +652,7 @@ def _distribute_databases(self) -> None: ) nodes = (self._persistent_node_map or {}).values() + side_effect_nodes: list[SideEffectJobNode] = [] for node in nodes: if isinstance(node, FunctionJobNode): if self._unresolved_result_database is not None: @@ -670,6 +671,15 @@ def _distribute_databases(self) -> None: node.attach_databases( pipeline_database=pipeline_db, ) + side_effect_nodes.append(node) + + current_completion_paths = frozenset( + path + for node in side_effect_nodes + if (path := node.completion_log_path) is not None + ) + for node in side_effect_nodes: + node.set_current_completion_paths(current_completion_paths) # ------------------------------------------------------------------ # _iter_function_job_nodes() / apply_node_config() diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 8f6c1a517..95e46aad8 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -1084,6 +1084,7 @@ def __init__( ) self._pipeline_database: ArrowDatabaseProtocol | None = None self._table_path: tuple[str, ...] | None = None + self._current_completion_paths: frozenset[tuple[str, ...]] = frozenset() self._unlisted_store_reported = False self._current_log_checked = False # The rows the last completed run passed on, in the order it passed them; @@ -1117,6 +1118,10 @@ def completion_log_path(self) -> tuple[str, ...] | None: """The attached invocation log path, including logs that only audit delivery.""" return self._table_path + def set_current_completion_paths(self, paths: frozenset[tuple[str, ...]]) -> None: + """Record the paths owned by live taps sharing this job's database view.""" + self._current_completion_paths = paths + def _previous_completion_path(self) -> tuple[str, ...] | None: from orcapod.core.function_pod import pipeline_hash_before_context_parameter @@ -1125,10 +1130,13 @@ def _previous_completion_path(self) -> tuple[str, ...] | None: previous = pipeline_hash_before_context_parameter(self) if previous == self.pipeline_hash(): return None - return self.node_uri + ( + path = self.node_uri + ( f"schema:{previous.to_hex()}", TRACKING_DB_SCHEMA_VERSION, ) + # Before ctx_arg entered the pipeline hash, this tap could share a + # pipeline identity with a live tap on the equivalent plain branch. + return None if path in self._current_completion_paths else path def _refuse_log_of_another_data_context(self) -> None: """Refuse invocation logs holding deliveries this run cannot match. @@ -1212,6 +1220,7 @@ def attach_databases( # before anything is delivered or changes (ITL-1162). self.require_storable_tables(pipeline_database) self._pipeline_database = pipeline_database + self._current_completion_paths = frozenset() self._unlisted_store_reported = False self._current_log_checked = False if pipeline_database is not None: 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 3a168ba9b..ed25a30ad 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 @@ -661,12 +661,12 @@ def my_fn(value: int, ctx: InvocationContext) -> str: @pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) -@pytest.mark.parametrize("only_downstream_log", [False, True], ids=["function", "tap"]) +@pytest.mark.parametrize("legacy_case", ["function_log", "tap_log", "tap_and_results"]) def test_reopening_pre_context_identity_completions_refuses_delivery( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, async_path: bool, - only_downstream_log: bool, + legacy_case: str, ) -> None: """Completions at the previous schema path refuse a run before redelivery.""" from orcapod import FunctionPod, PipelineJob, function_pod @@ -677,6 +677,7 @@ def test_reopening_pre_context_identity_completions_refuses_delivery( delivered: list[tuple[str, int]] = [] root = tmp_path / "store" + only_downstream_log = legacy_case != "function_log" def build_job(root: Path) -> PipelineJob: @function_pod(output_keys="result", ctx_arg="ctx") @@ -713,6 +714,11 @@ def run(job: PipelineJob) -> None: 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) @@ -721,8 +727,8 @@ def run(job: PipelineJob) -> None: path for path in table_paths if path[-1] == PIPELINE_DB_SCHEMA_VERSION ) if only_downstream_log: - # Keep the shared result cache and the prior tap log. This lets the run - # reach the tap, even though the function would otherwise refuse first. + # 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: @@ -737,6 +743,12 @@ def run(job: PipelineJob) -> None: ) expected_label = "tap" 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(part.startswith("ctx:") for part in expected_path) + expected_label = "contextual" else: expected_path = function_log expected_label = "contextual" @@ -753,6 +765,156 @@ def run(job: PipelineJob) -> None: 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_refuse_delivery( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + async_path: bool, + run_in_job: bool, + cache_kind: str, +) -> None: + """Standalone results from the old exact cache path protect a finished action.""" + from orcapod import PipelineJob, function_pod + from orcapod.databases import DeltaTableDatabase + from orcapod.errors import SideEffectLogDataContextError + from orcapod.sources import DictSource + + deliveries: list[int] = [] + cache_root = tmp_path / "cache" + + def build_pod(): + 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(part.startswith("ctx:") 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 + + pod = build_pod() + with pytest.raises(SideEffectLogDataContextError) as info: + if run_in_job: + with PipelineJob( + name="upgrade", database=DeltaTableDatabase(tmp_path / "job") + ) as job: + pod.process(source, label="action") + asyncio.run(job.run_async()) if async_path else job.run() + else: + stream = pod.process(source) + if async_path: + + async def consume() -> None: + async for _ in stream.async_iter_data(): + pass + + asyncio.run(consume()) + else: + list(stream.iter_data()) + assert info.value.record_paths == (previous_path,) + assert deliveries == [10] + reopened = DeltaTableDatabase(cache_root) + assert reopened.list_table_paths() == [previous_path] + assert reopened.get_all_records(previous_path) == before + + +@pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize( + "plain_written_first", [False, True], ids=["both", "plain_first"] +) +def test_current_sibling_log_is_not_a_previous_context_completion( + tmp_path: Path, async_path: bool, plain_written_first: bool +) -> None: + """A live plain sibling owns the log at the contextual tap's former path.""" + 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(*, both: bool) -> PipelineJob: + source = DictSource( + [{"id": 1, "value": 10}], + tag_columns=["id"], + tag_only_columns=True, + source_id="input", + ) + with PipelineJob(name="siblings", database=DeltaTableDatabase(root)) as job: + observe = SideEffectPod(tap) + observe.process(plain.pod(source, label="plain"), label="plain_tap") + if both: + 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 plain_written_first: + run(build_job(both=False)) + assert deliveries == [("tap", 110)] + + job = build_job(both=True) + run(job) + run(job) + reopened = build_job(both=True) + 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)] + + @pytest.mark.parametrize( "previous_identity", [False, True], ids=["current", "previous"] ) From 8026d4a7084372fb1564d7a2b0eee3f443b03d0f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:05:26 -0800 Subject: [PATCH 6/7] fix(pipeline): keep current plain tap logs usable --- .zed/rules | 8 +- CLAUDE.md | 8 +- changelog.d/ITL-1559.md | 19 ++-- docs/dev/design_issues/ITL-1559-CXP1.md | 10 +- docs/reference/hashing.md | 2 +- src/orcapod/contexts/stored.py | 25 +---- src/orcapod/core/data_function.py | 16 --- src/orcapod/core/result_cache.py | 12 +-- src/orcapod/pipeline/job.py | 10 -- src/orcapod/side_effects.py | 34 +------ .../function_pod/test_function_pod_ctx_arg.py | 99 +++++++++++++------ 11 files changed, 106 insertions(+), 137 deletions(-) diff --git a/.zed/rules b/.zed/rules index 80b65794b..d7dd4d1ec 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1033,9 +1033,11 @@ generation of hashing; rows of the current data context are the current entries. , side_effect_function/, side_effects/, relative to the node's database; /source for a cached source) and every table there whose last component is not in contexts/stored.CURRENT_LAYOUTS is of another layout (tables_of_another_layout). - For a node that tracks completions, the same listing checks the exact current-layout path - computed from that node's pipeline identity before the context parameter entered the hash - (previous_completion_path, ITL-1559). + For a context-taking function node, the same listing checks the exact current-layout path + in its reserved namespace computed from the node's pipeline identity before the context + parameter entered the hash (previous_completion_path, ITL-1559). Tap logs and decorator + cache tables at shared paths belong to the current plain branch, even when that branch + is absent. A new layout constant must be added to CURRENT_LAYOUTS. A store that cannot list raises TableListingNotSupportedError: side-effecting nodes then warn and proceed (developer, November 11, 2026). Every database class implements list_table_paths. Stores of the diff --git a/CLAUDE.md b/CLAUDE.md index 92f3557bf..e901d6a39 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1064,9 +1064,11 @@ current data context are the current entries. ``, `side_effect_function/`, `side_effects/`, relative to the node's database; `/source` for a cached source) and every table there whose last component is not in `contexts/stored.CURRENT_LAYOUTS` is of another layout - (`tables_of_another_layout`). For a node that tracks completions, the same listing - checks the exact current-layout path computed from that node's pipeline identity - before the context parameter entered the hash (`previous_completion_path`, ITL-1559). + (`tables_of_another_layout`). For a context-taking function node, the same listing + checks the exact current-layout path in its reserved namespace computed from the node's + pipeline identity before the context parameter entered the hash + (`previous_completion_path`, ITL-1559). Tap logs and decorator cache tables at shared + paths belong to the current plain branch, even when that branch is absent. A new layout constant must be added to `CURRENT_LAYOUTS`. A store that cannot list raises `TableListingNotSupportedError`: side-effecting nodes then warn and proceed (developer, November 11, 2026). Every database class implements diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index e3b2b03d7..67cfcfa56 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -8,18 +8,17 @@ 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. - Side-effecting function nodes and tracked side-effect pods refuse to run when - a completion table exists at that node's exact previous pipeline path. A - tracked tap can reopen alongside a live sibling that owns the tap's former path. Result tables for context-taking function pods have a new `ctx:` path component. Decorator caches also move context-taking results into the - `side_effect_function` namespace. The pod and job caches refuse delivery if - their exact previous result table exists. For a decorator cache, the old path - was shared with plain calls. The check refuses delivery when a row there - matches the configured function's signature hash. A different or missing hash - cannot identify a legacy contextual result, and a plain result with the same - hash cannot be distinguished from one. Saved jobs continue reading their - original result tables. + `side_effect_function` namespace. Live jobs use the new paths for + completions and results. Older downstream tap logs and decorator results + can share paths with current plain calls, so upgrading can repeat actions + previously recorded there. Delete or rebuild stores written by an earlier + development version before running affected jobs, and account for repeat + deliveries for previously processed inputs. A context-taking function still + refuses delivery if it finds its exact previous pipeline, pod cache, or job + cache table in the namespace reserved for context-taking functions. Saved + jobs continue reading their original result tables. (ITL-1559) ### Fixed diff --git a/docs/dev/design_issues/ITL-1559-CXP1.md b/docs/dev/design_issues/ITL-1559-CXP1.md index c2deb0acd..066f677e4 100644 --- a/docs/dev/design_issues/ITL-1559-CXP1.md +++ b/docs/dev/design_issues/ITL-1559-CXP1.md @@ -12,8 +12,8 @@ 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. The stale-table check looks at the exact previous pipeline and result -paths. A live tap that owns a path keeps it available to that tap. A decorator -cache's previous path was shared with plain calls, so the check uses the stored -function signature to recognize previously completed calls. A saved job restores -its context-taking function nodes and reads their results from the original paths. +their paths. The stale-table check looks for exact previous pipeline and result +paths reserved for context-taking functions. Downstream tap logs and decorator +results at shared paths belong to the current plain branch, even when that +branch is absent from the job. A saved job restores its context-taking function +nodes and reads their results from the original paths. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 5b8e27f39..12e458abb 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -376,7 +376,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | function `uri` (output-schema digest) | `core/data_function.py:DataFunctionBase.output_data_schema_hash` | | operator `uri` | `core/operators/static_output_pod.py:StaticOutputOperatorPod.uri` | | `schema:` / `instance:` / `node:` path components | `core/nodes/function_node.py:FunctionNodeBase.node_identity_path`, `core/nodes/operator_node.py:OperatorNodeBase.node_identity_path`, `side_effects.py:SideEffectJobNode.attach_databases`, `core/sources/cached_source.py:CachedSource._unversioned_cache_path` | -| Previous completion table path (ITL-1559) | `core/function_pod.py:pipeline_hash_before_context_parameter..resolve`, `core/nodes/function_node.py:FunctionJobNode._previous_completion_path`, `side_effects.py:SideEffectJobNode._previous_completion_path` | +| Previous context-taking function completion table path (ITL-1559) | `core/function_pod.py:pipeline_hash_before_context_parameter..resolve`, `core/nodes/function_node.py:FunctionJobNode._previous_completion_path` | | source-node slot names | `core/nodes/source_node.py:SourceNode.from_stream`, `core/nodes/source_node.py:SourceJobNode.from_stream` | | source system-tag column name (schema digest) | `utils/schema_utils.py:compute_schema_hash` | | system-tag suffixes of `Join`, `MergeJoin`, `Batch`, `GroupBy` | `core/operators/join.py:Join._compute_system_tag_suffixes`, `core/operators/join.py:Join._predict_system_tag_schema`, `core/operators/join.py:Join.static_process`, `core/operators/merge_join.py:MergeJoin._system_tag_suffix`, `core/operators/batch.py:Batch.unary_output_schema`, `core/operators/batch.py:Batch.unary_static_process`, `core/operators/group_by.py:GroupBy.unary_output_schema`, `core/operators/group_by.py:GroupBy.unary_static_process` | diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index b1151c891..c259578c2 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -454,7 +454,7 @@ def find_stale_tables( name_path: tuple[str, ...] | None = None, result_revision: str | None = None, previous_completion_path: tuple[str, ...] | None = None, - previous_result: tuple[tuple[str, ...], tuple[str, bytes] | None] | None = None, + previous_result_path: tuple[str, ...] | None = None, ) -> StaleTables: """Find the stored rows of other generations that belong to one table of a node. @@ -476,8 +476,8 @@ def find_stale_tables( (``tables_of_another_layout``). previous_completion_path: The exact path of this node's completion table before its pipeline identity changed, relative to this database. - previous_result: The exact previous result table path and optional - column/value pair identifying a result in a shared legacy namespace. + previous_result_path: The exact previous result table path in a namespace + reserved for context-taking pods. Returns: The tables of another layout found, then one entry per other data context @@ -514,23 +514,8 @@ def find_stale_tables( found.other_completion_paths.append( database.base_path + previous_completion_path ) - if previous_result is not None: - path, match = previous_result - if match is None: - completed = database.table_exists(path) - else: - column, value = match - rows = database.get_all_records(path) - completed = ( - rows is not None - and column in rows.column_names - and pc.any( - pc.equal(rows[column], pa.scalar(value, type=pa.large_binary())) - ).as_py() - is True - ) - if completed: - found.other_completion_paths.append(database.base_path + path) + if previous_result_path is not None and database.table_exists(previous_result_path): + found.other_completion_paths.append(database.base_path + previous_result_path) if current is not None: current_path, current_context = current for key, rows in sorted(stored_data_contexts(database, current_path).items()): diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 6a581b5e3..8b197ab19 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -45,7 +45,6 @@ check_conformance, normalize_output_numbers, ) -from orcapod.system_constants import constants from orcapod.types import ContentHash, DataValue, Schema, SchemaLike from orcapod.utils import schema_utils from orcapod.utils.canonical_type_names import stabilize_type_names @@ -1548,20 +1547,7 @@ def __init__( super().__init__(data_function, **kwargs) self._result_database = result_database self._record_path_prefix = record_path_prefix - previous_record_path = None - previous_result_match = None if context_parameter is not None: - # Decorator caches used the plain namespace. The stored signature - # lets us recognize results from the same declared interface. - signature = self.get_function_variation_data().get( - "function_signature_hash" - ) - if isinstance(signature, bytes): - previous_record_path = record_path_prefix + self.uri - previous_result_match = ( - f"{constants.PF_VARIATION_PREFIX}function_signature_hash", - signature, - ) record_path_prefix += ("side_effect_function",) self._cache = ResultCache( result_database=result_database, @@ -1573,8 +1559,6 @@ def __init__( 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], - previous_record_path=previous_record_path, - previous_result_match=previous_result_match, ) @property diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index 7d8a20a16..e3401b4c0 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -212,7 +212,6 @@ def __init__( delivers_side_effects: bool = False, name_path: tuple[str, ...] | None = None, previous_record_path: tuple[str, ...] | None = None, - previous_result_match: tuple[str, bytes] | None = None, ) -> None: """Create a result cache over one result table. @@ -234,8 +233,6 @@ def __init__( ``None`` looks at the paths computed from ``record_path`` only. previous_record_path: Result path through the type component before context-taking results moved to their own path (ITL-1559). - previous_result_match: The stored column and value that identify the - function's results if the previous path is shared with plain calls. """ self._result_database = result_database self._record_path = record_path @@ -243,11 +240,8 @@ def __init__( self._auto_flush = auto_flush self._delivers_side_effects = delivers_side_effects self._name_path = name_path - self._previous_result = ( - ( - previous_record_path + (revision, RESULT_DB_SCHEMA_VERSION), - previous_result_match, - ) + self._previous_result_path = ( + previous_record_path + (revision, RESULT_DB_SCHEMA_VERSION) if previous_record_path is not None and previous_record_path != record_path else None ) @@ -305,7 +299,7 @@ def stale_tables( else None, name_path=self._name_path, result_revision=self._revision, - previous_result=self._previous_result, + previous_result_path=self._previous_result_path, ) def stale_tables_accounted_for(self) -> None: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index e73d01066..011cbb588 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -652,7 +652,6 @@ def _distribute_databases(self) -> None: ) nodes = (self._persistent_node_map or {}).values() - side_effect_nodes: list[SideEffectJobNode] = [] for node in nodes: if isinstance(node, FunctionJobNode): if self._unresolved_result_database is not None: @@ -671,15 +670,6 @@ def _distribute_databases(self) -> None: node.attach_databases( pipeline_database=pipeline_db, ) - side_effect_nodes.append(node) - - current_completion_paths = frozenset( - path - for node in side_effect_nodes - if (path := node.completion_log_path) is not None - ) - for node in side_effect_nodes: - node.set_current_completion_paths(current_completion_paths) # ------------------------------------------------------------------ # _iter_function_job_nodes() / apply_node_config() diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 95e46aad8..c24d54597 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -1084,7 +1084,6 @@ def __init__( ) self._pipeline_database: ArrowDatabaseProtocol | None = None self._table_path: tuple[str, ...] | None = None - self._current_completion_paths: frozenset[tuple[str, ...]] = frozenset() self._unlisted_store_reported = False self._current_log_checked = False # The rows the last completed run passed on, in the order it passed them; @@ -1113,40 +1112,15 @@ def clear_cache(self) -> None: self._run_load_only = False self._set_modified_time(None) - @property - def completion_log_path(self) -> tuple[str, ...] | None: - """The attached invocation log path, including logs that only audit delivery.""" - return self._table_path - - def set_current_completion_paths(self, paths: frozenset[tuple[str, ...]]) -> None: - """Record the paths owned by live taps sharing this job's database view.""" - self._current_completion_paths = paths - - def _previous_completion_path(self) -> tuple[str, ...] | None: - from orcapod.core.function_pod import pipeline_hash_before_context_parameter - - if not self._pod.pod_config.track_completion: - return None - previous = pipeline_hash_before_context_parameter(self) - if previous == self.pipeline_hash(): - return None - path = self.node_uri + ( - f"schema:{previous.to_hex()}", - TRACKING_DB_SCHEMA_VERSION, - ) - # Before ctx_arg entered the pipeline hash, this tap could share a - # pipeline identity with a live tap on the equivalent plain branch. - return None if path in self._current_completion_paths else path - def _refuse_log_of_another_data_context(self) -> None: """Refuse invocation logs holding deliveries this run cannot match. A delivery already made is found by a record id hashed under this node's data context, so deliveries logged under another one would not be found and every side effect would be delivered again (ITL-944). The search looks under - the pod's name for older layouts and, when tracking completions, the log at - this node's previous pipeline identity (ITL-954, ITL-1559). Checked at the - start of every run, so a log that appears between runs is found too. + the pod's name for older layouts (ITL-954). Logs at other pipeline paths + in the current layout belong to other taps (ITL-1559). Checked at the start + of every run, so a log of an older layout that appears between runs is found too. The current log is read and counted by data context the first time only; the later runs list the database, which reads no table. @@ -1162,7 +1136,6 @@ def _refuse_log_of_another_data_context(self) -> None: current=None if self._current_log_checked else (self._table_path, current), # ("side_effects", ): the part of the path that holds no hash. name_path=self.node_uri, - previous_completion_path=self._previous_completion_path(), ) if found.unlisted: # The check runs before every run; that the database cannot list its tables @@ -1220,7 +1193,6 @@ def attach_databases( # before anything is delivered or changes (ITL-1162). self.require_storable_tables(pipeline_database) self._pipeline_database = pipeline_database - self._current_completion_paths = frozenset() self._unlisted_store_reported = False self._current_log_checked = False if pipeline_database is not None: 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 ed25a30ad..e7855e763 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 @@ -662,13 +662,13 @@ def my_fn(value: int, ctx: InvocationContext) -> str: @pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) @pytest.mark.parametrize("legacy_case", ["function_log", "tap_log", "tap_and_results"]) -def test_reopening_pre_context_identity_completions_refuses_delivery( +def test_reopening_pre_context_identity_completions( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, async_path: bool, legacy_case: str, ) -> None: - """Completions at the previous schema path refuse a run before redelivery.""" + """Only the unambiguous old completion paths block redelivery.""" from orcapod import FunctionPod, PipelineJob, function_pod from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.errors import SideEffectLogDataContextError @@ -757,25 +757,32 @@ def run(job: PipelineJob) -> None: before = store.get_all_records(expected_path) assert before is not None and before.num_rows == 1 - with pytest.raises(SideEffectLogDataContextError) as info: - run(build_job(root)) - assert info.value.node_label == expected_label - assert expected_path in info.value.record_paths - assert delivered == expected_deliveries + if legacy_case == "tap_log": + job = build_job(root) + run(job) + run(job) + assert delivered == [*expected_deliveries, ("tap", 100)] + assert job.nodes["tap"].as_table()["result"].to_pylist() == [100] + else: + with pytest.raises(SideEffectLogDataContextError) as info: + run(build_job(root)) + assert info.value.node_label == expected_label + assert expected_path in info.value.record_paths + 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_refuse_delivery( +def test_pre_context_cache_only_results( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, async_path: bool, run_in_job: bool, cache_kind: str, ) -> None: - """Standalone results from the old exact cache path protect a finished action.""" + """Only the old result cache in the contextual namespace blocks redelivery.""" from orcapod import PipelineJob, function_pod from orcapod.databases import DeltaTableDatabase from orcapod.errors import SideEffectLogDataContextError @@ -828,40 +835,54 @@ def action(value: int, ctx: InvocationContext) -> int: before = store.get_all_records(previous_path) assert before is not None and before.num_rows == 1 - pod = build_pod() - with pytest.raises(SideEffectLogDataContextError) as info: + def run() -> None: + pod = build_pod() if run_in_job: with PipelineJob( name="upgrade", database=DeltaTableDatabase(tmp_path / "job") ) as job: pod.process(source, label="action") - asyncio.run(job.run_async()) if async_path else job.run() + 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: - async for _ in stream.async_iter_data(): - pass + assert [ + data.as_dict()["result"] + async for _, data in stream.async_iter_data() + ] == [110] asyncio.run(consume()) else: - list(stream.iter_data()) - assert info.value.record_paths == (previous_path,) - assert deliveries == [10] + assert [data.as_dict()["result"] for _, data in stream.iter_data()] == [ + 110 + ] + + if cache_kind == "decorator": + run() + run() + assert deliveries == [10, 10] + else: + with pytest.raises(SideEffectLogDataContextError) as info: + run() + assert info.value.record_paths == (previous_path,) + assert deliveries == [10] reopened = DeltaTableDatabase(cache_root) - assert reopened.list_table_paths() == [previous_path] + assert len(reopened.list_table_paths()) == (2 if cache_kind == "decorator" else 1) assert reopened.get_all_records(previous_path) == before @pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) @pytest.mark.parametrize( - "plain_written_first", [False, True], ids=["both", "plain_first"] + "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, plain_written_first: bool + tmp_path: Path, async_path: bool, scenario: str ) -> None: - """A live plain sibling owns the log at the contextual tap's former path.""" + """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 @@ -882,17 +903,20 @@ def contextual(value: int, ctx: InvocationContext) -> int: def tap(result: int, ctx: InvocationContext) -> None: deliveries.append(("tap", result)) - def build_job(*, both: bool) -> PipelineJob: + def build_job( + *, keep_plain: bool = True, keep_contextual: bool = True, value: int = 10 + ) -> PipelineJob: source = DictSource( - [{"id": 1, "value": 10}], + [{"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) - observe.process(plain.pod(source, label="plain"), label="plain_tap") - if both: + 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" ) @@ -901,19 +925,36 @@ def build_job(*, both: bool) -> PipelineJob: def run(job: PipelineJob) -> None: assert (asyncio.run(job.run_async()) if async_path else job.run()).ok - if plain_written_first: - run(build_job(both=False)) + if scenario == "plain_first": + run(build_job(keep_contextual=False)) assert deliveries == [("tap", 110)] - job = build_job(both=True) + job = build_job() run(job) run(job) - reopened = build_job(both=True) + 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"] From c20a7184582dd4d4b3b4a227d7f5e9fc9229d140 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 06:32:24 -0800 Subject: [PATCH 7/7] fix(function_pod): address context identity review findings --- .zed/rules | 14 +- CLAUDE.md | 16 +- changelog.d/ITL-1559.md | 18 +-- docs/dev/design_issues/ITL-1559-CXP1.md | 10 +- docs/reference/data-function-types.md | 6 +- docs/reference/hashing.md | 3 +- src/orcapod/contexts/stored.py | 83 +++++------ src/orcapod/core/cached_function_pod.py | 1 - src/orcapod/core/function_pod.py | 45 +----- src/orcapod/core/nodes/function_node.py | 33 +---- src/orcapod/core/result_cache.py | 18 +-- src/orcapod/errors.py | 28 ++-- src/orcapod/side_effects.py | 15 +- .../function_pod/test_function_pod_ctx_arg.py | 138 ++++++++++++++---- tests/test_databases/test_list_table_paths.py | 6 +- 15 files changed, 208 insertions(+), 226 deletions(-) diff --git a/.zed/rules b/.zed/rules index d7dd4d1ec..a9e521532 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1004,8 +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 and add a ctx: - component immediately before the data function type (ITL-1559). +- 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 @@ -1021,8 +1023,7 @@ generation of hashing; rows of the current data context are the current entries. every read or lookup keeps rows of the current data context only (keep_rows_of_data_context, or a lookup constraint on the column). - A table at an older layout is never read as current and never modified. What a node does - about such tables, rows of another data context, and completion tables at a node's - previous pipeline identity is decided in one place, + about such tables, and about rows of another data context, is decided in one place, contexts/stored.account_for_stale_tables: count and report, or, for a node that delivers side effects (a SideEffectPod node, or a function node whose pod takes the invocation context, ctx_arg), raise SideEffectLogDataContextError before any delivery. A new kind of @@ -1033,11 +1034,6 @@ generation of hashing; rows of the current data context are the current entries. , side_effect_function/, side_effects/, relative to the node's database; /source for a cached source) and every table there whose last component is not in contexts/stored.CURRENT_LAYOUTS is of another layout (tables_of_another_layout). - For a context-taking function node, the same listing checks the exact current-layout path - in its reserved namespace computed from the node's pipeline identity before the context - parameter entered the hash (previous_completion_path, ITL-1559). Tap logs and decorator - cache tables at shared paths belong to the current plain branch, even when that branch - is absent. A new layout constant must be added to CURRENT_LAYOUTS. A store that cannot list raises TableListingNotSupportedError: side-effecting nodes then warn and proceed (developer, November 11, 2026). Every database class implements list_table_paths. Stores of the diff --git a/CLAUDE.md b/CLAUDE.md index e901d6a39..507a8b29f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1035,8 +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` and add a - `ctx:` component immediately before the data function type (ITL-1559). +- 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 @@ -1052,8 +1054,7 @@ current data context are the current entries. and every read or lookup keeps rows of the current data context only (`keep_rows_of_data_context`, or a lookup constraint on the column). - A table at an older layout is never read as current and never modified. What a node does - about such tables, rows of another data context, and completion tables at a node's - previous pipeline identity is decided in one place, + about such tables, and about rows of another data context, is decided in one place, `contexts/stored.account_for_stale_tables`: count and report, or, for a node that delivers side effects (a `SideEffectPod` node, or a function node whose pod takes the invocation context, `ctx_arg`), raise `SideEffectLogDataContextError` before any delivery. A new kind @@ -1064,12 +1065,7 @@ current data context are the current entries. ``, `side_effect_function/`, `side_effects/`, relative to the node's database; `/source` for a cached source) and every table there whose last component is not in `contexts/stored.CURRENT_LAYOUTS` is of another layout - (`tables_of_another_layout`). For a context-taking function node, the same listing - checks the exact current-layout path in its reserved namespace computed from the node's - pipeline identity before the context parameter entered the hash - (`previous_completion_path`, ITL-1559). Tap logs and decorator cache tables at shared - paths belong to the current plain branch, even when that branch is absent. - A new layout constant must be added to `CURRENT_LAYOUTS`. A + (`tables_of_another_layout`). A new layout constant must be added to `CURRENT_LAYOUTS`. A store that cannot list raises `TableListingNotSupportedError`: side-effecting nodes then warn and proceed (developer, November 11, 2026). Every database class implements `list_table_paths`. Stores of the versions before 0.4 are not looked for otherwise (no diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index 67cfcfa56..20903c136 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -8,17 +8,13 @@ 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 have a new `ctx:` - path component. Decorator caches also move context-taking results into the - `side_effect_function` namespace. Live jobs use the new paths for - completions and results. Older downstream tap logs and decorator results - can share paths with current plain calls, so upgrading can repeat actions - previously recorded there. Delete or rebuild stores written by an earlier - development version before running affected jobs, and account for repeat - deliveries for previously processed inputs. A context-taking function still - refuses delivery if it finds its exact previous pipeline, pod cache, or job - cache table in the namespace reserved for context-taking functions. Saved - jobs continue reading their original result tables. + 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 diff --git a/docs/dev/design_issues/ITL-1559-CXP1.md b/docs/dev/design_issues/ITL-1559-CXP1.md index 066f677e4..eeeb47352 100644 --- a/docs/dev/design_issues/ITL-1559-CXP1.md +++ b/docs/dev/design_issues/ITL-1559-CXP1.md @@ -11,9 +11,7 @@ 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. The stale-table check looks for exact previous pipeline and result -paths reserved for context-taking functions. Downstream tap logs and decorator -results at shared paths belong to the current plain branch, even when that -branch is absent from the job. A saved job restores its context-taking function -nodes and reads their results from the original paths. +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 449081c96..6baa5b047 100644 --- a/docs/reference/data-function-types.md +++ b/docs/reference/data-function-types.md @@ -20,12 +20,14 @@ path starts at ``, in that database, with no `/_result`. 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 +/_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. Saved jobs record the result path through the type +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 diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 12e458abb..dbd7db9e5 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -376,7 +376,6 @@ test session with `-p tests.test_hashing.hash_site_trace`. | function `uri` (output-schema digest) | `core/data_function.py:DataFunctionBase.output_data_schema_hash` | | operator `uri` | `core/operators/static_output_pod.py:StaticOutputOperatorPod.uri` | | `schema:` / `instance:` / `node:` path components | `core/nodes/function_node.py:FunctionNodeBase.node_identity_path`, `core/nodes/operator_node.py:OperatorNodeBase.node_identity_path`, `side_effects.py:SideEffectJobNode.attach_databases`, `core/sources/cached_source.py:CachedSource._unversioned_cache_path` | -| Previous context-taking function completion table path (ITL-1559) | `core/function_pod.py:pipeline_hash_before_context_parameter..resolve`, `core/nodes/function_node.py:FunctionJobNode._previous_completion_path` | | source-node slot names | `core/nodes/source_node.py:SourceNode.from_stream`, `core/nodes/source_node.py:SourceJobNode.from_stream` | | source system-tag column name (schema digest) | `utils/schema_utils.py:compute_schema_hash` | | system-tag suffixes of `Join`, `MergeJoin`, `Batch`, `GroupBy` | `core/operators/join.py:Join._compute_system_tag_suffixes`, `core/operators/join.py:Join._predict_system_tag_schema`, `core/operators/join.py:Join.static_process`, `core/operators/merge_join.py:MergeJoin._system_tag_suffix`, `core/operators/batch.py:Batch.unary_output_schema`, `core/operators/batch.py:Batch.unary_static_process`, `core/operators/group_by.py:GroupBy.unary_output_schema`, `core/operators/group_by.py:GroupBy.unary_static_process` | @@ -728,7 +727,7 @@ 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` | Same as `identity_structure()` | 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 | +| `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 | diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index c259578c2..3369233a3 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -17,8 +17,8 @@ not looked for at a computed path. The beginning of the path, up to the name of the function or pod, holds no hash: the tables under it are listed (``list_table_paths``), and a table whose last path component is not one of the current layouts is of another layout -(ITL-954). This listing also finds current-layout completion tables that the -current job does not address, which can happen when a pipeline hash changes (ITL-1559). +(ITL-954). Tables of the versions before 0.4 are not looked for otherwise: nobody has such +a store, and their layouts had the names the first release uses (ITL-1259). Example: To list the data contexts a stored table holds, call @@ -373,13 +373,10 @@ class StaleTables: tables: The tables found, each once. unlisted: The places that could not be searched because the database cannot list its tables. - other_completion_paths: Current-layout tables recording completions at - the caller's previous pipeline or result cache path. """ tables: list[StaleTable] = field(default_factory=list) unlisted: list[UnlistedTables] = field(default_factory=list) - other_completion_paths: list[tuple[str, ...]] = field(default_factory=list) def include(self, other: "StaleTables") -> None: """Add what another search found, leaving out tables already known. @@ -394,34 +391,38 @@ def include(self, other: "StaleTables") -> None: if (table.record_path, table.old_layout) not in known ) self.unlisted.extend(other.unlisted) - for path in other.other_completion_paths: - if path not in self.other_completion_paths: - self.other_completion_paths.append(path) def tables_of_another_layout( - paths: list[tuple[str, ...]], + database: object, + name_path: tuple[str, ...], result_revision: str | None = None, ) -> list[tuple[str, ...]]: - """Select the listed tables with another layout than this build's. + """List the tables under ``name_path`` that are at another layout than this build's. Another layout and the current ones are told apart by path components, never by a hash: every table this version writes ends in one of ``CURRENT_LAYOUTS``, and a function result table has its data function type's revision just before its layout - (``.../rev1/rdb_v1``, ITL-1259). + (``.../rev1/rdb_v1``, ITL-1259). ``name_path`` is expected to end with the name of one + function or pod, so that every table under it belongs to a node of that name. Args: - paths: The database's table paths under the function or pod name. + database: The database to list. + name_path: Leading path components, relative to the database's ``base_path``. result_revision: The revision component of the result tables the caller reads - (``rev1``). A listed result table with another revision is of another - layout too. ``None`` checks the last component only. + (``rev1``). A result table under ``name_path`` with another revision is then + of another layout too. ``None`` checks the last component only. Returns: - The paths of tables that are not at a current layout, in listing order. + The paths, relative to the database's ``base_path``, of the tables under + ``name_path`` that are not at a current layout, sorted. + + Raises: + TableListingNotSupportedError: If the database cannot list its tables. """ return [ path - for path in paths + for path in _list_table_paths(database, name_path) if path[-1] not in CURRENT_LAYOUTS or ( result_revision is not None @@ -453,16 +454,14 @@ def find_stale_tables( current: tuple[tuple[str, ...], str] | None = None, name_path: tuple[str, ...] | None = None, result_revision: str | None = None, - previous_completion_path: tuple[str, ...] | None = None, - previous_result_path: tuple[str, ...] | None = None, ) -> StaleTables: """Find the stored rows of other generations that belong to one table of a node. + Two searches, neither of which writes anything: + - under ``name_path``, by listing the database, for tables of another layout - wherever their hashes put them (ITL-954), and for the completion table of - this node's previous pipeline identity (ITL-1559); - - in the current table, for rows of another data context; - - at the exact previous result path, for evidence of completed calls (ITL-1559). + wherever their hashes put them (ITL-954; not read, so not counted); + - in the current table, for rows of another data context. Args: database: The database the paths belong to. @@ -474,25 +473,20 @@ def find_stale_tables( result_revision: For a result cache, the revision of its data function type's record: a result table under ``name_path`` at another revision is listed too (``tables_of_another_layout``). - previous_completion_path: The exact path of this node's completion table - before its pipeline identity changed, relative to this database. - previous_result_path: The exact previous result table path in a namespace - reserved for context-taking pods. Returns: The tables of another layout found, then one entry per other data context - found in the current table (in key order), the alternate completion paths, - and ``name_path`` under ``unlisted`` if the database could not list its tables. + found in the current table (in key order); and ``name_path`` under + ``unlisted`` if the database could not list its tables. """ found = StaleTables() if name_path is not None: under = database.base_path + name_path try: - paths = _list_table_paths(database, name_path) + listed = tables_of_another_layout(database, name_path, result_revision) except TableListingNotSupportedError as exc: found.unlisted.append(UnlistedTables(under, str(exc))) else: - other_layouts = tables_of_another_layout(paths, result_revision) found.include( StaleTables( [ @@ -503,19 +497,10 @@ def find_stale_tables( True, under, ) - for path in other_layouts + for path in listed ] ) ) - if ( - previous_completion_path is not None - and previous_completion_path in paths - ): - found.other_completion_paths.append( - database.base_path + previous_completion_path - ) - if previous_result_path is not None and database.table_exists(previous_result_path): - found.other_completion_paths.append(database.base_path + previous_result_path) if current is not None: current_path, current_context = current for key, rows in sorted(stored_data_contexts(database, current_path).items()): @@ -537,11 +522,12 @@ def account_for_stale_tables( nodes) reports each table with its number of rows and moves on. - A node whose run is an external action (a side-effect pod, or a function pod that takes the invocation context) must not act again for inputs it already - handled when those completions cannot be matched at the current path or under - the current data context. It fails before doing anything. Every old-layout table - and a completion table at the node's previous pipeline or result path count. - The error names the tables. Where the database cannot list its tables, the - node warns and proceeds (developer, November 11, 2026). + handled, and those completions cannot be matched under the current data + context. It fails before doing anything. Every old-layout table under the + node's name counts, so a table of another function or pod with the same name + in the job, or of another node of the same function, fails it too: the error + names the tables. Where the database cannot list its tables, the node warns and + proceeds (developer, November 11, 2026). Args: found: What ``find_stale_tables`` found for the node's tables. @@ -553,11 +539,10 @@ def account_for_stale_tables( found. The caller adds the node label. """ if delivers_side_effects: - if found.tables or found.other_completion_paths: + if found.tables: raise SideEffectLogDataContextError( - tuple(table.record_path for table in found.tables) - + tuple(found.other_completion_paths), - found.tables[0].data_context if found.tables else None, + tuple(table.record_path for table in found.tables), + found.tables[0].data_context, current_context, ) if found.unlisted: diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index 2a85bcd81..edee43f22 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -79,7 +79,6 @@ def __init__( # The uri holds no hash up to the function's name, which comes after # "side_effect_function" for a pod that takes the invocation context. name_path=self.uri[: 2 if function_pod.ctx_arg_name is not None else 1], - previous_record_path=self.uri if self.ctx_arg_name is not None else None, ) def require_storable_results(self) -> None: diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index cfb40cdd0..df9055d4e 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -51,13 +51,11 @@ TrackerManagerProtocol, ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol -from orcapod.protocols.hashing_protocols import PipelineElementProtocol from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol from orcapod.semantic_types import infer_python_schema_from_pylist_data from orcapod.system_constants import constants from orcapod.types import ( ColumnConfig, - ContentHash, PipelineConfig, PodConfig, Schema, @@ -90,44 +88,6 @@ def _executor_supports_concurrent( return executor is not None and executor.supports_concurrent_execution -def pipeline_hash_before_context_parameter(stream: StreamBase) -> ContentHash: - """Recompute a stream's pipeline hash using the pre-ITL-1559 pod identity. - - Only the pipeline identity of a context-taking function changed. Reuse the - current identities of the sources and other leaves, and resolve the former - pod identity through the existing identity structures of its descendants. - """ - hasher = stream.data_context.semantic_hasher - hashes: dict[int, ContentHash] = {} - - def resolve(obj: Any) -> ContentHash: - if not isinstance(obj, PipelineElementProtocol): - return obj.content_hash(hasher) - key = id(obj) - if key not in hashes: - if isinstance(obj, _FunctionPodBase) and obj.ctx_arg_name is not None: - structure = ( - obj.data_function - if type(obj).pipeline_identity_structure - is _FunctionPodBase.pipeline_identity_structure - else obj.pipeline_identity_structure() - ) - hashes[key] = hasher.hash_object(structure, resolver=resolve) - elif ( - isinstance(obj, StreamBase) - and obj.producer is not None - and obj.upstreams - ): - hashes[key] = hasher.hash_object( - obj.pipeline_identity_structure(), resolver=resolve - ) - else: - hashes[key] = obj.pipeline_hash(hasher) - return hashes[key] - - return resolve(stream) - - class _FunctionPodBase(TraceableBase): """Base pod that applies a data function to each input data.""" @@ -223,7 +183,7 @@ def identity_structure(self) -> Any: 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.identity_structure() + return (self.data_function, self._ctx_arg_name) return self.data_function def _build_invocation_context( @@ -1879,6 +1839,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 @@ -1895,6 +1857,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") diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 5898b9d98..2e6a2cd63 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -38,7 +38,6 @@ fall_through_tags, function_input, function_input_schema, - pipeline_hash_before_context_parameter, result_data_schema, result_pod, with_fall_through, @@ -84,6 +83,7 @@ UnstorableColumnError, ) from orcapod.contexts.stored import ( + StaleTables, keep_rows_of_data_context, require_same_data_context, account_for_stale_tables, @@ -1523,26 +1523,6 @@ def _delivers_side_effects(self) -> bool: and self._function_pod.ctx_arg_name is not None ) - @property - def completion_log_path(self) -> tuple[str, ...] | None: - """The pipeline table storing this live context-taking node's completions.""" - return self._versioned_pipeline_path if self._delivers_side_effects else None - - def _previous_completion_path(self) -> tuple[str, ...] | None: - path = self.completion_log_path - if path is None: - return None - previous = pipeline_hash_before_context_parameter(self) - if previous == self.pipeline_hash(): - return None - # The layout is last, with an instance component only at content scope. - schema_index = -2 if self._table_scope == "pipeline_hash" else -3 - return ( - *path[:schema_index], - f"schema:{previous.to_hex()}", - *path[schema_index + 1 :], - ) - def _begin_run(self) -> None: """Reset schema preflight and refresh the stored tables for this run. @@ -1613,10 +1593,10 @@ def _account_for_stale_tables(self) -> None: unchanged, and their number is reported (ITL-944). Such tables are looked for at this node's own path and, because the hashes in a path can differ between versions, anywhere under the function's name in the database (ITL-954). A node - that delivers side effects fails instead. A completion table at the node's - previous pipeline identity, stale result tables, and rows of another data - context in the current tables also count because their completions cannot - be matched. + that delivers side effects fails instead, and for it the result tables and + rows of another data context in the current tables count too: none of them + can be matched with current inputs, so every side effect would be delivered + again. Raises: SideEffectLogDataContextError: If this node delivers side effects and @@ -1632,7 +1612,6 @@ def _account_for_stale_tables(self) -> None: if delivers and not self._current_tables_checked else None, name_path=self.node_name_path or None, - previous_completion_path=self._previous_completion_path(), ) if delivers: for cached_pod in (self._cached_function_pod, self._ephemeral_cached_pod): @@ -1646,7 +1625,7 @@ def _account_for_stale_tables(self) -> None: # That the database cannot list its tables is reported once per node # object and attached database, not at every run. if self._unlisted_store_reported: - found.unlisted.clear() + found = StaleTables(tables=found.tables) self._unlisted_store_reported = True try: account_for_stale_tables( diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index e3401b4c0..8dbae4be1 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -176,10 +176,15 @@ def _with_declared_token_columns( def context_result_path( uri: tuple[str, ...], context_parameter: str | None ) -> tuple[str, ...]: - """Scope context-taking result tables by the configured parameter name.""" + """Scope context-taking results without adding to the store's required depth.""" if context_parameter is None: return uri - return (*uri[:-1], f"ctx:{context_parameter}", uri[-1]) + *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: @@ -211,7 +216,6 @@ def __init__( auto_flush: bool = True, delivers_side_effects: bool = False, name_path: tuple[str, ...] | None = None, - previous_record_path: tuple[str, ...] | None = None, ) -> None: """Create a result cache over one result table. @@ -231,8 +235,6 @@ def __init__( the part that holds no hash. Result tables written before v0.3 are looked for under it, whatever hashes their paths hold (ITL-954). ``None`` looks at the paths computed from ``record_path`` only. - previous_record_path: Result path through the type component before - context-taking results moved to their own path (ITL-1559). """ self._result_database = result_database self._record_path = record_path @@ -240,11 +242,6 @@ def __init__( self._auto_flush = auto_flush self._delivers_side_effects = delivers_side_effects self._name_path = name_path - self._previous_result_path = ( - previous_record_path + (revision, RESULT_DB_SCHEMA_VERSION) - if previous_record_path is not None and previous_record_path != record_path - else None - ) # Set once a read has reported the stored rows it skipped. self._skipped_rows_reported = False # Set once stored results of other generations have been accounted for. @@ -299,7 +296,6 @@ def stale_tables( else None, name_path=self._name_path, result_revision=self._revision, - previous_result_path=self._previous_result_path, ) def stale_tables_accounted_for(self) -> None: diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index cb421e7ab..eda66139c 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -1282,7 +1282,7 @@ def __str__(self) -> str: class SideEffectLogDataContextError(OrcapodDatabaseError): - """Raised when a side-effecting node finds incompatible stored completions. + """Raised when a side-effecting node finds completions logged under another data context. A node whose run is an external action finds what it already did by keys hashed under its data context: a side-effect pod in its invocation log, a function pod @@ -1296,10 +1296,11 @@ class SideEffectLogDataContextError(OrcapodDatabaseError): operator and source tables do not fail this way: there, such rows are reported, skipped and computed again. - The search lists tables under the node's function or pod name (ITL-954). - A table at an older layout or evidence of completion at the node's previous - pipeline or result cache path (ITL-1559) counts. ``record_paths`` - names every table found. + Tables written by Orcapod up to v0.2 are found by name: every table at an older + layout stored under the node's function or pod name in the job counts, + whatever hashes its path holds (ITL-954). A table of another function or pod + with the same name in the same job, or of another node of the same function, + therefore raises this error too; ``record_paths`` names every table found. A fresh database is not a safe way around this error: it holds no completions, so on it the node performs every side effect again. Run the node on a fresh database only @@ -1311,8 +1312,7 @@ class SideEffectLogDataContextError(OrcapodDatabaseError): record_paths: Paths, from the root of the database, of the tables holding such completions. record_path: The first of ``record_paths``. - found_context: Data context key of the completions that do not match, or - ``None`` when only alternate current-layout paths were found. + found_context: Data context key of the completions that do not match. current_context: Data context key of the node. node_label: Label of the node. """ @@ -1320,7 +1320,7 @@ class SideEffectLogDataContextError(OrcapodDatabaseError): def __init__( self, record_paths: tuple[tuple[str, ...], ...], - found_context: str | None, + found_context: str, current_context: str, node_label: str | None = None, ) -> None: @@ -1328,7 +1328,7 @@ def __init__( Args: record_paths: Paths of the tables holding completions that do not match. - found_context: Data context key of those completions, if known. + found_context: Data context key of those completions. current_context: Data context key of the node. node_label: Label of the node, if known. """ @@ -1336,7 +1336,7 @@ def __init__( tuple(path) for path in record_paths ) self.record_path: tuple[str, ...] = self.record_paths[0] - self.found_context = found_context + self.found_context: str = found_context self.current_context: str = current_context super().__init__( self.record_paths, found_context, current_context, node_label=node_label @@ -1346,14 +1346,6 @@ def __str__(self) -> str: """Describe the tables, both data contexts and the remedy.""" node = f"Node {self.node_label!r}" if self.node_label else "This node" tables = ", ".join(repr("/".join(path)) for path in self.record_paths) - if self.found_context is None: - return ( - f"{node} performs side effects, and stored completions exist at " - f"a previous pipeline or result cache path ({tables}). They cannot be " - "matched with current inputs, so nothing was delivered or written by " - "this node. Reopen the job with the version and pipeline that wrote " - "these tables to reuse the completions." - ) return ( f"{node} performs side effects, and its stored completions were logged " f"under the data context {self.found_context!r} (in {tables}), but the " diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index c24d54597..dd691c62d 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -45,6 +45,7 @@ UnstorableColumnError, ) from orcapod.contexts.stored import ( + StaleTables, account_for_stale_tables, data_context_field, find_stale_tables, @@ -1113,14 +1114,16 @@ def clear_cache(self) -> None: self._set_modified_time(None) def _refuse_log_of_another_data_context(self) -> None: - """Refuse invocation logs holding deliveries this run cannot match. + """Refuse an invocation log holding deliveries of another data context. A delivery already made is found by a record id hashed under this node's data context, so deliveries logged under another one would not be found and - every side effect would be delivered again (ITL-944). The search looks under - the pod's name for older layouts (ITL-954). Logs at other pipeline paths - in the current layout belong to other taps (ITL-1559). Checked at the start - of every run, so a log of an older layout that appears between runs is found too. + every side effect would be delivered again (ITL-944). Two cases: a log at an + older table layout (written by Orcapod up to v0.2), and rows of another data + context in the current log. An older log is looked for at this node's own + path and, because the hash in the path can differ between versions, anywhere + under the pod's name in the database (ITL-954). Checked at the start of every + run, so a log that appears between two runs of one node object is found too. The current log is read and counted by data context the first time only; the later runs list the database, which reads no table. @@ -1141,7 +1144,7 @@ def _refuse_log_of_another_data_context(self) -> None: # The check runs before every run; that the database cannot list its tables # is reported once per node object and attached database. if self._unlisted_store_reported: - found.unlisted.clear() + found = StaleTables(tables=found.tables) self._unlisted_store_reported = True try: account_for_stale_tables( 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 e7855e763..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 @@ -321,7 +321,12 @@ def renamed(value: int, invocation: InvocationContext) -> int: RESULT_DB_SCHEMA_VERSION, ) expected_paths: set[tuple[str, ...]] = { - (*pod.uri[:-1], f"ctx:{pod.ctx_arg_name}", pod.uri[-1], *result_suffix) + ( + *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": @@ -346,6 +351,75 @@ def identity_structure(self) -> tuple[object, str]: 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( @@ -661,25 +735,30 @@ def my_fn(value: int, ctx: InvocationContext) -> str: @pytest.mark.parametrize("async_path", [False, True], ids=["sync", "async"]) -@pytest.mark.parametrize("legacy_case", ["function_log", "tap_log", "tap_and_results"]) +@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: - """Only the unambiguous old completion paths block redelivery.""" + """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 SideEffectLogDataContextError + 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 != "function_log" + 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)) @@ -706,6 +785,7 @@ def tap(result: int, ctx: InvocationContext) -> None: 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 @@ -741,34 +821,36 @@ def run(job: PipelineJob) -> None: (expected_path,) = ( path for path in table_paths if path[-1] == TRACKING_DB_SCHEMA_VERSION ) - expected_label = "tap" 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(part.startswith("ctx:") for part in expected_path) - expected_label = "contextual" + assert not any(":ctx:" in part for part in expected_path) else: expected_path = function_log - expected_label = "contextual" 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 - if legacy_case == "tap_log": + 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) - assert delivered == [*expected_deliveries, ("tap", 100)] + 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] - else: - with pytest.raises(SideEffectLogDataContextError) as info: - run(build_job(root)) - assert info.value.node_label == expected_label - assert expected_path in info.value.record_paths - assert delivered == expected_deliveries + assert delivered == expected_deliveries assert DeltaTableDatabase(root).get_all_records(expected_path) == before @@ -782,16 +864,16 @@ def test_pre_context_cache_only_results( run_in_job: bool, cache_kind: str, ) -> None: - """Only the old result cache in the contextual namespace blocks redelivery.""" + """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.errors import SideEffectLogDataContextError 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( @@ -830,12 +912,13 @@ def action(value: int, ctx: InvocationContext) -> int: store = DeltaTableDatabase(cache_root) (previous_path,) = store.list_table_paths() - assert not any(part.startswith("ctx:") for part in previous_path) + 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( @@ -861,17 +944,11 @@ async def consume() -> None: 110 ] - if cache_kind == "decorator": - run() - run() - assert deliveries == [10, 10] - else: - with pytest.raises(SideEffectLogDataContextError) as info: - run() - assert info.value.record_paths == (previous_path,) - assert deliveries == [10] + run() + run() + assert deliveries == [10, 10] reopened = DeltaTableDatabase(cache_root) - assert len(reopened.list_table_paths()) == (2 if cache_kind == "decorator" else 1) + assert len(reopened.list_table_paths()) == 2 assert reopened.get_all_records(previous_path) == before @@ -989,6 +1066,7 @@ def tap(result: int, ctx: InvocationContext) -> None: 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: diff --git a/tests/test_databases/test_list_table_paths.py b/tests/test_databases/test_list_table_paths.py index 1171f1416..8e2e5cad0 100644 --- a/tests/test_databases/test_list_table_paths.py +++ b/tests/test_databases/test_list_table_paths.py @@ -366,9 +366,9 @@ def test_stale_lookup_uses_layout_and_revision_after_a_long_name( current = name + ("new_hash", "rev1", "rdb_v1") other = (name[0][:-1] + "-", "old_hash", "rev0", "rdb_v0") _fill(store, [old_layout, old_revision, current, other]) - assert tables_of_another_layout( - store.list_table_paths(name), "rev1" - ) == sorted([old_layout, old_revision]) + assert tables_of_another_layout(store, name, "rev1") == sorted( + [old_layout, old_revision] + ) def test_the_last_component_is_the_layout(self, tmp_path: Path): """The last listed component is the original layout component."""