diff --git a/.zed/rules b/.zed/rules index bcfb8afbf..c3b0ad7a4 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1534,6 +1534,9 @@ data. The rules: commit clears only the nodes that ran; nodes it held keep their earlier run. A load-only run's rows have status loaded_only. Only job nodes' run() takes an argument (load_only). A loaded job (PipelineJob.load) runs only with load_only=True. + As a stopgap (ITL-1560), the loaded job and its cached blueprint refuse capture + and recompilation. Build the job from its pipeline to change the graph. + Source binding is supported. job.run()/run_async() use the same state rule and plan (node_run.plan_run): a current node is held (not run; its rows feed its successors, both orchestrators take held rows), sources are read only for nodes that run, a failed end-of-run commit clears only the nodes that ran, @@ -1598,6 +1601,23 @@ data. The rules: match its previous one (bind does not compare the two), but bind refuses, before replacing any binding, a bind after which two slots would read one source identity under different restrictions (below). A job run over a restricted source feeding GroupBy, Batch or MergeJoin issues one RestrictedAggregationWarning. + Each source content hash belongs to one source object per pipeline or job + (ITL-1469). Capture, compile, binding through either API, loading and running + check the sources the graph reads. A slot binding replaces its former source. + A job accepts new steps only while every slot holds the exact source object + it held when that slot was first compiled. A slot originally compiled unbound + must be unbound. Rebinding or unbinding a slot blocks recording until all + original bindings are restored. InconsistentSourceError names the changed + slots. Restore the original bindings or build a new job. A job can compile + and run with its replacement bindings. ITL-1559 tracks capture after rebinding. + As a stopgap pending ITL-1559, a job refuses another job's or a standalone + SourceJobNode, including through prebuilt streams. Its bound_source can change + even if currently unbound. Pass the source itself, or use node.as_source() + for another job's stored results. The job's own slots are allowed with their + original bindings. A schema-only SourceNode declares a new unbound slot. + Call where() once and reuse the resulting object. A source object conflict + raises InconsistentSourceError before the separate restriction check, which + can see restrictions beneath wrappers. A pipeline keeps one restriction (or none) per source identity (a restriction leaves the identity unchanged), so one table restricted two ways (or with and without a restriction) in one pipeline is refused (restrictions.require_one_restriction, over the sources the streams @@ -1605,9 +1625,11 @@ data. The rules: what they read) at capture, at compile, by bind before it binds and at the start of every run (refuse_restriction_conflicts), whatever streams lead there: projections, operator chains, streams built before the capture. A bind's walk matches the job's own slots by object - (Rebinding), never by name. RunSummary keeps one condition and one limit per slot (ITL-1293). Every restriction walk goes through a slot's bound source, - a SourceProxy's delegate and a CachedSource's source (_streams_beneath); a - DerivedSource is a root. A CachedSource + (Rebinding), never by name. RunSummary keeps one condition and one limit per slot (ITL-1293). + Capture and restriction checks follow job bindings and the live_source_inputs + declared by wrappers. A wrapper over stored results ends this walk. Source + registration uses the wrapper itself and its content hash. + A CachedSource over a restricted source is refused at construction (a cache is kept under the table's identity; developer, November 18, 2026), and so is an operator job node that caches (LOG or REPLAY) over a restricted source (developer, November 19, 2026: its cache is kept under the diff --git a/CLAUDE.md b/CLAUDE.md index dd9e6450e..3ac506603 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1583,6 +1583,9 @@ data. The rules: commit clears only the nodes that ran; nodes it held keep their earlier run. A load-only run's rows have status `loaded_only`. Only job nodes' `run()` takes an argument (`load_only`). A loaded job (`PipelineJob.load`) runs only with `load_only=True`. + As a stopgap (ITL-1560), the loaded job and its cached blueprint refuse capture + and recompilation. Build the job from its pipeline to change the graph. + Source binding is supported. `job.run()`/`run_async()` use the same state rule and plan (`node_run.plan_run`): a current node is held (not run; its rows feed its successors, both orchestrators take held rows), sources are read only for nodes that run, a failed end-of-run commit clears only the nodes that ran, @@ -1647,6 +1650,23 @@ data. The rules: match its previous one (bind does not compare the two), but `bind` refuses, before replacing any binding, a bind after which two slots would read one source identity under different restrictions (below). A job run over a restricted source feeding `GroupBy`, `Batch` or `MergeJoin` issues one `RestrictedAggregationWarning`. + Each source content hash belongs to one source object per pipeline or job + (ITL-1469). Capture, compile, binding through either API, loading and running + check the sources the graph reads. A slot binding replaces its former source. + A job accepts new steps only while every slot holds the exact source object + it held when that slot was first compiled. A slot originally compiled unbound + must be unbound. Rebinding or unbinding a slot blocks recording until all + original bindings are restored. InconsistentSourceError names the changed + slots. Restore the original bindings or build a new job. A job can compile + and run with its replacement bindings. ITL-1559 tracks capture after rebinding. + As a stopgap pending ITL-1559, a job refuses another job's or a standalone + SourceJobNode, including through prebuilt streams. Its bound_source can change + even if currently unbound. Pass the source itself, or use node.as_source() + for another job's stored results. The job's own slots are allowed with their + original bindings. A schema-only SourceNode declares a new unbound slot. + Call where() once and reuse the resulting object. A source object conflict + raises InconsistentSourceError before the separate restriction check, which + can see restrictions beneath wrappers. A pipeline keeps one restriction (or none) per source identity (a restriction leaves the identity unchanged), so one table restricted two ways (or with and without a restriction) in one pipeline is refused (`restrictions.require_one_restriction`, over the sources the streams @@ -1654,9 +1674,11 @@ data. The rules: what they read) at capture, at compile, by `bind` before it binds and at the start of every run (`refuse_restriction_conflicts`), whatever streams lead there: projections, operator chains, streams built before the capture. A bind's walk matches the job's own slots by object - (`Rebinding`), never by name. `RunSummary` keeps one condition and one limit per slot (ITL-1293). Every restriction walk goes through a slot's bound source, - a `SourceProxy`'s delegate and a `CachedSource`'s source (`_streams_beneath`); a - `DerivedSource` is a root. A `CachedSource` + (`Rebinding`), never by name. `RunSummary` keeps one condition and one limit per slot (ITL-1293). + Capture and restriction checks follow job bindings and the live_source_inputs + declared by wrappers. A wrapper over stored results ends this walk. Source + registration uses the wrapper itself and its content hash. + A `CachedSource` over a restricted source is refused at construction (a cache is kept under the table's identity; developer, November 18, 2026), and so is an operator job node that caches (`LOG` or `REPLAY`) over a restricted source (developer, November 19, 2026: its cache is kept under the diff --git a/changelog.d/ITL-1469.md b/changelog.d/ITL-1469.md new file mode 100644 index 000000000..35a07fc42 --- /dev/null +++ b/changelog.d/ITL-1469.md @@ -0,0 +1,21 @@ +### Fixed + +- A pipeline or job accepts one source object per content hash. Capture, binding, + loading and execution reject distinct objects with the same hash, even if + their rows agree. Build a source once and reuse it, or give each source its own + source ID. Rebinding replaces a slot's source, and loading shares one rebuilt + object across slots with identical source configurations. +- Sources with the same source ID must agree on their Arrow schema and key + columns, including when they occupy different slots. +- A capture refused by any active pipeline or job leaves all their graphs + unchanged. + +### Known limitations + +- ITL-1506 tracks distinct readings of one dataset in distinct slots. ITL-1531 + tracks sources that read their rows later. ITL-1553 tracks accepting distinct + objects that represent the same source. +- As a stopgap pending ITL-1559, a job refuses foreign and standalone bindable + slots (`SourceJobNode`), including through streams built from them. Pass the + source itself, or use `node.as_source()` for another job's stored results. + Schema-only `SourceNode` declarations still create independent slots. diff --git a/changelog.d/ITL-1560.md b/changelog.d/ITL-1560.md new file mode 100644 index 000000000..032ebf47a --- /dev/null +++ b/changelog.d/ITL-1560.md @@ -0,0 +1,6 @@ +### Known limitations + +- As a stopgap (ITL-1560), loaded pipeline jobs and their cached blueprints raise + `RuntimeError` on step capture or `compile()` to protect the restored graph. + Build the job from its pipeline to change the graph. Source binding and + load-only runs are supported. diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 9de222bca..20be4f67b 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -1117,6 +1117,10 @@ print(loaded.nodes["bmi"].as_table().num_rows, summary.nodes["bmi"].not_stored) To compute again, build the job from your code as before. +As a stopgap (ITL-1560), a loaded job and its cached `job.pipeline` blueprint raise +`RuntimeError` if you try to capture steps into either or call `compile()`. +Build the job from its pipeline to change the graph. + The database is the source of truth: a loaded job's stored views show what the database holds for it. The job file names each run's rows by the content hash the run stored them under, so a loaded node's stored view reads exactly what the same node built from your code would read diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index cedf58b29..82ac38ac7 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -13,7 +13,7 @@ The content hash captures schema, topology, and the **identity of the sources** pipeline. It is computed recursively: each element's content hash depends on its own identity plus the content hashes of all its upstream elements, all the way back to the sources. -A source's identity is its class, its schema, its `source_id` and its key columns (the +A source's identity is its schema, its `source_id` and its key columns (the `record_id_columns` that name its rows, or none when rows are named by position). What the `source_id` is depends on how the source was created: @@ -23,13 +23,15 @@ A source's identity is its class, its schema, its `source_id` and its key column - File- and table-backed sources default to a name derived from their location (the file path for `CSVSource`, the table folder's path or URI for `DeltaTableSource`), not from the rows. -- If you pass `source_id` yourself, you are naming the source: two sources with the same - class, schema, `source_id` and key columns have the same content hash even when their rows - differ. +- If you pass `source_id` yourself, you are naming the source. The kind is part of the + canonical ID. Two sources with the same ID, schema and key columns have the same + content hash even when their rows differ. A pipeline or job registers one source + object per content hash at capture, binding, loading and execution. + See [source consistency](sources.md#source-ids-name-the-kind-that-reads-the-data). Two sources that differ only in their key columns name the same rows differently, so they -are two sources: different content hashes (each gets its own cache), the same pipeline hash -and the same `source_id`. +have different content hashes and the same pipeline hash and `source_id`. A pipeline or +job currently refuses to use both readings under that shared ID (ITL-1506). Rows are still identified individually. Each row carries its own content hash, and that per-row hash is what caching uses. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 68672e28c..c40568153 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -111,6 +111,14 @@ Three more things a job node offers: the node has run in this process, to use as the input of another pipeline. - **`upstreams`** and **`label`** let you walk the pipeline backwards. +As a stopgap pending ITL-1559, a job cannot absorb steps from another job by +capturing compiled nodes or other streams that depend on the other job's +bindable source slots (`SourceJobNode`). The same restriction applies to +standalone `SourceJobNode` objects, even when unbound. Pass the source itself to +record a new chain, or use `node.as_source()` to read the stored results of an +earlier job. A job can use its own slots while their original bindings are in +place. A schema-only `SourceNode` declares an independent slot for each job. + ## The database Any Orcapod database can hold a job's results. Two are used most: @@ -537,6 +545,11 @@ print(loaded.nodes["bmi"].as_table().num_rows, summary.nodes["bmi"].not_stored) # 3 0 ``` +As a stopgap (ITL-1560), a loaded job and its cached `job.pipeline` blueprint raise +`RuntimeError` if you try to capture steps into either or call `compile()`. +Build the job from its pipeline to change the graph. +Binding sources and running with `load_only=True` remain supported. + The full rules (which sources are rebuilt from the file, operators, side effects, a database that holds other rows than the file expects) are in [Saving and loading a job](function-pods.md#saving-and-loading-a-job). diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 589c57427..31e879edb 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -78,6 +78,72 @@ same rows read by another kind, or by another version of one kind, are another s record id names a row within its source and never holds the source id. A job names an input slot by the source's name (`job.bind(sources={"units": ...})`). +Each source content hash is registered to one Python object per pipeline or job. +Build the source once and reuse that object wherever you read it. For sources +whose hash includes their `source_id`, each source can instead have its own ID. +Two distinct objects with the same content hash raise +`InconsistentSourceError` even when their rows agree, including sources that read +rows later. Capture, binding, loading and execution all check for conflicts. +Rebinding replaces a slot's source. On load, slots with identical saved source +configurations share one reconstructed object. + +A job accepts new steps only while every slot holds the exact source object +it held when that slot was first compiled. A slot originally compiled unbound +must be unbound. Rebinding or unbinding a slot blocks recording until all +original bindings are restored. InconsistentSourceError names the changed +slots. Restore the original bindings or build a new job. A job can compile +and run with its replacement bindings. ITL-1559 tracks capture after rebinding. + +As a stopgap pending ITL-1559, a job refuses bindable source slots +(`SourceJobNode`) from another job or created standalone, including through a +stream built from one. Pass the source itself, or use `node.as_source()` to read +another job's stored results. A schema-only `SourceNode` declares a new unbound +slot for each job that captures it. + +The capture and restriction checks follow wrappers that can read live inputs. +This includes tag-copy `DerivedSource` over a live source. A `DerivedSource` +over a job node reads stored results, so the checks stop there. Source object +registration uses the wrapper itself and its content hash. + +Capturing into a loaded job or recompiling it can lose its restored graph +(ITL-1560). Recompilation preserves the loaded job's public `sources` mapping. + +The same rule applies to wrappers. Each of these pairs raises +`InconsistentSourceError` when the objects share one content hash. + +| Sources used together | How to share the source | +| --- | --- | +| A source and a `CachedSource` over it | Build the cache once and use it in both places. | +| Two caches over one source, or a cache and its inner cache | Choose one cache object and reuse it. | +| Two calls to `node.as_source()` on one node | Call `as_source()` once and reuse the result. | +| Two `DerivedSource(tags_as_data=...)` objects with the same hash | Build one derived source and reuse it. | +| A source or its cache paired with a `SourceProxy` restored for it | Choose one source object and reuse it. | + +ITL-1553 tracks accepting distinct objects that represent the same source. +ITL-1531 tracks sources that read their rows later. + +```python +from orcapod import Pipeline, function_pod +from orcapod.errors import InconsistentSourceError +from orcapod.sources import DictSource + + +@function_pod(output_keys="adjusted") +def adjust(rate: float) -> float: + return rate + 1 + + +first = DictSource([{"rate": 3.5}], source_id="rates") +second = DictSource([{"rate": 3.5}], source_id="rates") +try: + with Pipeline("rates"): + adjust.pod(first, label="first") + adjust.pod(second, label="second") +except InconsistentSourceError as error: + print(error) +# Source 'dict_v1:rates' has distinct source objects with one content hash in step 'first' and step 'second'. Build the source once and reuse the object. If the source ID contributes to the hash, give each source its own source_id. +``` + A kind's version moves when a row read before a change of its implementation could read differently after it (other values, other Arrow types, another record id). Saved jobs keep each source's name and version apart; a job loaded where a kind's version moved rebuilds the @@ -629,12 +695,15 @@ print(Condition.of(day=day, started=started, recorded=recorded)) `{"float": "-inf"}`, since JSON has no such number. - **One restriction per source identity in a pipeline.** Restrictions are equal by statement. On an integer column, `t >= 3` and `t > 2` select the same rows but count as two - restrictions. A restriction leaves the `source_id` and `content_hash` unchanged, so reading - one table under two windows with the same source identity in one pipeline raises - `ValueError`. Give each window its own `source_id` to use both in the same pipeline. The - same check covers restricted and unrestricted reads of one source identity, including - reads through projections, operator chains, and source wrappers. It runs at pipeline - construction, compilation, binding, and the start of each run. + restrictions. A restriction leaves the `source_id` and `content_hash` unchanged. Each + call to `where()` returns a new source object. Call `where()` once and reuse its result + when several parts of the pipeline need the same restriction. Distinct source objects + with the same content hash raise `InconsistentSourceError` even when their restrictions + are equal. The separate one-restriction check looks through projections, operator + chains and live source wrappers. It rejects different restrictions on the same source, + including a restricted and an unrestricted read. Give each window its own `source_id` + to use both in the same pipeline. These checks run at construction, compilation, + binding and the start of each run. - **With `limit=`.** A source built with `limit=n` reads the first `n` rows that match, in key order: the conditions are applied first. - **Conditions as values.** Equality compares the columns, operators and values in any @@ -1020,6 +1089,12 @@ order or content can vary between runs, pass an explicit, stable `source_id` **a key columns that are unique per row; this avoids both the duplicate entries and the repeated deliveries. +Sources with one `source_id` must agree on their Arrow schema and key columns. +Differences raise `InconsistentSourceError` during capture, binding, loading and +execution through `job.run()` or a node's `run()`. ITL-1506 tracks support for +distinct readings of one dataset in distinct named slots. Give each reading its +own `source_id` for now. + An in-memory source with key columns and no `source_id` can instead hash its rows in key order: pass `hash_in_key_order=True` (`ArrowTableSource`, `DictSource`, `DataFrameSource`, `ListSource`; ITL-1272). The table is hashed sorted by the key columns, in the order you list diff --git a/docs/dev/design_issues/ITL-1560-LJ5.md b/docs/dev/design_issues/ITL-1560-LJ5.md new file mode 100644 index 000000000..16a4fc351 --- /dev/null +++ b/docs/dev/design_issues/ITL-1560-LJ5.md @@ -0,0 +1,17 @@ +## `src/orcapod/pipeline/job.py` + +### LJ5 — Capturing steps or recompiling erased the graph of a loaded job +**Status:** resolved +**Severity:** high +**Issue:** ITL-1560 + +`PipelineJob.load` restores the compiled graph without the invocations that built it. +Capturing a step in the loaded job's context replaced the restored graph with the new +branch. Calling `compile()` directly rebuilt from the empty invocation record and discarded +the restored nodes. + +**Fix:** As a stopgap, a loaded job and its cached blueprint refuse capture and +recompilation. Capture validates every tracker before it records in any tracker, +and the cached blueprint retains the graph that saving writes. The loaded job +still supports binding and load-only runs. Support for editing the graph of a +loaded job is a separate design question (ITL-1559). diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index e05ee87b3..ee849045d 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -397,7 +397,8 @@ A record id is the row identifier (rule 8), built from row positions or key valu |---|---| | observer events (`node_hash`) | `core/nodes/function_node.py:FunctionJobNode.execute`, `core/nodes/function_node.py:FunctionJobNode.async_execute`, `core/nodes/function_node.py:FunctionJobNode._execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_cache_only`, `core/nodes/operator_node.py:OperatorJobNode.execute`, `core/nodes/operator_node.py:OperatorJobNode.async_execute`, `core/nodes/source_node.py:SourceNodeBase.execute`, `core/nodes/source_node.py:SourceNodeBase.async_execute` | | hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` | -| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | +| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase.prepare_invocation`, `pipeline/base.py:AbstractPipelineBase.prepare_invocation..`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations..`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | +| in-memory source registration keys | `pipeline/source_consistency.py:require_consistent_sources` | | in-memory topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map..order_key` | | canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams..` | | in-memory identity and repr | `core/base.py:ContentIdentifiableBase.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__eq__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__repr__` | @@ -613,11 +614,11 @@ The table below shows what each class returns from `identity_structure()`. | `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 | | `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 | +| `RootSource` (`ArrowTableSource`, `ListSource` and every other root source without its own rule) | `(source_id, (hash_schema(tag), hash_schema(data)), record ID key tuple)`, the Arrow schemas of its rows (ITL-640) | `source_id` is `_v:`, the name being the explicit user-supplied value; when not provided it defaults to `::` of the Arrow hash of the raw table (site 4). The class name is not part of it (ITL-1425): the kind part names the kind and implementation version, and the kind enters a datum's identity there only. `PollingSource` is `(source_id, impl.identity(), sorted tag columns, record ID key tuple)` (provisional, ITL-1316). The record ID key tuple lists the columns used to identify rows, in key order (`record_id_columns`, or a database or SpiralDB table's primary key), `()` for the position: two sources that differ only in how they name their rows are two sources (developer decision, November 16, 2026, ITL-1154). Data-inclusive base case of the Merkle chain. A `ListSource` has no rule of its own (developer, November 21, 2026, ITL-1272): its elements and tags enter its identity only through its default source id and its Arrow schema (their types), and with a given `source_id` it is an address like every other source (other elements of the same types leave its content hash unchanged); it used to hold its elements and a hash of its tag function (and took `tag_function_hash_mode`), and with a given `source_id` its content hash did not depend on that id at all. A review of every built-in source's identity is ITL-1311 | | `DerivedSource` | Origin node's `content_hash` | Inherits its generating node's identity | -| `DerivedSource` with `tags_as_data` | `(source_id, Arrow schema identity, key_columns, ("tags_as_data", sorted items))`; a `source_id` is required (ITL-1313), and the full id is `derived_v1:` | The rule of every root source plus the mapping, which enters the `content_hash` directly (two mappings can give one schema and one `source_id`); the origin enters only through the output schema, so the source is an address like every other source with a given `source_id` | -| `PollingSource` | `(source_id, impl.identity(), sorted tag_columns, key_columns)` | The source id (`polling_source_v1:`) first, as for every root source (ITL-1425), so a given `source_id` tells two polling sources apart; then the implementer's identity; the tag columns in name order, so their declared order changes nothing; `key_columns` (always given for a polling source, in key order) as for every root source. Provisional (`PROVISIONAL_SOURCES`, ITL-1314): this identity may change in a later release (ITL-1316) | -| `SpiralDBTableSource` | `(source_id, Arrow schema identity, key_columns)`, the rule of every root source (no class name, ITL-1425), then the sorted `tags_as_data` items when given | A restriction (`where`, `limit`, `asof`) chooses rows of the same table and adds nothing | +| `DerivedSource` with `tags_as_data` | `(source_id, Arrow schema identity, record ID key tuple, ("tags_as_data", sorted items))`; a `source_id` is required (ITL-1313), and the full id is `derived_v1:` | The rule of every root source plus the mapping, which enters the `content_hash` directly (two mappings can give one schema and one `source_id`); the origin enters only through the output schema, so the source is an address like every other source with a given `source_id` | +| `PollingSource` | `(source_id, impl.identity(), sorted tag_columns, record ID key tuple)` | The source id (`polling_source_v1:`) first, as for every root source (ITL-1425), so a given `source_id` tells two polling sources apart; then the implementer's identity; the tag columns in name order, so their declared order changes nothing; the record ID key tuple (required for a polling source) as for every root source. Provisional (`PROVISIONAL_SOURCES`, ITL-1314): this identity may change in a later release (ITL-1316) | +| `SpiralDBTableSource` | `(source_id, Arrow schema identity, record ID key tuple)`, the rule of every root source (no class name, ITL-1425), then the sorted `tags_as_data` items when given | A restriction (`where`, `limit`, `asof`) chooses rows of the same table and adds nothing | | `CachedSource` | the wrapped source's identity | | | Operators (unary) | `(operator_class_name, upstream_stream)` | Stream reference resolved via `content_resolver` | | Operators (binary/N-ary) | `(operator_class_name, argument_symmetry(streams))` | `frozenset` for commutative (Join); `tuple` for ordered (SemiJoin, MergeJoin: ITL-1281) | diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index d2ff1fb3e..34b10d550 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -37,7 +37,11 @@ StreamView, ) from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER -from orcapod.errors import OrcapodDatabaseError, TypeIdentityError +from orcapod.errors import ( + InconsistentSourceError, + OrcapodDatabaseError, + TypeIdentityError, +) from orcapod.utils.database_errors import keep_database_error, note_callback_failure from orcapod.protocols.core_protocols import ( ArgumentGroup, @@ -851,7 +855,12 @@ def __call__( # The select is Orcapod's own step: the data-tags it turns into # plain tags are not reported (ITL-1023). with materialization_diagnostic_off(): - input_stream = SelectDataColumns(columns=kept)(input_stream) + try: + input_stream = SelectDataColumns(columns=kept)(input_stream) + except InconsistentSourceError as exc: + raise InconsistentSourceError( + f"While capturing step {label or self.label!r}: {exc}" + ) from exc if fall_through_pod is not None and data_tags: return FallThroughPod(fall_through_pod, data_tags).process( input_stream, label=label diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 43fb63fb2..12ca0dde8 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -324,7 +324,8 @@ def run_job_node( ) -> None: """Run a job node as its ``run()`` does (developer, November 13, 2026; ITL-1095). - Every source feeding the node is first checked for new data (``check_sources``, + Source registrations are checked as in ``job.run()`` before reading new data. Every + source feeding the node is first checked for new data (``check_sources``, ITL-1102). Nothing runs when the node then holds a current run (``holds_current_run``). Otherwise a node that depends on job nodes runs with them (``run_with_dependencies``) and one built over streams outside a job runs alone @@ -347,7 +348,9 @@ def run_job_node( ) from orcapod.pipeline.restrictions import refuse_restriction_conflicts from orcapod.pipeline.run_summary import warn_row_failures + from orcapod.pipeline.source_consistency import require_consistent_sources + require_consistent_sources([(f"node {node.label!r}", node)]) # A source read under two restrictions, or a caching operator over a restricted # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). @@ -4338,6 +4341,8 @@ def run(self, *, load_only: bool = False) -> StreamView: compute (loaded without a function pod, or a placeholder pod) and ``load_only`` is false; or if its input is unavailable (``CACHE_ONLY``): read its stored rows with ``as_source()``. + InconsistentSourceError: If distinct source objects share a content + hash, or sources with one ID differ in schema or key columns. """ from orcapod.pipeline.serialization import LoadStatus diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 59c74de21..71dc27f83 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1938,6 +1938,8 @@ def run(self, *, load_only: bool = False) -> StreamView: ``load_only`` is false. ValueError: If this node or one it depends on caches (``LOG`` or ``REPLAY``) over a restricted source (ITL-1218); nothing has run. + InconsistentSourceError: If distinct source objects share a content + hash, or sources with one ID differ in schema or key columns. """ from orcapod.pipeline.node_run import ( check_sources, @@ -1947,9 +1949,11 @@ def run(self, *, load_only: bool = False) -> StreamView: ) from orcapod.pipeline.restrictions import refuse_restriction_conflicts from orcapod.pipeline.run_summary import warn_row_failures + from orcapod.pipeline.source_consistency import require_consistent_sources if self._loaded and not load_only: raise self._cannot_compute_error() + require_consistent_sources([(f"node {self.label!r}", self)]) # A source read under two restrictions, or a caching operator over a restricted # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..913a9c4c2 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -13,6 +13,7 @@ import functools import json import logging +import weakref from abc import ABC, abstractmethod from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence from datetime import datetime @@ -65,6 +66,7 @@ ) if TYPE_CHECKING: + from orcapod.pipeline.job import PipelineJob from orcapod.types.explanation import Explanation from orcapod.channels import WritableChannel from orcapod.protocols.core_protocols import StreamProtocol @@ -1630,6 +1632,7 @@ def __init__( ) self._bound_source: StreamProtocol | None = None self._declared_form: _DeclaredForm | None = None + self._binding_owner: weakref.ReferenceType[PipelineJob] | None = None if bound_source is not None: # Checks the source and, for a narrower one, records how its rows become # rows of the declared schema (ITL-1112), as the setter does, but does not @@ -1655,12 +1658,15 @@ def run(self, *, load_only: bool = False) -> StreamView: load_only: Accepted for every job node; a source reads its rows either way. Raises: + InconsistentSourceError: If the bound stream reads conflicting sources. UnboundSourceError: When no concrete source is bound. ValueError: If ``load_only`` and the bound stream computes or delivers when read (``node_run.refuse_unloadable_inputs``). """ from orcapod.pipeline.node_run import check_sources, refuse_unloadable_inputs + from orcapod.pipeline.source_consistency import require_consistent_sources + require_consistent_sources([(f"node {self.label!r}", self)]) _ = check_sources([self]) if load_only: refuse_unloadable_inputs(self) @@ -1675,33 +1681,55 @@ def bound_source(self) -> StreamProtocol | None: def bound_source(self, value: StreamProtocol | None) -> None: """Bind *value* as the concrete source and invalidate both hash caches. - A source is checked against the slot's declared schema first (``validate``), so - one that does not fit is refused before anything changes. A narrower source - (``x: int`` for a slot declaring ``x: int | None``) is accepted, and the node - gives its rows as rows of the declared schema (ITL-1112). ``None`` unbinds. + A source must fit the slot's declared schema before the binding changes. + A narrower source (``x: int`` for a slot declaring ``x: int | None``) is + accepted, and the node gives its rows as rows of the declared schema + (ITL-1112). ``None`` unbinds. + In a job, assignment uses the binding checks of ``PipelineJob.bind()``. Binding stamps the slot as modified, so every job node fed by it is stale and reads empty until it runs again (ITL-1095). Raises: + InconsistentSourceError: If the replacement introduces conflicting sources. SourceSpecMismatchError: If *value* does not fit the declared schema. """ - self._bind(value) - self._update_modified_time() + owner = self._binding_owner() if self._binding_owner is not None else None + if owner is None: + self._bind(value) + self._update_modified_time() + else: + owner._replace_source_binding(self, value) # pyright: ignore[reportPrivateUsage] # the setter uses the job's binding transaction + + def _set_binding_owner(self, owner: PipelineJob | None) -> None: + """Route changes to a job while this is one of its active slots.""" + self._binding_owner = weakref.ref(owner) if owner is not None else None def _bound_stream(self) -> StreamProtocol | None: """The concrete stream bound to this slot, or ``None``.""" return self._bound_source def _bind(self, value: StreamProtocol | None) -> None: - """Check *value* and bind it, invalidating both hash caches. + """Check and install a binding without a job-wide transaction. The binding the setter and ``__init__`` share. Only the setter stamps the slot as modified (ITL-1095): a node built with its source is not a rebinding. Raises: + InconsistentSourceError: If the bound stream reads conflicting sources. SourceSpecMismatchError: If *value* does not fit the declared schema. """ - form = None if value is None else self._declared_form_for(value) + from orcapod.pipeline.source_consistency import require_consistent_sources + + form = None + if value is not None: + require_consistent_sources([(f"slot {self.name!r}", value)]) + form = self._declared_form_for(value) + self._apply_binding(value, form) + + def _apply_binding( + self, value: StreamProtocol | None, form: _DeclaredForm | None + ) -> None: + """Install a validated binding and invalidate its cached hashes.""" self._bound_source = value self._declared_form = form self._invalidate_content_hash_cache() diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 07221924c..88a0e8e6b 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -416,6 +416,17 @@ def _schema_identity(self) -> tuple[ContentHash, ContentHash]: """ return arrow_schema_identity(*self.arrow_schemas, self.data_context) + @property + def _resolved_key_columns(self) -> tuple[str, ...] | None: + """The resolved key columns that name this source's rows, in key order. + + ``()`` means a row is named by its position. Key columns belong to how the + rows are read, not to the dataset the source id names. A source over another + (``CachedSource``, ``SourceProxy``) answers with what it wraps, or ``None`` + when that is unknown (an unbound proxy). + """ + return self._key_columns + def identity_structure(self) -> Any: """Identity from the ``source_id``, the Arrow schema and the key columns. @@ -502,6 +513,16 @@ def upstreams(self) -> tuple[StreamProtocol, ...]: """Sources have no upstream dependencies.""" return () + @property + def live_source_inputs(self) -> tuple[StreamProtocol, ...] | None: + """Identify the inputs read live through this source. + + Wrappers that can read another stream live override this property. They + return an empty tuple when disconnected. A source that supplies its + own rows or reads stored results returns ``None``, ending the walk. + """ + return None + # ------------------------------------------------------------------------- # Stream delegation defaults # ------------------------------------------------------------------------- diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 15501c76c..545078f9b 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -42,7 +42,12 @@ report_rows_of_other_data_contexts, with_data_context, ) -from orcapod.protocols.core_protocols import DataProtocol, SourceProtocol, TagProtocol +from orcapod.protocols.core_protocols import ( + DataProtocol, + SourceProtocol, + StreamProtocol, + TagProtocol, +) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.system_constants import SOURCE_DB_SCHEMA_VERSION, constants from orcapod.types import ColumnConfig, Schema @@ -268,6 +273,14 @@ def source_name(self) -> str: """The name part of the wrapped source's source id.""" return parse_source_id(self._source.source_id).name + @property + @override + def _resolved_key_columns(self) -> tuple[str, ...] | None: + """The wrapped source's key columns, or ``None`` when it is not a root source.""" + if isinstance(self._source, RootSource): + return self._source._resolved_key_columns + return None + def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": """The wrapped source's Arrow schemas: the cache stores that source's rows.""" schemas = typed_arrow_schemas(self._source) @@ -349,6 +362,11 @@ def cached_source(self) -> SourceProtocol: """The source this cache reads and keeps the rows of.""" return self._source + @property + def live_source_inputs(self) -> tuple[StreamProtocol, ...]: + """A cache can read its wrapped source live.""" + return (self._source,) + def _live_records(self) -> pa.Table: """Read the wrapped source's rows, each with its record hash in front. diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index aeef4bfd5..4bd337d39 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -43,6 +43,7 @@ if TYPE_CHECKING: from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.protocols.core_protocols import StreamProtocol def validate_tags_as_data( @@ -471,6 +472,11 @@ def _data_tags(self) -> tuple[str, ...]: """ return stream_data_tags(self._origin) + @property + def live_source_inputs(self) -> tuple[StreamProtocol, ...] | None: + """Tag copies over a source read it live. Job nodes give stored results.""" + return (self._origin,) if isinstance(self._origin, RootSource) else None + def _origin_records(self) -> "pa.Table | None": """Return the origin's rows, or ``None`` when a job node has none stored. diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 83eb6238d..50961f369 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -35,7 +35,11 @@ import pyarrow as pa - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) class SourceProxy(RootSource): @@ -95,6 +99,19 @@ def delegate(self) -> SourceProtocol | None: """The bound live source, or ``None`` if no source has been bound.""" return self._delegate + @property + def live_source_inputs(self) -> tuple[StreamProtocol, ...]: + """A bound proxy reads its delegate live.""" + return () if self._delegate is None else (self._delegate,) + + @property + @override + def _resolved_key_columns(self) -> tuple[str, ...] | None: + """The bound source's key columns, or ``None`` while unbound.""" + if isinstance(self._delegate, RootSource): + return self._delegate._resolved_key_columns + return None + @property def is_bound(self) -> bool: """``True`` if a live source has been bound via `bind`.""" diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 9b4642981..b438f42e7 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -571,9 +571,10 @@ def where( built beforehand is accepted as it is. The source's ``limit`` is its own and is not changed. - This source is not changed. ``where`` is a copy of the source with the - restriction applied to the copy in place; a later version offers those two - steps (``copy()`` and ``apply_restriction``) on their own. + Each call to ``where()`` makes a new source object. Call it once and reuse + the resulting object when the same restriction feeds multiple parts of a + pipeline. A later version offers ``copy()`` and ``apply_restriction`` as + separate steps. Args: *conditions: Mappings of column name to value, and conditions (built with diff --git a/src/orcapod/core/tracker.py b/src/orcapod/core/tracker.py index 16ecb1803..677587854 100644 --- a/src/orcapod/core/tracker.py +++ b/src/orcapod/core/tracker.py @@ -1,12 +1,16 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Generator +from collections.abc import Callable, Generator from contextlib import contextmanager -from typing import Any +from functools import partial +from typing import TYPE_CHECKING, Any from orcapod.protocols import core_protocols as cp +if TYPE_CHECKING: + from orcapod.pipeline.pod_invocation import PodInvocation + class BasicTrackerManager: def __init__(self) -> None: @@ -35,13 +39,14 @@ def get_active_trackers(self) -> list[cp.TrackerProtocol]: def record_operator_pod_invocation( self, - pod: cp.PodProtocol, + pod: cp.OperatorPodProtocol, upstreams: tuple[cp.StreamProtocol, ...] = (), label: str | None = None, ) -> None: """Record the invocation of a pod in the tracker.""" - for tracker in self.get_active_trackers(): - tracker.record_operator_pod_invocation(pod, upstreams, label=label) + from orcapod.pipeline.pod_invocation import OperatorInvocation + + self._record(partial(OperatorInvocation, pod, upstreams, label)) def record_function_pod_invocation( self, @@ -50,8 +55,9 @@ def record_function_pod_invocation( label: str | None = None, ) -> None: """Record the invocation of a data function to the tracker.""" - for tracker in self.get_active_trackers(): - tracker.record_function_pod_invocation(pod, input_stream, label=label) + from orcapod.pipeline.pod_invocation import FunctionInvocation + + self._record(partial(FunctionInvocation, pod, (input_stream,), label)) def record_side_effect_pod_invocation( self, @@ -60,8 +66,19 @@ def record_side_effect_pod_invocation( label: str | None = None, ) -> None: """Record a side-effect pod invocation in all active trackers.""" - for tracker in self.get_active_trackers(): - tracker.record_side_effect_pod_invocation(pod, input_stream, label=label) + from orcapod.pipeline.pod_invocation import SideEffectInvocation + + self._record(partial(SideEffectInvocation, pod, (input_stream,), label)) + + def _record(self, make_invocation: Callable[[], PodInvocation]) -> None: + """Prepare every active tracker's recording before committing in order.""" + trackers = self.get_active_trackers() + if not trackers: + return + invocation = make_invocation() + recordings = [tracker.prepare_invocation(invocation) for tracker in trackers] + for record in recordings: + record() @contextmanager def no_tracking(self) -> Generator[None, Any, None]: @@ -90,6 +107,9 @@ def set_active(self, active: bool = True) -> None: def is_active(self) -> bool: return self._active + @abstractmethod + def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: ... + @abstractmethod def record_operator_pod_invocation( self, diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index a00e171ed..a6bd41974 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -557,17 +557,15 @@ class SourceSpecMismatchError(InputValidationError, ValueError): class InconsistentSourceError(ValueError): - """Raised when two source nodes in the same pipeline share a name but differ in schema. + """Raised when sources conflict in a pipeline or job. - Source node names are identity-forming: the same name in a given pipeline - must always refer to the same input slot (same schema). If ``compile()`` - finds two source nodes with identical names but different schemas — which - can happen when two ``RootSource`` objects share the same ``source_id`` but - produce different column sets — it raises this error rather than silently - renaming one of them. + Each content hash can be registered by one source object. Sources + sharing a ``source_id`` must have the same schema and key columns + (ITL-1506). Two different schemas competing for one input slot also + raise this error. - Resolution: assign distinct ``source_id`` values to the conflicting sources - so each slot has a unique, stable identity. + Build a source once and reuse that object, or give each source its + own ``source_id``. """ diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 966809d94..d8e761aa9 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -4,9 +4,10 @@ import logging from abc import ABC, abstractmethod -from collections.abc import Hashable +from collections.abc import Callable, Hashable, Iterable, Iterator from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar +from itertools import chain +from typing import TYPE_CHECKING, Any, Generic, Literal, Self, TypeVar from orcapod.core.nodes.function_node import FunctionNodeBase from orcapod.core.tracker import AutoRegisteringContextBasedTracker @@ -17,6 +18,10 @@ PodInvocation, SideEffectInvocation, ) +from orcapod.pipeline.source_consistency import ( + invocation_source_uses, + require_consistent_sources, +) from orcapod.side_effects import SideEffectNode from orcapod.protocols import core_protocols as cp from orcapod.utils.lazy_module import LazyModule @@ -26,6 +31,8 @@ from orcapod.pipeline.diagram import PipelineDiagram from orcapod.types.provenance import Highlight from orcapod.protocols.database_protocols import ArrowDatabaseProtocol + from orcapod.pipeline.source_consistency import SourceUse + from orcapod.protocols.core_protocols import StreamProtocol else: nx = LazyModule("networkx") @@ -46,6 +53,9 @@ def _refuse_sources_sharing_a_slot_name( Only sources are refused here: a slot of another stream is named by its label and content hash. + Sources with one source id and schema whose key columns differ never get here: + ``require_consistent_sources`` refuses them first (ITL-1506). + Raises: SourceSlotNameCollisionError: Naming every full source id and the remedy. """ @@ -125,6 +135,8 @@ def __init__( # --- Additive recording state (never cleared) ----------------- # Maps content-hash-string → PodInvocation for each recorded invocation. self._invocation_lut: dict[str, PodInvocation] = {} + # Ordered graph keys chosen at capture, which stay fixed across rebindings. + self._invocation_input_keys: dict[str, tuple[str, ...]] = {} # Maps content-hash-string → raw stream for each unregistered upstream. self._source_streams: dict[str, Any] = {} # Topology graph — vertices and edges are content-hash strings. @@ -136,6 +148,8 @@ def __init__( self._nodes: dict[str, NodeT] = {} self._node_graph: OrcaDAG[NodeT] | None = None self._compiled: bool = False + # Set by PipelineJob.load() on the job and its embedded blueprint. + self._loaded_job_graph: bool = False # --- Fields populated by compile(); used by is_runnable(), run(), save() ---- # Populated from _persistent_node_map / _hash_graph at end of compile(). @@ -257,6 +271,16 @@ def side_effect_node_class(self) -> type: # Recording # ------------------------------------------------------------------ + def _require_editable_graph(self) -> None: + """Refuse graph changes on a loaded job and its cached blueprint.""" + # Stopgap (ITL-1560): the compiled graph was restored without the + # recorded invocations needed to compile it again. See ITL-1559. + if self._loaded_job_graph: + raise RuntimeError( + "A loaded job cannot be extended or recompiled yet " + "(stopgap, ITL-1560). Build the job from its pipeline to change it." + ) + def record_function_pod_invocation( self, pod: "cp.FunctionPodProtocol", @@ -309,7 +333,13 @@ def record_side_effect_pod_invocation( ) def _record_invocation(self, invocation: PodInvocation) -> None: - """Store *invocation* and update the topology graph. + self.prepare_invocation(invocation)() + + def _validate_capture_sources(self, streams: Iterable[StreamProtocol]) -> None: + """Check the streams of a new capture before recording it.""" + + def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: + """Validate *invocation* and prepare to update the topology graph. Non-source nodes in ``_persistent_node_map`` are keyed by the corresponding ``PodInvocation.content_hash()`` string. For @@ -330,51 +360,67 @@ def _record_invocation(self, invocation: PodInvocation) -> None: Args: invocation: The pod invocation to record. + Returns: + A callback that records the validated invocation. + Raises: + RuntimeError: If the graph is a loaded job or its cached blueprint. ValueError: If the invocation reads a source under another restriction than the pipeline's streams read it under now, or two of its inputs read one source under two restrictions (ITL-1218), whatever streams lead there. Nothing is recorded then. """ + self._require_editable_graph() + from orcapod.pipeline.restrictions import require_one_restriction - key = invocation.content_hash().to_string() inputs = tuple(invocation.input_streams) - upstreams = [ - (upstream, upstream.content_hash().to_string()) for upstream in inputs - ] + self._validate_capture_sources(inputs) + key = invocation.content_hash().to_string() + input_keys = tuple(upstream.content_hash().to_string() for upstream in inputs) # Checked before anything is recorded, so a refused invocation leaves the # graph as it was. A restriction does not change a source's identity, so the # pipeline keeps one restriction (or none) per source identity, whatever # streams lead to it: every source this invocation reads is checked with # every source the pipeline's streams read now (nothing is remembered: a # slot rebound since the last invocation changes what they read). - require_one_restriction([*self._held_streams(), *inputs]) - self._remember_invocation(key, invocation) - self._hash_graph.add_node(key) - for upstream, upstream_hash in upstreams: - self._hash_graph.add_edge(upstream_hash, key) - if upstream_hash not in self._source_streams: - self._source_streams[upstream_hash] = upstream - - def _remember_invocation(self, key: str, invocation: PodInvocation) -> None: + uses = tuple(self._source_uses(invocation)) + require_consistent_sources(uses) + require_one_restriction(stream for _, stream in uses) + + def record() -> None: + self._remember_invocation(key, invocation, input_keys) + self._hash_graph.add_node(key) + for upstream, upstream_hash in zip(inputs, input_keys, strict=True): + self._hash_graph.add_edge(upstream_hash, key) + self._source_streams.setdefault(upstream_hash, upstream) + + return record + + def _remember_invocation( + self, key: str, invocation: PodInvocation, input_keys: tuple[str, ...] + ) -> None: """Keep the smallest explicit label when identical invocations share a node.""" previous = self._invocation_lut.get(key) if previous is not None and previous.label is not None: if invocation.label is None or previous.label < invocation.label: return self._invocation_lut[key] = invocation - - def _held_streams(self) -> list[Any]: - """Every stream the pipeline holds: its leaves and every recorded input.""" - return [ - *self._source_streams.values(), - *( - stream - for invocation in self._invocation_lut.values() - for stream in invocation.input_streams - ), - ] + self._invocation_input_keys[key] = input_keys + + def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: + """Held inputs and, when supplied, the candidate's inputs before deduplication.""" + # Prefer the labelled endpoint of a chain over an implicit projection. + for invocation in reversed(self._invocation_lut.values()): + yield from invocation_source_uses(invocation) + if extra is not None: + yield from invocation_source_uses(extra) + for stream in self._source_streams.values(): + yield f"source {stream.label!r}", stream + + def _source_node_from_recording(self, key: str) -> Any: + """Create the source node for a recorded leaf.""" + return self.source_node_class.from_stream(self._source_streams[key]) # ------------------------------------------------------------------ # Diagram (ITL-1197) @@ -453,6 +499,16 @@ def reset(self) -> None: ``compile()`` call. Nothing needs to be cleared on re-entry. """ + def __enter__(self) -> Self: + """Enter the recording context and return the graph. + + Raises: + RuntimeError: If the graph is a loaded job or its cached blueprint. + """ + self._require_editable_graph() + super().__enter__() + return self + def __exit__(self, exc_type=None, exc_value=None, traceback=None) -> None: """Exit the recording context, compiling if no exception occurred.""" super().__exit__(exc_type, exc_value, traceback) @@ -498,9 +554,12 @@ def compile(self) -> None: incremental compilation. Raises: + RuntimeError: If the graph is a loaded job or its cached blueprint. ValueError: If one source is read under two different restrictions (ITL-1218), judged from what the recorded streams read now. """ + self._require_editable_graph() + import networkx as _nx from orcapod.pipeline.restrictions import require_one_restriction @@ -508,14 +567,16 @@ def compile(self) -> None: # Checked again here, from what the streams read now: a slot rebound after # the last invocation would otherwise connect a branch recorded over one # restriction to another (ITL-1218). - require_one_restriction(self._held_streams()) + uses = tuple(self._source_uses()) + require_consistent_sources(uses) + require_one_restriction(stream for _, stream in uses) source_node_cls = self.source_node_class # 1. Resolve source nodes in hash order, then insert them by their slot # labels. The original stream hash breaks ties between identical labels. sources = [ - (h, source_node_cls.from_stream(self._source_streams[h])) + (h, self._source_node_from_recording(h)) for h in sorted(self._source_streams.keys() - self._invocation_lut.keys()) ] node_map: dict[str, Any] = dict( @@ -574,9 +635,7 @@ def compile(self) -> None: if key not in self._invocation_lut: continue # vertex with no invocation (e.g. pure source hash) inv = self._invocation_lut[key] - upstream_nodes = [ - node_map[up.content_hash().to_string()] for up in inv.input_streams - ] + upstream_nodes = [node_map[up] for up in self._invocation_input_keys[key]] if isinstance(inv, FunctionInvocation): node_map[key] = self.function_node_class( function_pod=inv.pod, @@ -800,13 +859,29 @@ def from_invocations( A compiled instance of ``cls``. """ instance = cls(name=name) + instance._validate_capture_sources( + chain( + graph.source_streams.values(), + chain.from_iterable( + invocation.input_streams for invocation in graph.invocations + ), + ) + ) + require_consistent_sources( + use + for invocation in graph.invocations + for use in invocation_source_uses(invocation) + ) instance._source_streams = dict(graph.source_streams) for inv in graph.invocations: key = inv.content_hash().to_string() - instance._remember_invocation(key, inv) + input_keys = tuple( + up.content_hash().to_string() for up in inv.input_streams + ) + instance._remember_invocation(key, inv, input_keys) instance._hash_graph.add_node(key) - for upstream in inv.input_streams: - instance._hash_graph.add_edge(upstream.content_hash().to_string(), key) + for input_key in input_keys: + instance._hash_graph.add_edge(input_key, key) # Also add source hashes as isolated nodes (no incoming edges) for h in graph.source_streams: if h not in instance._hash_graph: diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index baec82ecf..1e142af83 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -690,6 +690,7 @@ def _clone_for_execution(self) -> "Pipeline": # Shared read-only structural state (recording + compiled) clone._name = self._name clone._invocation_lut = self._invocation_lut + clone._invocation_input_keys = self._invocation_input_keys clone._source_streams = self._source_streams clone._node_lut = self._node_lut clone._upstreams = self._upstreams @@ -699,6 +700,7 @@ def _clone_for_execution(self) -> "Pipeline": clone._node_graph = self._node_graph clone._auto_compile = self._auto_compile clone._compiled = self._compiled + clone._loaded_job_graph = self._loaded_job_graph clone._loaded_output_schemas = self._loaded_output_schemas # Mutable per-execution state — own copy so runs don't interfere clone._nodes = dict(self._nodes) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 82f59257c..77024bc0b 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -6,7 +6,7 @@ import enum import logging import sys -from collections.abc import Iterator +from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast @@ -20,6 +20,7 @@ from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.core.tracker import AutoRegisteringContextBasedTracker from orcapod.errors import ( + InconsistentSourceError, OrcapodDatabaseError, OrcapodDatabaseReadError, OrcapodDatabaseWriteError, @@ -36,6 +37,7 @@ refuse_restricted_operator_caches, refuse_restriction_conflicts, restrictions_in_force, + streams_beneath, warn_restricted_aggregation, ) from orcapod.pipeline.run_summary import ( @@ -44,6 +46,10 @@ run_node_summaries, warn_row_failures, ) +from orcapod.pipeline.source_consistency import ( + invocation_source_uses, + require_consistent_sources, +) from orcapod.protocols import core_protocols as cp from orcapod.databases.utils import as_table_committing from orcapod.types import NodeConfig @@ -52,9 +58,14 @@ if TYPE_CHECKING: from pathlib import Path + from orcapod.core.nodes.source_node import _DeclaredForm # pyright: ignore[reportPrivateUsage] # shared binding transaction + from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.execution_context import ExecutionContext from orcapod.pipeline.graph import Pipeline + from orcapod.pipeline.pod_invocation import PodInvocation + from orcapod.pipeline.restrictions import Rebinding + from orcapod.pipeline.source_consistency import SourceUse from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import ExecutionObserverProtocol @@ -190,11 +201,8 @@ def __init__( self._auto_compile = auto_compile # name → bound concrete source (user-facing API: job.sources). self._sources: dict[str, cp.StreamProtocol] = {} - # hash → bound concrete source, keyed by the same hash as - # _persistent_node_map. Used by bind() for O(1) lookup by content - # hash; avoids name collisions when multiple concrete sources share - # the same class name (e.g. two ArrowTableSource objects). - self._sources_by_hash: dict[str, cp.StreamProtocol] = {} + self._rebound_source_keys: set[str] = set() + self._sources_as_captured: dict[str, cp.StreamProtocol | None] = {} self._has_run: bool = False # True only while the last run started has finished and committed its writes: # what the database then holds for each node is what that run left (ITL-1043). @@ -202,8 +210,6 @@ def __init__( self._run_id: str | None = None # The summary of the last run this object completed (ITL-997). self._last_run: RunSummary | None = None - # True for a job built by load(): it reads stored results and never runs. - self._loaded: bool = False # Lazy cache for the corresponding Pipeline blueprint. # Set to None after compile() to force recomputation on next access. @@ -222,6 +228,75 @@ def __exit__(self, exc_type=None, exc_value=None, traceback=None) -> None: if exc_type is None and self._auto_compile: self.compile() + def _validate_capture_sources(self, streams: Iterable[cp.StreamProtocol]) -> None: + """Require original bindings and refuse bindable slots outside this job.""" + # ITL-1559: refuse additive capture until the relationship between captured + # objects and slots is defined. Check at recording so a bind inside an + # open capture context cannot bypass the rule. + changed = sorted( + { + node.name + for key, node in self._persistent_node_map.items() + if isinstance(node, SourceJobNode) + and key in self._sources_as_captured + and node.bound_source is not self._sources_as_captured[key] + } + ) + if changed: + names = ", ".join(repr(name) for name in changed) + raise InconsistentSourceError( + f"Cannot record a step because these job slots are not as captured: " + f"{names}. Bind them back to their original objects or build a new " + "job (ITL-1559)." + ) + # ITL-1559 stopgap: SourceJobNode has a mutable bound_source even when + # unbound. SourceNode only declares a name and schemas. + own_slots = { + id(node) + for node in self._persistent_node_map.values() + if isinstance(node, SourceJobNode) + } + visited: set[int] = set() + pending = list(streams) + while pending: + stream = pending.pop() + if id(stream) in visited: + continue + visited.add(id(stream)) + if isinstance(stream, SourceJobNode) and id(stream) not in own_slots: + raise InconsistentSourceError( + f"Capturing source slot {stream.name!r} from outside this job " + "is not supported yet (ITL-1559). Pass the source itself, or " + "use node.as_source() to read another job's stored results." + ) + pending.extend(streams_beneath(stream)) + + def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]: + """Validate actual graph leaves after a binding replaces a captured input.""" + if not self._rebound_source_keys: + yield from super()._source_uses(extra) + return + # A recorded operator's Python stream still holds its old upstreams. + # Compilation connects its recorded keys to the job's actual leaves. + for key, stream in self._source_streams.items(): + if key in self._invocation_lut: + continue + slot = self._persistent_node_map.get(key) + if key in self._rebound_source_keys and isinstance(slot, SourceJobNode): + yield f"node {slot.label!r}", slot + else: + yield f"source {stream.label!r}", stream + if extra is not None: + yield from invocation_source_uses(extra) + + def _source_node_from_recording(self, key: str) -> SourceJobNode: + """Preserve an explicit binding when recompiling its slot.""" + if key in self._rebound_source_keys: + slot = self._persistent_node_map.get(key) + if isinstance(slot, SourceJobNode): + return self.source_node_class.from_stream(slot) + return self.source_node_class.from_stream(self._source_streams[key]) + def compile(self) -> None: """Compile recorded invocations into a frozen DAG of job nodes. @@ -238,31 +313,26 @@ def compile(self) -> None: If ``_database`` is set, distributes databases to all function and operator job nodes. - """ - # Preserve any sources already bound (e.g. from a prior bind() call). - pre_sources = dict(self._sources) - pre_sources_by_hash = dict(self._sources_by_hash) + Raises: + RuntimeError: If this job was loaded from a saved file. + """ + previous_slots = [ + node + for node in self._persistent_node_map.values() + if isinstance(node, SourceJobNode) + ] super().compile() - # Collect bound SourceJobNodes created during compilation. - # _sources is name-keyed (user-facing API via job.sources). - # _sources_by_hash is hash-keyed (internal use by bind()). - # Two concrete sources of the same class (e.g. two ArrowTableSource objects) - # would collide on name but have distinct hash keys. - compiled_by_name: dict[str, Any] = {} - compiled_by_hash: dict[str, Any] = {} - for h, n in self._persistent_node_map.items(): - if isinstance(n, SourceJobNode) and n.bound_source is not None: - compiled_by_name[n.name] = n.bound_source - compiled_by_hash[h] = n.bound_source - # Also index by schema-based hash (matches blueprint pipeline keys). - schema_hash = n.as_node().content_hash().to_string() - compiled_by_hash[schema_hash] = n.bound_source - # pre_sources / pre_sources_by_hash win over compiled (explicit bind() takes priority). - self._sources = {**compiled_by_name, **pre_sources} - self._sources_by_hash = {**compiled_by_hash, **pre_sources_by_hash} - + for slot in previous_slots: + slot._set_binding_owner(None) # pyright: ignore[reportPrivateUsage] # the replaced slot no longer belongs to this job + self._sources = {} + for key, node in self._persistent_node_map.items(): + if isinstance(node, SourceJobNode): + self._sources_as_captured.setdefault(key, node.bound_source) + node._set_binding_owner(self) # pyright: ignore[reportPrivateUsage] # setters participate in this job's binding transaction + if node.bound_source is not None: + self._sources[node.name] = node.bound_source # Invalidate the lazy compiled_pipeline cache. self._compiled_pipeline = None @@ -395,7 +465,7 @@ def from_pipeline( bound_sources: dict[str, cp.StreamProtocol] = dict(sources or {}) - # Validate sources against SourceNode schemas. + # Report unknown names against the blueprint. Bind checks the sources. if bound_sources: source_names = { node.name @@ -408,17 +478,10 @@ def from_pipeline( f"from_pipeline() received source keys with no matching SourceNode: " f"{sorted(unknown)}. Known names: {sorted(source_names)}" ) - for node in pipeline._persistent_node_map.values(): - if isinstance(node, SourceNodeBase) and node.name in bound_sources: - node.validate(bound_sources[node.name]) # Reconstruct via InvocationGraph (creates unbound SourceJobNodes). - # _compiled_pipeline is intentionally left as None here so the lazy - # property computes a schema-normalized blueprint via as_pipeline(). - # Setting it to the original pipeline would cause hash-key mismatches in - # _build_execution_graph(): the original pipeline may carry concrete - # (data-inclusive) hash keys in _upstreams, while _sources_by_hash is - # keyed by schema-based hashes derived from the unbound SourceJobNodes. + # Leave the compiled blueprint lazy so as_pipeline() builds it with + # the schema-based keys of the new job's slots. job = cls.from_invocations(pipeline.to_invocations(), name=pipeline._name) job._database = database # pyright: ignore[reportAttributeAccessIssue] # from_invocations is typed as the base class; the instance is a PipelineJob job._execution_context = execution_context @@ -471,6 +534,9 @@ def bind( the job's own database again, at ``/_result`` (ITL-1408). Raises: + InconsistentSourceError: If distinct source objects share a content + hash, or sources with one ID differ in schema or key columns + (ITL-1506). The job is left as it was. SourceSpecMismatchError: If any source's columns differ from its slot's declared names, roles or types. ValueError: If a source key has no matching ``SourceJobNode`` slot, or an @@ -506,9 +572,6 @@ def bind( f"(SourceJobNode): {sorted(unknown)}. " f"Known slot names: {sorted(source_names)}" ) - for node in (self._persistent_node_map or {}).values(): - if isinstance(node, SourceNodeBase) and node.name in sources: - node.validate(sources[node.name]) # A database that cannot store a node's tables is refused before anything # changes too (ITL-1162), and so is a caching operator over a restricted @@ -522,9 +585,7 @@ def bind( for node in (self._persistent_node_map or {}).values() if isinstance(node, SourceJobNode) and node.name in to_bind ] - refuse_restriction_conflicts( - (self._persistent_node_map or {}).values(), rebinding=rebinding - ) + prepared = self._prepare_source_bindings(rebinding) new_database = database if database is not None else self._database new_result_database = ( self._result_database @@ -543,25 +604,7 @@ def bind( if result_database_given: self._unresolved_result_database = None - if sources is not None: - # Update bound_source on SourceJobNodes and maintain both dicts. - for h, job_node in (self._persistent_node_map or {}).items(): - if isinstance(job_node, SourceJobNode) and job_node.name in sources: - job_node.bound_source = sources[job_node.name] - self._sources_by_hash[h] = sources[job_node.name] - # Also index by schema-based hash (matches blueprint pipeline keys). - schema_hash = job_node.as_node().content_hash().to_string() - self._sources_by_hash[schema_hash] = sources[job_node.name] - self._sources.update(sources) - # Every node predicts its schema again (ITL-1111). Since ITL-1112 a bind - # should never change a prediction: ``validate`` refuses a source of other - # column names or types, and the slot gives the declared schema, so this - # clear is expected to find nothing to change. It is kept so that a bind - # can never leave a stale prediction if a bound source's schema ever - # differs in a way the check does not see. - for job_node in (self._persistent_node_map or {}).values(): - if isinstance(job_node, StreamBase): - job_node._forget_output_schema() # pyright: ignore[reportPrivateUsage] # the job owns its nodes' bindings + self._apply_source_bindings(prepared) if execution_context is not None: self._execution_context = execution_context @@ -569,6 +612,56 @@ def bind( if database_changed and self._database is not None: self._distribute_databases() + def _replace_source_binding( + self, slot: SourceJobNode, source: cp.StreamProtocol | None + ) -> None: + """Apply a setter change through the same transaction as bind().""" + self._apply_source_bindings(self._prepare_source_bindings([(slot, source)])) + + def _prepare_source_bindings( + self, rebinding: Rebinding + ) -> list[tuple[SourceJobNode, cp.StreamProtocol | None, _DeclaredForm | None]]: + """Validate the prospective job and prepare each changed slot's row form.""" + nodes = self._persistent_node_map.values() + require_consistent_sources( + ((f"node {node.label!r}", node) for node in nodes), rebinding + ) + prepared = [ + ( + slot, + source, + slot._declared_form_for(source) if source is not None else None, # pyright: ignore[reportPrivateUsage] # validate the exact binding before committing it + ) + for slot, source in rebinding + ] + refuse_restriction_conflicts(nodes, rebinding=rebinding) + return prepared + + def _apply_source_bindings( + self, + prepared: Sequence[ + tuple[SourceJobNode, cp.StreamProtocol | None, _DeclaredForm | None] + ], + ) -> None: + """Commit validated slot replacements and invalidate dependent predictions.""" + if not prepared: + return + keys = {id(node): key for key, node in self._persistent_node_map.items()} + for slot, source, form in prepared: + slot._apply_binding(source, form) # pyright: ignore[reportPrivateUsage] # install the validated row form + slot._update_modified_time() # pyright: ignore[reportPrivateUsage] # the job owns the slot's binding + self._rebound_source_keys.add(keys[id(slot)]) + if source is None: + self._sources.pop(slot.name, None) + else: + self._sources[slot.name] = source + + # A binding preserves the declared schema. Clear predictions anyway so + # that each node reads the schema from its current inputs (ITL-1111). + for node in self._persistent_node_map.values(): + if isinstance(node, StreamBase): + node._forget_output_schema() # pyright: ignore[reportPrivateUsage] # the job owns its nodes' bindings + # ------------------------------------------------------------------ # _distribute_databases() # ------------------------------------------------------------------ @@ -938,7 +1031,7 @@ def is_runnable(self, node_label: str) -> bool: Returns: ``True`` if the node can be executed with current bindings. """ - if self._loaded or not self._compiled: + if self._loaded_job_graph or not self._compiled: return False target = self._nodes.get(node_label) @@ -1229,7 +1322,7 @@ def _prepare_run( # A loaded job never computes: function pods are not saved with it, and even # an operator-only loaded job, whose operators are rebuilt, stays read-only. # A load-only run fills it from the database (ITL-1095). - if self._loaded and not load_only: + if self._loaded_job_graph and not load_only: raise RuntimeError( "PipelineJob.run() cannot execute a loaded job: its function pods are " "not saved with it, so it cannot compute. Fill its nodes from the " @@ -1302,6 +1395,11 @@ def _prepare_run( ) # --- Build hash-keyed OrcaDAG for topological ordering + exclusion --- + # A caller can change a slot or proxy directly after binding the job. + require_consistent_sources( + (f"node {node.label!r}", node) + for node in self._persistent_node_map.values() + ) hash_dag: OrcaDAG[str] = OrcaDAG() for u, v in self._graph_edges: hash_dag.add_edge(u, v) @@ -1328,7 +1426,7 @@ def _prepare_run( # A loaded job whose graph lost a node (the file records a node of a kind # PipelineJob.load does not restore) cannot feed the nodes below it: every # saved input of a node must be a restored node. - if self._loaded: + if self._loaded_job_graph: for node_hash, node in self._persistent_node_map.items(): if node_hash in excluded_hashes: continue # below an unbound source: not part of this run @@ -1764,6 +1862,9 @@ def load( results. Raises: + InconsistentSourceError: If distinct reconstructed source objects + share a content hash, or sources with one ID differ in schema + or key columns (ITL-1506). ValueError: If the file's format version is not the one this Orcapod writes (an earlier format is refused, never migrated), or if it was saved before the database key was renamed (``bindings.store`` @@ -1848,6 +1949,7 @@ def load( if isinstance(node, SourceNodeBase) } sources: dict[str, cp.StreamProtocol] = {} + sources_by_config: dict[str, cp.StreamProtocol | None] = {} for spec_name, src_config in ( data.get("bindings", {}).get("sources", {}).items() ): @@ -1871,7 +1973,13 @@ def load( except ValueError as exc: raise ValueError(f"{path}: source {spec_name!r}: {exc}") from exc try: - source = resolve_source_from_config(src_config) + # Slots written with the same complete config share one rebuild. + config_key = _json.dumps(src_config, sort_keys=True) + if config_key not in sources_by_config: + sources_by_config[config_key] = resolve_source_from_config( + src_config + ) + source = sources_by_config[config_key] if source is not None: # A rebuilt source its slot refuses (a file whose column types # changed) is one that could not be rebuilt (ITL-1112). @@ -1910,6 +2018,10 @@ def load( spec_name, ) + require_consistent_sources( + (f"slot {name!r}", source) for name, source in sources.items() + ) + # Reconstruct database effective_database = database unresolved_database: dict[str, Any] | None = None @@ -1994,7 +2106,8 @@ def load( ) job._unresolved_result_database = unresolved_result_database job._unresolved_database = unresolved_database - job._loaded = True + job._loaded_job_graph = True + pipeline._loaded_job_graph = True job._compiled_pipeline = pipeline # Mark compiled so save() / compiled_pipeline can be accessed. job._compiled = True @@ -2061,9 +2174,8 @@ def load( sjn = SourceJobNode._from_loaded_slot( # pyright: ignore[reportPrivateUsage] # the loader is the one caller bp_node, bound_source=sources.get(bp_node.name) ) + sjn._set_binding_owner(job) # pyright: ignore[reportPrivateUsage] # loading assigns the job's active slots job._persistent_node_map[node_hash] = sjn - if bp_node.name in sources: - job._sources_by_hash[node_hash] = sources[bp_node.name] elif isinstance(bp_node, _FunctionNode): descriptor = getattr(bp_node, "_descriptor", None) or {} diff --git a/src/orcapod/pipeline/loaded_side_effects.py b/src/orcapod/pipeline/loaded_side_effects.py index aa5182742..d77155a30 100644 --- a/src/orcapod/pipeline/loaded_side_effects.py +++ b/src/orcapod/pipeline/loaded_side_effects.py @@ -336,6 +336,8 @@ def run(self, *, load_only: bool = False) -> StreamView: Raises: RuntimeError: If ``load_only`` is false; nothing runs then. + InconsistentSourceError: If distinct source objects share a content + hash, or sources with one ID differ in schema or key columns. """ import sys diff --git a/src/orcapod/pipeline/restrictions.py b/src/orcapod/pipeline/restrictions.py index 3679d515f..ae3de57b1 100644 --- a/src/orcapod/pipeline/restrictions.py +++ b/src/orcapod/pipeline/restrictions.py @@ -6,8 +6,7 @@ This module holds every rule that reads them: - the walk from streams down to the sources they read (``restrictions_beneath``, - ``sources_read``), through a slot's bound source, a proxy's delegate and a cache's - source; + ``sources_read``), through a slot's bound source and a wrapper's live inputs; - the refusals: one source read under two restrictions in one pipeline (``require_one_restriction``), an operator node that caches over a restricted source (``refuse_restricted_operator_cache``), a ``CachedSource`` over one @@ -42,10 +41,11 @@ (``source_name``), its condition and its limit.""" -Rebinding: TypeAlias = "Sequence[tuple[SourceJobNode, StreamProtocol]]" +Rebinding: TypeAlias = "Sequence[tuple[SourceJobNode, StreamProtocol | None]]" """The sources a bind is about to bind: ``(slot, source)`` pairs, one per slot of the job that the bind changes. A slot is matched by object identity, never by name: a -source being bound can itself be a slot of another job, of the same name.""" +source being bound can itself be a slot of another job, of the same name. +``None`` unbinds the slot.""" def source_name(source: RootSource) -> str: @@ -106,21 +106,17 @@ def _inputs(stream: StreamProtocol) -> tuple[StreamProtocol, ...]: return tuple(upstream for upstream in upstreams if upstream is not None) -def _streams_beneath( +def streams_beneath( current: StreamProtocol, rebinding: Rebinding | None = None ) -> tuple[StreamProtocol, ...]: - """Return what ``current`` reads: the streams a restriction walk goes on to. - - A ``SourceJobNode`` reads its bound source (or, when it is one of the slots of - ``rebinding``, the source a bind is about to bind there), a bound - ``SourceProxy`` its delegate, a ``CachedSource`` the source it caches; any other - stream its ``upstreams``. A ``DerivedSource`` is a root: it reads the rows stored - for its origin, never its origin's sources, so the walk ends there, as at every - other root source. + """Return the streams ``current`` reads when a graph walk goes upstream. + + A job slot reads its bound source, with prospective bindings taking precedence. + Sources declare their live inputs themselves. Other streams read their + graph upstreams. """ from orcapod.core.nodes.source_node import SourceJobNode - from orcapod.core.sources.cached_source import CachedSource - from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.core.sources.base import RootSource if isinstance(current, SourceJobNode): bound = current.bound_source @@ -128,10 +124,8 @@ def _streams_beneath( if slot is current: bound = source return () if bound is None else (bound,) - if isinstance(current, SourceProxy): - return () if current.delegate is None else (current.delegate,) - if isinstance(current, CachedSource): - return (current.cached_source,) + if isinstance(current, RootSource): + return current.live_source_inputs or () return _inputs(current) @@ -141,8 +135,8 @@ def restrictions_beneath( ) -> frozenset[tuple[str, Restriction]]: """Return the restrictions of every source the streams read, order-free. - Walks down to the root sources (``_streams_beneath``: through a slot's bound - source, a proxy's delegate and a cache's source); each restricted root gives + Walks down to the root sources (through job bindings and live wrappers); + each restricted root gives ``(source name, restriction)``. Two results are equal when the same sources are restricted equally. @@ -165,7 +159,7 @@ def restrictions_beneath( restriction = restriction_of(current) if restriction is not None and isinstance(current, RootSource): found.add((source_name(current), restriction)) - pending.extend(_streams_beneath(current, rebinding)) + pending.extend(streams_beneath(current, rebinding)) return frozenset(found) @@ -186,13 +180,11 @@ def sources_read( """Return every root source the streams read, with its restriction. ``(content hash, source name, restriction or None)`` for each root source met by - ``_streams_beneath``, once per object. The content hash is the source's identity, + ``streams_beneath``, once per object. The content hash is the source's identity, which a restriction leaves unchanged, so it is the key of the one-restriction rule. ``rebinding``: the job's slots a bind is about to bind, with their sources. """ from orcapod.core.sources.base import RootSource - from orcapod.core.sources.cached_source import CachedSource - from orcapod.core.sources.source_proxy import SourceProxy found: list[tuple[str, str, Restriction | None]] = [] visited: list[StreamProtocol] = [] @@ -202,12 +194,7 @@ def sources_read( if any(current is seen for seen in visited): continue visited.append(current) - beneath = _streams_beneath(current, rebinding) - if ( - isinstance(current, RootSource) - and not isinstance(current, (CachedSource, SourceProxy)) - and not beneath - ): + if isinstance(current, RootSource) and current.live_source_inputs is None: found.append( ( current.content_hash().to_string(), @@ -215,7 +202,8 @@ def sources_read( restriction_of(current), ) ) - pending.extend(beneath) + else: + pending.extend(streams_beneath(current, rebinding)) return found @@ -465,10 +453,10 @@ def restrictions_in_force( elif (str(stream.label), entry) not in direct: direct.append((str(stream.label), entry)) if isinstance(stream, SourceJobNode): - pending.extend((inner, stream.name) for inner in _streams_beneath(stream)) + pending.extend((inner, stream.name) for inner in streams_beneath(stream)) else: # A slot bound to a stream over a source keeps its name down to it. - pending.extend((inner, slot) for inner in _streams_beneath(stream)) + pending.extend((inner, slot) for inner in streams_beneath(stream)) found = dict(slots) for label, entry in direct: if found.get(label) == entry: diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py new file mode 100644 index 000000000..b4cf85703 --- /dev/null +++ b/src/orcapod/pipeline/source_consistency.py @@ -0,0 +1,150 @@ +"""Validate source object registrations within one graph.""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import TYPE_CHECKING, cast + +from orcapod.errors import InconsistentSourceError +from orcapod.utils.schema_utils import arrow_schema_identity + +if TYPE_CHECKING: + from orcapod.core.sources.base import RootSource + from orcapod.pipeline.pod_invocation import PodInvocation + from orcapod.pipeline.restrictions import Rebinding + from orcapod.protocols.core_protocols import StreamProtocol + from orcapod.types import ContentHash + +SourceUse = tuple[str, "StreamProtocol"] + + +def invocation_source_uses(invocation: PodInvocation) -> Iterable[SourceUse]: + """Name the input streams of a recorded step for diagnostics.""" + label = invocation.label or getattr( + invocation.pod, "label", type(invocation.pod).__name__ + ) + for index, stream in enumerate(invocation.input_streams, 1): + name = f"step {label!r}" + if len(invocation.input_streams) > 1: + name += f" input {index}" + yield name, stream + + +def root_source_uses( + uses: Iterable[SourceUse], + rebinding: Rebinding = (), +) -> Iterable[tuple[str, RootSource]]: + """Walk to the source objects registered by the graph. + + A ``RootSource`` supplies the registered object and ends this walk even if it + reads live inputs. Registering those inputs too would make a cache conflict + with the source whose hash it preserves. Capture safety and restrictions + instead follow live reads through sources. + """ + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.sources.base import RootSource + + replacements = {id(slot): source for slot, source in rebinding} + visited: set[int] = set() + pending = list(uses) + pending.reverse() + while pending: + location, stream = pending.pop() + if id(stream) in visited: + continue + visited.add(id(stream)) + if isinstance(stream, RootSource): + yield location, stream + elif isinstance(stream, SourceJobNode): + bound = replacements.get(id(stream), stream.bound_source) + if bound is not None: + slot_use = f"slot {stream.name!r}" + if location != f"node {stream.label!r}": + slot_use = f"{location} via {slot_use}" + pending.append((slot_use, bound)) + else: + # Loaded nodes can have inputs that could not be reconstructed. + upstreams = cast("tuple[StreamProtocol | None, ...]", stream.upstreams) + for index in reversed(range(len(upstreams))): + upstream = upstreams[index] + if upstream is not None: + upstream_location = location + if len(upstreams) > 1: + upstream_location += f", {stream.label!r} input {index + 1}" + pending.append((upstream_location, upstream)) + + +def _comparison_schema(source: RootSource) -> tuple[ContentHash, ContentHash]: + """Use the live proxy schema for the comparison, even after an unbound read.""" + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.core.streams.base import typed_arrow_schemas + + if isinstance(source, SourceProxy) and source.is_bound: + # The cached schema can describe the unbound proxy's Python types. + schemas = typed_arrow_schemas(source, own=False) + else: + schemas = source.arrow_schemas + return arrow_schema_identity(*schemas, source.data_context) + + +def require_consistent_sources( + uses: Iterable[SourceUse], + rebinding: Rebinding = (), +) -> None: + """Require one object per content hash and one schema and key per source ID. + + Args: + uses: The graph's streams and where they are used. + rebinding: Prospective slot replacements to check before changing a binding. + + Raises: + InconsistentSourceError: Naming both locations and how to resolve the conflict. + """ + by_hash: dict[str, tuple[str, RootSource]] = {} + by_id: dict[str, list[tuple[str, RootSource]]] = {} + for location, source in root_source_uses(uses, rebinding): + content_hash = source.content_hash().to_string() + first_location, first = by_hash.setdefault(content_hash, (location, source)) + if first is not source: + reuse = "Build the source once and reuse the object" + if first.condition.equalities or source.condition.equalities: + reuse = "Call where() once and reuse the resulting source object" + remedy = f"{reuse}." + if first.source_id == source.source_id: + remedy += ( + " If the source ID contributes to the hash, give each source " + "its own source_id." + ) + raise InconsistentSourceError( + f"Source {source.source_id!r} has distinct source objects with one " + f"content hash in {first_location} and {location}. {remedy}" + ) + by_id.setdefault(source.source_id, []).append((location, source)) + + for source_id, group in by_id.items(): + if len(group) < 2: + continue + first_location, first = group[0] + schema = _comparison_schema(first) + for location, source in group[1:]: + if _comparison_schema(source) != schema: + raise InconsistentSourceError( + f"Source {source_id!r} has different schemas in {first_location} " + f"and {location}. Give the sources different source_id values." + ) + + known_keys = [ + (location, keys) + for location, source in group + if (keys := source._resolved_key_columns) is not None # pyright: ignore[reportPrivateUsage] # source consistency + ] + if known_keys: + first_location, first_keys = known_keys[0] + for location, keys in known_keys[1:]: + if keys != first_keys: + raise InconsistentSourceError( + f"Source {source_id!r} has different key columns " + f"(record_id_columns) in {first_location} and {location}. " + "Give the sources different source_id values. ITL-1506 " + "tracks distinct readings in distinct named slots." + ) diff --git a/src/orcapod/protocols/core_protocols/trackers.py b/src/orcapod/protocols/core_protocols/trackers.py index 614dd87e5..0abd90b32 100644 --- a/src/orcapod/protocols/core_protocols/trackers.py +++ b/src/orcapod/protocols/core_protocols/trackers.py @@ -1,16 +1,25 @@ +from __future__ import annotations + +from collections.abc import Callable from contextlib import AbstractContextManager -from typing import Protocol, runtime_checkable +from typing import TYPE_CHECKING, Protocol, runtime_checkable from orcapod.protocols.core_protocols.function_pod import FunctionPodProtocol from orcapod.protocols.core_protocols.operator_pod import OperatorPodProtocol from orcapod.protocols.core_protocols.side_effect_pod import SideEffectPodProtocol from orcapod.protocols.core_protocols.streams import StreamProtocol +if TYPE_CHECKING: + from orcapod.pipeline.pod_invocation import PodInvocation + @runtime_checkable class TrackerProtocol(Protocol): """ - Records kernel invocations and stream creation for computational graph tracking. + Internal contract for recording invocations and stream creation. + + Every tracker implements ``prepare_invocation()`` so the manager can validate + a capture across all active trackers before any tracker records it. Trackers are responsible for maintaining the computational graph by recording relationships between kernels, streams, and invocations. They enable: @@ -50,6 +59,20 @@ def is_active(self) -> bool: """ ... + def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: + """Validate an invocation without recording it. + + All checks that can refuse an invocation belong here. The manager calls + the returned callbacks only after every active tracker has accepted. + + Args: + invocation: The pod and inputs to record. + + Returns: + A callback that records the validated invocation. + """ + ... + def record_operator_pod_invocation( self, pod: OperatorPodProtocol, diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index dd691c62d..00790b7e8 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -1422,6 +1422,8 @@ def run(self, *, load_only: bool = False) -> StreamView: Raises: SideEffectLogDataContextError: As for ``execute``. OrcapodDatabaseWriteError: If committing the invocation log fails. + InconsistentSourceError: If distinct source objects share a content + hash, or sources with one ID differ in schema or key columns. """ import sys diff --git a/tests/test_core/data_tags/test_derived_source.py b/tests/test_core/data_tags/test_derived_source.py index 76a85fd7c..2ba5d0894 100644 --- a/tests/test_core/data_tags/test_derived_source.py +++ b/tests/test_core/data_tags/test_derived_source.py @@ -99,9 +99,10 @@ def _operator_job( ) -> PipelineJob: """A ``LOG`` join of the function node's output with itself filtered by ``unit``.""" job = PipelineJob(name=JOB, database=store) + source = _source() with job: - doubled = double.pod(_source(), label="double") - _ = Join()(doubled, _source().select_data_columns(["unit"]), label="joined") + doubled = double.pod(source, label="double") + _ = Join()(doubled, source.select_data_columns(["unit"]), label="joined") job.nodes["joined"].attach_databases( pipeline_database=store.at(JOB), cache_mode=CacheMode.LOG ) diff --git a/tests/test_core/sources/test_provisional_sources.py b/tests/test_core/sources/test_provisional_sources.py index 84c1bfc28..8c67b7eb0 100644 --- a/tests/test_core/sources/test_provisional_sources.py +++ b/tests/test_core/sources/test_provisional_sources.py @@ -227,9 +227,10 @@ def _ran_job() -> Any: from orcapod.operators import SelectDataColumns job = PipelineJob(name="derived", database=InMemoryArrowDatabase()) + origin = _origin() with job: - _total.pod(_origin(), label="total") - SelectDataColumns(["age", "weight"])(_origin(), label="picked") + _total.pod(origin, label="total") + SelectDataColumns(["age", "weight"])(origin, label="picked") job.run() return job diff --git a/tests/test_core/sources/test_spiraldb_table_source_ranges.py b/tests/test_core/sources/test_spiraldb_table_source_ranges.py index c47f0a0eb..3a5297636 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_ranges.py +++ b/tests/test_core/sources/test_spiraldb_table_source_ranges.py @@ -25,7 +25,7 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import DeltaTableDatabase -from orcapod.errors import SourceTooLargeError +from orcapod.errors import InconsistentSourceError, SourceTooLargeError from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.sources import SpiralDBTableSource from orcapod.types import Condition, col @@ -749,7 +749,7 @@ def same(n: int | None) -> int | None: return n job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: same.pod( events.where(col("unit") < 2).select_data_columns(["n"]), label="a" diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 65ccbf78a..0bf5b8d85 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -23,7 +23,7 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import DeltaTableDatabase -from orcapod.errors import RestrictedAggregationWarning +from orcapod.errors import InconsistentSourceError, RestrictedAggregationWarning from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.restrictions import restrictions_in_force from orcapod.core.sources.base import RootSource @@ -1098,7 +1098,7 @@ def second(channel: int | None) -> int | None: events = _source(source_id="events", tag_only_columns=True) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: first.pod(events.where(subject_id="m1"), label="first") second.pod(events.where(subject_id="m2"), label="second") @@ -1120,7 +1120,7 @@ def second(amplitude: float | None) -> float | None: m1 = events.where(subject_id="m1").select_data_columns(["amplitude"]) m2 = events.where(subject_id="m2").select_data_columns(["amplitude"]) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: first.pod(m1, label="first") second.pod(m2, label="second") @@ -1152,7 +1152,7 @@ def first(amplitude: float | None) -> float | None: events = _source(source_id="events", tag_only_columns=True) outside = events.where(**prebuilt).select_data_columns(["amplitude"]) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: if prebuilt_first: first.pod(outside, label="first") @@ -1166,22 +1166,22 @@ def first(amplitude: float | None) -> float | None: def test_a_stream_with_the_hash_of_an_equal_captured_output_is_accepted( self, project, tmp_path, prebuilt_first ): - """The same restriction, its conditions in another order, is one stream.""" + """Prebuilt and captured projections can reuse one restricted source.""" @function_pod(output_keys="a") def first(amplitude: float | None) -> float | None: """Return ``amplitude``.""" return amplitude - events = _source(source_id="events", tag_only_columns=True) - outside = events.where(flag=True, subject_id="m1").select_data_columns( - ["amplitude"] + events = _source(source_id="events", tag_only_columns=True).where( + flag=True, subject_id="m1" ) + outside = events.select_data_columns(["amplitude"]) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) with job: if prebuilt_first: first.pod(outside, label="first") - events.where(subject_id="m1", flag=True).select_data_columns(["amplitude"]) + events.select_data_columns(["amplitude"]) if not prebuilt_first: first.pod(outside, label="first") @@ -1222,7 +1222,7 @@ def test_two_inputs_of_one_invocation_are_checked(self, project): """One operator over two differently restricted sources of one table.""" events = _source(source_id="events", tag_only_columns=True) job = PipelineJob(name="two") - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: events.where(subject_id="m1").semi_join( events.where(subject_id="m2"), label="both" @@ -1232,7 +1232,7 @@ def test_two_inputs_of_one_invocation_are_checked(self, project): def test_one_restriction_twice_in_one_job_is_accepted( self, project, tmp_path, restrict ): - """Two source objects with the same restriction (or none) are one source.""" + """Two branches can reuse one source with or without a restriction.""" @function_pod(output_keys="a") def first(amplitude: float | None) -> float | None: @@ -1244,16 +1244,13 @@ def second(channel: int | None) -> int | None: """Return ``channel``.""" return channel - def events(*conditions: tuple[str, object]) -> SpiralDBTableSource: - """Return the events source, with ``conditions`` in the order given.""" - source = _source(source_id="events", tag_only_columns=True) - return source.where(dict(conditions)) if restrict else source - + events = _source(source_id="events", tag_only_columns=True) + if restrict: + events = events.where(subject_id="m1", flag=True) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) with job: - # The same conditions given in another order are the same restriction. - first.pod(events(("subject_id", "m1"), ("flag", True)), label="first") - second.pod(events(("flag", True), ("subject_id", "m1")), label="second") + first.pod(events, label="first") + second.pod(events, label="second") job.run() expected = [3] if restrict else [1, 2, 3, 4, 5] @@ -1293,7 +1290,7 @@ def second(channel: int | None) -> int | None: return channel job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: first.pod(_source(source_id="events", limit=1), label="first") second.pod(_source(source_id="events", limit=2), label="second") @@ -1498,6 +1495,38 @@ def test_equal_float_conditions_of_two_reads_are_refused(self, project, values): for value in values: events.where(amplitude=value) + @pytest.mark.parametrize("values", [(0.0, 0.0), (0.5, 0.5)]) + def test_equal_float_conditions_still_require_one_source_object( + self, project, tmp_path, values + ): + """Equal conditions can belong to distinct source objects.""" + + @function_pod(output_keys="a") + def first(amplitude: float | None) -> float | None: + """Return ``amplitude``.""" + return amplitude + + @function_pod(output_keys="b") + def second(channel: int | None) -> int | None: + """Return ``channel``.""" + return channel + + events = _source(source_id="events", tag_only_columns=True) + first_read = events.where(amplitude=values[0]) + second_read = events.where(amplitude=values[1]) + assert first_read.condition == second_read.condition + assert first_read.content_hash() == second_read.content_hash() + job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) + with job: + first.pod(first_read, label="first") + with pytest.raises(InconsistentSourceError, match=r"Call where\(\) once"): + second.pod(second_read, label="second") + second.pod(first_read, label="second") + + summary = job.run() + + assert summary.conditions == {"events": Condition.of(amplitude=values[0])} + _RESTRICTED_FORMS: dict[str, tuple[Callable[[], SpiralDBTableSource], list[str]]] = { "a condition": (lambda: _source().where(subject_id="m2"), ["subject_id='m2'"]), @@ -1692,14 +1721,13 @@ def test_binding_a_restricted_source_under_a_cache_is_refused( def test_a_slot_rebound_directly_is_refused_when_the_run_starts( self, project, tmp_path, mode, run ): - """A source set on the slot itself (no job to check it) is refused by the - run, sync or async, before any source is read or anything written.""" + """Invalid job state is refused at run time before any reads or writes.""" events = self._events() folder = tmp_path / "store" store = DeltaTableDatabase(folder) job = self._job(store, events) self._cache(job, "rename", mode, store) - job.nodes["events"].bound_source = events.where(subject_id="m1") + job.nodes["events"]._bind(events.where(subject_id="m1")) scans = len(fake_spiral_sdk.scan_log) with pytest.raises(ValueError, match="cannot cache a restricted read"): @@ -1874,8 +1902,8 @@ def test_async_execute_over_a_restricted_slot_is_refused( folder = tmp_path / "s" node = self._logged_node(DeltaTableDatabase(folder), mode) (slot,) = node.upstreams - slot.bound_source = _source(source_id="events", tag_only_columns=True).where( - subject_id="m1" + slot._bind( + _source(source_id="events", tag_only_columns=True).where(subject_id="m1") ) inputs, output = Channel(buffer_size=8), Channel(buffer_size=8) @@ -1972,8 +2000,8 @@ class TestRestrictionThroughWrappers: CodeRabbit (PR 435): a proxy bound to a restricted source has no condition of its own and binds by identity, which a restriction leaves unchanged, so the walks must look through it. Wrappers checked: ``SourceJobNode`` (bound source), - ``SourceProxy`` (delegate), ``CachedSource`` (cached source); a ``DerivedSource`` - is a root (it reads stored rows, not its origin's sources). + ``SourceProxy`` (delegate), ``CachedSource`` (cached source), and + ``DerivedSource`` when it reads a source live. """ @staticmethod @@ -1983,6 +2011,26 @@ def _bound_proxy(restriction: str) -> Any: proxy.bind(restricted) return proxy + def test_live_derived_sources_expose_their_origins_restrictions( + self, project, tmp_path + ): + from orcapod.sources import DerivedSource + + def derive(subject: str) -> DerivedSource: + return DerivedSource( + _events().where(subject_id=subject), + tags_as_data={"subject_id": "copied"}, + source_id=f"copy_{subject}", + ) + + first, second = derive("m1"), derive("m2") + with PipelineJob(database=DeltaTableDatabase(tmp_path / "store")) as job: + first.map_data({"amplitude": "renamed"}, label="first") + with pytest.raises(ValueError, match="two different restrictions"): + second.map_data({"amplitude": "renamed"}, label="second") + + assert job.run().conditions == {"copy_m1": Condition.of(subject_id="m1")} + @staticmethod def _cached_job(store: DeltaTableDatabase, mode: CacheMode) -> PipelineJob: job = PipelineJob(name="events", database=store) @@ -2036,7 +2084,7 @@ def test_a_proxy_and_a_source_restricted_two_ways_are_refused_at_capture( other = _events().where(subject_id="m2") first, second = (proxy, other) if order == "proxy first" else (other, proxy) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: first.select_data_columns(["amplitude"], label="a") second.select_data_columns(["channel"], label="b") @@ -2105,7 +2153,7 @@ def test_nothing_changes_and_a_second_bind_behaves_alike( store = DeltaTableDatabase(tmp_path / "s") job = TestRestrictionThroughWrappers._cached_job(store, mode) node = job.nodes["rename"] - job.nodes["events"].bound_source = _events().where(subject_id="m1") + job.nodes["events"]._bind(_events().where(subject_id="m1")) before = (job.database, node._pipeline_database) # pyright: ignore[reportPrivateUsage] other = DeltaTableDatabase(tmp_path / "other") @@ -2185,7 +2233,7 @@ def keep(amplitude: float | None) -> float | None: return amplitude job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: chains[first_chain](_events().where(subject_id="m1")) chains[second_chain](second()) @@ -2210,7 +2258,7 @@ def test_chains_built_before_the_job_over_two_restrictions_are_refused( m2 = built[chains[1]](_events().where(subject_id="m2")) first, second = (m1, m2) if order == "m1 first" else (m2, m1) job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): with job: first.semi_join(second, label="both") @@ -2221,22 +2269,18 @@ def test_one_restriction_through_two_chains_is_accepted( chains = self._chains() names = ["select", "drop"] if order == "select first" else ["drop", "select"] job = PipelineJob(name="one", database=DeltaTableDatabase(tmp_path / "s")) + events = _events().where(flag=True, subject_id="m1") with job: for name in names: - chains[name](_events().where(flag=True, subject_id="m1")) + chains[name](events) summary = job.run() assert summary.conditions == { "events": Condition.of(subject_id="m1", flag=True) } -class TestRestrictionsCheckedLive: - """The one-restriction rule reads what each stream reads now (CodeRabbit, PR 435). - - A slot rebound during the capture changes what the streams recorded from it read, - so nothing is kept from an earlier check: every invocation checks every stream - the pipeline holds with its own inputs, and compilation checks them again. - """ +class TestForeignRestrictedSlots: + """A job refuses foreign slots even when their sources are restricted.""" @staticmethod def _slot(source: Any) -> Any: @@ -2245,11 +2289,9 @@ def _slot(source: Any) -> Any: return SourceJobNode.from_stream(source) @pytest.mark.parametrize("step", ["select", "drop"]) - def test_a_slot_rebound_between_invocations_is_refused_at_the_next( + def test_a_foreign_slot_is_refused_before_its_restriction_changes( self, project, tmp_path, step ): - """A projection from a slot bound to m1, the slot rebound to m2, then a - projection from the m1 source: compiled, both would read m2's rows.""" m1 = _events().where(subject_id="m1") slot = self._slot(m1) later = { @@ -2257,34 +2299,41 @@ def test_a_slot_rebound_between_invocations_is_refused_at_the_next( "drop": lambda s: s.drop_data_columns(["note"]), }[step] job = PipelineJob(name="live", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): - with job: + with job: + with pytest.raises(InconsistentSourceError, match="not supported yet"): MapData({"channel": "lane"})(slot) - slot.bound_source = _events().where(subject_id="m2") - later(m1) + slot.bound_source = _events().where(subject_id="m2") + later(m1) + assert job.sources["events"] is m1 + assert job.run().conditions == {"events": Condition.of(subject_id="m1")} - def test_a_slot_rebound_after_the_last_invocation_is_refused_at_compile( + def test_a_foreign_slot_does_not_replace_a_captured_restricted_source( self, project, tmp_path ): m1 = _events().where(subject_id="m1") slot = self._slot(m1) job = PipelineJob(name="live", database=DeltaTableDatabase(tmp_path / "s")) - with pytest.raises(ValueError, match="different rows in one pipeline"): - with job: + with job: + m1.select_data_columns(["amplitude"]) + with pytest.raises(InconsistentSourceError, match="not supported yet"): MapData({"channel": "lane"})(slot) - m1.select_data_columns(["amplitude"]) - slot.bound_source = _events().where(subject_id="m2") + slot.bound_source = _events().where(subject_id="m2") + assert job.sources["events"] is m1 + assert job.run().conditions == {"events": Condition.of(subject_id="m1")} - def test_a_slot_rebound_to_an_equal_restriction_is_accepted( + def test_a_foreign_slot_with_an_equal_restriction_is_refused( self, project, tmp_path ): m1 = _events().where(subject_id="m1") slot = self._slot(m1) job = PipelineJob(name="live", database=DeltaTableDatabase(tmp_path / "s")) with job: - MapData({"channel": "lane"})(slot) - slot.bound_source = _events().where(subject_id="m1") + replacement = _events().where(subject_id="m1") + slot.bound_source = replacement + with pytest.raises(InconsistentSourceError, match="not supported yet"): + MapData({"channel": "lane"})(slot) m1.select_data_columns(["amplitude"]) + assert job.sources["events"] is m1 assert job.run().conditions == {"events": Condition.of(subject_id="m1")} @@ -2344,7 +2393,9 @@ def test_a_bind_reading_a_source_two_ways_is_refused_before_anything_changes( other_db = DeltaTableDatabase(tmp_path / "other") for _ in range(2): - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): job.bind(sources={"events": stream}, database=other_db) assert job.database is before[0] assert slot.bound_source is before[1] @@ -2354,12 +2405,12 @@ def test_a_slot_rebound_directly_is_refused_when_the_run_starts( self, project, other_table, tmp_path, run ): job = self._job(tmp_path, self._others().where(subject_id="m1")) - job.nodes["events"].bound_source = _events().semi_join( - self._others().where(subject_id="m2") + job.nodes["events"]._bind( + _events().semi_join(self._others().where(subject_id="m2")) ) scans = len(fake_spiral_sdk.scan_log) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): if run == "job.run": job.run() elif run == "job.run_async": @@ -2374,9 +2425,9 @@ def test_two_tables_restricted_once_each_are_accepted( ): """Two sources, one restriction each: no conflict; the run reads only the rows both restrictions keep.""" - job = self._job(tmp_path, self._others().where(subject_id="m2")) - events = _events().where(subject_id="m2") others = self._others().where(subject_id="m2") + job = self._job(tmp_path, others) + events = _events().where(subject_id="m2") stream = ( events.semi_join(others) if order == "events first" @@ -2422,14 +2473,19 @@ def _pick(source: Any) -> Any: return source.select_data_columns(["amplitude", "flag"]) def _job(self, tmp_path: Path) -> PipelineJob: - from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.nodes.source_node import SourceJobNode, SourceNode m1 = _events().where(subject_id="m1") - pick = SourceJobNode.from_stream(self._pick(m1), name="pick") + selected = self._pick(m1) + borrowed = SourceJobNode.from_stream(selected, name="pick") + pick = SourceNode.from_stream(selected, name="pick") job = PipelineJob(name="two", database=DeltaTableDatabase(tmp_path / "s")) with job: m1.map_data({"amplitude": "a"}, label="rename") + with pytest.raises(InconsistentSourceError, match="not supported yet"): + MapData({"amplitude": "b"})(borrowed) MapData({"amplitude": "b"})(pick) + job.bind(sources={"pick": selected}) return job @staticmethod @@ -2437,12 +2493,12 @@ def _bound(job: PipelineJob) -> tuple[Any, Any]: return job.nodes["events"].bound_source, job.nodes["pick"].bound_source @pytest.mark.parametrize("order", ["events first", "pick first"]) - def test_equivalent_restrictions_for_both_slots_are_accepted( + def test_one_restricted_object_for_both_slots_is_accepted( self, project, tmp_path, order ): job = self._job(tmp_path) events = _events().where(subject_id="m2", flag=True) - pick = self._pick(_events().where(flag=True).where(subject_id="m2")) + pick = self._pick(events) sources: dict[str, Any] = {"events": events, "pick": pick} if order == "pick first": sources = dict(reversed(sources.items())) @@ -2483,7 +2539,9 @@ def test_conflicting_restrictions_are_refused_and_nothing_changes( other = DeltaTableDatabase(tmp_path / "other") for _ in range(2): - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): job.bind(sources=sources, database=other) after = (job.database, *self._bound(job)) assert all(a is b for a, b in zip(after, before, strict=True)) @@ -2497,17 +2555,17 @@ def test_one_slot_changed_away_from_the_other_is_refused( m2 = _events().where(subject_id="m2") new = m2 if slot == "events" else self._pick(m2) - with pytest.raises(ValueError, match="different rows in one pipeline"): + with pytest.raises(InconsistentSourceError, match="distinct source objects"): job.bind(sources={slot: new}) after = self._bound(job) assert after[0] is before[0] and after[1] is before[1] @pytest.mark.parametrize("slot", ["events", "pick"]) - def test_one_slot_changed_to_an_equal_restriction_is_accepted( + def test_one_slot_rebound_to_the_same_restricted_source_is_accepted( self, project, tmp_path, slot ): job = self._job(tmp_path) - m1 = _events().where(subject_id="m1") + m1, _ = self._bound(job) new = m1 if slot == "events" else self._pick(m1) job.bind(sources={slot: new}) diff --git a/tests/test_pipeline/fixtures/itl_1469_main_shared_source.json b/tests/test_pipeline/fixtures/itl_1469_main_shared_source.json new file mode 100644 index 000000000..fc87518a5 --- /dev/null +++ b/tests/test_pipeline/fixtures/itl_1469_main_shared_source.json @@ -0,0 +1,310 @@ +{ + "orcapod_pipeline_job_version": "0.4.0", + "orcapod_version": "0.4.0rc8.dev23+ga40296cb5.d20261127", + "run": { + "run_id": null, + "status": "pending", + "unbound_sources": [], + "node_job_content_hashes": { + "result_b": "semantic_v1:4883ca3500eca6bfde3021cbb145483ddb180085bd756be99cadf05d1c5fbb62", + "result_a": "semantic_v1:0e509b410605f3c4b76310e3269afe91275f3d25fd7670447644077c2e51f90a" + } + }, + "pipeline": { + "orcapod_pipeline_version": "0.4.0", + "orcapod_version": "0.4.0rc8.dev23+ga40296cb5.d20261127", + "pipeline": { + "name": [ + "legacy_shared_source" + ] + }, + "nodes": { + "semantic_v1:cd7048c441163cf717c33b17636f39387d979ca491e0669317d2ee4d877c4cb2": { + "node_type": "source", + "label": "a", + "content_hash": "semantic_v1:cd7048c441163cf717c33b17636f39387d979ca491e0669317d2ee4d877c4cb2", + "pipeline_hash": "semantic_v1:21bd6a19a207bf8c14f0f39eb30c670608059cb59de15f5a1bfcc275b23caa44", + "output_schema": { + "tag": { + "t1": "large_string", + "t2": "large_string" + }, + "data": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "source_node", + "a" + ], + "data_context_key": "std:v1:default", + "config": null, + "source_config": { + "source_type": "node", + "name": "a", + "tag_schema": { + "t1": "large_string", + "t2": "large_string" + }, + "data_schema": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "reconstructable": true + }, + "semantic_v1:e7b8e6eead280bf3de166e930850b9844b6d29416c75c8a08b0567edc2fd5072": { + "node_type": "source", + "label": "b", + "content_hash": "semantic_v1:e7b8e6eead280bf3de166e930850b9844b6d29416c75c8a08b0567edc2fd5072", + "pipeline_hash": "semantic_v1:21bd6a19a207bf8c14f0f39eb30c670608059cb59de15f5a1bfcc275b23caa44", + "output_schema": { + "tag": { + "t1": "large_string", + "t2": "large_string" + }, + "data": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "source_node", + "b" + ], + "data_context_key": "std:v1:default", + "config": null, + "source_config": { + "source_type": "node", + "name": "b", + "tag_schema": { + "t1": "large_string", + "t2": "large_string" + }, + "data_schema": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "reconstructable": true + }, + "semantic_v1:35ebef3ad6fab56bcb5a830e63f05c96cd8614c3617f54db65daa4334acd81c7": { + "node_type": "function", + "label": "result_b", + "content_hash": "semantic_v1:35ebef3ad6fab56bcb5a830e63f05c96cd8614c3617f54db65daa4334acd81c7", + "pipeline_hash": "semantic_v1:6ba45e187c1d9f4c70471a461d00119370d652c9a19f084c996fef929b1cb272", + "output_schema": { + "tag": { + "t1": "large_string", + "t2": "large_string" + }, + "data": { + "out": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "subtract", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "data_context_key": "std:v1:default", + "config": null, + "function_config": { + "uri": [ + "subtract", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "data_function": { + "data_function_type_id": "python.function.v1", + "uri": [ + "subtract", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "config": { + "module_path": "__main__", + "callable_name": "subtract", + "version": "v0.0", + "input_data_schema": { + "x": "", + "y": "" + }, + "output_data_schema": { + "out": "" + }, + "output_keys": [ + "out" + ] + } + }, + "pod_config": null, + "ctx_arg_name": null + }, + "table_scope": "pipeline_hash", + "fall_through_tags": [] + }, + "semantic_v1:ed95f485c964d7d06671c14d6a0741ef9108338e5276873a830a83bc2fde0fee": { + "node_type": "function", + "label": "result_a", + "content_hash": "semantic_v1:ed95f485c964d7d06671c14d6a0741ef9108338e5276873a830a83bc2fde0fee", + "pipeline_hash": "semantic_v1:b1d774df931735c498e6ae6c33f270acf67a3f5c547127cf726114e58c0a295f", + "output_schema": { + "tag": { + "t1": "large_string", + "t2": "large_string" + }, + "data": { + "out": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "add", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "data_context_key": "std:v1:default", + "config": null, + "function_config": { + "uri": [ + "add", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "data_function": { + "data_function_type_id": "python.function.v1", + "uri": [ + "add", + "8ec7327fae9a46cdb6c57a16d8634c52ca3a594e50df2da4e5833143ad63618b", + "v0", + "python.function.v1" + ], + "config": { + "module_path": "__main__", + "callable_name": "add", + "version": "v0.0", + "input_data_schema": { + "x": "", + "y": "" + }, + "output_data_schema": { + "out": "" + }, + "output_keys": [ + "out" + ] + } + }, + "pod_config": null, + "ctx_arg_name": null + }, + "table_scope": "pipeline_hash", + "fall_through_tags": [] + } + }, + "edges": [ + [ + "semantic_v1:cd7048c441163cf717c33b17636f39387d979ca491e0669317d2ee4d877c4cb2", + "semantic_v1:ed95f485c964d7d06671c14d6a0741ef9108338e5276873a830a83bc2fde0fee" + ], + [ + "semantic_v1:e7b8e6eead280bf3de166e930850b9844b6d29416c75c8a08b0567edc2fd5072", + "semantic_v1:35ebef3ad6fab56bcb5a830e63f05c96cd8614c3617f54db65daa4334acd81c7" + ] + ] + }, + "bindings": { + "sources": { + "a": { + "source_type": "csv", + "file_path": "shared.csv", + "tag_columns": [ + "t1", + "t2" + ], + "tag_only_columns": true, + "system_tag_columns": [], + "record_id_columns": null, + "source_name": "shared", + "source_name_given": true, + "source_version": 1, + "full_source_id": "csv_v1:shared", + "content_hash": "semantic_v1:7db9f47918267ecf78b37089217b1e009ddb5093b9a52463c174c1e032a033f4", + "pipeline_hash": "semantic_v1:21bd6a19a207bf8c14f0f39eb30c670608059cb59de15f5a1bfcc275b23caa44", + "tag_schema": { + "t1": "large_string", + "t2": "large_string" + }, + "data_schema": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "b": { + "source_type": "csv", + "file_path": "shared.csv", + "tag_columns": [ + "t1", + "t2" + ], + "tag_only_columns": true, + "system_tag_columns": [], + "record_id_columns": null, + "source_name": "shared", + "source_name_given": true, + "source_version": 1, + "full_source_id": "csv_v1:shared", + "content_hash": "semantic_v1:7db9f47918267ecf78b37089217b1e009ddb5093b9a52463c174c1e032a033f4", + "pipeline_hash": "semantic_v1:21bd6a19a207bf8c14f0f39eb30c670608059cb59de15f5a1bfcc275b23caa44", + "tag_schema": { + "t1": "large_string", + "t2": "large_string" + }, + "data_schema": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + } + }, + "database": null, + "result_database": null + } +} \ No newline at end of file diff --git a/tests/test_pipeline/loaded_job/test_loaded_load_only.py b/tests/test_pipeline/loaded_job/test_loaded_load_only.py index da6517734..f4b2a86c3 100644 --- a/tests/test_pipeline/loaded_job/test_loaded_load_only.py +++ b/tests/test_pipeline/loaded_job/test_loaded_load_only.py @@ -10,6 +10,7 @@ from __future__ import annotations import asyncio +from contextlib import ExitStack from pathlib import Path from typing import Any @@ -17,9 +18,13 @@ import pytest from orcapod import PipelineJob, function_pod -from orcapod.core.operators import Join +from orcapod.core.function_pod import FunctionPod +from orcapod.core.nodes.source_node import SourceJobNode +from orcapod.core.operators import DropNulls, Join from orcapod.core.streams import ViewStatus +from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER from orcapod.databases import InMemoryArrowDatabase +from orcapod.side_effects import SideEffectPod from orcapod.sources import ArrowTableSource, CSVSource, DictSource from orcapod.types import CacheMode @@ -101,6 +106,202 @@ def _bound(path: Path, db: Any) -> PipelineJob: return loaded +@pytest.fixture +def loaded_csv_job(tmp_path: Path) -> tuple[PipelineJob, CSVSource, CSVSource]: + """Load a two-slot job saved after one of its CSV sources was replaced.""" + sources = [] + for source_id, value in (("first", 2), ("second", 3), ("replacement", 5)): + path = tmp_path / f"{source_id}.csv" + path.write_text(f"id,x\n0,{value}\n") + sources.append( + CSVSource( + str(path), + tag_columns=["id"], + tag_only_columns=True, + source_id=source_id, + ) + ) + first, second, replacement = sources + database = InMemoryArrowDatabase() + job = PipelineJob(name=JOB, database=database) + with job: + double.pod(first, label="left") + double.pod(second, label="right") + job.run() + job.bind(sources={"first": replacement}) + job.run() + saved = tmp_path / "two-slots.json" + job.save(saved) + return PipelineJob.load(saved, database=database), first, replacement + + +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +@pytest.mark.parametrize("operation", ["capture", "record", "compile"]) +def test_loaded_job_refuses_graph_changes( + loaded_csv_job: tuple[PipelineJob, CSVSource, CSVSource], + operation: str, + orchestrator: str, +) -> None: + """A refused edit keeps both slots, their bindings, and held results.""" + loaded, first, _ = loaded_csv_job + held_run = loaded.run(load_only=True) + nodes = dict(loaded.nodes) + dag = loaded.dag + sources = loaded.sources + bindings = { + label: node.bound_source + for label, node in nodes.items() + if isinstance(node, SourceJobNode) + } + assert set(bindings) == {"first", "second"} + assert nodes["left"].as_table()["dbl"].to_pylist() == [10] + assert nodes["right"].as_table()["dbl"].to_pylist() == [6] + + with pytest.raises(RuntimeError, match=r"ITL-1560"): + if operation == "capture": + with loaded: + double.pod(first, label="extra") + elif operation == "record": + pod = double.pod + assert isinstance(pod, FunctionPod) + live = PipelineJob() + with live: + double.pod(first, label="live") + foreign = live.nodes["first"] + assert isinstance(foreign, SourceJobNode) + # The loaded-job refusal takes precedence over the foreign-slot check. + loaded.record_function_pod_invocation(pod, foreign, label="extra") + else: + loaded.compile() + + assert not loaded.is_active() + assert loaded.nodes.keys() == nodes.keys() + assert all(loaded.nodes[label] is node for label, node in nodes.items()) + assert loaded.dag is dag + assert loaded.sources.keys() == sources.keys() + assert all(loaded.sources[name] is source for name, source in sources.items()) + for label, binding in bindings.items(): + node = loaded.nodes[label] + assert isinstance(node, SourceJobNode) + assert node.bound_source is binding + assert loaded.last_run is held_run + assert loaded.nodes["left"].as_table()["dbl"].to_pylist() == [10] + assert loaded.nodes["right"].as_table()["dbl"].to_pylist() == [6] + + if orchestrator == "sync": + summary = loaded.run(load_only=True) + else: + summary = asyncio.run(loaded.run_async(load_only=True)) + assert summary.load_only + assert summary.nodes["left"].held == summary.nodes["right"].held == 1 + assert loaded.nodes["left"].as_table()["dbl"].to_pylist() == [10] + assert loaded.nodes["right"].as_table()["dbl"].to_pylist() == [6] + + +def test_loaded_job_can_still_bind_sources( + loaded_csv_job: tuple[PipelineJob, CSVSource, CSVSource], +) -> None: + """Both binding paths keep the loaded graph usable for load-only runs.""" + loaded, first, replacement = loaded_csv_job + nodes = dict(loaded.nodes) + slot = nodes["first"] + assert isinstance(slot, SourceJobNode) + loaded.bind(sources={"first": first}) + assert slot.bound_source is loaded.sources["first"] is first + loaded.run(load_only=True) + assert loaded.nodes["left"].as_table()["dbl"].to_pylist() == [4] + assert loaded.nodes["right"].as_table()["dbl"].to_pylist() == [6] + + slot.bound_source = replacement + assert slot.bound_source is replacement + loaded.run(load_only=True) + assert loaded.nodes["left"].as_table()["dbl"].to_pylist() == [10] + assert loaded.nodes["right"].as_table()["dbl"].to_pylist() == [6] + assert loaded.nodes.keys() == nodes.keys() + assert all(loaded.nodes[label] is node for label, node in nodes.items()) + + +@pytest.mark.parametrize("loaded_first", [False, True]) +@pytest.mark.parametrize("kind", ["function", "operator", "side_effect"]) +def test_loaded_job_refusal_leaves_every_active_job_unchanged( + loaded_csv_job: tuple[PipelineJob, CSVSource, CSVSource], + loaded_first: bool, + kind: str, +) -> None: + """Validate every target of a capture before recording in any job.""" + loaded, first, replacement = loaded_csv_job + loaded_nodes = loaded.nodes + live = PipelineJob() + with live: + double.pod(first, label="kept") + live_nodes = live.nodes + live_graph = (set(live.graph.nodes), set(live.graph.edges)) + + def deliver(ctx: Any, x: int) -> None: + """A side-effect function whose invocation can be recorded.""" + + manager = DEFAULT_TRACKER_MANAGER + pod = double.pod + assert isinstance(pod, FunctionPod) + with ExitStack() as stack: + if not loaded_first: + stack.enter_context(live) + loaded.set_active(True) + stack.callback(loaded.set_active, False) + if loaded_first: + stack.enter_context(live) + with pytest.raises(RuntimeError, match="ITL-1560"): + if kind == "function": + manager.record_function_pod_invocation(pod, replacement, label="extra") + elif kind == "operator": + manager.record_operator_pod_invocation( + DropNulls(), (replacement,), label="extra" + ) + else: + manager.record_side_effect_pod_invocation( + SideEffectPod(deliver), replacement, label="extra" + ) + assert all(live.nodes[label] is node for label, node in live_nodes.items()) + + assert (set(live.graph.nodes), set(live.graph.edges)) == live_graph + assert live.nodes.keys() == live_nodes.keys() + assert loaded.nodes == loaded_nodes + + +@pytest.mark.parametrize("operation", ["compile", "capture", "record"]) +def test_loaded_job_blueprint_refuses_edits_and_preserves_saved_graph( + loaded_csv_job: tuple[PipelineJob, CSVSource, CSVSource], + tmp_path: Path, + operation: str, +) -> None: + """The exposed blueprint keeps the graph that save writes.""" + loaded, first, _ = loaded_csv_job + blueprint = loaded.pipeline + nodes = blueprint.nodes + edges = set(blueprint.graph.edges) + pod = double.pod + assert isinstance(pod, FunctionPod) + with pytest.raises(RuntimeError, match="ITL-1560"): + if operation == "compile": + blueprint.compile() + elif operation == "capture": + with blueprint: + double.pod(first, label="extra") + else: + blueprint.record_function_pod_invocation(pod, first, label="extra") + assert blueprint.nodes == nodes + assert set(blueprint.graph.edges) == edges + + saved = tmp_path / "saved-again.json" + loaded.save(saved) + reloaded = PipelineJob.load(saved, database=loaded.database) + assert reloaded.nodes.keys() == loaded.nodes.keys() + assert set(reloaded.pipeline.graph.edges) == edges + reloaded.run(load_only=True) + assert reloaded.nodes["left"].as_table()["dbl"].to_pylist() == [10] + assert reloaded.nodes["right"].as_table()["dbl"].to_pylist() == [6] + + @pytest.mark.parametrize("orchestrator", ["sync", "async"]) def test_a_load_only_run_fills_a_loaded_job_and_writes_nothing( tmp_path: Path, orchestrator: str diff --git a/tests/test_pipeline/test_job_node_rows_after_run.py b/tests/test_pipeline/test_job_node_rows_after_run.py index 465674b6d..7084498a0 100644 --- a/tests/test_pipeline/test_job_node_rows_after_run.py +++ b/tests/test_pipeline/test_job_node_rows_after_run.py @@ -86,10 +86,11 @@ def _source(data: list[dict[str, int]]) -> DictSource: def _build(data: list[dict[str, int]], db: Any) -> PipelineJob: """Return a job over ``db``: ``rowwise``, ``downstream`` of it, and ``grouped``.""" job = PipelineJob(name="itl1093", database=db) + source = _source(data) with job: - rowwise = inc.pod(_source(data), label="rowwise") + rowwise = inc.pod(source, label="rowwise") dbl.pod(rowwise, label="downstream") - total.pod(_source(data).group_by("g"), label="grouped") + total.pod(source.group_by("g"), label="grouped") return job diff --git a/tests/test_pipeline/test_pipeline_base_recording.py b/tests/test_pipeline/test_pipeline_base_recording.py index 577038223..770e23d25 100644 --- a/tests/test_pipeline/test_pipeline_base_recording.py +++ b/tests/test_pipeline/test_pipeline_base_recording.py @@ -15,6 +15,15 @@ from orcapod.core.sources import ArrowTableSource from orcapod.pipeline import Pipeline +from ..test_core.operators.several_items import ( + DATA_FIRST_REVERSED, + MAIN, + P, + PLAIN, + Arrangement, + make_source, +) + def _src(tag_col: str, data_col: str) -> ArrowTableSource: table = pa.table( @@ -208,43 +217,25 @@ def test_explicit_source_id_overrides_hash_name(self): ) assert names == ["left_input", "right_input"] - def test_same_source_id_different_schema_raises_inconsistent_source_error(self): + @pytest.mark.parametrize("reverse", [False, True]) + def test_same_source_id_different_schema_raises_inconsistent_source_error( + self, reverse: bool + ) -> None: """Two sources with the same source_id but different schemas raise an error.""" from orcapod.errors import InconsistentSourceError - s1 = ArrowTableSource( - pa.table( - { - "key": pa.array(["a"], type=pa.large_string()), - "value": pa.array([1], type=pa.int64()), - } - ), - tag_columns=["key"], - tag_only_columns=True, - source_id="shared_id", - infer_nullable=True, - ) - s2 = ArrowTableSource( - pa.table( - { - "key": pa.array(["a"], type=pa.large_string()), - "score": pa.array( - [1.0], type=pa.float64() - ), # different data column - } - ), - tag_columns=["key"], - tag_only_columns=True, + main = make_source(MAIN, source_id="shared_id") + partner = make_source( + P, + Arrangement(tuple(reversed(P.tags)), DATA_FIRST_REVERSED, PLAIN), source_id="shared_id", - infer_nullable=True, ) + inputs = (partner, main) if reverse else (main, partner) join = Join() pipeline = Pipeline(name="test", auto_compile=False) - with pipeline: - join(s1, s2, label="joined") - with pytest.raises(InconsistentSourceError, match="shared_id"): - pipeline.compile() + with pipeline: + join(*inputs, label="joined") class TestRecordOperatorPodInvocation: diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py new file mode 100644 index 000000000..f3c489d19 --- /dev/null +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -0,0 +1,717 @@ +"""Source registration and source ID conflicts (ITL-1469).""" + +from __future__ import annotations + +import itertools +import json +from pathlib import Path + +import pyarrow as pa +import pytest + +from orcapod import Pipeline, PipelineJob, function_pod +from orcapod.core.function_pod import _FunctionPodBase +from orcapod.core.sources.base import RootSource +from orcapod.core.sources.source_proxy import SourceProxy +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ( + InconsistentSourceError, + SourceSlotNameCollisionError, +) +from orcapod.operators import SemiJoin +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.source_consistency import require_consistent_sources +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator +from orcapod.sources import ( + ArrowTableSource, + CSVSource, + DataFrameSource, + DerivedSource, + DictSource, + ListSource, +) + +from ..test_core.operators.several_items import ( + DATA_FIRST_REVERSED, + MIXED, + P, + PLAIN, + ROLES, + TAGS_FIRST, + Arrangement, + make_table, +) + + +@function_pod(output_keys="out") +def increment(x: int) -> int: + return x + 1 + + +@function_pod(output_keys="out") +def increment_again(x: int) -> int: + return x + 2 + + +@function_pod(output_keys="out") +def both(x: int, y: int) -> int: + return x + y + + +@function_pod(output_keys="out") +def with_pair(p1: int, p2: str) -> int: + return p1 + len(p2) + + +@function_pod(output_keys="out") +def with_copy(x: int, tag_value: str) -> int: + return x + len(tag_value) + + +@function_pod(output_keys="out") +def with_string(x: str) -> int: + return len(x) + + +@function_pod(output_keys="next") +def consume_output(out: int) -> int: + return out * 2 + + +def _dict(x: int, name: str = "shared") -> DictSource: + return DictSource(data=[{"x": x}], source_id=name) + + +def _refused( + first: RootSource, + second: RootSource, + graph: Pipeline | PipelineJob, + pod: _FunctionPodBase = increment.pod, +) -> None: + with graph: + pod(first, label="fa") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + pod(second, label="fb") + for part in (first.source_id, "fa", "fb", "reuse"): + assert part in str(error.value) + assert "fb" not in graph.nodes + + +@pytest.mark.parametrize("kind", ["arrow", "dict", "frame"]) +@pytest.mark.parametrize("role", ROLES) +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_in_memory_sources_register_by_object( + kind: str, role: str, reverse: bool, orchestrator: type +) -> None: + def source(row: int, arrangement: Arrangement) -> RootSource: + table = make_table(P, arrangement, rows=[row]) + tag_only = True if role == PLAIN else [P.mixed_plain] if role == MIXED else [] + if kind == "arrow": + return ArrowTableSource( + table, + tag_columns=arrangement.tag_order, + tag_only_columns=tag_only, + source_id="shared", + ) + cls = DictSource if kind == "dict" else DataFrameSource + return cls( + data=table.to_pylist(), + tag_columns=arrangement.tag_order, + tag_only_columns=tag_only, + source_id="shared", + ) + + arrangements = [ + Arrangement(P.tags, TAGS_FIRST, role), + Arrangement(tuple(reversed(P.tags)), DATA_FIRST_REVERSED, role), + ] + first, second = arrangements[::-1] if reverse else arrangements + with PipelineJob(database=InMemoryArrowDatabase()) as job: + with_pair.pod(source(0, first), label="fa") + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + with_pair.pod(source(0, second), label="same") + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + with_pair.pod(source(1, second), label="conflict") + assert set(job.function_pods) == {"fa"} + job.run(orchestrator=orchestrator()) + assert job.fa.as_table()["out"].to_pylist() == [8] + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_list_sources_register_by_object(reverse: bool, orchestrator: type) -> None: + def source(x: int, tag_order: tuple[str, ...]) -> ListSource: + tags = {"t1": "a", "t2": "b"} + return ListSource( + "x", + [x], + tag_function=lambda _x, _i: {name: tags[name] for name in tag_order}, + source_id="shared", + ) + + tags = ("t2", "t1") if reverse else ("t1", "t2") + with PipelineJob(database=InMemoryArrowDatabase()) as job: + increment.pod(source(1, tags), label="fa") + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + increment.pod(source(1, tags[::-1]), label="same") + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + increment.pod(source(100, tags[::-1]), label="conflict") + assert set(job.function_pods) == {"fa"} + job.run(orchestrator=orchestrator()) + assert job.fa.as_table()["out"].to_pylist() == [2] + + +def test_proxy_and_delegate_register_as_distinct_objects() -> None: + right = _dict(100) + wrapper = SourceProxy( + right.source_id, + right.content_hash().to_string(), + right.pipeline_hash().to_string(), + *right.output_schema(), + ) + wrapper.bind(right) + assert wrapper.content_hash() == right.content_hash() + _refused(right, wrapper, PipelineJob()) + + +@pytest.mark.parametrize("value", [1, 100]) +def test_bound_proxy_uses_its_live_arrow_schema_for_collision_checks( + value: int, +) -> None: + def source(x: int, keys: str | None = None) -> ArrowTableSource: + return ArrowTableSource( + pa.table({"x": pa.array([x], type=pa.int32())}), + infer_nullable=True, + source_id="shared", + record_id_columns=keys, + ) + + first, delegate = source(1), source(value, "x") + proxy = SourceProxy( + delegate.source_id, + delegate.content_hash().to_string(), + delegate.pipeline_hash().to_string(), + *delegate.output_schema(), + ) + # An unbound proxy knows only the Python type, which defaults to int64. + assert proxy.arrow_schemas[1].field("x").type == pa.int64() + proxy.bind(delegate) + + assert first.content_hash() != proxy.content_hash() + message = _capture(first, proxy, increment.pod) + assert "different key columns" in message + assert "different schemas" not in message + + +def test_implicit_projection_conflict_names_both_function_steps() -> None: + first = DictSource([{"x": 1, "y": 2}], source_id="shared") + second = DictSource([{"x": 100, "y": 2}], source_id="shared") + _refused(first, second, PipelineJob()) + + +def test_derived_from_fixed_sources() -> None: + def derived(x: int) -> DerivedSource: + origin = DictSource( + [{"t": "a", "x": x}], + tag_columns="t", + tag_only_columns=True, + source_id="origin", + ) + return DerivedSource( + origin, tags_as_data={"t": "tag_value"}, source_id="shared" + ) + + _refused(derived(1), derived(100), PipelineJob(), with_copy.pod) + + +def test_same_name_across_kinds_still_collides_at_capture_but_can_bind_separate_slots() -> ( + None +): + table = ArrowTableSource( + pa.table({"x": [100]}), infer_nullable=True, source_id="shared" + ) + dictionary = _dict(1) + with pytest.raises(SourceSlotNameCollisionError): + with Pipeline("conflicts"): + increment.pod(dictionary, label="fa") + increment.pod(table, label="fb") + job = _job() + job.bind(sources={"left": dictionary, "right": table}) + assert job.sources["left"] is dictionary + assert job.sources["right"] is table + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_same_source_id_with_different_key_columns_is_refused_at_build( + tmp_path: Path, reverse: bool +) -> None: + path = tmp_path / "shared.csv" + path.write_text("t1,t2,x,y\na,b,1,2\nc,d,3,4\n") + sources = [ + CSVSource( + str(path), + source_id="shared", + tag_columns=["t1", "t2"], + tag_only_columns=True, + record_id_columns=keys, + ) + for keys in (["t1", "x"], ["t2", "y"]) + ] + first, second = sources[::-1] if reverse else sources + assert first.source_id == second.source_id + assert first.arrow_schemas == second.arrow_schemas + assert first.content_hash() != second.content_hash() + + with pytest.raises(InconsistentSourceError, match="ITL-1506"): + with Pipeline("conflicts"): + both.pod(first, label="fa") + both.pod(second, label="fb") + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_bind_refuses_same_rows_with_different_keys(reverse: bool) -> None: + # Refused in any slots for now: distinct slots for distinct readings of one + # dataset are ITL-1506, after the multi-slot binding work (ITL-1442). + positional = _dict(1) + keyed = DictSource([{"x": 1}], record_id_columns="x", source_id="shared") + pair = (keyed, positional) if reverse else (positional, keyed) + job = _job() + before = dict(job.sources) + with pytest.raises(InconsistentSourceError) as error: + job.bind(sources={"left": pair[0], "right": pair[1]}) + message = str(error.value) + assert "different key columns" in message + assert "ITL-1506" in message + assert "slot 'left'" in message and "slot 'right'" in message + assert dict(job.sources) == before + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_bind_refuses_different_rows_with_different_keys(reverse: bool) -> None: + positional = _dict(1) + other = DictSource([{"x": 100}], record_id_columns="x", source_id="shared") + pair = (other, positional) if reverse else (positional, other) + with pytest.raises(InconsistentSourceError, match="different key columns"): + _job().bind(sources={"left": pair[0], "right": pair[1]}) + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_bind_refuses_live_sources_with_different_keys( + tmp_path: Path, reverse: bool +) -> None: + path = tmp_path / "shared.csv" + path.write_text("x\n1\n2\n") + positional = CSVSource(str(path), source_id="shared") + keyed = CSVSource(str(path), source_id="shared", record_id_columns="x") + pair = (keyed, positional) if reverse else (positional, keyed) + with pytest.raises(InconsistentSourceError) as error: + _job().bind(sources={"left": pair[0], "right": pair[1]}) + message = str(error.value) + assert "ITL-1506" in message + + +def _job() -> PipelineJob: + with PipelineJob(database=InMemoryArrowDatabase()) as job: + increment.pod(_dict(2, "left"), label="fa") + increment.pod(_dict(3, "right"), label="fb") + return job + + +@pytest.mark.parametrize("loaded", [False, True]) +def test_bind_checks_all_prospective_slots_atomically( + tmp_path: Path, loaded: bool +) -> None: + job = _job() + if loaded: + path = tmp_path / "job.json" + job.save(path) + job = PipelineJob.load(path) + first, second = _dict(1), _dict(100) + before = dict(job.sources) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + job.bind(sources={"left": first, "right": second}) + for part in (first.source_id, "left", "right", "source_id"): + assert part in str(error.value) + assert job.sources == before + job.bind(sources={"left": first}) + job.bind(sources={"left": second}) + assert job.sources["left"] is second + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + job.bind(sources={"right": first}) + job.bind(sources={"right": second}) + assert job.sources["right"] is second + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + job.bind(sources={"left": _dict(100)}) + + +def test_from_pipeline_checks_the_initial_bind() -> None: + with Pipeline("conflicts") as graph: + increment.pod(_dict(2, "left"), label="fa") + increment.pod(_dict(3, "right"), label="fb") + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + PipelineJob.from_pipeline( + graph, sources={"left": _dict(1), "right": _dict(100)} + ) + + +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_run_checks_slots_changed_outside_job_bind(orchestrator: type) -> None: + job = _job() + job.nodes["left"]._bind(_dict(1)) + job.nodes["right"]._bind(_dict(100)) + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + job.run(orchestrator=orchestrator()) + assert not job.fa.as_table().num_rows + assert not job.fb.as_table().num_rows + + +def test_additive_recording_resumes_when_original_binding_is_restored() -> None: + original = _dict(1) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + increment.pod(original, label="fa") + + replacement = _dict(100) + job.bind(sources={"shared": replacement}) + with job: + with pytest.raises(InconsistentSourceError, match="not as captured"): + consume_output.pod(job.fa, label="conflict") + job.run() + assert job.fa.as_table()["out"].to_pylist() == [101] + + job.bind(sources={"shared": original}) + with job: + consume_output.pod(job.fa, label="next") + job.run() + assert "conflict" not in job.nodes + assert job.fa.as_table()["out"].to_pylist() == [2] + assert job.next.as_table()["next"].to_pylist() == [4] + + +def test_load_checks_schema_of_reconstructed_sources(tmp_path: Path) -> None: + left, right = tmp_path / "left.csv", tmp_path / "right.csv" + left.write_text("x\n1\n") + right.write_text("x\ntext\n") + with PipelineJob() as job: + increment.pod(CSVSource(str(left), source_id="left"), label="fa") + with_string.pod(CSVSource(str(right), source_id="right"), label="fb") + path = tmp_path / "job.json" + job.save(path) + saved = json.loads(path.read_text()) + saved["bindings"]["sources"]["right"]["source_name"] = "left" + path.write_text(json.dumps(saved)) + with pytest.raises(InconsistentSourceError, match="different schemas") as error: + PipelineJob.load(path) + for part in ("csv_v1:left", "slot 'left'", "slot 'right'", "source_id"): + assert part in str(error.value) + + +def test_schema_conflicts_at_capture_and_bind() -> None: + def source(kind: pa.DataType, name: str) -> ArrowTableSource: + return ArrowTableSource( + pa.table({"x": pa.array([1], type=kind)}), + infer_nullable=True, + source_id=name, + ) + + first, second = source(pa.int32(), "shared"), source(pa.int64(), "shared") + with pytest.raises(InconsistentSourceError, match="different schemas"): + with Pipeline("conflicts"): + increment.pod(first, label="fa") + increment.pod(second, label="fb") + + with PipelineJob() as job: + increment.pod(source(pa.int32(), "left"), label="fa") + increment.pod(source(pa.int64(), "right"), label="fb") + with pytest.raises(InconsistentSourceError, match="different schemas") as error: + job.bind(sources={"left": first, "right": second}) + for part in (first.source_id, "left", "right", "source_id"): + assert part in str(error.value) + + +@pytest.mark.parametrize("graph_type", [Pipeline, PipelineJob]) +def test_one_object_is_allowed_in_several_steps( + graph_type: type[Pipeline] | type[PipelineJob], +) -> None: + source = _dict(1) + with graph_type("reuse") as job: + increment.pod(source, label="fa") + increment_again.pod(source, label="fb") + assert set(job.nodes) == {"shared", "fa", "fb"} + + +def test_cache_and_its_source_register_as_distinct_objects() -> None: + source = _dict(1) + cached = source.cached(InMemoryArrowDatabase()) + assert cached.content_hash() == source.content_hash() + _refused(source, cached, PipelineJob()) + _refused(cached, source.cached(InMemoryArrowDatabase()), PipelineJob()) + + +def test_stored_derived_sources_register_by_object() -> None: + def derived(x: int) -> DerivedSource: + with PipelineJob(database=InMemoryArrowDatabase()) as job: + increment.pod(_dict(x), label="result") + job.run() + return job.result.as_source() + + first, second = derived(1), derived(100) + assert first.source_id == second.source_id + assert first.as_table()["out"].to_pylist() == [2] + assert second.as_table()["out"].to_pylist() == [101] + + @function_pod(output_keys="value") + def downstream(out: int) -> int: + return out + 1 + + _refused(first, second, PipelineJob(), downstream.pod) + + +_ROWS = [ + {"t1": "a", "t2": "p", "x": 1, "y": 10}, + {"t1": "b", "t2": "q", "x": 2, "y": 20}, + {"t1": "c", "t2": "r", "x": 3, "y": 30}, +] + + +def _keyed( + rows: list[dict[str, str | int]], + keys: list[str] | None, + tags: list[str] | None = None, +) -> DictSource: + return DictSource( + rows, + tag_columns=tags or ["t1", "t2"], + tag_only_columns=True, + record_id_columns=keys, + source_id="shared", + ) + + +def _capture(first: RootSource, second: RootSource, pod: _FunctionPodBase) -> str: + """Refused when the second step is captured, not later at compile.""" + graph = Pipeline("conflicts") + with graph: + _ = pod(first, label="fa") + with pytest.raises(InconsistentSourceError) as error: + _ = pod(second, label="fb") + assert "fb" not in graph.nodes + return str(error.value) + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize( + "keys", [(["t1"], ["t2", "x"]), (None, ["t2", "t1"]), (["x", "y"], None)] +) +def test_capture_refuses_materialized_sources_with_different_key_columns( + reverse: bool, keys: tuple[list[str] | None, list[str] | None] +) -> None: + first = _keyed(_ROWS, keys[0]) + # Another row order and tag order: the same dataset, read with other keys. + second = _keyed(list(reversed(_ROWS)), keys[1], tags=["t2", "t1"]) + if reverse: + first, second = second, first + assert first.content_hash() != second.content_hash() + message = _capture(first, second, both.pod) + assert "different key columns" in message + assert "ITL-1506" in message + assert "source_id" in message + + +@function_pod(output_keys="out") +def with_copies(x: int, y: int, c1: str, c2: str) -> int: + return x + y + len(c1) + len(c2) + + +def _derived( + origin: RootSource, mapping: dict[str, str], keys: list[str] | None +) -> DerivedSource: + return DerivedSource( + origin, tags_as_data=mapping, record_id_columns=keys, source_id="shared" + ) + + +# The second mapping changes the order. The third changes which column c2 copies. +_COPIES = {"t1": "c1", "t2": "c2"} +_COPIES_REVERSED = {"t2": "c2", "t1": "c1"} +_SECOND_COPY_CHANGED = {"t1": "c1", "t3": "c2"} +_ORIGIN_TEXT = "t1,t2,t3,x,y\na,p,u,1,10\nb,q,v,2,20\n" + + +def test_derived_sources_over_live_origins_with_other_mapping_and_keys( + tmp_path: Path, +) -> None: + path = tmp_path / "origin.csv" + path.write_text(_ORIGIN_TEXT) + origin = CSVSource( + str(path), + source_id="origin", + tag_columns=["t1", "t2", "t3"], + tag_only_columns=True, + ) + for mapping in (_COPIES_REVERSED, _SECOND_COPY_CHANGED): + first = _derived(origin, _COPIES, ["t1", "t2"]) + second = _derived(origin, mapping, ["t3", "t1"]) + assert first.arrow_schemas == second.arrow_schemas + message = _capture(first, second, with_copies.pod) + assert "different key columns" in message + assert "ITL-1506" in message + + +def test_unknown_key_columns_never_hide_a_conflict_between_known_ones() -> None: + # An unbound proxy of the same id and schema has unknown key columns: it neither + # causes nor suppresses a refusal between the sources whose keys are known. + positional = DictSource([{"x": 1}, {"x": 2}], source_id="shared") + keyed = DictSource([{"x": 1}, {"x": 2}], record_id_columns="x", source_id="shared") + proxy = SourceProxy( + positional.source_id, + _dict(0, "other").content_hash().to_string(), + positional.pipeline_hash().to_string(), + *positional.output_schema(), + ) + assert proxy._resolved_key_columns is None # pyright: ignore[reportPrivateUsage] # unbound proxy state + for uses in itertools.permutations( + [("slot 'p'", proxy), ("slot 'a'", positional), ("slot 'b'", keyed)] + ): + with pytest.raises(InconsistentSourceError) as error: + require_consistent_sources(uses) + assert "different key columns" in str(error.value) + require_consistent_sources([("slot 'p'", proxy), ("slot 'a'", positional)]) + require_consistent_sources([("slot 'p'", proxy), ("slot 'b'", keyed)]) + + +@function_pod(output_keys="out") +def increment_matched(x: int) -> int: + return x + 1 + + +def _semi_join_job() -> PipelineJob: + def source(name: str) -> DictSource: + return DictSource( + [{"k": "a", "x": 1}, {"k": "b", "x": 2}], + tag_columns="k", + tag_only_columns=True, + source_id=name, + ) + + with PipelineJob(database=InMemoryArrowDatabase()) as job: + matched = SemiJoin()(source("left"), source("right"), label="matched") + _ = increment_matched.pod(matched, label="fm") + return job + + +def _rebind_outside_bind(job: PipelineJob, right_keys: str | None, x: int) -> None: + # Inject invalid job state to test the run-time checks. + job.nodes["left"]._bind( + DictSource( + [{"k": "a", "x": 1}, {"k": "b", "x": 2}], + tag_columns="k", + tag_only_columns=True, + source_id="shared", + ) + ) + job.nodes["right"]._bind( + DictSource( + [{"k": "a", "x": 1}, {"k": "b", "x": x}], + tag_columns="k", + tag_only_columns=True, + record_id_columns=right_keys, + source_id="shared", + ) + ) + + +@pytest.mark.parametrize("node", ["matched", "fm"]) +@pytest.mark.parametrize( + ("right_keys", "x", "message"), + [("k", 2, "different key columns"), (None, 200, "distinct source objects")], +) +def test_node_run_checks_its_sources_like_job_run( + node: str, right_keys: str | None, x: int, message: str +) -> None: + job = _semi_join_job() + _rebind_outside_bind(job, right_keys, x) + with pytest.raises(InconsistentSourceError, match=message): + _ = job.run() + with pytest.raises(InconsistentSourceError, match=message): + _ = job.nodes[node].run() + for name in ("matched", "fm"): + assert job.nodes[name].as_table().num_rows == 0 + + +def _arranged( + arrangement: Arrangement, + source_id: str, + keys: list[str] | None, + changed: bool = False, +) -> ArrowTableSource: + """``P`` (two tags, two data columns) in ``arrangement``; ``changed`` alters p2.""" + table = make_table(P, arrangement) + if changed: + index = table.schema.get_field_index("p2") + values = table["p2"].to_pylist() + values[-1] = "changed" + table = table.set_column( + index, table.schema.field(index), pa.array(values, pa.large_string()) + ) + role = arrangement.roles + return ArrowTableSource( + table, + tag_columns=list(arrangement.tag_order), + tag_only_columns=True + if role == PLAIN + else [P.mixed_plain] + if role == MIXED + else [], + record_id_columns=keys, + source_id=source_id, + ) + + +@pytest.mark.parametrize("role", ROLES) +@pytest.mark.parametrize( + ("left_keys", "right_keys", "changed", "message"), + [ + (["t1", "t2"], ["t2", "t1"], False, "different key columns"), + (None, ["t2", "t1"], False, "different key columns"), + (["t1", "t2"], ["t2", "t1"], True, "different key columns"), + (None, None, True, "distinct source objects"), + ], +) +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +def test_node_run_checks_its_sources_on_several_columns( + role: str, + left_keys: list[str] | None, + right_keys: list[str] | None, + changed: bool, + message: str, + orchestrator: type, +) -> None: + left = Arrangement(P.tags, TAGS_FIRST, role) + right = Arrangement(tuple(reversed(P.tags)), DATA_FIRST_REVERSED, role) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + matched = SemiJoin()( + _arranged(left, "left", None), _arranged(right, "right", None), label="m" + ) + _ = with_pair.pod(matched, label="fm") + # Rebound outside bind, so only the run-time checks can refuse. + job.nodes["left"]._bind(_arranged(left, "shared", left_keys)) + job.nodes["right"]._bind(_arranged(right, "shared", right_keys, changed)) + with pytest.raises(InconsistentSourceError, match=message): + _ = job.run(orchestrator=orchestrator()) + for node in ("m", "fm"): + with pytest.raises(InconsistentSourceError, match=message): + _ = job.nodes[node].run() + assert job.nodes[node].as_table().num_rows == 0 diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py new file mode 100644 index 000000000..cecf9a451 --- /dev/null +++ b/tests/test_pipeline/test_source_object_registration.py @@ -0,0 +1,1184 @@ +"""A pipeline binds each source content hash to a single object (ITL-1469).""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from orcapod import Pipeline, PipelineJob, function_pod, side_effect_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InconsistentSourceError +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.side_effects import SideEffectPod +from orcapod.sources import CSVSource, DictSource + +Orchestrator = type[AsyncPipelineOrchestrator] | type[SyncPipelineOrchestrator] +ORCHESTRATORS = [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +ROWS = [{"t1": "a", "t2": "b", "x": 1, "y": 2}, {"t1": "c", "t2": "d", "x": 3, "y": 4}] + + +@function_pod(output_keys="out") +def total(x: int, y: int) -> int: + """Add the two data columns.""" + return x + y + + +@function_pod(output_keys="out") +def difference(x: int, y: int) -> int: + """Subtract the second data column from the first.""" + return x - y + + +@function_pod(output_keys="out") +def product(x: int, y: int) -> int: + """Multiply the two data columns.""" + return x * y + + +def _source( + tmp_path: Path, kind: str, name: str, *, reverse: bool = False, change: bool = False +) -> DictSource | CSVSource: + rows = [dict(row) for row in ROWS] + if change: + rows[-1]["y"] = 40 + columns = ["t1", "t2", "x", "y"] + tags = ["t1", "t2"] + if reverse: + columns.reverse() + tags.reverse() + if kind == "csv": + path = tmp_path / f"{name}-{reverse}.csv" + path.write_text( + ",".join(columns) + + "\n" + + "".join(",".join(str(row[col]) for col in columns) + "\n" for row in rows) + ) + return CSVSource( + str(path), source_id=name, tag_columns=tags, tag_only_columns=True + ) + return DictSource( + [{col: row[col] for col in columns} for row in rows], + source_id=name, + tag_columns=tags, + tag_only_columns=True, + ) + + +def _shifted_source(name: str, offset: int) -> DictSource: + """Build a fixture whose output values distinguish it from other slot bindings.""" + return DictSource( + [{**row, "x": int(row["x"]) + offset} for row in ROWS], + source_id=name, + tag_columns=["t1", "t2"], + tag_only_columns=True, + ) + + +def _pair( + tmp_path: Path, kind: str, reverse: bool +) -> tuple[DictSource | CSVSource, DictSource | CSVSource]: + first = _source(tmp_path, kind, "shared") + second = _source(tmp_path, kind, "shared", reverse=True, change=kind != "equal") + assert first is not second + assert first.content_hash() == second.content_hash() + return (second, first) if reverse else (first, second) + + +def _job(tmp_path: Path, slots: tuple[str, ...] = ("a", "b")) -> PipelineJob: + with PipelineJob(database=InMemoryArrowDatabase()) as job: + for slot, compute in zip(slots, (total, difference, product)): + compute.pod(_source(tmp_path, "dict", slot), label=f"result_{slot}") + return job + + +def _rebind(job: PipelineJob, sources: dict[str, StreamProtocol], setter: bool) -> None: + if setter: + for name, source in sources.items(): + job.nodes[name].bound_source = source + else: + job.bind(sources=sources) + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("kind", ["equal", "different", "csv"]) +@pytest.mark.parametrize("graph_type", [Pipeline, PipelineJob]) +def test_capture_refuses_two_objects_with_one_hash( + tmp_path: Path, + graph_type: type[Pipeline] | type[PipelineJob], + kind: str, + reverse: bool, +) -> None: + first, second = _pair(tmp_path, kind, reverse) + with graph_type("registration") as graph: + total.pod(first, label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + total.pod(second, label="second") + for part in ("step 'first'", "step 'second'", "reuse", "source_id"): + assert part in str(error.value) + assert "second" not in graph.nodes + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("kind", ["equal", "different", "csv"]) +def test_bind_refuses_two_objects_with_one_hash( + tmp_path: Path, kind: str, reverse: bool +) -> None: + first, second = _pair(tmp_path, kind, reverse) + job = _job(tmp_path) + before = job.sources.copy() + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + job.bind(sources={"a": first, "b": second}) + assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) + assert job.sources == before + + job.bind(sources={"a": first, "b": first}) + assert job.sources["a"] is job.sources["b"] is first + job.bind(sources={"a": _source(tmp_path, kind, "replacement")}) + job.bind(sources={"b": second}) + assert job.sources["b"] is second + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("kind", ["equal", "different", "csv"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_run_refuses_two_objects_with_one_hash( + tmp_path: Path, kind: str, reverse: bool, orchestrator: Orchestrator +) -> None: + first, second = _pair(tmp_path, kind, reverse) + job = _job(tmp_path) + # Inject invalid job state to exercise the run-time check independently. + job.nodes["a"]._bind(first) + job.nodes["b"]._bind(second) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + job.run(orchestrator=orchestrator()) + assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) + assert job.last_run is None + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("kind", ["equal", "different", "csv"]) +def test_load_refuses_different_configs_that_rebuild_to_one_hash( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, kind: str, reverse: bool +) -> None: + from orcapod.pipeline import serialization + + first, second = _pair(tmp_path, kind, reverse) + job = _job(tmp_path) + path = tmp_path / "job.json" + job.save(path) + saved = json.loads(path.read_text()) + saved["bindings"]["sources"] = {"a": first.to_config(), "b": second.to_config()} + if kind != "csv": + # In-memory sources have no persisted rows. Simulate their reconstruction + # from distinct configs without changing the saved-format support for them. + for name in ("a", "b"): + saved["bindings"]["sources"][name]["fixture_slot"] = name + restored = {"a": first, "b": second} + monkeypatch.setattr( + serialization, + "resolve_source_from_config", + lambda config: restored[config["fixture_slot"]], + ) + path.write_text(json.dumps(saved)) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + PipelineJob.load(path) + assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_load_refuses_one_source_id_with_different_key_columns( + tmp_path: Path, reverse: bool +) -> None: + csv = _source(tmp_path, "csv", "shared") + job = _job(tmp_path) + path = tmp_path / "job.json" + job.save(path) + saved = json.loads(path.read_text()) + first = {**csv.to_config(), "record_id_columns": ["t1", "x"]} + second = {**csv.to_config(), "record_id_columns": ["t2", "y"]} + configs = (second, first) if reverse else (first, second) + saved["bindings"]["sources"] = dict(zip(("a", "b"), configs, strict=True)) + path.write_text(json.dumps(saved)) + + with pytest.raises(InconsistentSourceError, match="different key columns") as error: + PipelineJob.load(path) + assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) + assert "ITL-1506" in str(error.value) + + +@pytest.mark.parametrize("slots", [("a", "b"), ("c", "b", "a")]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_load_reuses_one_object_for_identical_saved_configs( + tmp_path: Path, slots: tuple[str, ...], orchestrator: Orchestrator +) -> None: + job = _job(tmp_path, slots) + db = InMemoryArrowDatabase() + source = _source(tmp_path, "csv", "shared") + job.bind(database=db, sources=dict.fromkeys(slots, source)) + job.run(orchestrator=orchestrator()) + path = tmp_path / "job.json" + job.save(path) + saved = json.loads(path.read_text()) + configs = saved["bindings"]["sources"] + assert all(configs[name] == configs[slots[0]] for name in slots) + + loaded = PipelineJob.load(path, database=db) + shared = loaded.sources[slots[0]] + for name in slots: + assert loaded.sources[name] is shared + copied = tmp_path / "copied.json" + loaded.save(copied) + assert copied.read_bytes() == path.read_bytes() + + def rows(graph: PipelineJob, name: str) -> list[dict[str, Any]]: + return graph.nodes[name].as_table(columns={"sort_by_tags": True}).to_pylist() + + stored = { + table_path: db.get_all_records(table_path) + for table_path in db.list_table_paths() + } + loaded.run(orchestrator=orchestrator(), load_only=True) + for name in slots: + assert rows(loaded, name) == ROWS + assert rows(loaded, f"result_{name}") == rows(job, f"result_{name}") + assert { + table_path: db.get_all_records(table_path) + for table_path in db.list_table_paths() + } == stored + + replacement = _source(tmp_path, "csv", "replacement") + loaded.bind(sources={slots[0]: replacement}) + assert loaded.sources[slots[0]] is replacement + for name in slots[1:]: + assert loaded.sources[name] is shared + + +@pytest.mark.parametrize("reverse_keys", [False, True]) +def test_load_shares_repeated_configs_written_by_main( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reverse_keys: bool +) -> None: + # origin/main (f55ed6d7) wrote a separate, identical config for each of two + # distinct CSVSource objects bound to different slots. + fixture = Path(__file__).with_name("fixtures") / "itl_1469_main_shared_source.json" + configs = json.loads(fixture.read_text())["bindings"]["sources"] + assert configs["a"] == configs["b"] + monkeypatch.chdir(tmp_path) + Path("shared.csv").write_text("t1,t2,x,y\na,b,1,2\nc,d,3,4\n") + path = fixture + if reverse_keys: + saved = json.loads(fixture.read_text()) + sources = saved["bindings"]["sources"] + sources["b"] = dict(reversed(sources["b"].items())) + path = tmp_path / "reordered.json" + path.write_text(json.dumps(saved)) + + job = PipelineJob.load(path) + assert job.sources["a"] is job.sources["b"] + assert job.nodes["a"].as_table().to_pylist() == ROWS + assert job.nodes["b"].as_table().to_pylist() == ROWS + + +def test_itl_1554_loading_shared_slots_feeding_the_same_pod(tmp_path: Path) -> None: + """Record the existing read-only DAG failure for this shared-source topology.""" + db = InMemoryArrowDatabase() + with PipelineJob(database=db) as job: + for slot in ("a", "b"): + total.pod(_source(tmp_path, "dict", slot), label=f"total_{slot}") + source = _source(tmp_path, "csv", "shared") + job.bind(sources={"a": source, "b": source}) + job.run() + path = tmp_path / "job.json" + job.save(path) + + with pytest.raises(NotImplementedError, match="StreamBase.identity_structure"): + PipelineJob.load(path, database=db) + + +@pytest.mark.parametrize("kind", ["equal", "different", "csv"]) +def test_slot_setter_refuses_duplicates_and_preserves_bindings( + tmp_path: Path, kind: str +) -> None: + first, second = _pair(tmp_path, kind, False) + job = _job(tmp_path) + job.nodes["a"].bound_source = first + original = job.nodes["b"].bound_source + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + job.nodes["b"].bound_source = second + assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value) + assert job.nodes["b"].bound_source is original + assert job.sources["a"] is first + assert job.sources["b"] is original + job.compile() + assert job.nodes["a"].bound_source is first + assert job.nodes["b"].bound_source is original + + +def test_slot_setter_same_hash_replacement_blocks_capture_but_runs( + tmp_path: Path, +) -> None: + first = _source(tmp_path, "dict", "a") + replacement = _source(tmp_path, "dict", "a", change=True) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + total.pod(first, label="first") + job.nodes["a"].bound_source = replacement + with job: + with pytest.raises(InconsistentSourceError, match="not as captured"): + difference.pod(replacement, label="second") + assert "second" not in job.nodes + assert job.sources["a"] is replacement + assert job.nodes["a"].bound_source is replacement + job.run() + assert sorted(job.first.as_table()["out"].to_pylist()) == [3, 43] + + +def test_slot_setter_can_unbind_and_recompile(tmp_path: Path) -> None: + job = _job(tmp_path) + job.nodes["a"].bound_source = None + assert "a" not in job.sources + job.compile() + assert job.nodes["a"].bound_source is None + assert job.unbound_sources == ["a"] + + +@pytest.mark.parametrize("binding", ["constructor", "from_stream", "setter"]) +@pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning") +def test_source_slot_refuses_composite_with_conflicting_roots( + tmp_path: Path, binding: str +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SemiJoin + + first, second = _pair(tmp_path, "different", False) + composite = SemiJoin()(first, second, label="matched") + slot = SourceJobNode.from_stream(first, name="standalone") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + if binding == "constructor": + SourceJobNode("standalone", bound_source=composite) + elif binding == "from_stream": + SourceJobNode.from_stream(composite, name="standalone") + else: + slot.bound_source = composite + for part in ("slot 'standalone'", "'matched' input 1", "'matched' input 2"): + assert part in str(error.value) + assert slot.bound_source is first + + +def test_coalesced_captures_release_duplicate_projections(tmp_path: Path) -> None: + import gc + from weakref import ref + + source = _source(tmp_path, "dict", "shared") + graph = Pipeline("retention") + + def capture_projection(): + projection = source.select_data_columns(["x", "y"]) + with graph: + _ = total.pod(projection, label="step") + return ref(projection) + + projections = [capture_projection() for _ in range(8)] + _ = gc.collect() + + assert "step" in graph.nodes + assert sum(projection_ref() is not None for projection_ref in projections) <= 2 + + +def test_capture_reports_both_uses_of_slots_with_the_same_name(tmp_path: Path) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + + first, second = _pair(tmp_path, "different", False) + left = SourceJobNode.from_stream(first, name="same") + right = SourceJobNode.from_stream(second, name="same") + with Pipeline("diagnostics"): + total.pod(left, label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + difference.pod(right, label="second") + message = str(error.value) + assert "step 'first'" in message and "step 'second'" in message + + +def test_plain_derived_collision_only_suggests_reusing_the_object( + tmp_path: Path, +) -> None: + job = _job(tmp_path, ("a",)) + job.run() + first = job.result_a.as_source(source_id="left") + second = job.result_a.as_source(source_id="right") + assert first.content_hash() == second.content_hash() + assert first.source_id != second.source_id + + @function_pod(output_keys="answer") + def consume(out: int) -> int: + return out + + with Pipeline("diagnostics"): + consume.pod(first, label="first") + with pytest.raises(InconsistentSourceError, match="reuse the object") as error: + consume.pod(second, label="second") + assert "source_id" not in str(error.value) + + +def test_compile_refuses_schema_conflict_introduced_through_live_slot() -> None: + import pyarrow as pa + + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.sources import ArrowTableSource + + def source(name: str, kind: pa.DataType) -> ArrowTableSource: + return ArrowTableSource( + pa.table({"x": pa.array([1], type=kind), "y": [2]}), + source_id=name, + infer_nullable=True, + ) + + first = SourceJobNode.from_stream(source("shared", pa.int32()), name="same") + second = SourceJobNode.from_stream(source("other", pa.int64()), name="same") + with Pipeline("compile", auto_compile=False) as pipeline: + total.pod(first, label="first") + difference.pod(second, label="second") + second.bound_source = source("shared", pa.int64()) + with pytest.raises(InconsistentSourceError, match="different schemas") as error: + pipeline.compile() + assert "step 'first'" in str(error.value) and "step 'second'" in str(error.value) + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning") +def test_source_slot_run_checks_roots_changed_after_binding(tmp_path: Path) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SemiJoin + + first, conflict = _pair(tmp_path, "different", False) + right = SourceJobNode.from_stream(_source(tmp_path, "dict", "other")) + composite = SemiJoin()(first, right, label="matched") + slot = SourceJobNode.from_stream(composite, name="standalone") + right.bound_source = conflict + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + slot.run() + + +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_binding_back_the_captured_object_restores_capture_and_rows( + tmp_path: Path, setter: bool, orchestrator: Orchestrator +) -> None: + original = _source(tmp_path, "dict", "a") + another_object = _source(tmp_path, "dict", "a", reverse=True, change=True) + replacement = _source(tmp_path, "dict", "b", change=True) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + total.pod(original, label="before") + + # Bind inside an open capture context so the check must run when recording. + with job: + _rebind(job, {"a": replacement}, setter) + for candidate in (replacement, original, another_object): + with pytest.raises( + InconsistentSourceError, match="not as captured" + ) as error: + difference.pod(candidate, label="refused") + assert "'a'" in str(error.value) + assert "ITL-1559" in str(error.value) + assert "Bind" in str(error.value) and "new job" in str(error.value) + job.run(orchestrator=orchestrator()) + assert sorted(job.before.as_table()["out"].to_pylist()) == [3, 43] + + _rebind(job, {"a": original}, setter) + job.compile() + with job: + difference.pod(original, label="after") + job.run(orchestrator=orchestrator()) + assert set(job.nodes) == {"a", "before", "after"} + assert sorted(job.before.as_table()["out"].to_pylist()) == [3, 7] + assert sorted(job.after.as_table()["out"].to_pylist()) == [-1, -1] + + +WRAPPER_PAIRS = [ + "source-cache", + "two-caches", + "nested-cache", + "two-as-source", + "two-tag-copies", + "source-proxy", + "cache-proxy", +] + + +@pytest.fixture(params=WRAPPER_PAIRS) +def wrapper_pair(tmp_path: Path, request: pytest.FixtureRequest): + from orcapod.core.sources.cached_source import CachedSource + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import DerivedSource + + source = _source(tmp_path, "dict", "shared") + kind = request.param + if kind == "two-as-source": + job = _job(tmp_path, ("a",)) + job.run() + first = job.result_a.as_source() + return first, job.result_a.as_source(), first, "out" + if kind == "two-tag-copies": + first = DerivedSource( + source, tags_as_data={"t1": "tag_value"}, source_id="copied" + ) + second = DerivedSource( + source, tags_as_data={"t1": "tag_value"}, source_id="copied" + ) + return first, second, first, "x" + if kind in ("source-proxy", "cache-proxy"): + cache = source.cached(DeltaTableDatabase(tmp_path / "cache")) + proxy = CachedSource.from_config(cache.to_config()).cached_source + assert isinstance(proxy, SourceProxy) + proxy.bind(source) + return source if kind == "source-proxy" else cache, proxy, proxy, "x" + + cache = source.cached(InMemoryArrowDatabase()) + if kind == "source-cache": + return source, cache, cache, "x" + if kind == "two-caches": + return cache, source.cached(InMemoryArrowDatabase()), cache, "x" + return cache, cache.cached(InMemoryArrowDatabase()), cache, "x" + + +def test_wrapper_pairs_with_one_content_hash_are_refused(wrapper_pair) -> None: + first, second, _, column = wrapper_pair + assert first is not second + assert first.content_hash() == second.content_hash() + with Pipeline("wrapper_conflict") as graph: + first.map_data({column: "a"}, label="first") + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + second.map_data({column: "b"}, label="second") + assert "first" in graph.nodes + assert "second" not in graph.nodes + + +def test_one_wrapper_object_can_be_reused(wrapper_pair) -> None: + _, _, shared, column = wrapper_pair + with Pipeline("wrapper_reuse") as graph: + shared.map_data({column: "a"}, label="first") + shared.map_data({column: "b"}, label="second") + assert {"first", "second"} <= graph.nodes.keys() + + +@function_pod(output_keys="out") +def increment(x: int) -> int: + """Increment the selected input.""" + return x + 1 + + +@function_pod(output_keys="doubled") +def double(out: int) -> int: + """Double the earlier output.""" + return out * 2 + + +@pytest.mark.parametrize("kind", ["select", "join", "function", "cache"]) +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +@pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning") +def test_rebound_job_refuses_prebuilt_streams_after_recompile( + tmp_path: Path, kind: str, setter: bool, orchestrator: Orchestrator +) -> None: + from orcapod.operators import SemiJoin + + original = _source(tmp_path, "dict", "a") + replacement = _shifted_source("b", 10) + peer = _source(tmp_path, "dict", "peer") + original_cache = original.cached(InMemoryArrowDatabase()) + consumer = double if kind == "function" else increment + + def build(prebuilt: bool = False): + if kind == "join": + return SemiJoin()(original, peer, label="joined") + if kind == "function": + return increment.pod(original, label="prepared") + source = ( + original + if kind == "select" + else ( + original.cached(InMemoryArrowDatabase()) if prebuilt else original_cache + ) + ) + return source.select_data_columns(["x"], label="selected") + + with PipelineJob(database=InMemoryArrowDatabase()) as job: + recorded = build() + consumer.pod(recorded, label="before") + if setter: + job.nodes["a"].bound_source = replacement + else: + job.bind(sources={"a": replacement}) + job.compile() + + prebuilt = build(prebuilt=True) + assert ( + prebuilt is not recorded and prebuilt.content_hash() == recorded.content_hash() + ) + with job: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: + consumer.pod(prebuilt, label="refused") + assert "'a'" in str(error.value) + job.run(orchestrator=orchestrator()) + assert "refused" not in job.nodes + column, expected = ( + ("doubled", [24, 28]) if kind == "function" else ("out", [12, 14]) + ) + assert sorted(job.before.as_table()[column].to_pylist()) == expected + + +@pytest.mark.parametrize( + "names", [("a", "b"), ("b", "a"), ("a", "b", "c"), ("c", "b", "a")] +) +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_swapping_or_rotating_slots_blocks_capture_but_preserves_rows( + names: tuple[str, ...], setter: bool, orchestrator: Orchestrator +) -> None: + sources = { + name: _shifted_source(name, 10 * index) for index, name in enumerate(names) + } + with PipelineJob(database=InMemoryArrowDatabase()) as job: + for name, source in sources.items(): + total.pod(source, label=f"original_{name}") + rotated = names[1:] + names[:1] + _rebind( + job, + {slot: sources[name] for slot, name in zip(names, rotated, strict=True)}, + setter, + ) + job.compile() + with job: + for source in reversed(sources.values()): + with pytest.raises( + InconsistentSourceError, match="not as captured" + ) as error: + difference.pod(source, label="added") + assert all(repr(name) in str(error.value) for name in names) + job.run(orchestrator=orchestrator()) + + assert "added" not in job.nodes + assert set(job.sources) == set(names) + for index, name in enumerate(names): + before = job.nodes[f"original_{name}"] + offset = 10 * ((index + 1) % len(names)) + assert sorted(before.as_table()["out"].to_pylist()) == [offset + 3, offset + 7] + + restored, *still_changed = names + _rebind(job, {restored: sources[restored]}, setter) + with job: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: + difference.pod(sources[restored], label="added") + assert repr(restored) not in str(error.value) + assert all(repr(name) in str(error.value) for name in still_changed) + + _rebind(job, {name: sources[name] for name in still_changed}, setter) + with job: + difference.pod(sources[restored], label="added") + job.run(orchestrator=orchestrator()) + assert sorted(job.added.as_table()["out"].to_pylist()) == [-1, -1] + + +def test_cached_derived_collision_only_suggests_reusing_the_object( + tmp_path: Path, +) -> None: + job = _job(tmp_path, ("a",)) + job.run() + first = job.result_a.as_source(source_id="left").cached(InMemoryArrowDatabase()) + second = job.result_a.as_source(source_id="right").cached(InMemoryArrowDatabase()) + assert first.content_hash() == second.content_hash() + assert first.source_id != second.source_id + with Pipeline("diagnostics"): + first.map_data({"out": "first_out"}, label="first") + with pytest.raises(InconsistentSourceError, match="reuse the object") as error: + second.map_data({"out": "second_out"}, label="second") + assert "source_id" not in str(error.value) + + +@pytest.mark.parametrize("setter", [False, True]) +def test_refusing_to_recompile_a_loaded_job_preserves_its_sources_mapping( + tmp_path: Path, setter: bool +) -> None: + original = _source(tmp_path, "csv", "a") + replacement = _source(tmp_path, "csv", "b", change=True) + db = InMemoryArrowDatabase() + with PipelineJob(database=db) as job: + total.pod(original, label="before") + job.bind(sources={"a": replacement}) + job.run() + path = tmp_path / "job.json" + job.save(path) + loaded = PipelineJob.load(path, database=db) + if setter: + loaded.nodes["a"].bound_source = original + before = loaded.sources + nodes = loaded.nodes + + with pytest.raises(RuntimeError, match="ITL-1560"): + loaded.compile() + + assert set(loaded.sources) == set(before) == {"a"} + assert loaded.sources["a"] is before["a"] + assert loaded.nodes == nodes + + +@pytest.mark.parametrize("prebuilt", [False, True], ids=["same-pod", "prebuilt"]) +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_rebound_job_refuses_same_pod_or_prebuilt_recapture( + tmp_path: Path, prebuilt: bool, setter: bool, orchestrator: Orchestrator +) -> None: + first = _source(tmp_path, "dict", "a") + second = _shifted_source("b", 10) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + if prebuilt: + increment.pod(first.select_data_columns(["x"]), label="original_a") + else: + total.pod(first, label="original_a") + total.pod(second, label="original_b") + if setter: + job.nodes["a"].bound_source = second + job.nodes["b"].bound_source = first + else: + job.bind(sources={"a": second, "b": first}) + job.compile() + + outside = first.select_data_columns(["x"]) if prebuilt else first + with job: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: + if prebuilt: + outside.map_data({"x": "selected"}, label="refused") + else: + total.pod(outside, label="refused") + assert "'a'" in str(error.value) and "'b'" in str(error.value) + + job.run(orchestrator=orchestrator()) + assert "refused" not in job.nodes + assert sorted(job.original_a.as_table()["out"].to_pylist()) == ( + [12, 14] if prebuilt else [13, 17] + ) + + +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_unbound_slot_blocks_prebuilt_capture_and_later_binding_still_runs( + setter: bool, orchestrator: Orchestrator +) -> None: + original, replacement, later = ( + _shifted_source(name, offset) + for name, offset in (("a", 0), ("b", 10), ("c", 20)) + ) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + recorded = increment.pod(original, label="before") + _rebind(job, {"a": replacement}, setter) + job.nodes["a"].bound_source = None + job.compile() + + prebuilt = increment.pod(original) + assert prebuilt.content_hash() == recorded.content_hash() + with job: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: + double.pod(prebuilt, label="refused") + assert "'a'" in str(error.value) + _rebind(job, {"a": later}, setter) + job.compile() + job.run(orchestrator=orchestrator()) + assert "refused" not in job.nodes + assert sorted(job.before.as_table()["out"].to_pylist()) == [22, 24] + + +@pytest.mark.parametrize("use_slot", [False, True], ids=["composite", "slot"]) +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_current_composite_binding_blocks_capture_but_preserves_rows( + use_slot: bool, setter: bool, orchestrator: Orchestrator +) -> None: + first, second, replacement = ( + _shifted_source(name, offset) + for name, offset in (("a", 0), ("b", 10), ("c", 20)) + ) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + total.pod(first, label="first") + difference.pod(second, label="second") + composite = first.select_data_columns(["x", "y"]) + _rebind(job, {"a": replacement, "b": composite}, setter) + job.compile() + + assert job.sources["b"] is composite + with job: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: + product.pod(job.nodes["b"] if use_slot else composite, label="refused") + assert "'a'" in str(error.value) and "'b'" in str(error.value) + job.run(orchestrator=orchestrator()) + assert "refused" not in job.nodes + assert sorted(job.first.as_table()["out"].to_pylist()) == [23, 27] + assert sorted(job.second.as_table()["out"].to_pylist()) == [-1, -1] + + +@pytest.mark.parametrize( + "wrapped_slot", [False, True], ids=["prebuilt", "source-job-node"] +) +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +def test_capture_uses_the_binding_of_the_first_compiled_slot( + wrapped_slot: bool, setter: bool +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + + source = _shifted_source("a", 0) + original = source.select_data_columns(["x", "y"]) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + if wrapped_slot: + foreign = SourceJobNode.from_stream(original, name="slot") + with pytest.raises(InconsistentSourceError, match="not supported yet"): + total.pod(foreign, label="borrowed") + total.pod(original, label="before") + (name,) = job.sources + assert job.sources[name] is original + + replacement = source.select_data_columns(["x", "y"]) + assert ( + replacement is not original + and replacement.content_hash() == original.content_hash() + ) + _rebind(job, {name: replacement}, setter) + job.compile() + with job: + with pytest.raises(InconsistentSourceError, match="not as captured") as error: + difference.pod(replacement, label="refused") + assert repr(name) in str(error.value) + + _rebind(job, {name: original}, setter) + with job: + difference.pod(original, label="after") + job.run() + assert sorted(job.after.as_table()["out"].to_pylist()) == [-1, -1] + + +@pytest.mark.parametrize( + "blocked_index,count", [(0, 2), (1, 2), (0, 3), (1, 3), (2, 3)] +) +@pytest.mark.parametrize("capture", ["function", "operator", "side_effect"]) +def test_nested_capture_refusal_leaves_every_job_unchanged( + blocked_index: int, count: int, capture: str +) -> None: + from contextlib import ExitStack + + def deliver(x: int, ctx: Any) -> None: + raise AssertionError("A refused side effect must never run") + + original = _shifted_source("a", 0) + replacement = _shifted_source("b", 10) + jobs = [PipelineJob(database=InMemoryArrowDatabase()) for _ in range(count)] + for job in jobs: + with job: + total.pod(original, label="before") + jobs[blocked_index].bind(sources={"a": replacement}) + + with ExitStack() as contexts: + for job in jobs: + contexts.enter_context(job) + with pytest.raises(InconsistentSourceError, match="not as captured"): + if capture == "function": + difference.pod(original, label="refused") + elif capture == "operator": + original.map_data({"x": "renamed"}, label="refused") + else: + tap = side_effect_pod(deliver) + assert isinstance(tap, SideEffectPod) + tap.process(original, label="refused") + + for job in jobs: + assert "refused" not in job.nodes + + +@pytest.mark.parametrize("foreign_origin", ["standalone", "other_job"]) +@pytest.mark.parametrize( + "form", + [ + "direct", + "hashed", + "select", + "function", + "join", + "record", + "invocations", + "isolated", + ], +) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_capture_refuses_foreign_source_slots( + foreign_origin: str, form: str, orchestrator: Orchestrator +) -> None: + from orcapod.core.function_pod import FunctionPod + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns, SemiJoin + from orcapod.pipeline.base import InvocationGraph + from orcapod.pipeline.pod_invocation import FunctionInvocation + + source = _shifted_source("a", 0) + if foreign_origin == "standalone": + slot = SourceJobNode.from_stream(source, name="a") + else: + with PipelineJob(database=InMemoryArrowDatabase()) as upstream: + total.pod(source, label="upstream") + slot = upstream.nodes["a"] + assert isinstance(slot, SourceJobNode) + + original = _shifted_source("kept", 0) + with PipelineJob(database=InMemoryArrowDatabase()) as receiver: + total.pod(original, label="kept_result") + + @function_pod(output_keys="scaled") + def scale(out: int) -> int: + return out * 10 + + prebuilt = { + "select": lambda: SelectDataColumns(["x", "y"])(slot), + "function": lambda: total.pod(slot), + "join": lambda: SemiJoin()(slot, _shifted_source("other", 0)), + } + pod = total.pod + assert isinstance(pod, FunctionPod) + if form == "record": + with pytest.raises(InconsistentSourceError, match="not supported yet") as error: + receiver.record_function_pod_invocation(pod, slot, label="borrowed") + elif form in {"invocations", "isolated"}: + invocations = ( + (FunctionInvocation(pod, (slot,), "borrowed"),) + if form == "invocations" + else () + ) + graph = InvocationGraph( + invocations=invocations, + source_streams={slot.content_hash().to_string(): slot}, + ) + with pytest.raises(InconsistentSourceError, match="not supported yet") as error: + PipelineJob.from_invocations(graph) + elif form in prebuilt: + stream = prebuilt[form]() + with ( + receiver, + pytest.raises(InconsistentSourceError, match="not supported yet") as error, + ): + if form == "function": + scale.pod(stream, label="borrowed") + else: + total.pod(stream, label="borrowed") + else: + with ( + receiver, + pytest.raises(InconsistentSourceError, match="not supported yet") as error, + ): + mid = total.pod(slot, label="borrowed") + if form == "hashed": + _ = mid.content_hash() + slot.bound_source = _shifted_source("changed", 10) + scale.pod(mid, label="downstream") + + assert "'a'" in str(error.value) + assert "Pass the source itself" in str(error.value) + assert "as_source()" in str(error.value) + assert "ITL-1559" in str(error.value) + assert slot.bound_source is source + assert set(receiver.nodes) == {"kept", "kept_result"} + receiver.run(orchestrator=orchestrator()) + assert sorted(receiver.kept_result.as_table()["out"].to_pylist()) == [3, 7] + + +@pytest.mark.parametrize("owner_first", [True, False]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_foreign_slot_refusal_leaves_every_active_job_unchanged( + owner_first: bool, orchestrator: Orchestrator +) -> None: + source = _shifted_source("a", 0) + with PipelineJob(database=InMemoryArrowDatabase()) as owner: + total.pod(source, label="before") + with PipelineJob(database=InMemoryArrowDatabase()) as receiver: + total.pod(source, label="before") + contexts = (owner, receiver) if owner_first else (receiver, owner) + with contexts[0], contexts[1]: + with pytest.raises(InconsistentSourceError, match="not supported yet"): + product.pod(owner.nodes["a"], label="borrowed") + for job in contexts: + assert set(job.nodes) == {"a", "before"} + job.run(orchestrator=orchestrator()) + assert sorted(job.before.as_table()["out"].to_pylist()) == [3, 7] + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_capture_accepts_own_slots_and_another_jobs_stored_results( + orchestrator: Orchestrator, +) -> None: + source = _shifted_source("a", 0) + with PipelineJob(database=InMemoryArrowDatabase()) as upstream: + total.pod(source, label="before") + with upstream: + product.pod(upstream.nodes["a"], label="own_slot") + upstream.run(orchestrator=orchestrator()) + assert sorted(upstream.own_slot.as_table()["out"].to_pylist()) == [2, 12] + + @function_pod(output_keys="scaled") + def scale(out: int) -> int: + return out * 10 + + with PipelineJob(database=InMemoryArrowDatabase()) as receiver: + with pytest.raises(InconsistentSourceError, match="not supported yet"): + scale.pod(upstream.before, label="borrowed") + scale.pod(upstream.before.as_source(), label="stored") + assert "borrowed" not in receiver.nodes + receiver.run(orchestrator=orchestrator()) + assert sorted(receiver.stored.as_table()["scaled"].to_pylist()) == [30, 70] + + +@pytest.mark.parametrize("origin", ["standalone", "pipeline", "job_blueprint"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_schema_declaration_gives_each_job_its_own_binding( + origin: str, orchestrator: Orchestrator +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode, SourceNode + + original = _shifted_source("a", 0) + if origin == "pipeline": + with Pipeline("blueprint") as blueprint: + total.pod(original, label="result") + declaration = blueprint.nodes["a"] + elif origin == "job_blueprint": + with PipelineJob(database=InMemoryArrowDatabase()) as upstream: + total.pod(original, label="result") + declaration = upstream.as_pipeline().nodes["a"] + assert isinstance(upstream.nodes["a"], SourceJobNode) + assert upstream.nodes["a"].bound_source is original + else: + declaration = SourceNode.from_stream(original, name="a") + assert isinstance(declaration, SourceNode) + assert not hasattr(declaration, "bound_source") + + with PipelineJob(database=InMemoryArrowDatabase()) as first: + total.pod(declaration, label="result") + first_slot = first.nodes["a"] + assert isinstance(first_slot, SourceJobNode) + assert first_slot is not declaration + assert first_slot.bound_source is None + first.bind(sources={"a": original}) + + with PipelineJob(database=InMemoryArrowDatabase()) as second: + total.pod(declaration, label="result") + product.pod(declaration, label="reused") + second_slot = second.nodes["a"] + assert isinstance(second_slot, SourceJobNode) + assert second_slot is not first_slot + assert second_slot.bound_source is None + second_slot.bound_source = _shifted_source("b", 10) + + first.run(orchestrator=orchestrator()) + second.run(orchestrator=orchestrator()) + assert first_slot.bound_source is original + assert sorted(first.result.as_table()["out"].to_pylist()) == [3, 7] + assert sorted(second.result.as_table()["out"].to_pylist()) == [13, 17] + assert sorted(second.reused.as_table()["out"].to_pylist()) == [22, 52] + + +@pytest.mark.parametrize("wrapper", ["cache", "proxy"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_live_derived_source_refuses_a_wrapped_foreign_slot( + wrapper: str, orchestrator: Orchestrator +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.sources.cached_source import CachedSource + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.protocols.core_protocols import SourceProtocol + from orcapod.protocols.database_protocols import DatabaseRegistryProtocol + from orcapod.sources import DerivedSource + from orcapod.types import Condition + + class SourceSlot(SourceJobNode): + @property + def source_id(self) -> str: + source = self.bound_source + assert isinstance(source, DictSource) + return source.source_id + + @property + def condition(self) -> Condition: + return Condition() + + @property + def row_limit(self) -> int | None: + return None + + def to_config( + self, db_registry: DatabaseRegistryProtocol | None = None + ) -> dict[str, Any]: + source = self.bound_source + assert isinstance(source, DictSource) + return source.to_config(db_registry) + + @classmethod + def from_config( + cls, + config: dict[str, Any], + db_registry: DatabaseRegistryProtocol | None = None, + ) -> SourceProtocol: + raise NotImplementedError + + source = _shifted_source("original", 0) + foreign = SourceSlot.from_stream(source, name="foreign") + assert isinstance(foreign, SourceProtocol) + if wrapper == "cache": + origin = CachedSource(foreign, InMemoryArrowDatabase()) + else: + proxy = SourceProxy( + foreign.source_id, + foreign.content_hash().to_string(), + foreign.pipeline_hash().to_string(), + *foreign.output_schema(), + ) + proxy.bind(foreign) + origin = proxy + derived = DerivedSource(origin, tags_as_data={"t1": "copied"}, source_id="tag_copy") + + with PipelineJob(database=InMemoryArrowDatabase()) as receiver: + total.pod(source, label="kept") + with receiver: + with pytest.raises(InconsistentSourceError, match="foreign.*not supported yet"): + total.pod(derived, label="borrowed") + + assert isinstance(foreign, SourceSlot) + foreign.bound_source = _shifted_source("original", 10) + receiver.run(orchestrator=orchestrator()) + assert sorted(receiver.kept.as_table()["out"].to_pylist()) == [3, 7] + assert set(receiver.nodes) == {"original", "kept"} + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_live_derived_source_and_its_source_are_both_capturable( + orchestrator: Orchestrator, +) -> None: + from orcapod.sources import DerivedSource + + original = _shifted_source("a", 0) + derived = DerivedSource( + original, tags_as_data={"t1": "copied"}, source_id="tag_copy" + ) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + total.pod(original, label="original") + product.pod(derived, label="derived") + job.run(orchestrator=orchestrator()) + assert sorted(job.original.as_table()["out"].to_pylist()) == [3, 7] + assert sorted(job.derived.as_table()["out"].to_pylist()) == [2, 12]