diff --git a/.zed/rules b/.zed/rules index 47691fb2e..c02e143d6 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1613,6 +1613,33 @@ 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. + The ITL-1559 stopgap also refuses prebuilt streams over the job's own slots. + Build the step inside the job from the slot, or pass the source itself. + A slot binding must be independent of every bindable slot and every node + of its own job, including through stored-result sources and other wrappers + (ITL-1559). Binding, direct reads, and both job and node runs (including + load-only) report a dependency as SourceSpecMismatchError. Pass the + underlying source or use another job's node.as_source() for stored results. + A stored-result source still uses its origin's schema and keys. Binding checks + follow the origin's inputs through other jobs and refuse cycles, naming the + slots involved. A one-way stored-result binding stays supported. + 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 @@ -1620,9 +1647,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 29205c0e3..be9064757 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1662,6 +1662,33 @@ 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. + The ITL-1559 stopgap also refuses prebuilt streams over the job's own slots. + Build the step inside the job from the slot, or pass the source itself. + A slot binding must be independent of every bindable slot and every node + of its own job, including through stored-result sources and other wrappers + (ITL-1559). Binding, direct reads, and both job and node runs (including + load-only) report a dependency as SourceSpecMismatchError. Pass the + underlying source or use another job's node.as_source() for stored results. + A stored-result source still uses its origin's schema and keys. Binding checks + follow the origin's inputs through other jobs and refuse cycles, naming the + slots involved. A one-way stored-result binding stays supported. + 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 @@ -1669,9 +1696,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..34553da16 --- /dev/null +++ b/changelog.d/ITL-1469.md @@ -0,0 +1,46 @@ +### 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. Distinct IDs separate + sources only when the ID contributes to the content hash. 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. For tag-copy sources + over a bound proxy, registration uses the live Arrow types. +- A capture refused by any active pipeline or job leaves all their graphs + unchanged, including when a stored result depends on the receiving job + through another job's bindings. Successful capture still calls each active + tracker's recording callback in registration order, including trackers that + do not support weak references. Passive trackers still receive source-pod + notifications with no upstream streams. Deferred recording checks source + conflicts again when the callback is called. +- Direct reads and job and node runs recheck source binding dependencies. + If an operator or wrapper introduces a forbidden dependency after binding, + they raise `SourceSpecMismatchError` before reading sources. If source + validation refuses a job run, saving the job retains the previous run's + expected row counts. +- Bindings to stored results reject cycles across jobs and name the slots + involved. They also reject acyclic dependencies on nodes of the receiving + job. Cold side-effect row reads recheck bindings. Pipeline capture and + compilation also reject circular wrapper inputs. + +### 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. +- The ITL-1559 stopgap also refuses prebuilt streams over the receiving job's + own slots. Build the step inside the job from its slot, or pass the source + itself. +- Binding a slot to a source or stream that depends on any bindable slot or + any node of its own job raises `SourceSpecMismatchError` (ITL-1559). A + refused batch leaves all bindings intact. Pass the underlying source, or + use another job's `node.as_source()` for stored results. +- Reassigning an invocation's upstreams is unsupported after capture. + Rewiring an operator can leave stale rows in direct reads (ITL-1586). diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index 05b463882..c9615c702 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 +Most sources use their schema, `source_id` and key columns in their identity (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,18 @@ 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. For sources whose identity uses only the ID, schema and key columns, + matching those fields gives the same content hash even when the rows differ. + `DerivedSource(tags_as_data=...)` also hashes the tag-copy mapping. A derived source + without tag copies takes its identity from the producing node's content hash. + 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 0515f10ac..5111c077a 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -111,6 +111,17 @@ 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 pass its own slots directly into new steps while their +original bindings are in place. The ITL-1559 stopgap refuses streams built +outside the job over one of its own slots. Build the step from the slot inside +the job, or pass the source itself. 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: @@ -372,6 +383,31 @@ tag_schema=Schema({...}), data_schema=Schema({...}))`) means one Arrow type per zones, declare the slot with Arrow schemas (`tag_schema=pa.schema([...])`). Binding a source never changes a node's schema or where its results are stored. +A binding must be independent of every bindable source slot and every node +of its own job, including dependencies reached through operators, +`node.as_source()`, or other source wrappers. As a stopgap pending ITL-1559, +Orcapod checks this when binding, when reading the slot directly, and before +each job or node run, including a load-only run. This also protects the schema +and hash lookups needed to construct an `as_source()` result. Pass the +underlying source, or use another job's `node.as_source()` to read stored results. +The stored-result source still uses its origin's schema and keys, so Orcapod +checks the origin's inputs across jobs. If those inputs reach another node in +the receiving job, the error names that node and the receiving slot. If those +inputs form a cycle, the error names the slots in the cycle. A side-effect node +also checks its bindings when read before its first run. + +```python +from orcapod.errors import SourceSpecMismatchError +from orcapod.operators import SelectDataColumns + +projection = SelectDataColumns(["weight", "height"])(job_b.nodes["mice"]) +try: + job_a.bind(sources={"mice": projection}) +except SourceSpecMismatchError as error: + print(error) +# Binding source slot 'mice' to a source that depends on source slot 'mice' is not supported yet (ITL-1559). Pass the underlying source, or use a non-slot node's as_source() to read stored results. +``` + A job made without sources has **unbound** slots. It can still be run: nodes that depend on an unbound source are skipped, and `job.unbound_sources` lists what is missing. Bind later with `job.bind(...)`: diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 05f70d013..f4a995561 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -78,6 +78,88 @@ 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 ITL-1559 stopgap also refuses a prebuilt stream over the receiving job's +own slot. Pass that slot directly into a step inside the job, or pass the +source itself. + +Binding through a live input to any bindable slot, or binding to a node of the +receiving job even through `as_source()`, raises `SourceSpecMismatchError` +(ITL-1559). Another job's `node.as_source()` can provide stored results when its +inputs are independent of the receiving job's nodes, including through other +jobs' bindings. The error names the dependency or the slots involved in a +cycle. A refused batch preserves all existing bindings. +Direct reads and job and node runs, including load-only runs, recheck the +binding because an operator or wrapper can change its inputs after binding. + +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. Capture checks for an origin from the +receiving job, and binding validation follows the origin's inputs because the +derived source still uses the node's live schema and keys. Restriction checks +stop at the wrapper, and 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 @@ -637,12 +719,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 @@ -1028,6 +1113,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/reference/hashing.md b/docs/reference/hashing.md index bd752c850..a304b9603 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -398,7 +398,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._validate_invocation`, `pipeline/base.py:AbstractPipelineBase._validate_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 lookup keys for a validated operator input or input pair (ITL-1358) | `core/operators/index.py:Index.validate_unary_input`, `core/operators/index.py:Index.async_execute`, `core/operators/pick.py:Pick.validate_unary_input`, `core/operators/pick.py:Pick.async_execute`, `core/operators/semijoin.py:SemiJoin.validate_binary_inputs`, `core/operators/semijoin.py:SemiJoin.async_execute` | | 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..` | @@ -615,11 +616,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 1d0f7d9ce..db62a212b 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 @@ -976,7 +985,7 @@ def process( input_stream=input_stream, label=label, ) - return output_stream + return output_stream._mark_recorded(self.tracker_manager) def __call__( self, @@ -2190,7 +2199,7 @@ def process( ) return FunctionPodStream( function_pod=self, input_stream=input_stream, label=label - ) + )._mark_recorded(self.tracker_manager) def process_data( self, diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9809760af..93be1232d 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -331,7 +331,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 bindings and registrations are checked as in ``job.run()``. Every + source feeding the node is then 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 @@ -354,7 +355,13 @@ 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_live_source_bindings, + ) + require_live_source_bindings([node]) + 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). @@ -4218,6 +4225,8 @@ def head( config, ViewStatus.UNAVAILABLE, note="no database attached" ) if self._run_entry_counts is None: + if status != LoadStatus.CACHE_ONLY: + self._require_live_bindings() return self._head_without_rows( config, ViewStatus.NOT_COMPUTED, note=JOB_NODE_NOT_RUN_NOTE ) @@ -4343,6 +4352,10 @@ 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. + SourceSpecMismatchError: If a bound source now depends on a bindable slot + or the live inputs contain a cycle (ITL-1559). """ 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 4f4632f3d..46910c0d7 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1951,6 +1951,10 @@ 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. + SourceSpecMismatchError: If a bound source now depends on a bindable slot + or the live inputs contain a cycle (ITL-1559). """ from orcapod.pipeline.node_run import ( check_sources, @@ -1960,9 +1964,15 @@ 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, + require_live_source_bindings, + ) if self._loaded and not load_only: raise self._cannot_compute_error() + require_live_source_bindings([self]) + 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). @@ -2064,7 +2074,12 @@ def _current_output(self) -> StreamProtocol | None: operator changed since). Before a run in this process it holds none, whatever its cache mode and database hold (ITL-1095). """ - if self._cached_output_stream is None or self.is_stale: + from orcapod.pipeline.source_consistency import require_live_source_bindings + + if self._cached_output_stream is None: + require_live_source_bindings((self,)) + return None + if self.is_stale: return None return self._cached_output_stream @@ -2147,16 +2162,15 @@ def head( """ check_head_size(n) config = ColumnConfig.handle_config(columns, all_info=all_info) - if self._cached_output_stream is None: - return self._head_without_rows( - config, ViewStatus.NOT_COMPUTED, note=JOB_NODE_NOT_RUN_NOTE - ) - if self.is_stale: - # run() would recompute; the kept rows are not the current result. - return self._head_without_rows( - config, ViewStatus.NOT_COMPUTED, note=STALE_NOTE + current = self._current_output() + if current is None: + note = ( + JOB_NODE_NOT_RUN_NOTE + if self._cached_output_stream is None + else STALE_NOTE ) - head = head_of(self._cached_output_stream.head(n, columns=config), self) + return self._head_without_rows(config, ViewStatus.NOT_COMPUTED, note=note) + head = head_of(current.head(n, columns=config), self) if self._run_load_only: # Output of a load-only run: its input may lack rows (ITL-1095). return dataclasses.replace( diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5b69d510d..aaaa972de 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 @@ -754,7 +756,7 @@ def content_hash(self, hasher=None) -> ContentHash: The saved value stands while no source is bound (ITL-1138); a bound source gives its own identity, as for any slot. """ - if self._saved_content_hash is not None and self._bound_stream() is None: + if self._bound_stream() is None and self._saved_content_hash is not None: return self._saved_content_hash return super().content_hash(hasher) @@ -1610,6 +1612,8 @@ class SourceJobNode(ProvenanceMethods, SourceNodeBase): data_context: Optional data context override. Raises: + SourceSpecMismatchError: If *bound_source* does not fit the slot or depends + on a bindable source slot (ITL-1559). ValueError: If both *tag_schema* and *data_schema* are omitted and *bound_source* is ``None``. """ @@ -1623,6 +1627,13 @@ def __init__( data_context: str | contexts.DataContext | None = None, arrow_schemas: "tuple[pa.Schema, pa.Schema] | None" = None, ) -> None: + from orcapod.pipeline.source_consistency import ( + binding_dependency_error, + independent_source_dependency, + ) + + if (dependency := independent_source_dependency(bound_source)) is not None: + raise binding_dependency_error(dependency, name) if tag_schema is None or data_schema is None: if bound_source is None: raise ValueError( @@ -1658,6 +1669,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 @@ -1683,12 +1695,21 @@ 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. + SourceSpecMismatchError: If the bound stream now depends on a source slot + or its live inputs contain a cycle (ITL-1559). 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_live_source_bindings, + ) + require_live_source_bindings([self]) + require_consistent_sources([(f"node {self.label!r}", self)]) _ = check_sources([self]) if load_only: refuse_unloadable_inputs(self) @@ -1703,33 +1724,69 @@ 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: - SourceSpecMismatchError: If *value* does not fit the declared schema. + InconsistentSourceError: If the replacement introduces conflicting sources. + SourceSpecMismatchError: If *value* does not fit the declared schema or + depends on a bindable source slot or on this job's own node (ITL-1559). """ - self._bind(value) - self._update_modified_time() + from orcapod.pipeline.source_consistency import ( + require_live_source_bindings, + ) + + owner = self._get_binding_owner() + if owner is None: + require_live_source_bindings((self,), rebinding=((self, value),)) + 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 _get_binding_owner(self) -> PipelineJob | None: + """Return the job that owns this active slot, if any.""" + return self._binding_owner() if self._binding_owner is not None else None def _bound_stream(self) -> StreamProtocol | None: - """The concrete stream bound to this slot, or ``None``.""" + """Resolve the live binding before reading it, even if its rows are cached.""" + from orcapod.pipeline.source_consistency import require_live_source_bindings + + if self._bound_source is not None: + require_live_source_bindings((self,)) 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 once its independence from slots is checked. 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() @@ -1749,9 +1806,10 @@ def last_modified(self) -> datetime | None: source object and bind it, or clear the dependent nodes. """ own = self._modified_time - if self._bound_source is None: + source = self._bound_stream() + if source is None: return own - bound = self._bound_source.last_modified + bound = source.last_modified if bound is None or own is None: return bound return max(own, bound) @@ -1866,8 +1924,9 @@ def identity_structure(self) -> Any: Bound source's identity structure when bound; schema-based identity (inherited from SourceNodeBase) when unbound. """ - if self._bound_source is not None: - return self._bound_source.identity_structure() + source = self._bound_stream() + if source is not None: + return source.identity_structure() return super().identity_structure() def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: @@ -1878,12 +1937,13 @@ def _row_keys(self) -> tuple[tuple[str, ...], tuple[str, ...]]: and an unbound slot answer with the slot's own keys: their description reports its types undeclared (``arrow_types_declared``). """ - if self._bound_source is None or self._declared_form is not None: + source = self._bound_stream() + if source is None or self._declared_form is not None: return self.keys() - table = typed_zero_row_input(self._bound_source) + table = typed_zero_row_input(source) if table is None: return self.keys() - return keys_of_rows(table, self._bound_source.keys()) + return keys_of_rows(table, source.keys()) def arrow_schema(self) -> pa.Schema: """The Arrow schema of the columns this stream passes between job nodes. @@ -1923,7 +1983,8 @@ def _rows_table( # without a bound source): its rows, as main iterated them (ITL-1347, the # one rule). return None - if self._bound_source is None: + source = self._bound_stream() + if source is None: raise UnboundSourceError( f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before running." @@ -1931,20 +1992,20 @@ def _rows_table( if self._declared_form is not None: return None if ( - not table_is_rows(self._bound_source) - or self._bound_source.data_context_key != self.data_context_key + not table_is_rows(source) + or source.data_context_key != self.data_context_key ): # Not a library source kind whose table is its rows (a side-effect or # function pod stream, an operator's result, a raw stream, a poller), or # one whose rows report another data context than the node's: its rows, # as main iterated them (the edge table is built in the node's context). return None - table = self._bound_source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + table = source.as_table(columns=ZERO_ROW_INPUT_COLUMNS) if not system_tags_as_rows_give(table): # System tags the rows would type otherwise (a narrow integer, a # nullable field): the rows decide, as on main. return None - return table, keys_of_rows(table, self._bound_source.keys()) + return table, keys_of_rows(table, source.keys()) def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Delegate to concrete source, or raise if unbound. @@ -1952,14 +2013,15 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: Raises: UnboundSourceError: When no concrete source is attached. """ - if self._bound_source is None: + source = self._bound_stream() + if source is None: raise UnboundSourceError( f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before running." ) if self._declared_form is None: - return self._bound_source.iter_data() - return self._declared_rows(self._bound_source.iter_data(), self._declared_form) + return source.iter_data() + return self._declared_rows(source.iter_data(), self._declared_form) def _typed_zero_row_table(self) -> "pa.Table | None": """The bound source's zero-row table in the declared form; ``None`` if unknown. @@ -1969,9 +2031,10 @@ def _typed_zero_row_table(self) -> "pa.Table | None": table (ITL-1112, ITL-912). ``None`` when unbound or when the source cannot type its rows without rows. See ``typed_zero_row_table``. """ - if self._bound_source is None: + source = self._bound_stream() + if source is None: return self._declared_zero_row_table() - table = typed_zero_row_table(self._bound_source) + table = typed_zero_row_table(source) if table is None or self._declared_form is None: return table return self._declared_form.apply(table) @@ -1988,9 +2051,8 @@ def _display_name(self) -> str: def _schema_requires_io(self, config: ColumnConfig) -> bool: """Whether reading the schema with ``config`` would poll: as for the bound source.""" - return self._bound_source is not None and schema_requires_io( - self._bound_source, config - ) + source = self._bound_stream() + return source is not None and schema_requires_io(source, config) def head( self, @@ -2003,7 +2065,8 @@ def head( A narrower bound source's rows are shown as rows of the declared schema. """ - if self._bound_source is None: + source = self._bound_stream() + if source is None: check_head_size(n) return self._head_without_rows( ColumnConfig.handle_config(columns, all_info=all_info), @@ -2011,15 +2074,13 @@ def head( note="no source bound", ) if self._declared_form is None: - return head_of( - self._bound_source.head(n, columns=columns, all_info=all_info), self - ) + return head_of(source.head(n, columns=columns, all_info=all_info), self) # The source's own head, read with every column group the declared stream # needs; the declared stream then selects the asked-for groups and computes # the content hashes of the declared rows. Nothing is computed. config = ColumnConfig.handle_config(columns, all_info=all_info) view = head_of( - self._bound_source.head( + source.head( n, columns=ColumnConfig( meta=True, @@ -2031,9 +2092,9 @@ def head( ), self, ) - table = self._declared_stream( - self._bound_source, self._declared_form, view.table - ).as_table(columns=config) + table = self._declared_stream(source, self._declared_form, view.table).as_table( + columns=config + ) renames = self._declared_form.renames tag_columns = {renames.get(c, c) for c in view.tag_columns} return dataclasses.replace( @@ -2056,13 +2117,14 @@ async def async_iter_data( Raises: UnboundSourceError: When no concrete source is attached. """ - if self._bound_source is None: + source = self._bound_stream() + if source is None: raise UnboundSourceError( f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before running." ) form = self._declared_form - async for tag, data in self._bound_source.async_iter_data(): + async for tag, data in source.async_iter_data(): yield (tag, data) if form is None else self._declared_row(tag, data, form) def output_schema( @@ -2089,10 +2151,11 @@ def output_schema( Returns: Tuple of ``(tag_schema, data_schema)``. """ - if self._bound_source is None or self._declared_form is not None: + source = self._bound_stream() + if source is None or self._declared_form is not None: # Unbound, or bound to a narrower source given as the declared schema. return super().output_schema(columns=columns, all_info=all_info) - return self._bound_source.output_schema(columns=columns, all_info=all_info) + return source.output_schema(columns=columns, all_info=all_info) def as_table( self, @@ -2112,14 +2175,15 @@ def as_table( Raises: UnboundSourceError: When no concrete source is attached. """ - if self._bound_source is None: + source = self._bound_stream() + if source is None: raise UnboundSourceError( f"SourceJobNode '{self._name}' has no concrete source bound. " "Call job.bind(sources={'': source}) before calling as_table()." ) if self._declared_form is None: - return self._bound_source.as_table(columns=columns, all_info=all_info) - table = self._bound_source.as_table( + return source.as_table(columns=columns, all_info=all_info) + table = source.as_table( columns={ "meta": True, "source": True, @@ -2128,9 +2192,9 @@ def as_table( "sort_by_tags": False, } ) - return self._declared_stream( - self._bound_source, self._declared_form, table - ).as_table(columns=columns, all_info=all_info) + return self._declared_stream(source, self._declared_form, table).as_table( + columns=columns, all_info=all_info + ) @classmethod def from_stream( @@ -2169,6 +2233,9 @@ def from_stream( Returns: A ``SourceJobNode`` configured according to the case above. + + Raises: + SourceSpecMismatchError: If the stream to be bound depends on a source slot. """ match stream: case SourceJobNode(): @@ -2197,6 +2264,14 @@ def from_stream( return node case _: # Case 3: concrete stream — bound SJN. + from orcapod.pipeline.source_consistency import ( + binding_dependency_error, + independent_source_dependency, + ) + + # Schema and source-name inference can consult the live inputs. + if (dependency := independent_source_dependency(stream)) is not None: + raise binding_dependency_error(dependency, name) # Slot name priority: # 1. explicit *name* parameter # 2. stream.source_name for RootSource (its id without the kind part) diff --git a/src/orcapod/core/nodes/staleness.py b/src/orcapod/core/nodes/staleness.py index b7a140a61..d767f7f3b 100644 --- a/src/orcapod/core/nodes/staleness.py +++ b/src/orcapod/core/nodes/staleness.py @@ -8,9 +8,13 @@ from __future__ import annotations +import importlib +import weakref from collections.abc import Iterable from typing import Any +from orcapod.errors import live_input_cycle_error + class RunHoldingNode: """Mixin of the job nodes that hold the rows of their current run. @@ -22,6 +26,15 @@ class RunHoldingNode: # The summary of the node's last ``run()`` (with the nodes it ran first); a class # default so nodes rebuilt from a saved descriptor start without one. _last_run: Any = None + _pipeline_job: weakref.ReferenceType[object] | None = None + + def _set_pipeline_job(self, job: object) -> None: + """Keep a node's job provenance through recompilation without owning the job.""" + self._pipeline_job = weakref.ref(job) + + def _belongs_to_job(self, job: object) -> bool: + """Whether this node was compiled or loaded as part of this job.""" + return self._pipeline_job is not None and self._pipeline_job() is job @property def last_run(self) -> Any: @@ -43,6 +56,7 @@ def is_stale(self) -> bool: stale (ITL-1095). A stale node reads empty until it runs again. Each node of the ancestry is checked once, however many paths lead to it. """ + self._require_live_bindings() return _stale(self, {}) def _own_staleness(self) -> bool: @@ -67,8 +81,18 @@ def holds_current_run(self, *, load_only: bool = False) -> bool: Returns: ``True`` if the node holds a current run for such a run. """ + self._require_live_bindings() return _current(self, load_only, {}, {}) + def _require_live_bindings(self) -> None: + """Validate the stream graph even when there are no held rows to check.""" + # Source consistency sits above this mixin in the import graph and uses it + # to recognize job nodes. Resolve the module when the graph is checked. + source_consistency = importlib.import_module( + "orcapod.pipeline.source_consistency" + ) + source_consistency.require_live_source_bindings((self,)) + def _holds_run(self, *, load_only: bool) -> bool: """Whether the node holds the rows of a completed run good for such a run.""" raise NotImplementedError @@ -93,25 +117,30 @@ def _job_upstreams(node: Any) -> list[RunHoldingNode]: return [upstream for upstream in upstreams if isinstance(upstream, RunHoldingNode)] -def _stale(node: RunHoldingNode, memo: dict[int, bool]) -> bool: +def _stale(node: RunHoldingNode, memo: dict[int, bool | None]) -> bool: """Whether ``node`` is stale; ``memo`` keeps each node's answer for one traversal.""" key = id(node) if key not in memo: + memo[key] = None # on the active path, answer still pending memo[key] = node._own_staleness() or any( # pyright: ignore[reportPrivateUsage] # the mixin's own helper _stale(upstream, memo) for upstream in _job_upstreams(node) ) - return memo[key] + result = memo[key] + if result is None: + raise live_input_cycle_error() + return result def _current( node: RunHoldingNode, load_only: bool, - memo: dict[int, bool], - stale_memo: dict[int, bool], + memo: dict[int, bool | None], + stale_memo: dict[int, bool | None], ) -> bool: """Whether ``node`` holds a current run; memoized for one traversal.""" key = id(node) if key not in memo: + memo[key] = None # on the active path, answer still pending memo[key] = ( node._holds_run(load_only=load_only) # pyright: ignore[reportPrivateUsage] # the mixin's own hook and not _stale(node, stale_memo) @@ -120,7 +149,10 @@ def _current( for upstream in _job_upstreams(node) ) ) - return memo[key] + result = memo[key] + if result is None: + raise live_input_cycle_error() + return result def upstream_job_node_stale(upstreams: Iterable[Any]) -> bool: @@ -135,7 +167,7 @@ def upstream_job_node_stale(upstreams: Iterable[Any]) -> bool: Returns: ``True`` if any upstream ``RunHoldingNode`` is stale. """ - memo: dict[int, bool] = {} + memo: dict[int, bool | None] = {} return any( isinstance(upstream, RunHoldingNode) and _stale(upstream, memo) for upstream in upstreams diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index cae6813fe..3c1534d7c 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -328,7 +328,7 @@ def process( upstreams=streams, label=label, ) - return output_stream + return output_stream._mark_recorded(self.tracker_manager) def to_config(self) -> dict[str, Any]: """Serialize this operator to a JSON-compatible config dict. 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..13ddd5cfe 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( @@ -259,6 +260,9 @@ def __init__( record_id_columns: str | Collection[str] | None = None, **kwargs: Any, ) -> None: + from orcapod.core.nodes.staleness import RunHoldingNode + from orcapod.pipeline.source_consistency import require_live_source_bindings + key_columns = normalize_record_id_columns(record_id_columns) if tags_as_data is None: if isinstance(origin, RootSource): @@ -270,11 +274,16 @@ def __init__( raise ValueError( "record_id_columns is only used together with tags_as_data." ) - self._tags_as_data: dict[str, str] | None = None - else: + elif source_id is None: # No default source id (ITL-1313): refused before the origin is read. - if source_id is None: - raise self._missing_source_id() + raise self._missing_source_id() + + if isinstance(origin, RunHoldingNode): + # Constructing a stored-result source can inspect the live node's + # schema or hash. + require_live_source_bindings((origin,)) + self._tags_as_data: dict[str, str] | None = None + if tags_as_data is not None: # The mapping names a set of copies: they are placed in the order of their # new names, so the order it is given in changes nothing (ITL-1271). self._tags_as_data = dict( @@ -319,6 +328,7 @@ def identity_structure(self) -> Any: Returns: The identity structure. """ + self._require_origin_bindings() self._note_provisional_identity_use() # a direct read is a use (ITL-1331) if self._tags_as_data is None: # Tied precisely to the specific node's data identity @@ -425,6 +435,7 @@ def output_schema( columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False, ) -> tuple[Schema, Schema]: + self._require_origin_bindings() if self._tags_as_data is None: return self._origin.output_schema(columns=columns, all_info=all_info) return self._columns_stream(self._tags_as_data).output_schema( @@ -437,6 +448,7 @@ def keys( columns: ColumnConfig | dict[str, Any] | None = None, all_info: bool = False, ) -> tuple[tuple[str, ...], tuple[str, ...]]: + self._require_origin_bindings() if self._tags_as_data is None: return self._origin.keys(columns=columns, all_info=all_info) return self._columns_stream(self._tags_as_data).keys( @@ -471,6 +483,28 @@ def _data_tags(self) -> tuple[str, ...]: """ return stream_data_tags(self._origin) + @property + def live_source_inputs(self) -> tuple[StreamProtocol, ...] | None: + """Expose live origins while treating stored-result job nodes as leaves.""" + from orcapod.core.nodes.source_node import SourceJobNode + + return ( + (self._origin,) + if isinstance(self._origin, (RootSource, SourceJobNode)) + else None + ) + + @property + def stored_result_origin(self) -> StreamProtocol | None: + """Return the stored-result node whose live schema and keys this source uses.""" + return self._origin if self.live_source_inputs is None else None + + def _require_origin_bindings(self) -> None: + """Check the origin before obtaining even cached rows or metadata.""" + from orcapod.pipeline.source_consistency import require_live_source_bindings + + require_live_source_bindings((self,)) + def _origin_records(self) -> "pa.Table | None": """Return the origin's rows, or ``None`` when a job node has none stored. @@ -571,7 +605,21 @@ def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": the origin stores rows. Rows read later must have these types (``_origin_records``). """ - table = self._empty_origin_table() + return self._arrow_schemas_from_origin_table(self._empty_origin_table()) + + def _arrow_schemas_from_origin( + self, tags: pa.Schema, data: pa.Schema + ) -> tuple[pa.Schema, pa.Schema]: + """Apply the tag copies to a live origin's schema for source registration.""" + fields = {field.name: field for field in (*tags, *data)} + return self._arrow_schemas_from_origin_table( + pa.schema(fields.values()).empty_table() + ) + + def _arrow_schemas_from_origin_table( + self, table: pa.Table + ) -> tuple[pa.Schema, pa.Schema]: + """Project the derived tag and data schemas from an origin's empty table.""" for tag, name in (self._tags_as_data or {}).items(): table = table.append_column( table.schema.field(tag).with_name(name), table.column(tag) @@ -630,6 +678,7 @@ def _derive_from( def _get_stream(self) -> ArrowTableStream: # Every read of rows notes the provisional use, also of rows kept from an # earlier read (ITL-1331), as a provisional operator's stream does. + self._require_origin_bindings() self._note_provisional_identity_use() if self._tags_as_data is not None: if self._cached_stream is not None: @@ -680,6 +729,7 @@ def check_for_new_data(self) -> bool: ``True`` if the source's modified time moved: it holds new rows, or it holds none and its origin changed. """ + self._require_origin_bindings() if isinstance(self._origin, RootSource): _ = self._origin.check_for_new_data() seen = self._origin.last_modified @@ -714,6 +764,7 @@ def check_for_new_data(self) -> bool: def _schema_requires_io(self, config: ColumnConfig) -> bool: """Whether reading the schema with ``config`` would poll: as for the origin.""" + self._require_origin_bindings() return schema_requires_io(self._origin, config) def head( @@ -734,6 +785,7 @@ def head( its head (see ``StreamBase.head``). """ check_head_size(n) + self._require_origin_bindings() # A preview is a read of rows: it notes the provisional use (ITL-1331). self._note_provisional_identity_use() config = ColumnConfig.handle_config(columns, all_info=all_info) diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 83eb6238d..c72518e59 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -10,6 +10,7 @@ from __future__ import annotations +from contextvars import ContextVar from datetime import datetime from typing import TYPE_CHECKING, Any @@ -22,6 +23,7 @@ StreamView, head_of, ) +from orcapod.errors import live_input_cycle_error from orcapod.types import ColumnConfig from orcapod.core.streams.base import ( check_head_size, @@ -35,7 +37,16 @@ import pyarrow as pa - from orcapod.protocols.core_protocols import DataProtocol, TagProtocol + from orcapod.protocols.core_protocols import ( + DataProtocol, + StreamProtocol, + TagProtocol, + ) + + +_modification_path: ContextVar[frozenset[int]] = ContextVar( + "source_proxy_modification_path", default=frozenset() +) class SourceProxy(RootSource): @@ -95,6 +106,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`.""" @@ -174,7 +198,15 @@ def last_modified(self) -> datetime | None: own = self._modified_time if self._delegate is None: return own - bound = self._delegate.last_modified + path = _modification_path.get() + key = id(self) + if key in path: + raise live_input_cycle_error() + token = _modification_path.set(path | {key}) + try: + bound = self._delegate.last_modified + finally: + _modification_path.reset(token) if bound is None or own is None: return bound return max(own, bound) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index dcce1443f..440a057fd 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/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..78d6ae944 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -17,7 +17,8 @@ from contextlib import contextmanager from contextvars import ContextVar from datetime import datetime -from typing import TYPE_CHECKING, Any, cast +from typing import TYPE_CHECKING, Any, Self, cast +from weakref import ReferenceType, ref import pandas as pd import polars as pl @@ -45,6 +46,7 @@ from orcapod.utils import arrow_utils if TYPE_CHECKING: + from orcapod.protocols.core_protocols import TrackerManagerProtocol, TrackerProtocol from orcapod.types.explanation import Explanation # TODO: consider using this instead of making copy of dicts @@ -751,6 +753,25 @@ def _rename_map( class StreamBase(TraceableBase): + _recording_trackers: tuple[ReferenceType[TrackerProtocol], ...] = () + + def _mark_recorded(self, manager: TrackerManagerProtocol) -> Self: + """Remember recording provenance where a tracker supports weak references.""" + recordings: list[ReferenceType[TrackerProtocol]] = [] + for tracker in manager.get_active_trackers(): + try: + recordings.append(ref(tracker)) + except TypeError: + # Trackers implementing only the public protocol can use slots + # without weak-reference support. Their callbacks still run. + continue + self._recording_trackers = tuple(recordings) + return self + + def _was_recorded_by(self, tracker: TrackerProtocol) -> bool: + """Check recording provenance without comparing stream hashes.""" + return any(recording() is tracker for recording in self._recording_trackers) + @property @abstractmethod def producer(self) -> PodProtocol | None: ... diff --git a/src/orcapod/core/tracker.py b/src/orcapod/core/tracker.py index 16ecb1803..8ebceb775 100644 --- a/src/orcapod/core/tracker.py +++ b/src/orcapod/core/tracker.py @@ -1,12 +1,23 @@ 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, Protocol, runtime_checkable from orcapod.protocols import core_protocols as cp +if TYPE_CHECKING: + from orcapod.pipeline.pod_invocation import PodInvocation + + +@runtime_checkable +class _PreparesInvocation(Protocol): + """Optional validation before dispatching a capture to multiple trackers.""" + + def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: ... + class BasicTrackerManager: def __init__(self) -> None: @@ -35,13 +46,19 @@ 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), + lambda tracker: tracker.record_operator_pod_invocation( + pod, upstreams, label=label + ), + ) def record_function_pod_invocation( self, @@ -50,8 +67,14 @@ 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), + lambda tracker: tracker.record_function_pod_invocation( + pod, input_stream, label=label + ), + ) def record_side_effect_pod_invocation( self, @@ -60,8 +83,34 @@ 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), + lambda tracker: tracker.record_side_effect_pod_invocation( + pod, input_stream, label=label + ), + ) + + def _record( + self, + make_invocation: Callable[[], PodInvocation], + record: Callable[[cp.TrackerProtocol], None], + ) -> None: + """Preflight nested captures before dispatching the recording callbacks.""" + trackers = self.get_active_trackers() + if len(trackers) > 1: + preparers = [ + tracker + for tracker in trackers + if isinstance(tracker, _PreparesInvocation) + ] + if preparers: + invocation = make_invocation() + for tracker in preparers: + _ = tracker.prepare_invocation(invocation) + for tracker in trackers: + record(tracker) @contextmanager def no_tracking(self) -> Generator[None, Any, None]: diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index eda66139c..87ccfa54b 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -612,28 +612,41 @@ class UnboundSourceError(RuntimeError): class SourceSpecMismatchError(InputValidationError, ValueError): - """Raised when a concrete source's schema differs from a source slot's declared schema. + """Raised for an incompatible source binding or a cycle in live inputs. A source fits a slot when its tag and data columns have the slot's names, roles and Python types (ITL-1112): those are what every downstream pipeline hash, and so every stored path, is built from. The message names the slot and the column, and for a type - difference both types. Raised by ``PipelineJob.bind(sources=...)`` and by assigning a - source node's ``bound_source``, before anything is bound. + difference both types. For a slot-dependent source, the message names the + dependency and any known receiving slot (ITL-1559). The error is raised before + installing, reading or running with an invalid binding. """ +def live_input_cycle_error( + label: str | None = None, *, slots: tuple[str, ...] = () +) -> SourceSpecMismatchError: + """Report a cycle found while following live and stored-result inputs.""" + if slots: + location = " through source slots " + ", ".join(map(repr, slots)) + else: + location = "" if label is None else f" at {label!r}" + return SourceSpecMismatchError( + f"A cycle in the live input graph{location} is not supported (ITL-1559). " + "Remove the circular input or replace it with an independent source." + ) + + 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. Distinct ``source_id`` values + give sources distinct hashes only when the ID contributes to the hash. """ diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 966809d94..b4134b9c4 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -4,8 +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 functools import partial +from itertools import chain from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar from orcapod.core.nodes.function_node import FunctionNodeBase @@ -17,6 +19,11 @@ PodInvocation, SideEffectInvocation, ) +from orcapod.pipeline.source_consistency import ( + invocation_source_uses, + require_consistent_sources, + require_live_source_bindings, +) from orcapod.side_effects import SideEffectNode from orcapod.protocols import core_protocols as cp from orcapod.utils.lazy_module import LazyModule @@ -26,6 +33,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 +55,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. """ @@ -60,7 +72,7 @@ def _refuse_sources_sharing_a_slot_name( described = ( ", ".join(repr(i) for i in ids) if len(ids) > 1 - else f"{ids[0]!r} ({len(sources)} sources with other key columns or rows)" + else f"{ids[0]!r} ({len(sources)} distinct content hashes)" ) raise SourceSlotNameCollisionError( f"{len(sources)} different sources would take the slot name {slot_name!r}: " @@ -125,6 +137,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. @@ -309,7 +323,40 @@ def record_side_effect_pod_invocation( ) def _record_invocation(self, invocation: PodInvocation) -> None: - """Store *invocation* and update the topology graph. + """Validate the invocation and record it immediately.""" + key, input_keys = self._validate_invocation(invocation) + self._remember_invocation(key, invocation, input_keys) + self._hash_graph.add_node(key) + for upstream, upstream_hash in zip( + invocation.input_streams, input_keys, strict=True + ): + self._hash_graph.add_edge(upstream_hash, key) + self._source_streams.setdefault(upstream_hash, upstream) + + 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. + + The callback validates again against the graph as it stands when called. + + Args: + invocation: The pod invocation to record. + + Returns: + A callback that validates and records the invocation. + + Raises: + ValueError: If the invocation cannot be recorded in the current graph. + """ + self._validate_invocation(invocation) + return partial(self._record_invocation, invocation) + + def _validate_invocation( + self, invocation: PodInvocation + ) -> tuple[str, tuple[str, ...]]: + """Check whether a capture can be recorded and resolve its graph keys. Non-source nodes in ``_persistent_node_map`` are keyed by the corresponding ``PodInvocation.content_hash()`` string. For @@ -330,6 +377,9 @@ def _record_invocation(self, invocation: PodInvocation) -> None: Args: invocation: The pod invocation to record. + Returns: + The invocation hash and the upstream stream hashes. + Raises: ValueError: If the invocation reads a source under another restriction than the pipeline's streams read it under now, or two of its inputs @@ -338,43 +388,48 @@ def _record_invocation(self, invocation: PodInvocation) -> None: """ 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) + uses = tuple(self._source_uses(invocation)) + require_live_source_bindings(stream for _, stream in uses) + 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 + require_consistent_sources(uses) + require_one_restriction(stream for _, stream in uses) - def _remember_invocation(self, key: str, invocation: PodInvocation) -> None: + return key, input_keys + + 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 + 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. + invocations = chain( + reversed(self._invocation_lut.values()), + (extra,) if extra is not None else (), + ) + yield from invocation_source_uses(invocations) + for stream in self._source_streams.values(): + yield f"source {stream.label!r}", stream - 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 - ), - ] + 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) @@ -508,14 +563,17 @@ 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_live_source_bindings(stream for _, stream in 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 +632,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 +856,27 @@ def from_invocations( A compiled instance of ``cls``. """ instance = cls(name=name) + inputs = tuple( + chain( + graph.source_streams.values(), + chain.from_iterable( + invocation.input_streams for invocation in graph.invocations + ), + ) + ) + instance._validate_capture_sources(inputs) + require_live_source_bindings(inputs) + require_consistent_sources(invocation_source_uses(graph.invocations)) 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 0b58b8f37..482898a33 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -698,6 +698,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 diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 82f59257c..d64b113dc 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -6,8 +6,9 @@ import enum import logging import sys -from collections.abc import Iterator +from collections.abc import Iterable, Iterator, Sequence from dataclasses import dataclass +from itertools import chain from typing import TYPE_CHECKING, Any, cast import orcapod @@ -15,11 +16,14 @@ from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode +from orcapod.core.nodes.staleness import RunHoldingNode +from orcapod.core.sources.base import RootSource from orcapod.core.sources.derived_source import DerivedSource from orcapod.core.streams.base import StreamBase from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.core.tracker import AutoRegisteringContextBasedTracker from orcapod.errors import ( + InconsistentSourceError, OrcapodDatabaseError, OrcapodDatabaseReadError, OrcapodDatabaseWriteError, @@ -36,6 +40,7 @@ refuse_restricted_operator_caches, refuse_restriction_conflicts, restrictions_in_force, + streams_beneath, warn_restricted_aggregation, ) from orcapod.pipeline.run_summary import ( @@ -44,6 +49,13 @@ run_node_summaries, warn_row_failures, ) +from orcapod.pipeline.source_consistency import ( + binding_dependency_error, + independent_source_dependency, + invocation_source_uses, + require_consistent_sources, + require_live_source_bindings, +) from orcapod.protocols import core_protocols as cp from orcapod.databases.utils import as_table_committing from orcapod.types import NodeConfig @@ -52,9 +64,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 +207,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). @@ -222,6 +236,103 @@ 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 captures that can detach a slot.""" + # 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. + # A prebuilt stream can retain an own slot after compile replaces it. + # Only recorded steps are rewired to their job's current slots. + own_nodes = {id(node) for node in self._persistent_node_map.values()} + visited: set[tuple[int, bool]] = set() + pending = [(stream, False) for stream in streams] + while pending: + stream, prebuilt = pending.pop() + key = id(stream), prebuilt + if key in visited: + continue + visited.add(key) + if ( + isinstance(stream, DerivedSource) + and stream.stored_result_origin is not None + and (dependency := independent_source_dependency(stream, self)) + is not None + ): + # The stored origin ends the live capture walk. Its metadata + # still follows bindings, which must be valid for the new slot. + raise binding_dependency_error(dependency, stream.source_name) + if isinstance(stream, SourceJobNode): + if id(stream) not in own_nodes: + 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." + ) + if prebuilt: + raise InconsistentSourceError( + f"Capturing a prebuilt stream over source slot {stream.name!r} " + "is not supported yet (ITL-1559). Build the step inside the " + "job from its slot, or pass the source itself." + ) + elif id(stream) not in own_nodes and not ( + isinstance(stream, StreamBase) and stream._was_recorded_by(self) + ): + prebuilt = True + pending.extend((upstream, prebuilt) for upstream in 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.""" + stream = self._source_streams[key] + if key in self._rebound_source_keys: + slot = self._persistent_node_map.get(key) + if isinstance(slot, SourceJobNode): + stream = slot + source = stream.bound_source if isinstance(stream, SourceJobNode) else stream + if (dependency := independent_source_dependency(source, self)) is not None: + name = None + if isinstance(stream, SourceJobNode): + name = stream.name + elif isinstance(stream, RootSource): + name = stream.source_name + raise binding_dependency_error(dependency, name) + return self.source_node_class.from_stream(stream) + def compile(self) -> None: """Compile recorded invocations into a frozen DAG of job nodes. @@ -239,29 +350,30 @@ 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) - + 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 + previous_sources = self._sources + self._sources = {} + for key, node in self._persistent_node_map.items(): + if isinstance(node, RunHoldingNode): + node._set_pipeline_job(self) # pyright: ignore[reportPrivateUsage] # compiled node provenance + if isinstance(node, SourceJobNode): + if not self._loaded: + 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 + if self._loaded: + # Loaded jobs have no recorded invocations (ITL-1560). Preserve the + # bindings restored from the saved job when recompiling. + self._sources.update(previous_sources) # Invalidate the lazy compiled_pipeline cache. self._compiled_pipeline = None @@ -395,7 +507,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 +520,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,8 +576,12 @@ 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. + declared names, roles or types, or the source depends on a bindable + source slot or a node of this job (ITL-1559). ValueError: If a source key has no matching ``SourceJobNode`` slot, or an operator node that caches (``LOG`` or ``REPLAY``) would read a restricted source, one this bind binds or one already bound @@ -506,9 +615,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 +628,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 +647,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 +655,62 @@ 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() + # Walk the proposed bindings in input order so a refused batch names the + # same receiving slot as a single bind, then check the rest of the graph. + require_live_source_bindings( + chain((slot for slot, _ in rebinding), nodes), + rebinding=rebinding, + ) + 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() # ------------------------------------------------------------------ @@ -1059,6 +1201,8 @@ def run( ``job.nodes``. Raises: + SourceSpecMismatchError: If a bound source now depends on a bindable slot + or the live inputs contain a cycle (ITL-1559). ValueError: If no database is set, or ``commit_every_rows`` is not a positive integer smaller than the database's ``batch_size``. RuntimeError: If no pipeline has been compiled, or the job was built @@ -1151,6 +1295,7 @@ async def run_async( Raises: TypeError: If ``orchestrator`` is not an ``AsyncPipelineOrchestrator``; run a ``SyncPipelineOrchestrator`` with ``job.run``. + SourceSpecMismatchError: As for ``run``. ValueError: As for ``run``. RuntimeError: As for ``run``. OrcapodDatabaseWriteError: As for ``run``. @@ -1238,8 +1383,8 @@ def _prepare_run( "computation, create a fresh PipelineJob from the original pipeline " "definition." ) - # Until this run finishes, what the database holds for a node is not certain. - self._last_run_finished = False + # Live inputs can change in place after a binding has been checked. + require_live_source_bindings(self._persistent_node_map.values()) # The job's database, then a separate result database (ITL-1408): each one # that commits table by table. @@ -1302,6 +1447,14 @@ 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() + ) + # Once source preflight passes, stored row counts may change during the run. + self._last_run_finished = False + hash_dag: OrcaDAG[str] = OrcaDAG() for u, v in self._graph_edges: hash_dag.add_edge(u, v) @@ -1764,6 +1917,11 @@ 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). + SourceSpecMismatchError: If a reconstructed source depends on a bindable + source slot (ITL-1559). 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 +2006,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() ): @@ -1870,15 +2029,33 @@ def load( check_saved_source_config(src_config) except ValueError as exc: raise ValueError(f"{path}: source {spec_name!r}: {exc}") from exc + failure: Exception | None = None try: - source = resolve_source_from_config(src_config) - 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). + # 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] + except Exception as exc: + failure = exc + else: + if source is None: + continue + if (dependency := independent_source_dependency(source)) is not None: + raise binding_dependency_error(dependency, spec_name) + try: + # A rebuilt source whose column types changed is treated as + # one that could not be rebuilt (ITL-1112). if spec_name in slots: slots[spec_name].validate(source) + except Exception as exc: + failure = exc + else: sources[spec_name] = source - except NotImplementedError: + + if isinstance(failure, NotImplementedError): # In-memory sources (DictSource, ListSource, ArrowTableSource, # DataFrameSource) are not saved with the job, by design. logger.info( @@ -1891,12 +2068,12 @@ def load( spec_name, spec_name, ) - except Warning: + elif isinstance(failure, Warning): # A warning turned into an error (a ProvisionalHashWarning under an # error filter) is the caller's request: it propagates, never read as a # source that could not be rebuilt (ITL-1331). - raise - except Exception as exc: + raise failure + elif failure is not None: logger.warning( "Could not reconstruct source %r (%s) from its saved config: %s. " "Stored function-node results are still readable from the database. " @@ -1905,11 +2082,15 @@ def load( spec_name, saved_source_kind(src_config), # Its type, never its text (ITL-1391). - type(exc).__name__, + type(failure).__name__, spec_name, 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 @@ -2061,9 +2242,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 {} @@ -2140,6 +2320,8 @@ def load( # Callers needing blueprint nodes for rendering use job.pipeline.dag. job_dag: OrcaDAG = OrcaDAG() for node in job._persistent_node_map.values(): + if isinstance(node, RunHoldingNode): + node._set_pipeline_job(job) # pyright: ignore[reportPrivateUsage] # restored node provenance job_dag.add_node(node) for u_hash, v_hash in job._graph_edges: u_node = job._persistent_node_map.get(u_hash) 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/node_run.py b/src/orcapod/pipeline/node_run.py index b1799c170..a18f23049 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -18,7 +18,11 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any -from orcapod.errors import OrcapodDatabaseError, OrcapodDatabaseWriteError +from orcapod.errors import ( + OrcapodDatabaseError, + OrcapodDatabaseWriteError, + live_input_cycle_error, +) from orcapod.pipeline.run_summary import ( RunCountingObserver, RunSummary, @@ -425,23 +429,29 @@ def run_with_dependencies( from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator graph: OrcaDAG[Any] = OrcaDAG() - seen: list[Any] = [] + active: set[int] = set() + seen: set[int] = set() outside: list[Any] = [] def visit(node: Any) -> None: """Add ``node`` and what it depends on, up to the sources of the job.""" - if any(node is other for other in seen): + key = id(node) + if key in active: + raise live_input_cycle_error() + if key in seen: return - seen.append(node) + seen.add(key) graph.add_node(node) if isinstance(node, SourceJobNode): return if not _is_job_node(node): outside.append(node) return + active.add(key) for upstream in node.upstreams: visit(upstream) graph.add_edge(upstream, node) + active.remove(key) visit(target) plan = plan_run(graph, load_only=load_only, outside=outside) 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..ea5ac9be8 --- /dev/null +++ b/src/orcapod/pipeline/source_consistency.py @@ -0,0 +1,347 @@ +"""Validate source object registrations within one graph.""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Iterable +from dataclasses import dataclass +from typing import TYPE_CHECKING, cast + +from orcapod.errors import ( + InconsistentSourceError, + SourceSpecMismatchError, + live_input_cycle_error, +) +from orcapod.utils.schema_utils import arrow_schema_identity + +if TYPE_CHECKING: + import pyarrow as pa + + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.sources.base import RootSource + from orcapod.pipeline.job import PipelineJob + 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 binding_dependency_error( + dependency: StreamProtocol, name: str | None = None +) -> SourceSpecMismatchError: + """Name the dependency that makes a slot binding unsupported.""" + from orcapod.core.nodes.source_node import SourceJobNode + + target = "a source slot" if name is None else f"source slot {name!r}" + if isinstance(dependency, SourceJobNode): + detail = f"source slot {dependency.name!r}" + remedy = "use a non-slot node's as_source() to read stored results" + else: + detail = f"node {dependency.label!r} of the same job" + remedy = "use another job's node.as_source() to read stored results" + return SourceSpecMismatchError( + f"Binding {target} to a source that depends on {detail} " + f"is not supported yet (ITL-1559). Pass the underlying source, or {remedy}." + ) + + +def owned_node_dependency( + stream: StreamProtocol, owner: PipelineJob +) -> StreamProtocol | None: + """Return an own-job node read directly or through a stored-result source.""" + from orcapod.core.nodes.staleness import RunHoldingNode + from orcapod.core.sources.derived_source import DerivedSource + + dependency = ( + stream.stored_result_origin if isinstance(stream, DerivedSource) else stream + ) + if isinstance(dependency, RunHoldingNode) and dependency._belongs_to_job(owner): # pyright: ignore[reportPrivateUsage] # binding checks use node provenance + return dependency + return None + + +@dataclass(frozen=True) +class _Binding: + """The policy for a slot's source, with an optional slot still being inferred.""" + + owner: PipelineJob | None + slot: SourceJobNode | None = None + + +def _binding_dependency( + streams: Iterable[StreamProtocol], + binding: _Binding | None = None, + rebinding: Rebinding = (), +) -> StreamProtocol | None: + """Walk live and stored-result dependencies before a read resolves them. + + The path tracks identity across all wrappers and jobs. At a stored-result + origin the live-slot restriction ends. The metadata dependency still leads + into the origin's inputs and bound slots, where the receiving binding's + own-job restriction applies. Check that ancestry after the cycle walk so + cycles still report all their slots. + """ + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.sources.derived_source import DerivedSource + from orcapod.pipeline.restrictions import streams_beneath + + pending = [(stream, binding, False) for stream in reversed(tuple(streams))] + active: dict[int, StreamProtocol] = {} + visited: set[tuple[int, bool, int]] = set() + stored_bindings: list[tuple[StreamProtocol, PipelineJob, SourceJobNode | None]] = [] + while pending: + stream, current_binding, leaving = pending.pop() + identity = id(stream) + owner = current_binding.owner if current_binding is not None else None + key = (identity, current_binding is not None, id(owner)) + if leaving: + del active[identity] + visited.add(key) + continue + if current_binding is not None: + dependency = None + if isinstance(stream, SourceJobNode): + dependency = stream + elif owner is not None: + dependency = owned_node_dependency(stream, owner) + if dependency is not None: + if current_binding.slot is None: + return dependency + raise binding_dependency_error(dependency, current_binding.slot.name) + if identity in active: + cycle = list(active.values())[list(active).index(identity) :] + slots = [node for node in cycle if isinstance(node, SourceJobNode)] + if len(slots) == 1 and not any( + isinstance(node, DerivedSource) + and node.stored_result_origin is not None + for node in cycle + ): + raise binding_dependency_error(slots[0], slots[0].name) + raise live_input_cycle_error( + stream.label, slots=tuple(slot.name for slot in slots) + ) + if key in visited: + continue + active[identity] = stream + pending.append((stream, current_binding, True)) + if ( + isinstance(stream, DerivedSource) + and (origin := stream.stored_result_origin) is not None + ): + if current_binding is not None and owner is not None: + stored_bindings.append((origin, owner, current_binding.slot)) + pending.append((origin, None, False)) + else: + if isinstance(stream, SourceJobNode): + slot_owner = stream._get_binding_owner() # pyright: ignore[reportPrivateUsage] # active slot's provenance + current_binding = _Binding(slot_owner, stream) + pending.extend( + (upstream, current_binding, False) + for upstream in reversed(streams_beneath(stream, rebinding)) + ) + + checked_origins: set[tuple[int, int]] = set() + for origin, owner, slot in stored_bindings: + ancestry = [origin] + while ancestry: + stream = ancestry.pop() + origin_key = (id(stream), id(owner)) + if origin_key in checked_origins: + continue + checked_origins.add(origin_key) + dependency = owned_node_dependency(stream, owner) + if dependency is not None: + if slot is None: + return dependency + raise binding_dependency_error(dependency, slot.name) + if ( + isinstance(stream, DerivedSource) + and (stored_origin := stream.stored_result_origin) is not None + ): + ancestry.append(stored_origin) + else: + ancestry.extend(reversed(streams_beneath(stream, rebinding))) + return None + + +def independent_source_dependency( + source: StreamProtocol | None, owner: PipelineJob | None = None +) -> StreamProtocol | None: + """Return a forbidden dependency before inferring or creating a source slot.""" + if source is None: + return None + return _binding_dependency((source,), _Binding(owner)) + + +def require_live_source_bindings( + streams: Iterable[StreamProtocol], rebinding: Rebinding = () +) -> None: + """Check live bindings before resolving schemas or hashes, reading rows or running.""" + _binding_dependency(streams, rebinding=rebinding) + + +def invocation_source_uses(invocations: Iterable[PodInvocation]) -> Iterable[SourceUse]: + """Name each invocation's inputs, numbering occurrences of repeated labels.""" + labelled = [ + ( + invocation.label + or getattr(invocation.pod, "label", type(invocation.pod).__name__), + invocation, + ) + for invocation in invocations + ] + counts = Counter(label for label, _ in labelled) + occurrences: Counter[str] = Counter() + for label, invocation in labelled: + step = f"step {label!r}" + if counts[label] > 1: + occurrences[label] += 1 + step += f" (occurrence {occurrences[label]})" + for index, stream in enumerate(invocation.input_streams, 1): + name = step + 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 a bound proxy's live Arrow types without changing source identity.""" + from orcapod.core.sources.cached_source import CachedSource + from orcapod.core.sources.derived_source import DerivedSource + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.core.streams.base import typed_arrow_schemas + + visited: set[int] = set() + + def live_schemas( + current: StreamProtocol, from_proxy: bool = False + ) -> tuple[pa.Schema, pa.Schema] | None: + if id(current) in visited: + return None + visited.add(id(current)) + if isinstance(current, CachedSource): + return live_schemas(current.cached_source, from_proxy=from_proxy) + if ( + isinstance(current, SourceProxy) + and (delegate := current.delegate) is not None + ): + return live_schemas(delegate, from_proxy=True) + if isinstance(current, DerivedSource) and ( + inputs := current.live_source_inputs + ): + origin_schemas = live_schemas(inputs[0]) + if origin_schemas is not None: + return current._arrow_schemas_from_origin(*origin_schemas) # pyright: ignore[reportPrivateUsage] # source consistency + return typed_arrow_schemas(current) if from_proxy else None + + schemas = live_schemas(source) or 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..a816ebfd5 100644 --- a/src/orcapod/protocols/core_protocols/trackers.py +++ b/src/orcapod/protocols/core_protocols/trackers.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from contextlib import AbstractContextManager from typing import Protocol, runtime_checkable @@ -10,7 +12,7 @@ @runtime_checkable class TrackerProtocol(Protocol): """ - Records kernel invocations and stream creation for computational graph tracking. + Internal contract for recording invocations and stream creation. Trackers are responsible for maintaining the computational graph by recording relationships between kernels, streams, and invocations. They enable: diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index dd691c62d..866298130 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -716,7 +716,7 @@ def process( side_effect_pod=self, input_stream=input_stream, label=label, - ) + )._mark_recorded(self.tracker_manager) def __call__( self, *streams: StreamProtocol, label: str | None = None @@ -1320,7 +1320,9 @@ def _current_rows(self) -> list[tuple[TagProtocol, DataProtocol]] | None: Held rows go stale, and are dropped, when an upstream changed after the run: the judgement ``FunctionJobNode`` uses for the rows it holds. """ - if self._held_rows is not None and self.is_stale: + if self._held_rows is None: + self._require_live_bindings() + elif self.is_stale: self._held_rows = None return self._held_rows @@ -1422,6 +1424,10 @@ 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. + SourceSpecMismatchError: If a bound source now depends on a bindable slot + or the live inputs contain a cycle (ITL-1559). """ 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/nodes/test_source_node.py b/tests/test_core/nodes/test_source_node.py index c88734df7..f59312046 100644 --- a/tests/test_core/nodes/test_source_node.py +++ b/tests/test_core/nodes/test_source_node.py @@ -8,6 +8,7 @@ from orcapod.core.nodes.source_node import SourceJobNode from orcapod.errors import SourceSpecMismatchError, UnboundSourceError +from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Schema @@ -252,6 +253,61 @@ def test_bound_source_property_updates_in_place(self, tag_schema, data_schema): job_node.bound_source = src assert job_node.bound_source is src + @pytest.mark.parametrize( + "length", [1, 2, 3], ids=["direct", "one_projection", "two_projections"] + ) + def test_slot_binding_refuses_cycles( + self, tag_schema: Schema, data_schema: Schema, length: int + ) -> None: + """Refuse a cycle and keep the previous binding and rows.""" + from orcapod.core.sources.dict_source import DictSource + from orcapod.operators import SelectDataColumns + + source = DictSource( + data=[{"id": 1, "value": 1.0}], tag_columns=["id"], tag_only_columns=True + ) + target = SourceJobNode( + name="target", + tag_schema=tag_schema, + data_schema=data_schema, + bound_source=source, + ) + upstream: StreamProtocol = target + for _ in range(length - 1): + upstream = SelectDataColumns(["value"])(upstream) + previous_modified = target.last_modified + + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'target'.*slot 'target'.*ITL-1559" + ): + target.bound_source = upstream + + assert target.bound_source is source + assert target.last_modified == previous_modified + assert target.as_table().equals(source.as_table()) + + @pytest.mark.parametrize("cached", [False, True]) + def test_slot_binding_accepts_slot_free_source_and_unbinding( + self, tag_schema: Schema, data_schema: Schema, cached: bool + ) -> None: + """Bind and unbind an independent source, with or without a cache.""" + from orcapod.core.sources.dict_source import DictSource + from orcapod.databases import InMemoryArrowDatabase + + source = DictSource( + data=[{"id": 1, "value": 1.0}], tag_columns=["id"], tag_only_columns=True + ) + binding = source.cached(InMemoryArrowDatabase()) if cached else source + target = SourceJobNode( + name="slot", tag_schema=tag_schema, data_schema=data_schema + ) + target.bound_source = binding + + assert target.bound_source is binding + assert target.as_table().equals(source.as_table()) + target.bound_source = None + assert target.bound_source is None + def test_bound_source_setter_clears_content_hash_cache( self, tag_schema, data_schema ): diff --git a/tests/test_core/operators/test_polars_filter_warning.py b/tests/test_core/operators/test_polars_filter_warning.py index 8e249807d..612d9f22d 100644 --- a/tests/test_core/operators/test_polars_filter_warning.py +++ b/tests/test_core/operators/test_polars_filter_warning.py @@ -201,11 +201,12 @@ def _saved_job(tmp_path: Path, *, rebuildable: bool) -> Path: [pl.col("depth") >= 10] if rebuildable else [[True, False, True]] ) job = PipelineJob(name="filtered", database=DeltaTableDatabase(tmp_path / "store")) + source = _source() with warnings.catch_warnings(): warnings.simplefilter("ignore", PolarsFilterWarning) with job: - _ = _source().polars_filter(*first, session="s1", label="first") - _ = _source().polars_filter(*second, unit=3, label="second") + _ = source.polars_filter(*first, session="s1", label="first") + _ = source.polars_filter(*second, unit=3, label="second") path = tmp_path / "job.json" job.save(path) return path 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..d5d8871da 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,14 +749,15 @@ 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 job: - same.pod( - events.where(col("unit") < 2).select_data_columns(["n"]), label="a" - ) - same.pod( - events.where(col("unit") >= 2).select_data_columns(["n"]), label="b" - ) + with job: + same.pod( + events.where(col("unit") < 2).select_data_columns(["n"]), label="a" + ) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): + events.where(col("unit") >= 2).select_data_columns(["n"], label="b") + assert {"a", "b"} & job.nodes.keys() == {"a"} def test_a_saved_job_keeps_the_window_in_canonical_order(self, project, tmp_path): store = tmp_path / "store" 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..d6de06ffc 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,10 +1098,13 @@ 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 job: - first.pod(events.where(subject_id="m1"), label="first") + with job: + first.pod(events.where(subject_id="m1"), label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): second.pod(events.where(subject_id="m2"), label="second") + assert {"first", "second"} & job.nodes.keys() == {"first"} def test_streams_built_before_the_capture_are_checked_too(self, project, tmp_path): """Streams over differently restricted sources, built outside, are refused.""" @@ -1120,10 +1123,13 @@ 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 job: - first.pod(m1, label="first") + with job: + first.pod(m1, label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): second.pod(m2, label="second") + assert {"first", "second"} & job.nodes.keys() == {"first"} @pytest.mark.parametrize( "captured, prebuilt", @@ -1152,13 +1158,26 @@ 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 job: - if prebuilt_first: - first.pod(outside, label="first") - events.where(**captured).select_data_columns(["amplitude"]) - if not prebuilt_first: + with job: + if prebuilt_first: + first.pod(outside, label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): + events.where(**captured).select_data_columns( + ["amplitude"], label="selected" + ) + else: + events.where(**captured).select_data_columns( + ["amplitude"], label="selected" + ) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): first.pod(outside, label="first") + assert {"first", "selected"} & job.nodes.keys() == { + "first" if prebuilt_first else "selected" + } @pytest.mark.parametrize( "prebuilt_first", [False, True], ids=["captured first", "prebuilt first"] @@ -1166,22 +1185,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,17 +1241,20 @@ 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 job: + with job: + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): events.where(subject_id="m1").semi_join( events.where(subject_id="m2"), label="both" ) + assert not job.nodes @pytest.mark.parametrize("restrict", [False, True]) 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 +1266,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,10 +1312,13 @@ 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 job: - first.pod(_source(source_id="events", limit=1), label="first") + with job: + first.pod(_source(source_id="events", limit=1), label="first") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): second.pod(_source(source_id="events", limit=2), label="second") + assert {"first", "second"} & job.nodes.keys() == {"first"} def test_node_run_reports_the_restriction(self, project, tmp_path): """A node's own ``run()`` reports the restriction in the same shape.""" @@ -1498,6 +1520,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 +1746,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 +1927,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 +2025,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 +2036,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) @@ -2035,11 +2108,16 @@ def test_a_proxy_and_a_source_restricted_two_ways_are_refused_at_capture( proxy = self._bound_proxy("a condition") # subject_id='m1' 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 job: - first.select_data_columns(["amplitude"], label="a") + job = PipelineJob( + name="two", database=DeltaTableDatabase(tmp_path / "s"), auto_compile=False + ) + with job: + first.select_data_columns(["amplitude"], label="a") + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): second.select_data_columns(["channel"], label="b") + assert {inv.label for inv in job._invocation_lut.values()} == {"a"} def test_a_cache_over_a_proxy_bound_later_refuses_to_read(self, project, tmp_path): proxy = _proxy_for(_events()) @@ -2105,7 +2183,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") @@ -2116,30 +2194,24 @@ def test_nothing_changes_and_a_second_bind_behaves_alike( assert after[0] is before[0] and after[1] is before[1] @pytest.mark.parametrize("mode", _CACHING, ids=lambda m: m.name) - @pytest.mark.parametrize("inner_name", ["events", "inner"]) @pytest.mark.parametrize("with_database", [True, False], ids=["db", "no-db"]) - def test_a_slot_over_a_restricted_slot_is_refused_before_anything_changes( - self, project, tmp_path, mode, inner_name, with_database + def test_binding_a_restricted_source_is_refused_before_anything_changes( + self, project, tmp_path, mode, with_database ): - """A source to bind that is itself a slot (of another job) bound to a - restricted source: its restriction is read, whatever its name. Only the - job's own slots take the source being bound (CodeRabbit, PR 435).""" - from orcapod.core.nodes.source_node import SourceJobNode - + """Refuse a cache over a prospective restricted binding (PR 435).""" store = DeltaTableDatabase(tmp_path / "s") job = TestRestrictionThroughWrappers._cached_job(store, mode) node, slot = job.nodes["rename"], job.nodes["events"] - inner = SourceJobNode.from_stream(_events(), name=inner_name) - inner.bound_source = _events().where(subject_id="m1") + restricted = _events().where(subject_id="m1") before = (job.database, node._pipeline_database, slot.bound_source) # pyright: ignore[reportPrivateUsage] other = DeltaTableDatabase(tmp_path / "other") for _ in range(2): with pytest.raises(ValueError, match="cannot cache a restricted read"): if with_database: - job.bind(sources={"events": inner}, database=other) + job.bind(sources={"events": restricted}, database=other) else: - job.bind(sources={"events": inner}) + job.bind(sources={"events": restricted}) after = (job.database, node._pipeline_database, slot.bound_source) # pyright: ignore[reportPrivateUsage] assert all(a is b for a, b in zip(after, before, strict=True)) @@ -2185,10 +2257,14 @@ 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 job: - chains[first_chain](_events().where(subject_id="m1")) + with job: + chains[first_chain](_events().where(subject_id="m1")) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): chains[second_chain](second()) + assert "events" in job.nodes + assert len(job.nodes) == (3 if first_chain == "map then select" else 2) @pytest.mark.parametrize("order", ["m1 first", "m2 first"]) @pytest.mark.parametrize( @@ -2210,9 +2286,12 @@ 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 job: + with job: + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ): first.semi_join(second, label="both") + assert not job.nodes @pytest.mark.parametrize("order", ["select first", "drop first"]) def test_one_restriction_through_two_chains_is_accepted( @@ -2221,22 +2300,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 +2320,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 +2330,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 +2424,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 +2436,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 +2456,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 +2504,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 +2524,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 +2570,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 +2586,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_core/test_tracker.py b/tests/test_core/test_tracker.py index 046239abb..1f7c4024b 100644 --- a/tests/test_core/test_tracker.py +++ b/tests/test_core/test_tracker.py @@ -16,9 +16,12 @@ from __future__ import annotations +from dataclasses import dataclass, field + import pyarrow as pa import pytest +from orcapod import side_effect_pod from orcapod.core.function_pod import FunctionPod, function_pod from orcapod.core.nodes import FunctionNode, OperatorNode, SourceNode from orcapod.core.nodes.source_node import SourceJobNode @@ -26,8 +29,11 @@ from orcapod.core.data_function import PythonDataFunction from orcapod.core.sources.arrow_table_source import ArrowTableSource from orcapod.core.streams import ArrowTableStream -from orcapod.core.tracker import BasicTrackerManager +from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER, BasicTrackerManager from orcapod.pipeline import Pipeline +from orcapod.protocols import core_protocols as cp +from orcapod.side_effects import SideEffectPod +from orcapod.sources import DictSource from orcapod.types import Schema # --------------------------------------------------------------------------- @@ -54,6 +60,144 @@ def _make_pipeline( ) +def test_capture_calls_existing_tracker_callbacks_in_registration_order() -> None: + callbacks: list[tuple[str, str | None]] = [] + + class RecordingPipeline(Pipeline): + def record_operator_pod_invocation( + self, + pod: cp.OperatorPodProtocol, + upstreams: tuple[cp.StreamProtocol, ...] = (), + label: str | None = None, + ) -> None: + callbacks.append((self.name[0], label)) + super().record_operator_pod_invocation(pod, upstreams, label=label) + + def record_function_pod_invocation( + self, + pod: cp.FunctionPodProtocol, + input_stream: cp.StreamProtocol, + label: str | None = None, + ) -> None: + callbacks.append((self.name[0], label)) + super().record_function_pod_invocation(pod, input_stream, label=label) + + def record_side_effect_pod_invocation( + self, + pod: cp.SideEffectPodProtocol, + input_stream: cp.StreamProtocol, + label: str | None = None, + ) -> None: + callbacks.append((self.name[0], label)) + super().record_side_effect_pod_invocation(pod, input_stream, label=label) + + @function_pod(output_keys="value") + def transform(x: int) -> int: + return x * 2 + + @side_effect_pod + def deliver(x: int) -> None: + pytest.fail("Capturing a side effect must never deliver") + + assert isinstance(deliver, SideEffectPod) + source = DictSource([{"x": 1}]) + with RecordingPipeline("first") as first, RecordingPipeline("second") as second: + _ = source.map_data({"x": "value"}, label="operator") + _ = transform.pod(source, label="function") + _ = deliver.process(source, label="side_effect") + + assert callbacks == [ + (name, label) + for label in ("operator", "function", "side_effect") + for name in ("first", "second") + ] + assert {"operator", "function", "side_effect"} <= first.nodes.keys() + assert first.nodes.keys() == second.nodes.keys() + + +@dataclass(slots=True, eq=False) +class InvocationLog: + """Record tracker notifications in arrival order.""" + + events: list[tuple[str, str | None]] = field(default_factory=list) + active: bool = True + + def set_active(self, active: bool = True) -> None: + """Set whether this tracker accepts notifications.""" + self.active = active + + def is_active(self) -> bool: + """Return whether this tracker accepts notifications.""" + return self.active + + def record_operator_pod_invocation( + self, + pod: cp.OperatorPodProtocol, + upstreams: tuple[cp.StreamProtocol, ...] = (), + label: str | None = None, + ) -> None: + """Log an operator notification.""" + self.events.append(("operator", label)) + + def record_function_pod_invocation( + self, + pod: cp.FunctionPodProtocol, + input_stream: cp.StreamProtocol, + label: str | None = None, + ) -> None: + """Log a function notification.""" + self.events.append(("function", label)) + + def record_side_effect_pod_invocation( + self, + pod: cp.SideEffectPodProtocol, + input_stream: cp.StreamProtocol, + label: str | None = None, + ) -> None: + """Log a side-effect notification.""" + self.events.append(("side_effect", label)) + + +def test_source_pod_notification_reaches_both_passive_trackers() -> None: + """Forward an empty-upstream notification to both protocol-only trackers.""" + manager = BasicTrackerManager() + first, second = InvocationLog(), InvocationLog() + manager.register_tracker(first) + manager.register_tracker(second) + manager.record_operator_pod_invocation(SelectTagColumns(["id"]), label="source") + assert first.events == second.events == [("operator", "source")] + + +@pytest.mark.parametrize("kind", ["operator", "function", "side_effect"]) +def test_capture_accepts_trackers_without_weak_reference_support(kind: str) -> None: + """Record each invocation even when the tracker cannot be weakly referenced.""" + + @function_pod(output_keys="value") + def transform(x: int) -> int: + return x * 2 + + @side_effect_pod + def deliver(x: int) -> None: + pytest.fail("Capturing a side effect must never deliver") + + assert isinstance(deliver, SideEffectPod) + tracker = InvocationLog() + source = DictSource([{"x": 1}]) + DEFAULT_TRACKER_MANAGER.register_tracker(tracker) + try: + if kind == "operator": + stream = source.map_data({"x": "value"}, label="mapped") + elif kind == "function": + stream = transform.pod(source, label="mapped") + else: + stream = deliver.process(source, label="mapped") + finally: + DEFAULT_TRACKER_MANAGER.deregister_tracker(tracker) + + assert stream.label == "mapped" + assert tracker.events == [(kind, "mapped")] + + def _make_source_node(name: str = "test_spec") -> SourceNode: """SourceNode matching the schema of _make_stream().""" return SourceNode( 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/test_bind_narrower_source.py b/tests/test_pipeline/test_bind_narrower_source.py index 8f555bc75..37733fb65 100644 --- a/tests/test_pipeline/test_bind_narrower_source.py +++ b/tests/test_pipeline/test_bind_narrower_source.py @@ -23,6 +23,8 @@ import orcapod from orcapod import PipelineJob, function_pod +from orcapod.core.function_pod import FunctionPod +from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.source_node import SourceJobNode, SourceNode from orcapod.core.operators import Join, MapData from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -583,24 +585,22 @@ def _xw_job() -> PipelineJob: def test_meta_columns_of_a_narrower_stream_are_kept() -> None: """The ``__`` columns a job node's rows carry reach the rows of a narrower bind.""" - @function_pod(output_keys="x") def same(v: int) -> int: """Return ``v``.""" return v - origin = PipelineJob(name="origin", database=InMemoryArrowDatabase()) - with origin: - _ = same.pod( - DictSource( - [{"id": 0, "v": 1}], - tag_columns=["id"], - tag_only_columns=True, - source_id="o", - ), - label="same", - ) - _ = origin.run() - stream = origin.nodes["same"] + stream = FunctionJobNode( + FunctionPod.from_fn(same, output_keys="x"), + DictSource( + [{"id": 0, "v": 1}], + tag_columns=["id"], + tag_only_columns=True, + source_id="o", + ), + pipeline_database=InMemoryArrowDatabase(), + label="same", + ) + _ = stream.run() job = PipelineJob(name="j", database=InMemoryArrowDatabase()) with job: _ = MapData({"x": "y"})(_slot(int | None), label="renamed") 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..a745e03c9 --- /dev/null +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -0,0 +1,920 @@ +"""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 MapData, SemiJoin +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.pod_invocation import OperatorInvocation +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 + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_cached_bound_proxy_uses_the_live_derived_schema(reverse: bool) -> None: + origin = ArrowTableSource( + pa.table({"t1": ["a"], "t2": ["b"], "x": pa.array([1], type=pa.int32())}), + tag_columns=["t1", "t2"], + tag_only_columns=True, + infer_nullable=True, + source_id="origin", + ) + first = DerivedSource(origin, tags_as_data={"t1": "copy"}, source_id="shared") + second = DerivedSource(origin, tags_as_data={"t2": "copy"}, source_id="shared") + assert first.content_hash() != second.content_hash() + proxy = SourceProxy( + first.source_id, + first.content_hash().to_string(), + first.pipeline_hash().to_string(), + *first.output_schema(), + ) + cached = proxy.cached(InMemoryArrowDatabase()) + assert cached.arrow_schemas[1].field("x").type == pa.int64() + proxy.bind(first) + assert first.arrow_schemas[1] == second.arrow_schemas[1] + assert first.arrow_schemas[1].field("x").type == pa.int32() + + # Prebuilt projections get their own slots, so the two sources are compared + # without also colliding on a direct slot name. + projected = { + "left": cached.map_data({"x": "left_x"}), + "right": second.map_data({"x": "right_x"}), + } + with Pipeline("comparison") as pipeline: + for label in ("right", "left") if reverse else ("left", "right"): + projected[label].map_data({f"{label}_x": "out"}, label=label) + assert {"left", "right"} <= pipeline.nodes.keys() + + +@pytest.mark.parametrize("cached_origin", [False, True]) +@pytest.mark.parametrize("same_arrow_type", [False, True]) +def test_tag_copy_uses_live_arrow_schema_after_proxy_binding( + cached_origin: bool, same_arrow_type: bool +) -> None: + def origin(arrow_type: pa.DataType) -> ArrowTableSource: + return ArrowTableSource( + pa.table( + { + "t1": pa.array([1], type=arrow_type), + "t2": pa.array([2], type=arrow_type), + "x": pa.array([3], type=arrow_type), + "y": [4], + } + ), + tag_columns=["t1", "t2"], + tag_only_columns=True, + infer_nullable=True, + source_id="origin", + ) + + live = origin(pa.int32()) + proxy = SourceProxy( + live.source_id, + live.content_hash().to_string(), + live.pipeline_hash().to_string(), + *live.output_schema(), + ) + wrapped = proxy.cached(InMemoryArrowDatabase()) if cached_origin else proxy + first = DerivedSource(wrapped, tags_as_data={"t1": "copy"}, source_id="shared") + assert first.arrow_schemas[1].field("x").type == pa.int64() + captured_hash = first.content_hash() + proxy.bind(live) + + second = DerivedSource( + origin(pa.int32() if same_arrow_type else pa.int64()), + tags_as_data={"t2": "copy"}, + source_id="shared", + ) + assert first.content_hash() != second.content_hash() + # Prebuilt projections separate the slot names so the guard compares the sources. + left = first.map_data({"x": "left_x"}) + right = second.map_data({"x": "right_x"}) + with Pipeline("comparison") as pipeline: + left.map_data({"left_x": "out"}, label="left") + if same_arrow_type: + right.map_data({"right_x": "out"}, label="right") + else: + with pytest.raises(InconsistentSourceError, match="different schemas"): + right.map_data({"right_x": "out"}, label="right") + assert "left" in pipeline.nodes + assert ("right" in pipeline.nodes) == same_arrow_type + assert first.content_hash() == captured_hash + assert first.arrow_schemas[1].field("x").type == pa.int64() + + +def test_refused_source_run_preserves_saved_expected_rows(tmp_path: Path) -> None: + """Keep the prior row counts when the source check refuses a new run.""" + + def source(kind: pa.DataType) -> ArrowTableSource: + """Build a tagged source whose columns all use the given Arrow type.""" + return ArrowTableSource( + pa.table({name: pa.array([1, 2], type=kind) for name in ("t1", "t2", "x")}), + tag_columns=["t1", "t2"], + tag_only_columns=True, + infer_nullable=True, + source_id="origin", + ) + + narrow = source(pa.int32()) + wide = source(pa.int64()) + proxy = SourceProxy( + narrow.source_id, + narrow.content_hash().to_string(), + narrow.pipeline_hash().to_string(), + *narrow.output_schema(), + ) + left = DerivedSource(proxy, tags_as_data={"t1": "copy"}, source_id="shared") + right = DerivedSource(narrow, tags_as_data={"t2": "copy"}, source_id="shared") + assert left.arrow_schemas[1].field("x").type == pa.int64() + proxy.bind(narrow) + + with PipelineJob(database=InMemoryArrowDatabase()) as job: + _ = increment.pod( + DerivedSource(wide, tags_as_data={"t1": "copy"}, source_id="slot_a"), + label="left", + ) + _ = increment_again.pod( + DerivedSource(narrow, tags_as_data={"t2": "copy"}, source_id="slot_b"), + label="right", + ) + job.bind(sources={"slot_a": left, "slot_b": right}) + _ = job.run() + path = tmp_path / "job.json" + job.save(path) + expected = json.loads(path.read_text())["run"]["expected_rows"] + assert expected["left"] == expected["right"] == 2 + + proxy.unbind() + with pytest.raises(InconsistentSourceError, match="different schemas"): + _ = job.run() + proxy.bind(narrow) + job.save(path) + assert json.loads(path.read_text())["run"].get("expected_rows") == expected + + +@pytest.mark.parametrize("label", [None, "repeated"]) +def test_capture_distinguishes_repeated_step_labels(label: str | None) -> None: + name = label or "increment" + with Pipeline("repeated-steps") as pipeline: + increment.pod(_dict(1), label=label) + with pytest.raises( + InconsistentSourceError, match="distinct source objects" + ) as error: + increment.pod(_dict(2), label=label) + assert f"step {name!r} (occurrence 1)" in str(error.value) + assert f"step {name!r} (occurrence 2)" in str(error.value) + assert name in pipeline.nodes + + +@pytest.mark.parametrize("graph_type", [Pipeline, PipelineJob]) +def test_same_slot_name_describes_distinct_derived_sources_with_equal_rows( + graph_type: type[Pipeline] | type[PipelineJob], +) -> None: + origin = DictSource( + [{"t1": "a", "t2": "a", "x": 1, "y": 2}], + tag_columns=["t1", "t2"], + tag_only_columns=True, + ) + first = DerivedSource(origin, tags_as_data={"t1": "copy"}, source_id="shared") + second = DerivedSource(origin, tags_as_data={"t2": "copy"}, source_id="shared") + assert first.as_table().equals(second.as_table()) + with pytest.raises(SourceSlotNameCollisionError, match="2 distinct content hashes"): + with graph_type("collision"): + first.map_data({"x": "left_x"}, label="left") + second.map_data({"x": "right_x"}, label="right") + + +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: + """Refuse different Arrow schemas during capture and during binding.""" + + def source(kind: pa.DataType, name: str) -> ArrowTableSource: + """Build the named source with the given physical Arrow type.""" + 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") + assert "different schemas" in _capture(first, second, increment.pod) + + 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) + + +def test_deferred_capture_refuses_new_source_conflict() -> None: + """Recheck the graph when a previously prepared invocation records.""" + + pipeline = Pipeline("deferred capture") + first = _dict(1) + second = _dict(2) + initial = MapData({"x": "initial"}) + other = MapData({"x": "other"}) + record_first = pipeline.prepare_invocation( + OperatorInvocation(initial, (first,), "first") + ) + record_conflicting = pipeline.prepare_invocation( + OperatorInvocation(other, (second,), "conflicting") + ) + record_shared = pipeline.prepare_invocation( + OperatorInvocation(other, (first,), "reused") + ) + record_first() + before = pipeline.graph.copy() + with pytest.raises(InconsistentSourceError, match="distinct source objects"): + record_conflicting() + assert set(pipeline.graph.nodes) == set(before.nodes) + assert set(pipeline.graph.edges) == set(before.edges) + record_shared() + pipeline.compile() + assert set(pipeline.nodes) == {"first", "reused", "shared"} + + +@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..bdafae460 --- /dev/null +++ b/tests/test_pipeline/test_source_object_registration.py @@ -0,0 +1,2137 @@ +"""A pipeline binds each source content hash to a single object (ITL-1469).""" + +from __future__ import annotations + +import asyncio +import json +import re +from collections.abc import Iterable +from pathlib import Path +from typing import Any, cast + +import pytest + +from orcapod import Pipeline, PipelineJob, function_pod, side_effect_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InconsistentSourceError, SourceSpecMismatchError +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.protocols.core_protocols import SourceProtocol, 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: + """Build the named source with optional changes to values and column order.""" + 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]: + """Return distinct sources with the same content hash and optional row changes.""" + 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: + """Compile independent slots with different sources and function identities.""" + 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: + """Rebind by independent setter calls or one atomic batch.""" + 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("setter", [False, True], ids=["batch_bind", "owned_setter"]) +def test_job_binding_refuses_slot_cycles_atomically( + tmp_path: Path, setter: bool +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + + job = _job(tmp_path) + slot_a = cast(SourceJobNode, job.nodes["a"]) + slot_b = cast(SourceJobNode, job.nodes["b"]) + original_a, original_b = slot_a.bound_source, slot_b.bound_source + previous_modified = slot_a.last_modified, slot_b.last_modified + original_database = job.database + + dependency = "a" if setter else "b" + with pytest.raises( + SourceSpecMismatchError, match=rf"slot 'a'.*slot '{dependency}'.*ITL-1559" + ): + if setter: + slot_a.bound_source = slot_a + else: + job.bind( + sources={"a": slot_b, "b": slot_a}, + database=InMemoryArrowDatabase(), + ) + + assert slot_a.bound_source is original_a + assert slot_b.bound_source is original_b + assert job.sources["a"] is original_a + assert job.sources["b"] is original_b + assert (slot_a.last_modified, slot_b.last_modified) == previous_modified + assert job.database is original_database + + +@pytest.mark.parametrize("path", ["standalone_setter", "owned_setter", "batch_bind"]) +def test_binding_refuses_projection_over_the_receiving_slot( + tmp_path: Path, path: str +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns + + job = _job(tmp_path) + original = job.sources["a"] + slot = ( + SourceJobNode("a", bound_source=original) + if path == "standalone_setter" + else cast(SourceJobNode, job.nodes["a"]) + ) + view = SelectDataColumns(["x", "y"])(slot) + before = job.sources + + with pytest.raises( + SourceSpecMismatchError, + match=r"slot 'a'.*slot 'a'.*not supported yet.*ITL-1559", + ): + if path == "batch_bind": + job.bind(sources={"b": _shifted_source("replacement", 10), "a": view}) + else: + slot.bound_source = view + + assert slot.bound_source is original + assert job.sources == before + assert slot.run().table.to_pylist() == ROWS + assert job.nodes["b"].bound_source is before["b"] + + +@pytest.mark.parametrize("load_only", [False, True]) +@pytest.mark.parametrize( + "entry", ["sync", "async_orchestrator", "run_async", "slot", "node"] +) +def test_run_refuses_slot_cycle_created_by_upstream_replacement( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, entry: str, load_only: bool +) -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns + + job = _job(tmp_path) + slot = cast(SourceJobNode, job.nodes["a"]) + source = job.sources["a"] + projection = OperatorJobNode(SelectDataColumns(["x", "y"]), [source]) + job.bind(sources={"a": projection}) + _ = projection.run() + assert slot.run().table.to_pylist() == ROWS + projection.upstreams = (slot,) + + def unexpected_check() -> bool: + pytest.fail("A source was checked before the invalid binding was refused") + + monkeypatch.setattr(job.sources["b"], "check_for_new_data", unexpected_check) + with pytest.raises(SourceSpecMismatchError, match=r"slot 'a'.*slot 'a'.*ITL-1559"): + if entry == "run_async": + _ = asyncio.run(job.run_async(load_only=load_only)) + elif entry == "slot": + _ = slot.run(load_only=load_only) + elif entry == "node": + _ = job.nodes["result_a"].run(load_only=load_only) + else: + orch = ( + AsyncPipelineOrchestrator + if entry == "async_orchestrator" + else SyncPipelineOrchestrator + ) + _ = job.run(orchestrator=orch(), load_only=load_only) + + projection.upstreams = (source,) + assert slot.bound_source is projection + assert slot.run().table.to_pylist() == ROWS + + +def test_standalone_slot_run_refuses_cycle_created_by_upstream_replacement() -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns + + source = _shifted_source("ordinary", 10) + projection = OperatorJobNode(SelectDataColumns(["x", "y"]), [source]) + slot = SourceJobNode("standalone", bound_source=projection) + _ = projection.run() + projection.upstreams = (slot,) + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'standalone'.*slot 'standalone'.*ITL-1559" + ): + _ = slot.run() + + +@pytest.mark.parametrize( + "entry", + ["table", "iteration", "async_iteration", "hash", "head", "preview", "as_source"], +) +def test_standalone_reads_refuse_slot_cycle_created_by_upstream_replacement( + entry: str, +) -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns + + source = DictSource( + [{"t": "a", "x": 80}, {"t": "b", "x": 81}], + source_id="ordinary", + tag_columns=["t"], + tag_only_columns=True, + ) + projection = OperatorJobNode( + SelectDataColumns(["x"]), [source], pipeline_database=InMemoryArrowDatabase() + ) + slot = SourceJobNode("a", bound_source=projection) + projection.upstreams = (slot,) + + async def read_async() -> None: + _ = [row async for row in slot.async_iter_data()] + + message = r"slot 'a'.*slot 'a'.*ITL-1559.*Pass the underlying source" + if entry == "preview": + preview = slot._repr_html_() + assert re.search(message, preview) + return + reads = { + "table": slot.as_table, + "iteration": lambda: list(slot.iter_data()), + "async_iteration": lambda: asyncio.run(read_async()), + "hash": slot.content_hash, + "head": slot.head, + "as_source": projection.as_source, + } + with pytest.raises(SourceSpecMismatchError, match=message): + _ = reads[entry]() + + +@pytest.mark.parametrize("warm", [False, True]) +@pytest.mark.parametrize("entry", ["run", "table", "iteration", "head", "preview"]) +def test_live_binding_refuses_foreign_slot_introduced_by_proxy_rebind( + tmp_path: Path, warm: bool, entry: str +) -> None: + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.sources import CachedSource, DerivedSource + + foreign = _job(tmp_path).nodes["b"] + ordinary = DerivedSource( + _shifted_source("ordinary", 10), source_id="copy", tags_as_data={"t1": "copy"} + ) + candidate = DerivedSource( + CachedSource( + cast(SourceProtocol, foreign), cache_database=InMemoryArrowDatabase() + ), + source_id="copy", + tags_as_data={"t1": "copy"}, + ) + proxy = SourceProxy( + ordinary.source_id, + ordinary.content_hash().to_string(), + ordinary.pipeline_hash().to_string(), + *ordinary.output_schema(), + ) + proxy.bind(ordinary) + outer = DerivedSource(proxy, source_id="outer", tags_as_data={"t2": "other"}) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + _ = total.pod(outer, label="result") + slot = job.nodes["outer"] + if warm: + assert slot.as_table()["x"].to_pylist() == [11, 13] + if entry == "run": + _ = job.run() + + proxy.bind(candidate) + message = r"slot 'outer'.*slot 'b'.*ITL-1559.*Pass the underlying source" + if entry == "preview": + assert re.search(message, slot._repr_html_()) + elif entry == "run": + for run in (slot.run, job.nodes["result"].run, job.run): + with pytest.raises(SourceSpecMismatchError, match=message): + _ = run() + else: + reads = { + "table": slot.as_table, + "iteration": lambda: list(slot.iter_data()), + "head": slot.head, + } + with pytest.raises(SourceSpecMismatchError, match=message): + _ = reads[entry]() + + +def test_operator_run_cycle_diagnostic_names_the_step_and_remedy() -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + + source = _shifted_source("ordinary", 10) + projection = OperatorJobNode(SelectDataColumns(["x"]), [source], label="project") + projection.upstreams = (projection,) + + with pytest.raises( + SourceSpecMismatchError, + match=r"cycle.*'project'.*ITL-1559.*Remove the circular input", + ): + _ = projection.run() + + +def test_warm_operator_read_validates_live_bindings_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Avoid a second validation walk when staleness already checks the operator.""" + from orcapod.pipeline import source_consistency + + with PipelineJob(database=InMemoryArrowDatabase()) as job: + _ = _source(tmp_path, "dict", "rows").map_data({"x": "value"}, label="mapped") + _ = job.run() + mapped = job.nodes["mapped"] + validate = source_consistency.require_live_source_bindings + calls = 0 + + def count_validation(streams: Iterable[StreamProtocol]) -> None: + """Count validations starting at the compiled operator.""" + nonlocal calls + roots = tuple(streams) + if len(roots) == 1 and roots[0] is mapped: + calls += 1 + validate(roots) + + monkeypatch.setattr( + source_consistency, "require_live_source_bindings", count_validation + ) + assert mapped.held_row_count() == len(ROWS) + assert calls == 1 + + +@pytest.mark.parametrize("target", ["proxy", "slot"]) +def test_last_modified_and_run_refuse_cycle_through_proxy_delegate(target: str) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.sources import DerivedSource + + source = _shifted_source("ordinary", 10) + proxy = SourceProxy( + source.source_id, + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + *source.output_schema(), + ) + proxy.bind(source) + derived = DerivedSource(proxy, source_id="copy", tags_as_data={"t1": "copy"}) + slot = SourceJobNode("a", bound_source=derived) + proxy.bind(proxy) + + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"): + _ = (proxy if target == "proxy" else slot).last_modified + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"): + _ = slot.run(load_only=True) + proxy.bind(source) + assert slot.last_modified is not None + + +def test_staleness_refuses_cycle_of_job_operators() -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + + source = _shifted_source("ordinary", 10) + projection = OperatorJobNode(SelectDataColumns(["x", "y"]), [source]) + _ = projection.run() + projection.upstreams = (projection,) + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"): + _ = projection.is_stale + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"): + _ = projection.run() + projection.upstreams = (source,) + assert not projection.is_stale + + +@pytest.mark.parametrize("name", [None, "a"]) +@pytest.mark.parametrize("wrapper", ["cache", "projection"]) +def test_from_stream_refuses_slot_dependency_before_inferring_name( + tmp_path: Path, name: str | None, wrapper: str +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SelectDataColumns + from orcapod.sources import CachedSource + + foreign = cast(SourceJobNode, _job(tmp_path).nodes["b"]) + candidate = ( + CachedSource( + cast(SourceProtocol, cast(object, foreign)), + cache_database=InMemoryArrowDatabase(), + ) + if wrapper == "cache" + else SelectDataColumns(["x", "y"])(foreign) + ) + target = r"slot 'a'" if name else r"a source slot" + with pytest.raises( + SourceSpecMismatchError, + match=rf"{target}.*slot 'b'.*ITL-1559.*Pass the underlying source.*as_source\(\)", + ): + _ = SourceJobNode.from_stream(candidate, name=name) + + +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +@pytest.mark.parametrize("kind", ["direct", "projection", "join", "cached", "derived"]) +def test_bind_refuses_other_slots_atomically_and_recompile_preserves_rows( + tmp_path: Path, kind: str, orchestrator: Orchestrator +) -> None: + from orcapod.operators import Join, SelectDataColumns + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.sources import CachedSource, DerivedSource + + job = _job(tmp_path, ("a", "b", "c")) + slot_b, slot_c = job.nodes["b"], job.nodes["c"] + candidate: StreamProtocol = slot_b + if kind == "projection": + candidate = SelectDataColumns(["x", "y"])(slot_b) + elif kind == "join": + candidate = Join()( + SelectDataColumns(["x"])(slot_b), SelectDataColumns(["y"])(slot_c) + ) + elif kind == "cached": + candidate = CachedSource( + cast(SourceProtocol, slot_b), cache_database=InMemoryArrowDatabase() + ) + elif kind == "derived": + candidate = DerivedSource( + cast(FunctionJobNode, slot_b), + source_id="from_slot", + tags_as_data={"t1": "t"}, + ) + + before = job.sources + with pytest.raises( + SourceSpecMismatchError, + match=r"slot 'a'.*slot '[bc]'.*not supported yet.*ITL-1559", + ): + job.bind(sources={"c": _shifted_source("replacement", 10), "a": candidate}) + + for name, source in before.items(): + assert job.sources[name] is job.nodes[name].bound_source is source + assert job.nodes[name].as_table().to_pylist() == ROWS + job.compile() + assert all( + job.nodes[name].bound_source is source for name, source in before.items() + ) + job.run(orchestrator=orchestrator()) + assert sorted(job.nodes["result_a"].as_table()["out"].to_pylist()) == [3, 7] + assert sorted(job.nodes["result_b"].as_table()["out"].to_pylist()) == [-1, -1] + assert sorted(job.nodes["result_c"].as_table()["out"].to_pylist()) == [2, 12] + + +@pytest.mark.parametrize("bound", [False, True]) +@pytest.mark.parametrize("path", ["constructor", "from_pipeline", "load"]) +def test_initial_bind_refuses_a_foreign_slot( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, bound: bool, path: str +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.pipeline import serialization + + other = _job(tmp_path) + foreign = cast(SourceJobNode, other.nodes["b"]) + if not bound: + foreign.bound_source = None + old_binding = foreign.bound_source + job = _job(tmp_path) + match = r"slot 'a'.*slot 'b'.*not supported yet.*ITL-1559" + + if path == "constructor": + with pytest.raises(SourceSpecMismatchError, match=match): + SourceJobNode("a", bound_source=foreign) + elif path == "from_pipeline": + pipeline = job.as_pipeline() + with pytest.raises(SourceSpecMismatchError, match=match): + PipelineJob.from_pipeline(pipeline, sources={"a": foreign}) + else: + job_path = tmp_path / "job.json" + job.save(job_path) + monkeypatch.setattr( + serialization, "resolve_source_from_config", lambda _config: foreign + ) + with pytest.raises(SourceSpecMismatchError, match=match): + PipelineJob.load(job_path) + + assert foreign.bound_source is old_binding + assert job.nodes["a"].as_table().to_pylist() == ROWS + + +@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, monkeypatch: pytest.MonkeyPatch +) -> None: + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SemiJoin + + first, conflict = _pair(tmp_path, "different", False) + right = _source(tmp_path, "dict", "other") + composite = SemiJoin()(first, right, label="matched") + slot = SourceJobNode.from_stream(composite, name="standalone") + # Simulate a rewired composite; its original binding uses only plain sources. + monkeypatch.setattr(composite, "_upstreams", (first, 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): + """Return two same-hash wrappers, one reusable source, and its input column.""" + 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): + """Build the selected stream over the same original source.""" + 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_recompiling_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 + + loaded.compile() + + assert set(loaded.sources) == set(before) == {"a"} + assert loaded.sources["a"] is before["a"] + + +@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) + expected_binding = source + 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 == "hashed": + mid = total.pod(slot, label="borrowed") + _ = mid.content_hash() + expected_binding = _shifted_source("changed", 10) + slot.bound_source = expected_binding + with ( + receiver, + pytest.raises(InconsistentSourceError, match="not supported yet") as error, + ): + scale.pod(mid, label="downstream") + 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, + ): + total.pod(slot, label="borrowed") + + 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 expected_binding + 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 + + stored_source = upstream.before.as_source() + with PipelineJob(database=InMemoryArrowDatabase()) as receiver: + with pytest.raises(InconsistentSourceError, match="not supported yet"): + scale.pod(upstream.before, label="borrowed") + scale.pod(stored_source, label="stored") + assert "borrowed" not in receiver.nodes + receiver.bind(sources={stored_source.source_name: stored_source}) + 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] + + +@pytest.mark.parametrize("setter", [False, True], ids=["bind", "setter"]) +@pytest.mark.parametrize("orchestrator", ORCHESTRATORS) +def test_prebuilt_stream_over_own_slot_is_refused_before_rebinding( + setter: bool, orchestrator: Orchestrator +) -> None: + from orcapod.operators import SelectDataColumns + + source = _shifted_source("a", 0) + replacement = _shifted_source("b", 10) + with PipelineJob(database=InMemoryArrowDatabase()) as job: + total.pod(source, label="direct") + + slot = job.nodes["a"] + prebuilt = SelectDataColumns(["x", "y"])(slot) + with Pipeline("also_tracking") as outer, job: + with pytest.raises( + InconsistentSourceError, match="'a'.*not supported yet" + ) as error: + total.pod(prebuilt, label="rejected") + assert "ITL-1559" in str(error.value) + assert "inside the job" in str(error.value) + + assert not outer.nodes + assert set(job.nodes) == {"a", "direct"} + slot = job.nodes["a"] + prebuilt_twin = SelectDataColumns(["x", "y"])(slot) + with job: + difference.pod(slot, label="own_slot") + recorded = SelectDataColumns(["x", "y"])(slot) + total.pod(recorded, label="inside") + assert prebuilt_twin.content_hash() == recorded.content_hash() + with pytest.raises(InconsistentSourceError, match="'a'.*not supported yet"): + total.pod(prebuilt_twin, label="rejected_twin") + assert {"rejected", "rejected_twin"}.isdisjoint(job.nodes) + + _rebind(job, {"a": replacement}, setter) + job.run(orchestrator=orchestrator()) + assert sorted(job.direct.as_table()["out"].to_pylist()) == [13, 17] + assert sorted(job.inside.as_table()["out"].to_pylist()) == [13, 17] + assert sorted(job.own_slot.as_table()["out"].to_pylist()) == [9, 9] + + +@function_pod(output_keys=("x", "y")) +def same_columns(x: int, y: int) -> tuple[int, int]: + """Return both input columns so stored results fit the original slot.""" + return x, y + + +def _stored_result_job( + kind: str, offset: int = 0, *, copy: bool = False +) -> PipelineJob: + """Materialize an operator or function result with the input column names.""" + from orcapod.types import CacheMode + + from orcapod.sources import DerivedSource + + base = _shifted_source("a", offset) + source = ( + DerivedSource(base, source_id="a", tags_as_data={"t1": "copy"}) + if copy + else base + ) + database = InMemoryArrowDatabase() + with PipelineJob("stored", database=database) as job: + if kind == "operator": + _ = source.select_data_columns(["x", "y"], label="result") + else: + _ = same_columns.pod(source, label="result") + if kind == "operator": + job.nodes["result"].attach_databases( + pipeline_database=database.at("stored"), cache_mode=CacheMode.LOG + ) + _ = job.run() + return job + + +@pytest.mark.parametrize("kind", ["operator", "function"]) +@pytest.mark.parametrize("wrapped", [False, True]) +@pytest.mark.parametrize("route", ["batch", "setter", "recompiled"]) +def test_slot_binding_refuses_its_own_stored_results( + kind: str, wrapped: bool, route: str +) -> None: + job = _stored_result_job(kind) + stored = job.nodes["result"].as_source() + source = stored.cached(InMemoryArrowDatabase()) if wrapped else stored + if route == "recompiled": + job.compile() + original = job.sources["a"] + + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'a'.*node 'result'.*ITL-1559" + ): + _rebind(job, {"a": source}, setter=route == "setter") + + assert job.nodes["a"].bound_source is original + assert job.sources["a"] is original + assert job.nodes["a"].as_table()["x"].to_pylist() == [1, 3] + + +def test_capture_refuses_its_own_stored_results() -> None: + job = _stored_result_job("operator") + stored = job.nodes["result"].as_source() + with job: + with pytest.raises( + SourceSpecMismatchError, match=r"slot .*node 'result'.*ITL-1559" + ): + _ = total.pod(stored, label="feedback") + + assert "feedback" not in job.nodes + + +@pytest.mark.parametrize( + "entry", ["sync", "async", "load_only", "slot", "node", "read"] +) +@pytest.mark.parametrize("kind", ["operator", "function"]) +def test_own_stored_results_introduced_by_proxy_rebind_are_refused( + entry: str, kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.sources import DerivedSource + + job = _stored_result_job(kind, copy=True) + foreign = _stored_result_job(kind, offset=10, copy=True) + foreign_results = foreign.nodes["result"].as_source() + own_results = job.nodes["result"].as_source() + proxy = SourceProxy( + foreign_results.source_id, + foreign_results.content_hash().to_string(), + foreign_results.pipeline_hash().to_string(), + *foreign_results.output_schema(), + ) + proxy.bind(foreign_results) + slot = job.nodes["a"] + result = job.nodes["result"] + wrapped = DerivedSource(proxy, source_id="bridged", tags_as_data={"t1": "copy"}) + job.bind(sources={"a": wrapped}) + _ = job.run() + assert sorted(result.as_table()["x"].to_pylist()) == [11, 13] + + proxy.bind(own_results) + + def unexpected_check() -> bool: + pytest.fail("A source was checked before the invalid binding was refused") + + monkeypatch.setattr(wrapped, "check_for_new_data", unexpected_check) + reads = { + "sync": job.run, + "async": lambda: asyncio.run(job.run_async()), + "load_only": lambda: job.run(load_only=True), + "slot": slot.run, + "node": result.run, + "read": slot.as_table, + } + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'a'.*node 'result'.*ITL-1559" + ): + _ = reads[entry]() + + +@pytest.mark.parametrize("read", ["iter_data", "async_iter_data", "held_row_count"]) +def test_cold_function_held_reads_refuse_a_slot_cycle( + tmp_path: Path, read: str +) -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.operators import SelectDataColumns + + job = _job(tmp_path) + slot = job.nodes["a"] + function = job.nodes["result_a"] + projection = OperatorJobNode(SelectDataColumns(["x", "y"]), [job.sources["a"]]) + job.bind(sources={"a": projection}) + projection.upstreams = (slot,) + + async def read_async() -> None: + _ = [row async for row in function.async_iter_data()] + + with pytest.raises(SourceSpecMismatchError, match=r"slot 'a'.*slot 'a'.*ITL-1559"): + if read == "iter_data": + _ = list(function.iter_data()) + elif read == "async_iter_data": + asyncio.run(read_async()) + else: + _ = function.held_row_count() + + +def _feedback_job(name: str, *, copy: bool = False) -> PipelineJob: + """Build a cold function job whose results fit another job's slot.""" + from orcapod.sources import DerivedSource + + root = _shifted_source(name, 0) + source = ( + DerivedSource(root, source_id=name, tags_as_data={"t1": "copy"}) + if copy + else root + ) + with PipelineJob(name, database=InMemoryArrowDatabase()) as job: + _ = same_columns.pod(source, label="result") + return job + + +def _independent_branches_job() -> PipelineJob: + """Compile two distinct branches and materialize only the left result.""" + with PipelineJob("branches", database=InMemoryArrowDatabase()) as job: + _ = same_columns.pod(_shifted_source("a", 0), label="left") + _ = same_columns.pod(_shifted_source("b", 10), label="right") + _ = job.nodes["left"].run() + return job + + +@pytest.mark.parametrize( + "job_first", [False, True], ids=["pipeline-first", "job-first"] +) +@pytest.mark.parametrize("cached", [False, True], ids=["direct", "cached"]) +def test_transitive_stored_result_capture_leaves_active_graphs_unchanged( + job_first: bool, cached: bool +) -> None: + job = _independent_branches_job() + other = _feedback_job("other") + other.bind(sources={"other": job.nodes["left"].as_source()}) + _ = other.run() + stored = other.nodes["result"].as_source() + source = stored.cached(InMemoryArrowDatabase()) if cached else stored + with Pipeline("outer", auto_compile=False) as outer: + _ = total.pod(_shifted_source("outer", 0), label="kept") + outer.compile() + + def public_state(pipeline: Pipeline | PipelineJob) -> tuple[object, ...]: + """Snapshot public topology, compiled nodes and registered sources.""" + invocations = pipeline.to_invocations() + return ( + tuple(pipeline.graph.nodes), + tuple(pipeline.graph.edges), + {label: id(node) for label, node in pipeline.nodes.items()}, + tuple(invocations.source_streams), + tuple(invocation.label for invocation in invocations.invocations), + ) + + before = [public_state(pipeline) for pipeline in (job, other, outer)] + bindings = [ + {name: id(source) for name, source in j.sources.items()} for j in (job, other) + ] + first, second = (job, outer) if job_first else (outer, job) + with first, second: + with pytest.raises( + SourceSpecMismatchError, match=r"slot .*node 'left'.*ITL-1559" + ): + _ = total.pod(source, label="feedback") + assert [public_state(pipeline) for pipeline in (job, other, outer)] == before + assert [ + {name: id(source) for name, source in j.sources.items()} + for j in (job, other) + ] == bindings + + outer.compile() + assert set(outer.nodes) == {"outer", "kept"} + assert set(job.nodes) == {"a", "b", "left", "right"} + + +@pytest.mark.parametrize("setter", [False, True], ids=["batch", "setter"]) +def test_slot_binding_refuses_acyclic_stored_results_from_its_own_job( + setter: bool, +) -> None: + job = _independent_branches_job() + other = _feedback_job("other") + other.bind(sources={"other": job.nodes["left"].as_source()}) + _ = other.run() + original = job.sources["b"] + + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'b'.*node 'left'.*ITL-1559" + ): + _rebind(job, {"b": other.nodes["result"].as_source()}, setter=setter) + + assert job.sources["b"] is original + assert job.nodes["b"].bound_source is original + + +@pytest.mark.parametrize("entry", ["run", "run_async", "load_only"]) +def test_run_refuses_acyclic_stored_results_after_other_job_rebinds( + entry: str, monkeypatch: pytest.MonkeyPatch +) -> None: + job = _independent_branches_job() + other = _feedback_job("other") + _ = other.run() + stored = other.nodes["result"].as_source() + job.bind(sources={"b": stored}) + other.bind(sources={"other": job.nodes["left"].as_source()}) + + def unexpected_check() -> bool: + pytest.fail("A source was checked before the invalid binding was refused") + + monkeypatch.setattr(stored, "check_for_new_data", unexpected_check) + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'b'.*node 'left'.*ITL-1559" + ): + if entry == "run_async": + _ = asyncio.run(job.run_async()) + else: + _ = job.run(load_only=entry == "load_only") + + +@pytest.mark.parametrize("read", ["iter_data", "async_iter_data", "held_row_count"]) +def test_cold_side_effect_held_reads_refuse_rebound_stored_results( + tmp_path: Path, read: str +) -> None: + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.databases import DeltaTableDatabase + from orcapod.sources import CachedSource, DerivedSource + + @side_effect_pod + def deliver(x: int, y: int) -> None: + pytest.fail("Reading a side-effect node must never deliver") + + assert isinstance(deliver, SideEffectPod) + root = DerivedSource( + _shifted_source("a", 0), source_id="a", tags_as_data={"t1": "copy"} + ) + with PipelineJob("with_effect", database=InMemoryArrowDatabase()) as job: + _ = same_columns.pod(root, label="result") + _ = deliver.process(root, label="deliver") + foreign = _feedback_job("a", copy=True) + own_rows = job.nodes["result"].as_source() + foreign_rows = foreign.nodes["result"].as_source() + disk = foreign_rows.cached(DeltaTableDatabase(tmp_path / "cache")) + restored = CachedSource.from_config(disk.to_config()) + proxy = restored.cached_source + assert isinstance(proxy, SourceProxy) + proxy.bind(foreign_rows) + source = DerivedSource(proxy, source_id="outer", tags_as_data={"t1": "copy"}) + job.bind(sources={"a": source}) + node = job.nodes["deliver"] + assert node.held_row_count() == 0 + proxy.bind(own_rows) + + async def read_async() -> None: + _ = [row async for row in node.async_iter_data()] + + with pytest.raises( + SourceSpecMismatchError, match=r"slot 'a'.*node 'result'.*ITL-1559" + ): + if read == "iter_data": + _ = list(node.iter_data()) + elif read == "async_iter_data": + asyncio.run(read_async()) + else: + _ = node.held_row_count() + + +@pytest.mark.parametrize("setter", [False, True], ids=["batch", "setter"]) +@pytest.mark.parametrize("chain", [False, True], ids=["mutual", "three_jobs"]) +def test_stored_result_bindings_refuse_cross_job_feedback( + setter: bool, chain: bool +) -> None: + left, right = _feedback_job("left"), _feedback_job("right") + left_rows = left.nodes["result"].as_source() + right_rows = right.nodes["result"].as_source() + middle = _feedback_job("middle") if chain else None + if middle is None: + left.bind(sources={"left": right_rows}) + else: + middle_rows = middle.nodes["result"].as_source() + middle.bind(sources={"middle": right_rows}) + left.bind(sources={"left": middle_rows.cached(InMemoryArrowDatabase())}) + assert left.nodes["left"].as_table().num_rows == 0 + right_source = right.sources["right"] + + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559") as error: + _rebind(right, {"right": left_rows}, setter=setter) + + assert "'left'" in str(error.value) and "'right'" in str(error.value) + if chain: + assert "'middle'" in str(error.value) + assert right.sources["right"] is right_source + assert right.nodes["right"].bound_source is right_source + assert left.nodes["left"].as_table().num_rows == 0 + + +@pytest.mark.parametrize( + "entry", + [ + "run", + "run_async", + "load_only", + "node_run", + "slot_table", + "node_table", + "derived_table", + "derived_head", + "node_head", + "staleness", + "current", + "preview", + ], +) +def test_reads_refuse_stored_result_feedback_introduced_by_proxy(entry: str) -> None: + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.sources import DerivedSource + + left, right, independent = ( + _feedback_job(name, copy=True) for name in ("left", "right", "left") + ) + result = left.nodes["result"] + left_rows = result.as_source() + independent_rows = independent.nodes["result"].as_source() + right_rows = right.nodes["result"].as_source() + proxy = SourceProxy( + independent_rows.source_id, + independent_rows.content_hash().to_string(), + independent_rows.pipeline_hash().to_string(), + *independent_rows.output_schema(), + ) + proxy.bind(independent_rows) + left.bind( + sources={ + "left": DerivedSource( + right_rows, source_id="read_right", tags_as_data={"t1": "copy"} + ) + } + ) + right.bind( + sources={ + "right": DerivedSource( + proxy, source_id="read_left", tags_as_data={"t1": "copy"} + ) + } + ) + proxy.bind(left_rows) + + if entry == "preview": + message = result._repr_html_() + else: + reads = { + "run": left.run, + "run_async": lambda: asyncio.run(left.run_async()), + "load_only": lambda: left.run(load_only=True), + "node_run": result.run, + "slot_table": left.nodes["left"].as_table, + "node_table": result.as_table, + "derived_table": left_rows.as_table, + "derived_head": left_rows.head, + "node_head": result.head, + "staleness": lambda: result.is_stale, + "current": result.holds_current_run, + } + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559") as error: + _ = reads[entry]() + message = str(error.value) + assert "'left'" in message and "'right'" in message + assert "cycle" in message and "ITL-1559" in message + + +@pytest.mark.parametrize("cached", [False, True], ids=["delegate", "cache"]) +@pytest.mark.parametrize("late", [False, True], ids=["capture", "compile"]) +def test_pipeline_refuses_a_proxy_cycle(cached: bool, late: bool) -> None: + from orcapod.core.sources.source_proxy import SourceProxy + + source = _shifted_source("input", 0) + proxy = SourceProxy( + source.source_id, + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + *source.output_schema(), + ) + circular = proxy.cached(InMemoryArrowDatabase()) if cached else proxy + graph = Pipeline("cycle") + if late: + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"), graph: + _ = total.pod(proxy, label="result") + proxy.bind(circular) + else: + proxy.bind(circular) + with graph: + with pytest.raises(SourceSpecMismatchError, match="cycle.*ITL-1559"): + _ = total.pod(proxy, label="result") + assert "result" not in graph.nodes + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="Reassigning operator inputs can leave stale held rows on direct reads (ITL-1586).", +) +def test_rewired_operator_slot_does_not_read_stale_rows_from_same_hash_roots() -> None: + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.operators import SemiJoin + + first, other, conflict = ( + DictSource( + [{"t": tag, "x": value}], + source_id=name, + tag_columns=["t"], + tag_only_columns=True, + ) + for name, tag, value in [("same", "a", 1), ("other", "a", 2), ("same", "b", 3)] + ) + assert first.content_hash() == conflict.content_hash() + operator = OperatorJobNode( + SemiJoin(), + [first, other], + label="op", + pipeline_database=InMemoryArrowDatabase(), + ) + slot = SourceJobNode.from_stream(operator, name="slot") + _ = operator.run() + assert slot.as_table().to_pylist() == [{"t": "a", "x": 1}] + + operator.upstreams = (first, conflict) + for run in (slot.run, operator.run): + with pytest.raises(InconsistentSourceError, match=r"input 1.*input 2"): + _ = run() + try: + rows = slot.as_table().to_pylist() + except InconsistentSourceError: + return + assert rows == []