From 2b55e4b7511fd75a00fc34beaccfde37b7054d1b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 07:54:36 -0800 Subject: [PATCH 01/20] feat(async): hand record batches through the async batch region (ITL-1845) ITL-1347 stage 5a. The async orchestrator picks a batch region: bound snapshot source job nodes and the library unary operator job nodes fed by one of them. Region nodes send Arrow record batches through OutputChannel/InputChannel; every other node keeps main's row form and gets rows from a boundary adapter, one batch at a time, so a function node still starts while the source is read (early delivery) and keeps what it computed before a failure (partial results). - SourceProtocol gains a required snapshot_batch_streams(); RootSource answers None, SpiralDBTableSource its per-batch streams, each wrapper answers for itself. - SourceNodeBase and OperatorJobNode get async_execute_batches with main's hook placement, LOG, REPLAY, zero-row keep and failure handling. - A failing region producer fails its channel, so region readers raise UpstreamFailedError and a region LOG node stores nothing by construction; the adapter closes rows as main does. - One BatchStreams per output channel: the description is derived once per channel, not per batch. - Spec: stage 5a section, e7 rewritten, e9 and e10 awaiting approval. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 16 +- CLAUDE.md | 16 +- changelog.d/ITL-1845.md | 11 + docs/dev/scripts/itl_1347/fixtures.py | 43 ++ .../dev/specs/itl-1347-job-table-transport.md | 62 ++- src/orcapod/core/nodes/operator_node.py | 154 ++++++ src/orcapod/core/nodes/source_node.py | 295 +++++++++++ src/orcapod/core/operators/batch.py | 5 +- .../core/operators/static_output_pod.py | 149 ++++-- src/orcapod/core/record_batch_channels.py | 37 +- src/orcapod/core/sources/base.py | 13 + src/orcapod/core/sources/cached_source.py | 8 + src/orcapod/core/sources/derived_source.py | 10 + src/orcapod/core/sources/source_proxy.py | 8 + .../core/sources/spiraldb_table_source.py | 11 + .../core/streams/record_batch_input.py | 31 +- src/orcapod/pipeline/async_orchestrator.py | 267 +++++++++- .../protocols/core_protocols/sources.py | 13 + .../protocols/core_protocols/streams.py | 19 + .../test_spiraldb_job_projection.py | 273 +++++++++- .../test_pipeline/test_async_batch_region.py | 500 ++++++++++++++++++ .../test_source_object_registration.py | 3 + 22 files changed, 1865 insertions(+), 79 deletions(-) create mode 100644 changelog.d/ITL-1845.md create mode 100644 tests/test_pipeline/test_async_batch_region.py diff --git a/.zed/rules b/.zed/rules index 48b2f4209..151d5146c 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1590,7 +1590,7 @@ data. The rules: datagrams' Arrow tables (as_table()), never from as_dict() values, and take the data context from those datagrams (data_context_key). Add new async operators to tests/test_core/operators/test_async_sync_equivalence.py. -- Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet): +- Record-batch channels (ITL-1347, ITL-1362; wired into the async batch region, ITL-1845): InputChannel (core/streams/record_batch_input.py) and OutputChannel (core/record_batch_channels.py) carry a stream's rows as Arrow record batches; operators see them only through the protocols RecordBatchInput / RecordBatchOutput of @@ -1616,6 +1616,20 @@ data. The rules: Batch with a size has its own form, grouping rows by arrival. A new operator whose output rows each come from one input row declares ROW_BY_ROW; write no other per-operator batch code. + The async orchestrator's batch region (stage 5a, ITL-1845; _batch_region): bound snapshot + source job nodes (the StreamBase default async_iter_data, or a source that answers + snapshot_batch_streams(), a required SourceProtocol member every source kind and wrapper + answers for itself: never probe it) and library unary operator job nodes whose one input is + a region node with declared Arrow types send record batches (async_execute_batches of + SourceNodeBase and OperatorJobNode, with main's hook placement, LOG, REPLAY, zero-row keep + and failure handling). Every other node (joins, function, side-effect, held, polling) keeps + the row form and gets rows from the boundary adapter _rows_from_batches, batch by batch, + which turns an UpstreamFailedError into a normal row-channel close. A region producer that + fails calls output.fail(error), so its readers raise at the failure point and a region LOG + node never stores a partial result; failure selection skips UpstreamFailedError. An output + channel and its readers share one BatchStreams (static_output_pod.py): the description is + derived once per channel, never per batch; read it when wiring, inside + shared_zero_row_memo(). - A Python declaration with a `float32` or `float16` dict key or set element raises `NarrowFloatKeyError` (ITL-1591, D16, D25 and D41). Narrowing can turn two distinct keys or elements into one stored value and lose an entry. The check in diff --git a/CLAUDE.md b/CLAUDE.md index b544f018c..62e7dafd3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1635,7 +1635,7 @@ data. The rules: datagrams' Arrow tables (`as_table()`), never from `as_dict()` values, and take the data context from those datagrams (`data_context_key`). Add new async operators to `tests/test_core/operators/test_async_sync_equivalence.py`. -- Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet): +- Record-batch channels (ITL-1347, ITL-1362; wired into the async batch region, ITL-1845): `InputChannel` (`core/streams/record_batch_input.py`) and `OutputChannel` (`core/record_batch_channels.py`) carry a stream's rows as Arrow record batches; operators see them only through the protocols `RecordBatchInput` / `RecordBatchOutput` of @@ -1661,6 +1661,20 @@ data. The rules: input (`to_stream()`); `Batch` with a size has its own form, grouping rows by arrival. A new operator whose output rows each come from one input row declares `ROW_BY_ROW`; write no other per-operator batch code. + The async orchestrator's batch region (stage 5a, ITL-1845; `_batch_region`): bound + snapshot source job nodes (the `StreamBase` default `async_iter_data`, or a source that + answers `snapshot_batch_streams()`, a required `SourceProtocol` member every source kind + and wrapper answers for itself: never probe it) and library unary operator job nodes whose + one input is a region node with declared Arrow types send record batches + (`async_execute_batches` of `SourceNodeBase` and `OperatorJobNode`, with `main`'s hook + placement, `LOG`, `REPLAY`, zero-row keep and failure handling). Every other node (joins, + function, side-effect, held, polling) keeps the row form and gets rows from the boundary + adapter `_rows_from_batches`, batch by batch, which turns an `UpstreamFailedError` into a + normal row-channel close. A region producer that fails calls `output.fail(error)`, so its + readers raise at the failure point and a region `LOG` node never stores a partial + result; failure selection skips `UpstreamFailedError`. An output channel and its readers + share one `BatchStreams` (`static_output_pod.py`): the description is derived once per + channel, never per batch; read it when wiring, inside `shared_zero_row_memo()`. - A Python declaration with a `float32` or `float16` dict key or set element raises `NarrowFloatKeyError` (ITL-1591, D16, D25 and D41). Narrowing can turn two distinct keys or elements into one stored value and lose an entry. The check in diff --git a/changelog.d/ITL-1845.md b/changelog.d/ITL-1845.md new file mode 100644 index 000000000..d42207a54 --- /dev/null +++ b/changelog.d/ITL-1845.md @@ -0,0 +1,11 @@ +### Changed + +- An async job (`job.run(orchestrator=AsyncPipelineOrchestrator())`, `run_async()`) now + passes Arrow record batches, not rows, from a source over a snapshot (an in-memory + source, a keyed SpiralDB table) through the single-input operators that follow it + (selects, drops, renames, `DropNulls`, `Filter`, `AddTags`, `TagBy`, `Pick`, `Index`, + `Batch`, `GroupBy`). Rows are built only where a function or side-effect node, a join or + a held node reads them, one record batch at a time, so a function node still starts on + the first rows while the source is being read. Every node shows the same rows, types and + hashes as before, and as the sync run. Where an upstream node's end event falls among a + downstream node's observer events now moves by a record batch rather than a row. diff --git a/docs/dev/scripts/itl_1347/fixtures.py b/docs/dev/scripts/itl_1347/fixtures.py index 4af2601dd..c8cc0dc18 100644 --- a/docs/dev/scripts/itl_1347/fixtures.py +++ b/docs/dev/scripts/itl_1347/fixtures.py @@ -166,7 +166,50 @@ def report_fn(n_bins: int, ctx: InvocationContext) -> None: return job +def build_wide(data_dir: Path, database: Any) -> Any: + """Stage 5a's batch region (ITL-1845): the spike table, above 65,536 rows so an + in-memory source sends several record batches, through every kind of unary + operator, two chained, then a select and a function node on several branches.""" + from orcapod import PipelineJob, function_pod + from orcapod.sources import ArrowTableSource + + spikes = ArrowTableSource( + spikes_table(data_dir), + tag_columns=["subject_id", "session", "probe", "unit", "spike"], + tag_only_columns=True, + source_id="spikes", + ) + + @function_pod(output_keys="bin") + def time_bin(time_s: float) -> int: + return int(time_s // 10.0) + + job = PipelineJob(name="itl1347_wide", database=database) + with job: + timed = spikes.select_data_columns(["time_s"], label="timed") + time_bin.pod(timed, label="binned") + early = spikes.filter(probe="imec0", label="probe0").select_data_columns( + ["time_s"], label="probe0_time" + ) + time_bin.pod(early, label="probe0_binned") + fours = spikes.batch(batch_size=4, label="fours") + firsts = fours.index("time_s", 0, label="first_of_four") + time_bin.pod( + firsts.select_data_columns(["time_s"], label="first_time"), + label="first_binned", + ) + spikes.batch(label="all_spikes") + spikes.group_by(["subject_id", "session", "probe", "unit"], label="per_unit") + spikes.map_data({"time_s": "t"}, label="renamed").add_tags( + study="itl1347", label="tagged" + ).drop_nulls(label="no_nulls") + spikes.tag_by("time_s", label="time_tagged") + spikes.drop_columns(["spike"], label="no_spike_index") + return job + + FIXTURES: dict[str, Callable[[Path, Any], Any]] = { "tutorial": build_tutorial, "spikes": build_spikes, + "wide": build_wide, } diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 21769a847..0e1340d90 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -549,8 +549,10 @@ is unsupported; what the run then does is undefined and is not part of the equal | e2 | An async input row of another data context | The async function node answers it from the cache (the ITL-858 inventory) | A whole-input error before the first batch, as on sync | **ITL-951** (its comment; ITL-858 decision 9). Reproducer: an async function node fed a stream of another data context, with its result stored | approved (developer, 2026-11-22) | | e3 | Function calls and stored rows for duplicate inputs, async; `RunSummary` computed counts | About 3× more calls than sync, and more stored rows (4,188 against 4,060 in ITL-1062's measurement) | Misses are deduplicated by base entry id, so calls, stored rows and counts equal sync | **ITL-1062.** Reproducer: ITL-1062's workshop-shaped pipeline with repeated input data, async | approved (developer, 2026-11-22) | | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | -| e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer sees a normal end and may finish, and a `LOG` operator node may store, a partial result before the task group cancels it | Readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so no consumer finishes, or stores its result, as if its input were complete. Batches a consumer processed before the failure are still processed, and a streaming node may already have passed them on or a function node stored results for them, as on `main`; there is no rollback. A barrier operator never computes over a partial input. The run raises the producer's own error, as today | A candidate race, to be confirmed with a reproducer in stage 5: a `fail_fast` function node raising on row 3 of 6, feeding a `Select` node in `LOG` mode; check the operator cache after the failed run. If `main` never stores in practice, this row is no difference | filed by the developer only once a test reproduces it | +| e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer's input ends normally; whether a `LOG` operator node after it stores a partial result depends on whether the task group's cancellation reaches it first | Stage 5a (ITL-1845), inside the batch region only: a region node's readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so a region operator never finishes, keeps or stores its output as if its input were complete. **A region `LOG` node stores nothing after an upstream failure, by construction**: it reads the failure from its input channel, raises, and never reaches its store; it no longer depends on cancellation timing. Batches a consumer processed before the failure stay processed, and a function node after the region keeps the results it stored for them, as on `main` (no rollback). At a row boundary the adapter turns the failure into `main`'s normal row-channel close, so nodes outside the region see what they see on `main`. The run raises the producer's own error, as today | **No observable difference found on `main` 2075e85e2**: the stored outcome is unchanged (nothing stored). Reproducers, run on `main` and on the branch: a keyed scan that fails on its third record batch, feeding a `Select` in `LOG` mode (5 runs under each error policy, 10 in all: 0 rows stored every time), and a `fail_fast` function node raising on row 3 of 6 feeding a `Select` in `LOG` mode (5 runs: 0 rows stored). The row documents the internal signal change; both cases are tests that pass on `main` and the branch, with no timing assumption (`test_a_logging_operator_stores_nothing_after_its_source_fails_mid_scan`, `test_a_logging_operator_after_a_failing_function_stores_nothing`) | documented; no approval needed unless the developer asks | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | +| e9 | Observer events across nodes, async (batch region) | Upstream end events (`on_node_end` of a source or operator) fall among a downstream node's data events at the granularity of one row: a source ends after about 16 rows have reached the function node, a `Select` after about 135 (in-memory, 200 rows); an off-loop keyed scan interleaves the same way | Each node's own event sequence is `main`'s, and hooks keep `main`'s placement (start at task start, end after the last send and before the output closes), so `main`'s invariants hold: (i) node starts in topological order; (ii) a node's data events lie between its start and end; (iii) an upstream node ends before its downstream node; (iv) a function node's row events in arrival order, in concurrency groups of 16; (v) downstream data events interleave with upstream end events. Only where an upstream end falls among downstream data events moves, in steps of one record batch (an in-memory source sends its table in 65,536-row batches, a keyed scan `batch_rows` rows) | Not a `main` bug: `main`'s interleaving itself depends on buffer sizes and timing, and no rule fixes it. The pinned-`main` observer test (`test_observer_main_compatibility.py`) exempts the end events of region nodes, as it already exempted `SelectDataColumns`' end; the invariants are tested on the branch | awaiting approval | +| e10 | The class of a region node's collected async output (`OrchestratorResult.node_outputs`) | An async node's output is `RowsOnRead` over its collected rows, which compares unequal to the sync route's output stream of the same rows | A region node's output is its output channel's `result()` (for a source with column demand, the whole read, as on sync), the sync route's stream form: the same rows, table, types and hashes, and it now compares equal to the sync output. A projected source's whole read still happens once, when the output is first read | Not a bug on `main`, a form change: the equality between the two routes' outputs followed from their classes, not their rows (`test_outputs_of_two_routes_compare_and_hash_as_main`) | awaiting approval | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its @@ -595,8 +597,9 @@ branch introduces: the branch keeps `main`'s behaviour, and they are documented - **The sync path**, at every stage, by construction and L0–L5. - **Error types and messages**: `Join`'s schema-level checks keep their messages, asserted in L6. -- **Observer events**: the same events in the same order and count. Function and side-effect - nodes are per row as today; operators and sources call node hooks only. +- **Observer events**: the same events, and each node's own events in the same order and + count. Function and side-effect nodes are per row as today; operators and sources call + node hooks only. Where an upstream node's end falls among downstream events moves (e9). - **`RunSummary`**: identical on sync; on async it differs only under e3. - **`head()` and the preview**: identical on sync. On async they show arrival order, as on `main`. @@ -1210,6 +1213,59 @@ as a row with its bug and reproducer, for the developer's approval. Benchmarks follow the round's rules. +### Stage 5a (ITL-1845): the batch region + +Built on `main` 2075e85e2 from the stage 5 survey (`main` had moved since this spec; +the corrections are listed below). Scope, as landed: + +- **The batch region.** The async orchestrator chooses, once per run, the nodes whose + outputs travel as record batches (`_batch_region`): + - a bound source job node whose source is a snapshot (its class keeps the + `StreamBase` default `async_iter_data`, or answers `snapshot_batch_streams()`, the + required `SourceProtocol` member: `RootSource` answers `None`, `SpiralDBTableSource` + its per-batch streams, and each wrapper answers for itself) and whose Arrow types are + declared; + - a library unary operator job node whose one input is a region node with declared + Arrow types (`ROW_BY_ROW` operators per record batch; barriers, `GroupBy`, + `PolarsFilter`, `Filter` and `Batch` without a size, by `to_stream()`; `Batch` with a + size by arrival). + + Joins, function, side-effect, held and polling nodes stay outside it and run `main`'s + row code (joins move in stage 5b). +- **Channels.** Each region node writes one `OutputChannel` (`retain` is + `materialize_results` for a source node and always true for an operator node, whose + kept output is the result). Every out-edge opens a reader before any task starts. A + region successor reads the `InputChannel`; any other successor gets rows from a + boundary adapter (`_rows_from_batches`), which builds each batch's rows as it arrives + (D1, early delivery) and turns an `UpstreamFailedError` into `main`'s normal close. +- **One description per channel.** An output channel's readers and its `result()` share + one `BatchStreams` (the per-batch stream maker over the channel's description), so the + description's zero-row table, tokens, keys and bindings are derived once per channel, + not once per batch. Descriptions are read when the channels are wired, inside + `shared_zero_row_memo()`. +- **Source nodes** (`SourceNodeBase.async_execute_batches`): with column demand, the + narrowed per-batch read, and the whole read collected lazily (`whole_on_read`) as on + sync; otherwise the snapshot's batch streams or `open_channel()` batches. Every batch + is converted to the transport form (F) on the scan's owner thread. Hooks keep `main`'s + placement. A failure calls `output.fail(error)`. +- **Operator nodes** (`OperatorJobNode.async_execute_batches`): `main`'s hook placement, + `LOG`, `REPLAY` (the stored table's batches, inputs drained), the zero-row keep, + `clear_cache` on failure and `_update_modified_time`; the kept output is + `output.result()`. +- **Differences.** e7 (documented, no observable difference), e9 and e10 (awaiting + approval). Row order: a region node keeps arrival order, which for one snapshot source + is the sync order. + +Corrections to this spec found by the survey, which the stage 5 sections above predate: +the channel modules are `core/streams/record_batch_input.py`, +`core/record_batch_channels.py` and `static_output_pod.py`, and `open_channel()` takes no +argument; source-info nullability and token types follow ITL-1557 and ITL-1491 (every +`_source_*` field nullable, token types from the pipeline, the first-batch rule), not the +value-derived rules described in F; system-tag suffixes come from the structural +argument-symmetry digest (ITL-1590); held rows stay unchecked on async (ITL-1534); e6 is +resolved on `main` (ITL-1358); the observer claim "same order" does not hold for any batch +hand-off (e9). + ### Release note (for the merge into `main`) In `changelog.d/.md`, under `### Breaking changes and migration`: diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 91e5f7b25..a93473acf 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -130,6 +130,10 @@ def _stored_only_fields() -> "tuple[pa.Field[Any], pa.Field[Any]]": if TYPE_CHECKING: + from orcapod.protocols.core_protocols.streams import ( + RecordBatchInput, + RecordBatchOutput, + ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol @@ -2600,3 +2604,153 @@ async def forward() -> None: # A close that raises or is cancelled fails the run: no rows. self.clear_cache() raise + + async def async_execute_batches( + self, + inputs: Sequence[RecordBatchInput], + output: RecordBatchOutput, + *, + observer: "ExecutionObserverProtocol | None" = None, + load_only: bool = False, + ) -> None: + """Run the node over input channels of Arrow record batches (ITL-1347, stage 5a). + + The record-batch form of ``async_execute``, for a unary operator whose every + output row comes from one input row (``ROW_BY_ROW``) or that reads its whole + input first (a barrier), in a job's async run. Everything ``async_execute`` + does is done here, at the same points: the loaded and restricted-cache + refusals, the observer hooks, ``REPLAY`` (the stored rows sent while every + input is read to its end), the data-context check of a ``LOG`` node before the + first batch, the kept output, the ``LOG`` store and the modified time. + + The operator runs its record-batch form (``async_execute_batches``): a + row-by-row operator sends each input batch's result as it arrives, a barrier + reads all of its input first (``InputChannel.to_stream``). The kept output is + what was sent (``output.result()``, the output retains its batches). A + failure of an input's producer reaches the operator as + ``UpstreamFailedError`` at the failure point, never as a normal end: the + operator then fails, so the node keeps and stores nothing, by construction. A + failure or cancellation fails ``output`` and closes every input. + + Args: + inputs: The input channels, one per upstream, in the operator's order. + output: The node's output channel (retaining); its stream is this node. + observer: Optional execution observer for hooks. + load_only: As for ``execute``: a ``LOG`` node stores nothing (ITL-1095). + + Raises: + ValueError: If the node caches (``LOG`` or ``REPLAY``) and a source + feeding its ``upstreams`` is restricted (ITL-1218); nothing is + read or written, and the output fails. + """ + from orcapod.core.operators.static_output_pod import close_inputs + from orcapod.pipeline.observer import NoOpObserver + from orcapod.pipeline.restrictions import refuse_restricted_operator_cache + + try: + # A loaded node runs only in a load-only run, with its rebuilt operator. + if self._loaded and (not load_only or self._operator is None): + raise self._cannot_compute_error() + refuse_restricted_operator_cache(self, self._cache_mode) + except BaseException as error: + output.fail(error) + await close_inputs(inputs, error) + raise + + obs = observer if observer is not None else NoOpObserver() + try: + require_current_outputs(self) + node_label = self.label + node_hash = self.content_hash().to_string() + ctx_obs = obs.contextualize(*self.node_identity_path) + ctx_obs.on_node_start(node_label, node_hash) + self._run_load_only = load_only + + if ( + self._pipeline_database is not None + and self._cache_mode == CacheMode.REPLAY + ): + await self._replay_batches(inputs, output) + ctx_obs.on_node_end(node_label, node_hash) + await output.close() + return + + should_store = ( + not load_only + and self._pipeline_database is not None + and self._cache_mode == CacheMode.LOG + ) + if should_store: + # Batches are sent while the operator runs, so an input this node + # will refuse to store must be refused before the first batch leaves. + for input_stream in self._input_streams: + require_same_data_context( + input_stream.data_context_key, self.data_context_key + ) + operator = cast(StaticOutputOperatorPod, self._operator) + # The operator closes its inputs, then the output, once it is done; it + # fails the output if it fails. Nothing awaits between that close and the + # bookkeeping below, so no successor runs before the node ends. + await operator.async_execute_batches(inputs, output) + kept = output.result() + if kept.as_table(columns=ZERO_ROW_INPUT_COLUMNS).num_rows: + self._cached_output_stream = kept + if should_store: + self._store_output_stream(kept) + else: + # A completed run with no rows keeps the operator's result over its + # inputs with no rows, typed as their rows are (ITL-1080, ITL-912), in + # the column order of a run with rows (ITL-1131). Nothing is stored. + empty_result = operator.process( + *( + StaticOutputOperatorPod._materialize_upstream( + [], channel.stream, zero_rows=True + ) + for channel in inputs + ) + ) + _ = list(empty_result.iter_data()) + self._cached_output_stream = ( + StaticOutputOperatorPod._zero_rows_in_row_order(empty_result) + ) + self._update_modified_time() + ctx_obs.on_node_end(node_label, node_hash) + except BaseException as error: + # A run that raised or was cancelled defines no rows; no reader takes the + # output for complete. + self.clear_cache() + output.fail(error) + await close_inputs(inputs, error) + raise + + async def _replay_batches( + self, inputs: Sequence[RecordBatchInput], output: RecordBatchOutput + ) -> None: + """``REPLAY`` in the record-batch form: send the stored rows, reading every + input to its end meanwhile, so the upstream nodes run over every row, as with + the sync orchestrator. + + The stored rows are sent as ``execute`` hands them on (the stored table, under + this node's identity). The node is stamped once every input has ended. + """ + from orcapod.core.operators.static_output_pod import close_inputs + + async def read_to_end(channel: RecordBatchInput) -> None: + async for _ in channel: + pass + + reads = [asyncio.ensure_future(read_to_end(channel)) for channel in inputs] + try: + self._replay_from_cache() + assert self._cached_output_stream is not None + table = self._cached_output_stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + for batch in table.to_batches(): + if batch.num_rows: + await output.send(batch) + _ = await asyncio.gather(*reads) + self._update_modified_time() + finally: + for read in reads: + _ = read.cancel() + _ = await asyncio.gather(*reads, return_exceptions=True) + await close_inputs(inputs) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7c0c1db3c..126113e50 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -46,11 +46,13 @@ from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied from orcapod.core.sources.base import RootSource, table_is_rows from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.core.data_tags import data_tag_names from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, CompleteStreamFeed, keys_of_rows, reads_as_its_class, + row_built_columns, system_tags_as_rows_give, stream_arrow_schema, schema_requires_io, @@ -91,6 +93,7 @@ from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, + RecordBatchOutput, ) from orcapod.protocols.hashing_protocols import ( IdentityWalkProtocol, @@ -1603,6 +1606,223 @@ async def async_execute( finally: await output.close() + # ------------------------------------------------------------------ + # Async execution on Arrow record batches (ITL-1347, stage 5a) + # ------------------------------------------------------------------ + + def batch_description( + self, read_columns: Collection[str] | None = None + ) -> StreamProtocol: + """The stream that describes the record batches this node sends in a job. + + This node, unless ``read_columns`` (``pipeline.column_demand``, ITL-1798) + leaves data columns out: the batches then hold only the columns every + successor reads, and are described by this node's output without the others + (its identity, pipeline hash and data context, with those keys and Arrow + types). Every successor of such a node is a column selection that keeps only + read columns, so it gives what it gives over the whole rows. Never reads a row: + when the node cannot type its rows without rows, it describes itself, and + sends whole batches. + + Args: + read_columns: The data columns every successor reads, or ``None``. + + Returns: + The describing stream: this node, or its narrowed output. + """ + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + if read_columns is None: + return self + unread = self._unread_columns(read_columns) + if not unread: + return self + try: + zero_rows = typed_zero_row_table(self) + except Exception: # noqa: BLE001 # the run's own read raises it, in the node's task + return self + if zero_rows is None: + return self + keys = keys_of_rows(zero_rows, self.keys()) + tag_keys, data_keys = keys + table = _without_columns(row_built_columns(zero_rows, keys), unread) + return StaticOutputOperatorPod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # this node's output, as F builds it + table, + tag_keys, + data_tag_names(tag_keys, [c for c in data_keys if c not in unread]), + self, + ) + + def _unread_columns(self, read_columns: Collection[str]) -> frozenset[str]: + """The data columns of this node (not tags) that ``read_columns`` leaves out.""" + tag_keys, data_keys = self.keys() + wanted = set(read_columns) + return frozenset( + c for c in data_keys if c not in wanted and c not in set(tag_keys) + ) + + def _snapshot_batch_streams(self) -> Iterator[StreamProtocol] | None: + """This node's whole rows as per-batch streams of a pinned snapshot, or + ``None``: the node is read whole (``open_channel``). + + ``None`` here: a node that carries no data of its own is read whole. A bound + job node gives its source's ``snapshot_batch_streams``, where a projected read + could be made of it (``_projection_snapshot``). + """ + return None + + def _transport_table( + self, stream: StreamProtocol, unread: frozenset[str] + ) -> pa.Table: + """One batch's rows (a stream of this node's source) as this node's output + sends them: the row-built form, without ``unread`` data columns. + + As ``_whole_output`` builds the whole output, per batch (``row_built_columns`` + gives the same result on a whole table and on each slice of it): the batch's + table in the row-built form when its system tags are what its rows give and F + is available; otherwise the batch's rows, built as main builds rows. + + Args: + stream: A batch of this node's rows, a stream of the bound source. + unread: The data columns the node's successors do not read. + + Returns: + The table to send. + """ + from orcapod.core.operators.static_output_pod import ( + RowBuiltFormUnavailable, + StaticOutputOperatorPod, + ) + + table = stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + built: pa.Table | None = None + if system_tags_as_rows_give(table): + try: + built = StaticOutputOperatorPod._row_built_form( # pyright: ignore[reportPrivateUsage] # F, as the whole read + table, keys_of_rows(table, stream.keys()) + ) + except RowBuiltFormUnavailable: + built = None + if built is None: + rows = list(stream.iter_data()) + if not rows: + return table.slice(0, 0) + built, _, _ = StaticOutputOperatorPod._rows_to_table( # pyright: ignore[reportPrivateUsage] # main's row-built table + rows, keep_token_fields=True + ) + return _without_columns(built, unread) + + async def async_execute_batches( + self, + output: RecordBatchOutput, + *, + observer: ExecutionObserverProtocol | None = None, + read_columns: Collection[str] | None = None, + ) -> StreamProtocol | None: + """Send this node's rows into ``output`` as Arrow record batches, as they are + read (ITL-1347, stage 5a). + + The record-batch form of ``async_execute``, for a node whose source reads a + fixed snapshot. The observer hooks are where ``async_execute`` calls them: the + start when the node starts, the end after the last batch is sent. + + Where the record batches come from: + + - with ``read_columns`` and a narrowed description (``batch_description``): + the narrowed read's batches (``_projected_batches``, ITL-1798) when the + source can make one; otherwise the whole read's, each narrowed; + - a source that reads a pinned snapshot in batches + (``SourceProtocol.snapshot_batch_streams``): one record batch per stream, + read off the event loop on one owner thread, which closes the scan when the + sending stops, fails or is cancelled, after a read in progress has ended; + - any other source: this node's ``execute()`` output (``open_channel``), read + whole at the first read and sent in batches of ``SOURCE_BATCH_ROWS`` rows. + + A failure or cancellation fails ``output`` (its readers raise + ``UpstreamFailedError``, never a normal end) and is raised. + + Args: + output: The node's output channel; its stream is ``batch_description``'s. + observer: Optional execution observer. + read_columns: The data columns every successor reads (as for + ``async_execute``). + + Returns: + The node's whole output when the batches sent are a narrowed read's + (``whole_on_read``, as ``execute`` gives it, or the whole batches read + as a stream), else + ``None``: the output channel's result is the node's output. + + Raises: + UnboundSourceError: When no concrete data is available. + """ + from orcapod.core.operators.static_output_pod import ( + stream_from_batches, + whole_on_read, + ) + from orcapod.core.output_bindings import capture_output_bindings + + node_label = self.label + whole: StreamProtocol | None = None + try: + node_hash = graph_hash(self).to_string() + if observer is not None: + observer.on_node_start(node_label, node_hash) + description = output.stream + unread = ( + self._unread_columns(description.keys()[1]) + if description is not self + else frozenset() + ) + sent_whole = False + if unread and read_columns is not None: + bindings = capture_output_bindings(self) + projected = await asyncio.to_thread( + self._projected_batches, read_columns, bindings + ) + if projected is not None: + streams, whole_read = projected + sent = await _send_record_batches( + streams, output, lambda s: self._transport_table(s, unread) + ) + if sent: + # The whole read's own stream, its rows read when first read, + # as ``execute`` gives it (``whole_on_read``). + whole = whole_on_read(self, whole_read(sent), bindings=bindings) + sent_whole = True + if not sent_whole: + # The whole batches, kept only when they are not what is sent: a + # narrowed description over a whole read (a source that cannot make + # the narrowed read), whose output is the whole batches. + kept: list[pa.RecordBatch] | None = [] if unread else None + streams = self._snapshot_batch_streams() + if streams is not None: + _ = await _send_record_batches( + streams, + output, + lambda s: self._transport_table(s, frozenset()), + unread=unread, + kept=kept, + ) + else: + async for batch in self.open_channel(): + if kept is not None: + kept.append(batch) + narrowed = _without_columns( + pa.Table.from_batches([batch]), unread + ) + for piece in narrowed.to_batches(): + await output.send(piece) + if kept is not None: + whole = stream_from_batches(self, kept) + if observer is not None: + observer.on_node_end(node_label, node_hash) + except BaseException as error: + output.fail(error) + raise + await output.close() + return whole + def __repr__(self) -> str: return ( f"{type(self).__name__}(name={self._name!r}, " @@ -2321,6 +2541,20 @@ def whole() -> ArrowTableStream: return streams, lambda num_rows: WholeRead(whole, None, keys, num_rows) + def _snapshot_batch_streams(self) -> Iterator[StreamProtocol] | None: + """The bound source's per-batch snapshot streams (ITL-1347, stage 5a), or + ``None``: read whole. + + Only where a projected read could be made of the source + (``_projection_snapshot``: the table route, no declared form, the node's data + context, a pinned version), so the batches are exactly the whole read's rows. + """ + found = self._projection_snapshot() + if found is None: + return None + _, snapshot, _ = found + return snapshot.snapshot_batch_streams() + def _projection_snapshot( self, ) -> tuple[SourceProtocol, SourceProtocol, pa.Table] | None: @@ -2745,3 +2979,64 @@ async def _send_batches( _ = owner.submit(close) owner.shutdown(wait=False) return sent + + +def _without_columns(table: pa.Table, unread: frozenset[str]) -> pa.Table: + """``table`` without the data columns ``unread`` and their source-info columns.""" + if not unread: + return table + dropped = unread | {f"{constants.SOURCE_PREFIX}{c}" for c in unread} + return table.drop_columns([c for c in table.column_names if c in dropped]) + + +async def _send_record_batches( + streams: Iterator[StreamProtocol], + output: RecordBatchOutput, + convert: Callable[[StreamProtocol], pa.Table], + *, + unread: frozenset[str] = frozenset(), + kept: list[pa.RecordBatch] | None = None, +) -> int: + """Send each stream of ``streams`` into ``output`` as record batches, as it is read. + + As ``_send_batches`` reads (ITL-1798): one thread owns the reader for its whole + life and reads and converts one stream at a time, the next only once the previous + one was sent; when the sending stops, fails or is cancelled that thread closes the + reader, after a read in progress has ended (ITL-1347, stage 5a). + + Args: + streams: The batches of a node's rows, read as they are asked for. + output: The node's output channel. + convert: Gives the table a batch's stream is sent as. + unread: Data columns left out of what is sent (after ``kept`` takes it). + kept: When given, receives every converted table's record batches before + ``unread`` is left out. + + Returns: + The number of rows sent. + """ + owner = ThreadPoolExecutor(max_workers=1, thread_name_prefix="source-read") + loop = asyncio.get_running_loop() + + def next_table() -> pa.Table | None: + stream = next(streams, None) + return None if stream is None else convert(stream) + + sent = 0 + try: + while True: + table = await loop.run_in_executor(owner, next_table) + if table is None: + break + if kept is not None: + kept.extend(b for b in table.to_batches() if b.num_rows) + for batch in _without_columns(table, unread).to_batches(): + if batch.num_rows: + await output.send(batch) + sent += batch.num_rows + finally: + close = getattr(streams, "close", None) + if close is not None: + _ = owner.submit(close) + owner.shutdown(wait=False) + return sent diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 0d854a1ae..b8a2744cb 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -331,6 +331,7 @@ async def async_execute_batches( await super().async_execute_batches(inputs, output) return (channel,) = inputs + streams = channel.batch_streams() try: waiting: list[pa.RecordBatch] = [] rows = 0 @@ -347,14 +348,14 @@ async def async_execute_batches( arrived = concatenate_batches(waiting) assert arrived is not None # they hold rows await self._send_processed( - arrived.slice(0, full).to_batches(), channel.stream, output + arrived.slice(0, full).to_batches(), streams, output ) waiting = arrived.slice(full).to_batches() rows -= full # The rows left over are fewer than one batch: the sync rule decides # whether they make a last one. if rows: - await self._send_processed(waiting, channel.stream, output) + await self._send_processed(waiting, streams, output) except BaseException as error: output.fail(error) await close_inputs(inputs, error) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 53387c926..4d1e2f0c5 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -6,6 +6,7 @@ from abc import abstractmethod from collections.abc import ( AsyncIterator, + Callable, Collection, Iterable, Iterator, @@ -1054,9 +1055,10 @@ async def async_execute_batches( # The input's token types across its batches: a batch that declares # another type than the earlier ones is refused, never processed alone. settled: dict[str, pa.DataType] = {} + streams = channel.batch_streams() async for batch in channel: settled = settle_token_types(batch, settled) - await self._send_processed([batch], channel.stream, output) + await self._send_processed([batch], streams, output) else: streams = await _streams_of(inputs) await self._send_result(self.static_process(*streams), output) @@ -1069,7 +1071,7 @@ async def async_execute_batches( async def _send_processed( self, batches: Sequence[pa.RecordBatch], - stream: StreamProtocol, + streams: Callable[[Sequence[pa.RecordBatch]], StreamProtocol], output: RecordBatchOutput, ) -> None: """Apply this operator to some record batches of one input and send the result. @@ -1079,12 +1081,10 @@ async def _send_processed( Args: batches: Record batches of the input's rows, in order. - stream: The input's describing stream. + streams: Makes streams of the input's describing stream. output: The channel to send the result into. """ - await self._send_result( - self.static_process(stream_from_batches(stream, batches)), output - ) + await self._send_result(self.static_process(streams(batches)), output) @staticmethod async def _send_result(result: StreamProtocol, output: RecordBatchOutput) -> None: @@ -1227,15 +1227,17 @@ def stream_from_batches( The one place a stream is made from Arrow record batches: what an output channel gives once closed (``OutputChannel.result``), what an input channel delivered - (``InputChannel.to_stream``), and the record batches a row-by-row operator is - applied to. The batches are put under one another in the order given, and the + (``InputChannel.to_stream``), the record batches a row-by-row operator is + applied to, and the rows a job hands a node outside its batch region. The + batches are put under one another in the order given, and the table is handed on as a node hands its rows to its successors (``_output_stream``): declared system-tag flags are restored, and source-info fields are nullable and keep the stream's declared types. If the stream has no token types yet, the populated batches establish them. The result keeps ``stream``'s producer, upstreams, pipeline hash and data context. With no batch it is ``stream``'s zero-row input, or the accepted channel schema - if the stream cannot supply a typed zero-row input. + if the stream cannot supply a typed zero-row input. ``BatchStreams`` makes + several such streams of one description, reading the description once. Args: stream: The describing stream: the node or stream the rows are of. @@ -1245,29 +1247,116 @@ def stream_from_batches( Returns: A complete, re-readable stream over the rows. """ - typed = typed_zero_row_table(stream) - if declared_schema is None and typed is not None: - declared_schema = typed.schema - if declared_schema is None and batches: - declared_schema = batches[0].schema - table = concatenate_batches( - batches, - declared_schema=declared_schema, - declared_tokens=declared_token_types(stream), - ) - if table is None: - if typed is not None or declared_schema is None: - return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator - table = declared_schema.empty_table() - tag_keys, data_keys = _keys_in_delivered_order( - stream.keys(), table.column_names + return BatchStreams(stream, declared_schema=declared_schema)(batches) + + +class BatchStreams: + """Makes streams of record batches of one describing stream (``stream_from_batches``). + + The description's zero-row table and token types are read once, at the first + stream that needs them, not once per stream: a channel's batches are made into + streams one by one (a row-by-row operator's input, a job's rows at the edge of + its batch region, ITL-1347), and the description does not change while they are + (its bindings are checked where the batches are read). Every stream it makes is + exactly what ``stream_from_batches`` gives for the same batches. + + Args: + stream: The describing stream. + declared_schema: The declaration already accepted by an output channel. + """ + + def __init__( + self, stream: StreamProtocol, *, declared_schema: pa.Schema | None = None + ) -> None: + """Hold the description; nothing is read until a stream is made.""" + self.stream = stream + self._declared_schema = declared_schema + self._typed: pa.Table | None = None + self._typed_known = False + self._tokens: dict[str, pa.DataType] | None = None + self._keys: tuple[Sequence[str], Sequence[str]] | None = None + self._bindings: OutputBindings | None = None + + def _description_keys(self) -> tuple[Sequence[str], Sequence[str]]: + """The description's keys, read once.""" + if self._keys is None: + self._keys = self.stream.keys() + return self._keys + + def _description_bindings(self) -> OutputBindings: + """The description's bindings, captured at the first stream made.""" + if self._bindings is None: + self._bindings = capture_output_bindings(self.stream) + return self._bindings + + def read_description( + self, declared_tokens: Mapping[str, pa.DataType] | None = None + ) -> None: + """Read the description's zero-row table and token types now (reads no row). + + Args: + declared_tokens: The description's token types, when already read + (``declared_token_types`` of the same stream). + """ + _ = self._typed_table() + if self._tokens is None: + self._tokens = ( + declared_token_types(self.stream) + if declared_tokens is None + else dict(declared_tokens) + ) + + def _typed_table(self) -> pa.Table | None: + """The description's typed zero-row table, read once.""" + if not self._typed_known: + self._typed = typed_zero_row_table(self.stream) + self._typed_known = True + return self._typed + + def __call__( + self, + batches: Sequence[pa.RecordBatch], + *, + declared_schema: pa.Schema | None = None, + ) -> StreamProtocol: + """Return ``batches`` as a stream of the description (``stream_from_batches``). + + Args: + batches: The record batches, in order. + declared_schema: The declaration an output channel accepted, in place of + the one given at construction. + """ + stream = self.stream + if declared_schema is None: + declared_schema = self._declared_schema + typed = self._typed_table() + if declared_schema is None and typed is not None: + declared_schema = typed.schema + if declared_schema is None and batches: + declared_schema = batches[0].schema + if self._tokens is None: + self._tokens = declared_token_types(stream) + table = concatenate_batches( + batches, + declared_schema=declared_schema, + declared_tokens=self._tokens, ) - return StaticOutputOperatorPod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the zero-row result under the channel declaration - table, tag_keys, data_tag_names(tag_keys, data_keys), stream + if table is None: + if typed is not None or declared_schema is None: + return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator + table = declared_schema.empty_table() + tag_keys, data_keys = _keys_in_delivered_order( + self._description_keys(), table.column_names + ) + return StaticOutputOperatorPod._as_upstream_stream( # pyright: ignore[reportPrivateUsage] # the zero-row result under the channel declaration + table, tag_keys, data_tag_names(tag_keys, data_keys), stream + ) + return StaticOutputOperatorPod._output_stream( # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's + table, + _keys_in_delivered_order(self._description_keys(), table.column_names), + stream, + bindings=self._description_bindings(), ) - return StaticOutputOperatorPod._output_stream( # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's - table, _keys_in_delivered_order(stream.keys(), table.column_names), stream - ) def _keys_in_delivered_order( diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index fb4f60194..9f0629182 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -26,9 +26,9 @@ require_current_bindings, ) from orcapod.core.operators.static_output_pod import ( + BatchStreams, declared_token_types, settle_token_types, - stream_from_batches, ) from orcapod.core.streams.base import row_built_names from orcapod.core.streams.record_batch_input import InputChannel @@ -160,9 +160,13 @@ def __init__( # Concrete token types, or the types settled by the populated batches. self._token_types: dict[str, pa.DataType] = {} self._has_declared_tokens = False + # The stream's data keys (data-tags included), for the token-shape check. + self._data_keys: tuple[str, ...] = () # The column order of the channel's batches: the first batch with rows'. self._order: list[str] | None = None self._changed = asyncio.Event() + # The maker of streams of its batches, shared by every reader. + self._batch_streams = BatchStreams(stream) @property def stream(self) -> StreamProtocol: @@ -215,11 +219,7 @@ def _check_schema(self, batch: pa.RecordBatch) -> pa.RecordBatch: f"A record batch sent as {_named(self._stream)} has a column more than " + f"once: {repeated}." ) - if not self._schema_known: - self._schema = _description(self._stream) - self._token_types = declared_token_types(self._stream, self._schema) - self._has_declared_tokens = bool(self._token_types) - self._schema_known = True + self.read_description() schema = self._schema if schema is None: # No Arrow types in the description: the first batch that passes sets them @@ -264,6 +264,24 @@ def _check_schema(self, batch: pa.RecordBatch) -> pa.RecordBatch: batch = batch.select(self._order) return batch + def read_description(self) -> None: + """Read what the channel's stream declares for its batches, once. + + Its Arrow schema and token types, which every batch sent is checked against, + and the description its readers make streams of their batches with. Done by + the first send, or before (a job reads every description of its batch region + in one zero-row derivation, ITL-1347); reads no row. + """ + if self._schema_known: + return + self._schema = _description(self._stream) + self._token_types = declared_token_types(self._stream, self._schema) + self._has_declared_tokens = bool(self._token_types) + self._data_keys = tuple(self._stream.keys()[1]) + self._schema_known = True + # The readers' streams take the same declared token types. + self._batch_streams.read_description(dict(self._token_types)) + async def send(self, batch: pa.RecordBatch) -> None: """Send one Arrow record batch of the stream's transport columns. @@ -373,7 +391,7 @@ def open_reader(self) -> InputChannel: feed = _OutputFeed(self) if not self._retain: self._readers.append(feed) - return InputChannel(self._stream, feed) + return InputChannel(self._stream, feed, batch_streams=self._batch_streams) def result(self) -> StreamProtocol: """Return the output as a stream, once the channel is closed. @@ -402,9 +420,8 @@ def result(self) -> StreamProtocol: ) require_current_bindings(self._bindings) if self._result is None: - result = stream_from_batches( - self._stream, self._batches, declared_schema=self._schema - ) + # ``stream_from_batches``, with the description its readers read. + result = self._batch_streams(self._batches, declared_schema=self._schema) require_current_bindings(self._bindings) self._result = result return self._result diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index cc06e210b..5171f4412 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -446,6 +446,19 @@ def projected_batch_streams( """ return None + def snapshot_batch_streams(self) -> "Iterator[StreamProtocol] | None": + """This source's whole rows as streams of record batches, or ``None``. + + See ``SourceProtocol.snapshot_batch_streams`` (ITL-1347, stage 5a). Every + source kind answers for itself, a wrapper too. + + Returns: + ``None``: this kind has no per-batch snapshot read; a job's async route + reads it whole (``open_channel``). ``SpiralDBTableSource`` returns its + batches. + """ + return None + def pinned_snapshot(self) -> "SourceProtocol | None": """A source that reads this source's current version, or ``None``. diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index c475f372e..e75b0b6c6 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -561,6 +561,14 @@ def _cached_record_hashes(self) -> set[bytes]: if h is not None } + @override + def snapshot_batch_streams(self) -> "Iterator[StreamProtocol] | None": + """``None``: a ``CachedSource`` has no per-batch snapshot read of its own, so a job's + async route reads it whole (ITL-1347, stage 5a). It answers for itself, never + by asking what it wraps. + """ + return None + @override def check_for_new_data(self) -> bool: """Check the wrapped source; move only if the next read shows new rows (ITL-1102). diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 656521b2a..6ce5e6139 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -54,6 +54,8 @@ from orcapod.utils.provisional import provisional_class_name if TYPE_CHECKING: + from collections.abc import Iterator + from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -840,6 +842,14 @@ def _held_rows(self) -> "pa.Table | None": ) return self._cached_table + @override + def snapshot_batch_streams(self) -> "Iterator[StreamProtocol] | None": + """``None``: a ``DerivedSource`` has no per-batch snapshot read of its own, so a job's + async route reads it whole (ITL-1347, stage 5a). It answers for itself, never + by asking what it wraps. + """ + return None + @override def check_for_new_data(self) -> bool: """Take in the origin's rows if they changed since this source read them. diff --git a/src/orcapod/core/sources/source_proxy.py b/src/orcapod/core/sources/source_proxy.py index 50d30c183..95a9a1c94 100644 --- a/src/orcapod/core/sources/source_proxy.py +++ b/src/orcapod/core/sources/source_proxy.py @@ -217,6 +217,14 @@ def last_modified(self) -> datetime | None: return bound return max(own, bound) + @override + def snapshot_batch_streams(self) -> "Iterator[StreamProtocol] | None": + """``None``: a ``SourceProxy`` has no per-batch snapshot read of its own, so a job's + async route reads it whole (ITL-1347, stage 5a). It answers for itself, never + by asking what it wraps. + """ + return None + @override def check_for_new_data(self) -> bool: """Check the bound source for new data; an unbound proxy has none (ITL-1102). diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index fe4c37a41..2a716e084 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1189,6 +1189,17 @@ def as_table( PROJECTS_COLUMNS: ClassVar[bool] = True + @override + def snapshot_batch_streams(self) -> "Iterator[ArrowTableStream]": + """The table's rows as ``async_iter_data`` reads them: streams of at most + ``batch_rows`` rows, the pinned version scanned once, one SpiralDB batch held + at a time, read as they are asked for (ITL-1347, stage 5a). + + Nothing is read until the first stream is asked for; the caller closes the + generator (on the thread that reads it) when it stops early. + """ + return self._batch_streams() + @override def pinned_snapshot(self) -> "SpiralDBTableSource": """A copy of this source that reads its pinned version (``_copy``). diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 158bfdbe4..82cbdd3a9 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -18,7 +18,7 @@ import asyncio import functools import weakref -from collections.abc import AsyncIterator, Coroutine +from collections.abc import AsyncIterator, Callable, Coroutine, Sequence from typing import TYPE_CHECKING, Any, Protocol from orcapod.channels import ChannelClosed @@ -66,15 +66,25 @@ class InputChannel: directly. """ - def __init__(self, stream: StreamProtocol, feed: BatchFeed) -> None: + def __init__( + self, + stream: StreamProtocol, + feed: BatchFeed, + *, + batch_streams: Callable[[Sequence[pa.RecordBatch]], StreamProtocol] + | None = None, + ) -> None: """Make an input channel; use ``open_channel`` or ``open_reader``. Args: stream: The stream whose rows the channel delivers: its description. feed: Where the record batches come from. + batch_streams: The maker of streams of its batches, shared by the readers + of one output channel; ``None`` makes one for this channel. """ self._stream = stream self._feed = feed + self._batch_streams = batch_streams self._received = 0 # The producer's end was reached (the feed returned ``None``). self._ended = False @@ -312,6 +322,23 @@ def _closed_early(self) -> ChannelClosed: + "producer completed; it has no complete input to give." ) + def batch_streams(self) -> Callable[[Sequence[pa.RecordBatch]], StreamProtocol]: + """Makes streams of some of this channel's record batches (``BatchStreams``). + + Each call of the maker gives exactly what ``stream_from_batches`` gives for + its batches and this channel's stream; the description is read once, by the + first stream made (once per output channel for all its readers). + + Returns: + The maker. + """ + if self._batch_streams is None: + # Imported here, as in ``_to_stream``: the operators sit above the streams. + from orcapod.core.operators.static_output_pod import BatchStreams + + self._batch_streams = BatchStreams(self._stream) + return self._batch_streams + def to_stream(self) -> Coroutine[Any, Any, StreamProtocol]: """Return what the channel delivers, as a stream: the one such conversion. diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 6d35331fe..966f96b88 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -16,13 +16,14 @@ import warnings from collections import defaultdict from collections.abc import Callable, Coroutine -from typing import TYPE_CHECKING, Any, Literal, TypeVar +from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast from orcapod.channels import BroadcastChannel, Channel from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseWriteError, TypeIdentityError, + UpstreamFailedError, ) from orcapod.core.output_bindings import capture_output_bindings from orcapod.protocols.core_protocols import StreamProtocol @@ -40,6 +41,8 @@ from collections.abc import Mapping from orcapod.channels import WritableChannel + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceJobNode from orcapod.pipeline.dag import GraphProtocol from orcapod.protocols.core_protocols import ( DataProtocol, @@ -212,6 +215,8 @@ async def _run_async( ) -> OrchestratorResult: """Core async logic: wire channels, launch tasks, collect results.""" from orcapod.core.nodes.operator_node import ordered_operator_inputs + from orcapod.core.record_batch_channels import OutputChannel + from orcapod.core.streams.base import shared_zero_row_memo from orcapod.core.operators.static_output_pod import ( rows_on_read, ) @@ -243,11 +248,60 @@ async def _run_async( for position, upstream in enumerate(predecessors): out_edges[upstream].append((node, position)) + # The batch region (ITL-1347, stage 5a): the nodes whose outputs travel + # as Arrow record batches. Each gets a record-batch output channel, and + # each of its successors a reader of it, opened before any task starts; + # a successor outside the region gets that reader's rows through a + # boundary adapter, into a row channel, as they arrive. + demands: dict[Any, frozenset[str] | None] = { + node: read_columns(node, graph) + for node in topo_order + if is_source_node(node) + } + batch_outputs: dict[Any, Any] = {} + adapters: list[tuple[Any, Any]] = [] + edge_readers: dict[tuple[Any, int], Any] = {} + # The region's descriptions are read here, in one zero-row derivation + # (each node derived once, not once per channel and per upstream path); + # the memo ends before any task starts. + with shared_zero_row_memo(): + region = _batch_region(topo_order, in_edges, held_rows) + for node in topo_order: + if node not in region: + continue + if is_source_node(node): + # A region source node is a ``SourceJobNode`` (``_batch_region``). + description = cast("SourceJobNode", node).batch_description( + demands[node] + ) + retain = materialize_results + else: + description = node + retain = True + batch_outputs[node] = OutputChannel(description, retain=retain) + try: + batch_outputs[node].read_description() + except Exception: # noqa: BLE001 # read again, and raised, by the node's first send + pass + for node in topo_order: + if node not in region: + continue + batch_output = batch_outputs[node] + for downstream in out_edges.get(node, []): + reader = batch_output.open_reader() + if downstream[0] in region: + edge_readers[downstream] = reader + else: + ch = Channel(buffer_size=buf) + edge_readers[downstream] = ch.reader + adapters.append((reader, ch.writer)) + # Create channels for each edge node_output_channels: dict[Any, Channel | BroadcastChannel] = {} - edge_readers: dict[tuple[Any, int], Any] = {} for node, downstreams in out_edges.items(): + if node in region: + continue if len(downstreams) == 1: ch = Channel(buffer_size=buf) node_output_channels[node] = ch @@ -261,7 +315,7 @@ async def _run_async( # Terminal nodes need sink channels terminal_channels: list[Channel] = [] for node in topo_order: - if node not in node_output_channels: + if node not in node_output_channels and node not in region: ch = Channel(buffer_size=buf) node_output_channels[node] = ch terminal_channels.append(ch) @@ -277,6 +331,7 @@ async def _run_async( # A source node that sent a narrowed read's rows (ITL-1798): its output is # the whole one it returned, never the narrowed rows collected. whole_outputs: dict[int, StreamProtocol] = {} + region_results: dict[Any, StreamProtocol] = {} def collected_output( rows: list[tuple[TagProtocol, DataProtocol]], node: StreamProtocol @@ -284,13 +339,34 @@ def collected_output( whole = whole_outputs.get(id(node)) if whole is not None: return whole + if node in region_results: + # A region node's output: the record batches it sent. + return region_results[node] return rows_on_read( rows, node, bindings=bindings_at_collection[id(node)] ) # Launch all nodes concurrently async with asyncio.TaskGroup() as tg: + for reader, row_writer in adapters: + tg.create_task(_rows_from_batches(reader, row_writer)) for node in topo_order: + if node in region: + _start_region_node( + tg, + failed_nodes, + node, + batch_outputs[node], + [ + edge_readers[(node, position)] + for position in range(len(in_edges.get(node, []))) + ], + observer=effective_observer, + demand=demands.get(node), + whole_outputs=whole_outputs, + load_only=load_only, + ) + continue writer = node_output_channels[node].writer if materialize_results: @@ -391,6 +467,16 @@ def collected_output( for ch in terminal_channels: tg.create_task(ch.reader.collect()) + if materialize_results: + # A region node's result is taken as the run ends, while the bindings + # it was computed under are current, as main collected its rows then; + # the stream carries those bindings, so using it after a rebind raises + # ``StaleOutputError``, as main's collected output does. + region_results.update( + (node, output.result()) + for node, output in batch_outputs.items() + if id(node) not in whole_outputs + ) return OrchestratorResult( node_outputs=( StreamsOnRead(collectors, collected_output) @@ -709,6 +795,173 @@ def create_data_logger(self, tag: Any, data: Any) -> Any: return NoOpLogger() +def _batch_region( + topo_order: list[Any], + in_edges: Mapping[Any, list[Any]], + held_rows: Mapping[Any, Any] | None, +) -> set[Any]: + """The nodes of a run whose outputs travel as Arrow record batches (ITL-1347, + stage 5a). + + The region is decided from the graph and the classes alone, never from rows: + + - a source job node that is not held, whose Arrow types are declared, bound to a + source that reads a fixed snapshot: its async read is the default one over its + whole read (``StreamBase.async_iter_data``), or it reads a pinned snapshot in + batches (``snapshot_batch_streams``, a ``SpiralDBTableSource``). A + ``PollingSource`` (its own async read) stays outside; + - an operator job node that is not held, of exactly a library unary operator + class (every one is row by row or a barrier), whose one input is a region node + with declared Arrow types. + + Every other node (a multi-input operator, a function, side-effect or held node, a + user's operator class) runs main's row form, its region inputs' rows given to it + at the boundary. + + Args: + topo_order: The run's nodes, in topological order. + in_edges: Each node's inputs, in the operator's order. + held_rows: The nodes the run holds rather than runs. + + Returns: + The region's nodes. + """ + from orcapod.core.nodes.operator_node import OperatorJobNode + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.sources.base import RootSource + from orcapod.core.streams.base import StreamBase, reads_as_its_class + + unary = _library_unary_operators() + region: set[Any] = set() + # Whether each region node declares its Arrow types, asked once per node. + declared: dict[int, bool] = {} + for node in topo_order: + if held_rows is not None and node in held_rows: + continue + if is_source_node(node): + if not reads_as_its_class(node, SourceJobNode): + continue + source_node = cast("SourceJobNode", node) + source = source_node.bound_source + if source is None: + continue + declared[id(node)] = source_node.arrow_types_declared + if not declared[id(node)]: + continue + kind = type(source) + reads_whole = kind.async_iter_data is StreamBase.async_iter_data + in_batches = isinstance(source, RootSource) and ( + type(source).snapshot_batch_streams + is not RootSource.snapshot_batch_streams + ) + if reads_whole or in_batches: + region.add(node) + elif is_operator_node(node): + if not reads_as_its_class(node, OperatorJobNode): + continue + operator_node = cast("OperatorJobNode", node) + predecessors = in_edges.get(node, []) + if ( + type(operator_node.producer) in unary + and len(predecessors) == 1 + and predecessors[0] in region + and declared[id(predecessors[0])] + ): + region.add(node) + declared[id(node)] = operator_node.arrow_types_declared + return region + + +def _library_unary_operators() -> frozenset[type]: + """The library's unary operator classes (exactly these, never a subclass).""" + import inspect + + import orcapod.operators as operators + from orcapod.core.operators.base import UnaryOperator + + return frozenset( + value + for value in vars(operators).values() + if inspect.isclass(value) and issubclass(value, UnaryOperator) + ) + + +def _start_region_node( + tg: asyncio.TaskGroup, + failed_nodes: dict[int, str], + node: Any, + output: Any, + inputs: list[Any], + *, + observer: Any, + demand: frozenset[str] | None, + whole_outputs: dict[int, Any], + load_only: bool, +) -> None: + """Start a region node's record-batch form (ITL-1347, stage 5a). + + Args: + tg: The run's task group. + failed_nodes: The run's record of which node raised each exception. + node: A source or unary operator job node of the region. + output: Its output channel. + inputs: Its input channels (none for a source node). + observer: The run's observer. + demand: A source node's successors' columns (ITL-1798), or ``None``. + whole_outputs: Where a source node's whole output is recorded when it sent + a narrowed read. + load_only: Whether the run is load-only. + """ + if is_source_node(node): + source_node = cast("SourceJobNode", node) + + async def source_work() -> None: + whole = await source_node.async_execute_batches( + output, observer=observer, read_columns=demand + ) + if whole is not None: + whole_outputs[id(node)] = whole + + _start_node(tg, failed_nodes, node, source_work()) + else: + _start_node( + tg, + failed_nodes, + node, + node.async_execute_batches( + inputs, output, observer=observer, load_only=load_only + ), + ) + + +async def _rows_from_batches(reader: Any, writer: Any) -> None: + """Hand a region node's record batches to a successor outside the region as rows. + + Each batch, as it arrives, becomes the rows of the stream it is part of + (``stream_from_batches`` of the batch with the producer's description, + read once: ``BatchStreams``), sent + into the successor's row channel at once. When the producer fails, the row + channel is closed as on ``main``, where a failing producer closed its output: the + successor runs as there, and the run raises the producer's own error. + + Args: + reader: The successor's input channel on the region node's output. + writer: The successor's row channel. + """ + streams = reader.batch_streams() + try: + async for batch in reader: + for pair in streams([batch]).iter_data(): + await writer.send(pair) + except UpstreamFailedError: + pass + finally: + try: + await reader.close() + finally: + await writer.close() + + async def _drain(reader: Any) -> None: """Read ``reader`` to its end, keeping nothing.""" async for _ in reader: @@ -794,7 +1047,13 @@ def _single_failure( """ leaves = _leaves(group) rank = {getattr(node, "label", None): i for i, node in enumerate(topo_order)} - chosen = min(leaves, key=lambda exc: rank.get(failed_nodes.get(id(exc)), len(rank))) + # A reader's ``UpstreamFailedError`` only stops it: its producer's own error is + # the run's (ITL-1347, stage 5a). + own = [exc for exc in leaves if not isinstance(exc, UpstreamFailedError)] + chosen = min( + own or leaves, + key=lambda exc: rank.get(failed_nodes.get(id(exc)), len(rank)), + ) for other in leaves: if other is chosen: continue diff --git a/src/orcapod/protocols/core_protocols/sources.py b/src/orcapod/protocols/core_protocols/sources.py index ed6f01a1a..5fcaf81b5 100644 --- a/src/orcapod/protocols/core_protocols/sources.py +++ b/src/orcapod/protocols/core_protocols/sources.py @@ -74,6 +74,19 @@ def projected_batch_streams( """ ... + def snapshot_batch_streams(self) -> Iterator[StreamProtocol] | None: + """This source's whole rows as streams of record batches, read as they are asked + for, or ``None`` when this kind has no per-batch snapshot read. + + A kind that reads a fixed snapshot in batches (``SpiralDBTableSource``: one + pinned version, scanned once) hands on the streams its ``async_iter_data`` + reads its rows from, in order. A job's async route sends a source node's rows + from them, a record batch per stream, as they are read (ITL-1347, stage 5a). + Every source kind answers for itself, a wrapper too: a wrapper answers + ``None`` unless it reads in batches itself, never by asking what it wraps. + """ + ... + def pinned_snapshot(self) -> SourceProtocol | None: """A source that reads this source's current version, whatever a later check pins, or ``None`` when this kind cannot keep a version. diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index bd681e63a..4345a33fd 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -2,6 +2,7 @@ from collections.abc import ( AsyncIterator, + Callable, Coroutine, Collection, Iterable, @@ -710,6 +711,15 @@ def reserve(self, claim: object | None = None) -> object: """ ... + def batch_streams(self) -> Callable[[Sequence[pa.RecordBatch]], StreamProtocol]: + """Makes streams of some of the channel's record batches (``BatchStreams``). + + Each call of the returned maker gives what ``stream_from_batches`` gives for + its batches and the channel's stream; the description is read once per + channel, or once per output channel for all of its readers (ITL-1347). + """ + ... + def to_stream(self) -> Coroutine[Any, Any, StreamProtocol]: """Return what the channel delivers, as a stream: the one such conversion. @@ -738,6 +748,15 @@ class RecordBatchOutput(Protocol): ``orcapod.core.record_batch_channels`` is the implementation. """ + @property + def stream(self) -> StreamProtocol: + """The stream whose rows are written here: the description.""" + ... + + def result(self) -> StreamProtocol: + """The output as a stream, once closed (a retaining output only).""" + ... + async def send(self, batch: pa.RecordBatch) -> None: """Send one Arrow record batch of the stream's transport columns.""" ... diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 197c8597a..8b5f25d1f 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -14,6 +14,7 @@ import copy import dataclasses import datetime +import threading from collections.abc import Callable from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast @@ -23,7 +24,6 @@ from orcapod import PipelineJob, function_pod from orcapod.core.operators.static_output_pod import ( - RowsOnRead, _RowsOfStream, # pyright: ignore[reportPrivateUsage] # main's sync output class ) from orcapod.core.streams.arrow_table_stream import pending_whole_read @@ -936,8 +936,10 @@ def _collected_output(route: str, *, whole: bool, monkeypatch: Any) -> Any: else AsyncPipelineOrchestrator() ) output = orchestrator.run(dag).node_outputs[node] - # Main's own class on each route: the table-built stream, or the rows. - assert type(output) is (_RowsOfStream if route == "sync" else RowsOnRead) + # Main's sync class on both routes: the table-built stream. On the async route a + # source node's output is its record batches' stream (ITL-1347, stage 5a), which + # is the sync route's own form, no longer main's async ``RowsOnRead``. + assert type(output) is _RowsOfStream return output @@ -982,9 +984,6 @@ def answer(output: Any) -> tuple[tuple[str, Any], list[list[str]]]: _same_value(got[1], expected[1]) if kind == "describe": assert scans == [] - elif kind == "rows" and name == "__eq__" and route == "async": - # Main's output on this route (``RowsOnRead``) compares by object. - assert scans == [] elif kind == "rows": assert scans == [_ALL] else: @@ -997,8 +996,8 @@ def answer(output: Any) -> tuple[tuple[str, Any], list[list[str]]]: def test_outputs_of_two_routes_compare_and_hash_as_main( project: Any, monkeypatch: pytest.MonkeyPatch ) -> None: - """Sync and async outputs, and two outputs of one route, compare and hash as - main's do (the mirror compared a sync and an async output equal with unequal + """Sync and async outputs, and two outputs of one route, compare and hash + consistently (the mirror compared a sync and an async output equal with unequal hashes).""" def answers(*, whole: bool) -> tuple[Any, ...]: @@ -1027,9 +1026,14 @@ def answers(*, whole: bool) -> tuple[Any, ...]: got = answers(whole=False) expected = answers(whole=True) assert got[0] == expected[0] - assert got[0][:3] == (False, False, True) - # Comparing two routes' outputs reads nothing, as on main. - assert got[1] == expected[1] == [] + # Both routes now collect one stream form (ITL-1347, stage 5a): a sync and an + # async output compare equal (main: unequal, ``RowsOnRead`` against a stream). + assert got[0][:3] == (True, True, False) + # Comparing them compares their identities, which read their rows, as comparing + # two sync outputs does on main: each projected output takes its one whole read + # then (a whole output holds its rows already). + assert got[1] == [_ALL, _ALL] + assert expected[1] == [] assert got[2] == expected[2] @@ -1049,7 +1053,7 @@ def test_a_shallow_copy_shares_the_one_whole_read( _same(copied.as_table(all_info=True), expected.as_table(all_info=True)) _same(output.as_table(all_info=True), expected.as_table(all_info=True)) assert _row_scans() == [_ALL] - # A copy of the async output fails as main's does (``RowsOnRead.__getattr__``). + # A copy of the async output behaves as a copy of the whole read's output. async_expected = _collected_output("async", whole=True, monkeypatch=monkeypatch) async_output = _collected_output("async", whole=False, monkeypatch=monkeypatch) got = _outcome(lambda: copy.copy(async_output)) @@ -1059,26 +1063,20 @@ def test_a_shallow_copy_shares_the_one_whole_read( assert got[1][0] == want[1][0] -@pytest.mark.parametrize("read_first", [True, False]) -def test_the_async_output_keeps_release_built( - project: Any, monkeypatch: pytest.MonkeyPatch, read_first: bool +def test_the_async_output_reads_its_whole_rows_once( + project: Any, monkeypatch: pytest.MonkeyPatch ) -> None: - """The async collected output is main's ``RowsOnRead``, with ``release_built``: a - read after it builds the same table again, from the one whole read of the - pinned snapshot (the mirror had no ``release_built``).""" + """The async collected output of a projected source node is the sync route's + form (ITL-1347, stage 5a; main's async output was ``RowsOnRead``): its rows are + the whole read's, read from the pinned snapshot once, when first read, and every + later read takes that read.""" expected = _collected_output("async", whole=True, monkeypatch=monkeypatch) output = _collected_output("async", whole=False, monkeypatch=monkeypatch) fake.scan_log.clear() fake.count_log.clear() - if read_first: - _same(output.as_table(all_info=True), expected.as_table(all_info=True)) - output.release_built() - expected.release_built() - assert _row_scans() == ([_ALL] if read_first else []) _same(output.as_table(all_info=True), expected.as_table(all_info=True)) - rows = [_pair(t, d) for t, d in output] - assert rows == [_pair(t, d) for t, d in expected] - output.release_built() + rows = [_pair(t, d) for t, d in output.iter_data()] + assert rows == [_pair(t, d) for t, d in expected.iter_data()] _same(output.as_table(all_info=True), expected.as_table(all_info=True)) assert _row_scans() == [_ALL] @@ -1423,3 +1421,226 @@ def test_two_threads_head_0_and_a_full_read_both_answer_as_main( assert shown[0] == "value", shown assert shown[1].table.equals(expected.table, check_metadata=True) assert shown[1].total_rows == expected.total_rows == 6 + + +@pytest.mark.parametrize("policy", ["continue", "fail_fast"]) +@pytest.mark.parametrize("projected", [True, False]) +def test_a_logging_operator_stores_nothing_after_its_source_fails_mid_scan( + project: Any, + monkeypatch: pytest.MonkeyPatch, + policy: Literal["continue", "fail_fast"], + projected: bool, +) -> None: + """e7, the scan case: the scan fails on its third record batch, after two were + sent. The LOG operator node after the source stores nothing, on main and here. + Here it holds by construction: the node reads the failure from its input + channel (``UpstreamFailedError``), raises, and never reaches its store; on main + its input ended normally and the run's cancellation came first.""" + if not projected: + _read_whole(monkeypatch) + original = fake.FakeReader.read_next_batch + + def failing(self: Any) -> Any: + if self._record.batches_read == 2: + raise RuntimeError("the scan failed on its third batch") + return original(self) + + monkeypatch.setattr(fake.FakeReader, "read_next_batch", failing) + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + SpiralDBTableSource( + "p", "wide", tag_only_columns=True, batch_rows=1 + ).select_data_columns(["x", "y"], label="sxy") + log = InMemoryArrowDatabase() + job.nodes["sxy"].attach_databases(pipeline_database=log, cache_mode=CacheMode.LOG) + with pytest.raises(Exception, match="third batch"): + asyncio.run( + job.run_async(orchestrator=AsyncPipelineOrchestrator(error_policy=policy)) + ) + assert not any( + (log.get_all_records(path) or pa.table({})).num_rows + for path in log.list_table_paths() + ) + + +# Calls of ``x_twice``, and an event set at each call (stage 5a's delivery tests). +X_CALLS: list[float] = [] +X_CALLED = threading.Event() + + +@function_pod(output_keys="x2") +def x_twice(x: float) -> float: + X_CALLS.append(x) + X_CALLED.set() + return 2 * x + + +def _reads_rows(record: Any) -> bool: + """Whether a scan reads the table's rows: all columns or several (a count reads + one, a schema read another table).""" + return record not in fake.schema_scan_log and ( + record.columns is None or len(record.columns) > 1 + ) + + +def _gate_scan( + monkeypatch: pytest.MonkeyPatch, before_batch: int, action: Callable[[], None] +) -> None: + """Run ``action`` on the scan's reading thread before it reads ``before_batch`` + (counted from 1) of a scan of the table's rows.""" + original = fake.FakeReader.read_next_batch + + def gated(self: Any) -> Any: + if _reads_rows(self._record) and ( + self._record.batches_read == before_batch - 1 + ): + action() + return original(self) + + monkeypatch.setattr(fake.FakeReader, "read_next_batch", gated) + + +def _function_job(monkeypatch: pytest.MonkeyPatch) -> PipelineJob: + """A source read one row per record batch, a select and ``x_twice``.""" + monkeypatch.setattr(fake, "scan_batch_rows", 1) + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + selected = SpiralDBTableSource( + "p", "wide", tag_only_columns=True, batch_rows=1 + ).select_data_columns(["x"], label="sx") + x_twice.pod(selected, label="fn") + return job + + +@pytest.mark.parametrize("policy", ["continue", "fail_fast"]) +def test_a_function_node_computes_the_first_batch_while_the_scan_reads( + project: Any, + monkeypatch: pytest.MonkeyPatch, + policy: Literal["continue", "fail_fast"], +) -> None: + """D1, early delivery: the scan does not read its second record batch until the + function node after the select has computed a row of the first.""" + X_CALLS.clear() + X_CALLED.clear() + waited: list[bool] = [] + _gate_scan(monkeypatch, 2, lambda: waited.append(X_CALLED.wait(timeout=60))) + job = _function_job(monkeypatch) + asyncio.run( + job.run_async(orchestrator=AsyncPipelineOrchestrator(error_policy=policy)) + ) + assert waited == [True] + assert len(list(job.nodes["fn"].iter_data())) == 6 + + +@pytest.mark.parametrize("policy", ["continue", "fail_fast"]) +def test_a_failing_scan_leaves_the_rows_before_it_computed( + project: Any, + monkeypatch: pytest.MonkeyPatch, + policy: Literal["continue", "fail_fast"], +) -> None: + """D2, partial results: the scan fails on its third record batch once the function + node has computed both rows before it; those two rows were computed, and the run + raises the scan's own error.""" + X_CALLS.clear() + X_CALLED.clear() + expected = sorted( + row["x"] + for row in sorted(_rows().to_pylist(), key=lambda r: (r["unit"], r["t"]))[:2] + ) + + def fail_after_two() -> None: + while len(X_CALLS) < 2: + assert X_CALLED.wait(timeout=60) + X_CALLED.clear() + raise RuntimeError("the scan failed on its third batch") + + _gate_scan(monkeypatch, 3, fail_after_two) + job = _function_job(monkeypatch) + with pytest.raises(Exception, match="third batch"): + asyncio.run( + job.run_async(orchestrator=AsyncPipelineOrchestrator(error_policy=policy)) + ) + assert sorted(X_CALLS) == expected + + +def test_cancelling_a_run_mid_scan_closes_the_scan_on_its_thread( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """A run cancelled while the scan reads: the scan's reader is closed on the thread + that read it, and no task of the run is left.""" + reading = threading.Event() + release = threading.Event() + closed = threading.Event() + threads: dict[str, int] = {} + + def wait_for_release() -> None: + threads["read"] = threading.get_ident() + reading.set() + assert release.wait(timeout=60) + + _gate_scan(monkeypatch, 2, wait_for_release) + original_close = fake.FakeReader.close + + def recorded_close(self: Any) -> None: + if _reads_rows(self._record): + threads["close"] = threading.get_ident() + closed.set() + original_close(self) + + monkeypatch.setattr(fake.FakeReader, "close", recorded_close) + job = _function_job(monkeypatch) + + async def main() -> set[asyncio.Task[Any]]: + run = asyncio.ensure_future(job.run_async()) + while not reading.is_set(): + await asyncio.sleep(0.01) + run.cancel() + release.set() + with pytest.raises(asyncio.CancelledError): + await run + return asyncio.all_tasks() - {asyncio.current_task()} + + left = asyncio.run(main()) + assert left == set() + assert closed.wait(timeout=60) + assert threads["close"] == threads["read"] + + +@pytest.mark.parametrize("batch_rows", [1, 2, None]) +def test_every_scan_layout_shows_the_sync_runs_rows( + project: Any, monkeypatch: pytest.MonkeyPatch, batch_rows: int | None +) -> None: + """A keyed scan in record batches of one row, two rows or the whole table, + through a chain of region operators to a function node: the async run shows what + the sync run shows, row order included.""" + monkeypatch.setattr(fake, "scan_batch_rows", batch_rows or 1000) + + def build() -> PipelineJob: + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + source = SpiralDBTableSource( + "p", "wide", tag_only_columns=True, batch_rows=batch_rows or 1000 + ) + kept = source.drop_nulls(["y"], label="kept").map_data( + {"y": "why"}, label="renamed" + ) + pairs = kept.batch(batch_size=2, label="pairs") + kept.group_by(["unit"], label="grouped") + x_twice.pod(kept.select_data_columns(["x"], label="sx"), label="fn") + pairs.select_data_columns(["x", "why"], label="pairs_x") + return job + + sync = build() + sync.run(orchestrator=SyncPipelineOrchestrator()) + got = build() + got.run(orchestrator=AsyncPipelineOrchestrator()) + for label in ("kept", "renamed", "pairs", "grouped", "sx", "pairs_x"): + assert ( + got.nodes[label] + .as_table(all_info=True) + .equals(sync.nodes[label].as_table(all_info=True)) + ), label + # The function node keeps main's async form: rows in completion order. + assert sorted( + repr(_pair(t, d)[0]) for t, d in got.nodes["fn"].iter_data() + ) == sorted(repr(_pair(t, d)[0]) for t, d in sync.nodes["fn"].iter_data()) diff --git a/tests/test_pipeline/test_async_batch_region.py b/tests/test_pipeline/test_async_batch_region.py new file mode 100644 index 000000000..783d5a193 --- /dev/null +++ b/tests/test_pipeline/test_async_batch_region.py @@ -0,0 +1,500 @@ +"""ITL-1347 stage 5a: an async job hands record batches through its batch region. + +Source job nodes over snapshot sources, and the library unary operator nodes fed by +one of them, send their rows to each other as Arrow record batches +(``docs/dev/specs/itl-1347-job-table-transport.md``, stage 5a). Every other node +receives rows, as on main. Nothing a run shows may change: every node's rows, row +order, column order, Arrow types, system tags, source-info tokens and hashes are the +sync run's, under both error policies, and a node that stores its rows stores the +same records. +""" + +from __future__ import annotations + +import asyncio +import threading +import warnings +from collections.abc import Iterator +from typing import Any, Literal + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.sources import ArrowTableSource, DictSource +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import ProvisionalHashWarning +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.pipeline.observer import NoOpObserver +from orcapod.types import CacheMode +from tests.test_core.operators.several_items import ( + MAIN, + Arrangement, + arrangements, + make_source, + row_fingerprint, +) + +Policy = Literal["continue", "fail_fast"] +POLICIES: tuple[Policy, ...] = ("continue", "fail_fast") + +ALL_COLUMNS = { + "meta": True, + "source": True, + "system_tags": True, + "context": True, + "content_hash": True, +} + + +@function_pod(output_keys="d1_doubled") +def doubled(d1: int) -> int: + return 2 * d1 + + +# Labels of the operator nodes a run must send record batches through. +REGION = ( + "selected", + "dropped", + "mapped", + "no_nulls", + "filtered", + "nothing", + "tagged", + "pairs", + "first", + "whole_batch", + "grouped", + "tag_by", + "columns", + "dropped_columns", + "after_no_nulls", + "after_filtered", + "after_nothing", + "after_first", +) + +# Function nodes: a fresh computation names a fresh result, so their source-info +# tokens are compared without values. +FUNCTIONS = ("doubled_no_nulls", "doubled_filtered", "doubled_nothing", "doubled_first") + + +def build_job(source: Any, database: Any = None) -> PipelineJob: + """Every library unary operator kind over one source, two of them chained, each + of several feeding a select and a function node.""" + job = PipelineJob(name="batch_region", database=database or InMemoryArrowDatabase()) + with job: + source.select_data_columns(["d3", "d1"], label="selected") + source.drop_data_columns(["d2", "d3"], label="dropped") + source.map_data({"d3": "e3", "d2": "e2"}, label="mapped") + no_nulls = source.drop_nulls(["d2", "d1"], label="no_nulls") + filtered = source.filter(d3="x", label="filtered") + nothing = source.filter(d1=999, label="nothing") + source.add_tags(run="a", k=1, label="tagged") + pairs = source.batch(batch_size=2, label="pairs") + first = pairs.index("d1", 0, label="first") + source.batch(label="whole_batch") + source.group_by(["t1"], label="grouped") + source.tag_by("d3", "d1", label="tag_by") + source.select_columns(["d1", "d3"], label="columns") + source.drop_columns(["d2"], label="dropped_columns") + for name, stream in ( + ("no_nulls", no_nulls), + ("filtered", filtered), + ("nothing", nothing), + ("first", first), + ): + kept = stream.select_data_columns(["d1"], label=f"after_{name}") + doubled.pod(kept, label=f"doubled_{name}") + return job + + +@pytest.fixture +def batch_nodes(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[str]]: + """The labels of the operator nodes a run sent record batches through.""" + seen: list[str] = [] + original = OperatorJobNode.async_execute_batches + + async def recorded(self: Any, *args: Any, **kwargs: Any) -> None: + seen.append(self.label) + await original(self, *args, **kwargs) + + monkeypatch.setattr(OperatorJobNode, "async_execute_batches", recorded) + yield seen + + +def _run(job: PipelineJob, orchestrator: Any, **kwargs: Any) -> Any: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + return job.run(orchestrator=orchestrator, **kwargs) + + +def _shown(job: PipelineJob) -> dict[str, Any]: + """What every node shows: its rows in order, its table's columns and types.""" + shown: dict[str, Any] = {} + for label, node in job.nodes.items(): + functional = label in FUNCTIONS + rows = [ + row_fingerprint(tag, data, source_info=not functional) + for tag, data in node.iter_data() + ] + table = node.as_table(columns=ALL_COLUMNS) + schema = [ + (field.name, str(field.type), field.nullable) + for field in table.schema + if not (functional and field.name.startswith("_source_")) + ] + shown[label] = { + "rows": rows, + "schema": schema, + "content_hash": node.content_hash().to_string(), + "pipeline_hash": node.pipeline_hash().to_string(), + } + return shown + + +def _build(arrangement: Arrangement) -> PipelineJob: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + return build_job(make_source(MAIN, arrangement)) + + +@pytest.mark.parametrize("policy", POLICIES) +@pytest.mark.parametrize("arrangement", arrangements(MAIN), ids=lambda a: a.id) +def test_every_node_shows_the_sync_runs_rows( + arrangement: Arrangement, policy: Policy, batch_nodes: list[str] +) -> None: + """Every region operator kind, chained and feeding a function node: the async run + shows what the sync run shows, in every tag order, layout and tag role.""" + sync_job = _build(arrangement) + _run(sync_job, SyncPipelineOrchestrator(error_policy=policy)) + async_job = _build(arrangement) + _run(async_job, AsyncPipelineOrchestrator(error_policy=policy)) + assert sorted(batch_nodes) == sorted(REGION) + assert _shown(async_job) == _shown(sync_job) + + +def _stored(database: InMemoryArrowDatabase) -> list[Any]: + """Every stored record, without the columns that hold a time or a random id.""" + records: list[Any] = [] + for path in sorted(database.list_table_paths()): + table = database.get_all_records(path) + if table is None: + continue + kept = [ + name + for name in table.column_names + if name not in ("__recorded_at",) and not name.startswith("__pod_ts") + ] + records.append((path, sorted(table.select(kept).to_pylist(), key=repr))) + return records + + +@pytest.mark.parametrize("policy", POLICIES) +def test_a_logging_region_node_stores_the_sync_runs_records( + policy: Policy, batch_nodes: list[str] +) -> None: + """A region operator node in LOG mode stores what the sync run stores; under + REPLAY it hands on the stored rows, as the sync run does.""" + + def run(orchestrator: Any, mode: CacheMode, log: InMemoryArrowDatabase) -> Any: + job = _build(arrangements(MAIN)[0]) + for label in ("filtered", "pairs", "first"): + job.nodes[label].attach_databases(pipeline_database=log, cache_mode=mode) + _run(job, orchestrator) + return job + + sync_log = InMemoryArrowDatabase() + async_log = InMemoryArrowDatabase() + sync_job = run( + SyncPipelineOrchestrator(error_policy=policy), CacheMode.LOG, sync_log + ) + async_job = run( + AsyncPipelineOrchestrator(error_policy=policy), CacheMode.LOG, async_log + ) + assert _stored(async_log) + assert _stored(async_log) == _stored(sync_log) + assert _shown(async_job) == _shown(sync_job) + + batch_nodes.clear() + replayed = run( + AsyncPipelineOrchestrator(error_policy=policy), + CacheMode.REPLAY, + async_log, + ) + assert {"filtered", "pairs", "first"} <= set(batch_nodes) + assert _shown(replayed) == _shown(sync_job) + assert _stored(async_log) == _stored(sync_log) + + +def test_a_load_only_run_shows_the_sync_runs_rows(batch_nodes: list[str]) -> None: + """A load-only run over a store a full run filled sends record batches too, and + shows the sync load-only run's rows.""" + database = InMemoryArrowDatabase() + + def build() -> PipelineJob: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + return build_job(make_source(MAIN), database) + + _run(build(), SyncPipelineOrchestrator()) + sync = build() + _run(sync, SyncPipelineOrchestrator(), load_only=True) + got = build() + _run(got, AsyncPipelineOrchestrator(), load_only=True) + assert sorted(batch_nodes) == sorted(REGION) + assert _shown(got) == _shown(sync) + + +@pytest.mark.parametrize("materialize_results", [True, False]) +def test_a_source_feeding_several_region_nodes_and_rows( + materialize_results: bool, batch_nodes: list[str] +) -> None: + """One source feeds region operators, a function node and a join, each opening + its reader before any node runs: every one reads every row, whether or not the + run keeps the results.""" + + def build() -> PipelineJob: + source = make_source(MAIN) + partner = DictSource( + [{"t1": "a", "p1": 1}, {"t1": "b", "p1": 2}], + tag_columns=["t1"], + tag_only_columns=True, + source_id="partner", + ) + job = PipelineJob(name="fan_out", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["d1"], label="one") + source.select_data_columns(["d3", "d1"], label="two") + doubled.pod(source.select_data_columns(["d1"]), label="fn") + source.join(partner, label="joined") + return job + + sync = build() + _run(sync, SyncPipelineOrchestrator(), materialize_results=materialize_results) + got = build() + _run(got, AsyncPipelineOrchestrator(), materialize_results=materialize_results) + assert {"one", "two"} <= set(batch_nodes) + assert "joined" not in batch_nodes + for label in ("one", "two", "fn", "joined"): + node = got.nodes[label] + expected = sync.nodes[label] + assert len(list(node.iter_data())) == len(list(expected.iter_data())) + assert _shown(got)["two"] == _shown(sync)["two"] + # The join is outside the region and keeps main's async form: rows in arrival + # order, as on main. + joined, expected_joined = _shown(got)["joined"], _shown(sync)["joined"] + assert sorted(joined.pop("rows")) == sorted(expected_joined.pop("rows")) + assert joined == expected_joined + + +def test_a_held_source_feeds_a_region_node_rows(batch_nodes: list[str]) -> None: + """A second run holds the source and the select; the cleared operator after them + runs on the held rows, as on main, and shows the first run's rows.""" + job = _build(arrangements(MAIN)[0]) + _run(job, AsyncPipelineOrchestrator()) + before = _shown(job) + job.nodes["first"].clear_cache() + batch_nodes.clear() + _run(job, AsyncPipelineOrchestrator()) + assert "pairs" not in batch_nodes + assert _shown(job) == before + + +def test_a_many_batch_source_shows_the_sync_runs_rows(batch_nodes: list[str]) -> None: + """A source of 70,000 rows in many record batches, through a chain of region + operators and a function node: the async run shows the sync run's rows, in order.""" + count = 70_000 + schema = pa.schema( + [ + pa.field("unit", pa.large_string(), nullable=False), + pa.field("t", pa.int64(), nullable=False), + pa.field("d1", pa.int64(), nullable=False), + pa.field("d2", pa.float64()), + ] + ) + table = pa.Table.from_pydict( + { + "unit": [f"u{i % 13}" for i in range(count)], + "t": list(range(count)), + "d1": [i % 1000 for i in range(count)], + "d2": [None if i % 7 == 0 else i * 0.5 for i in range(count)], + }, + schema=schema, + ) + table = pa.Table.from_batches(table.to_batches(max_chunksize=4096)) + + def build() -> PipelineJob: + source = ArrowTableSource( + table, tag_columns=["unit", "t"], tag_only_columns=True, source_id="many" + ) + job = PipelineJob(name="many", database=InMemoryArrowDatabase()) + with job: + kept = source.drop_nulls(["d2"], label="kept").filter( + unit="u3", label="unit" + ) + pairs = kept.batch(batch_size=3, label="triples").index( + "d1", 0, label="first" + ) + doubled.pod(pairs.select_data_columns(["d1"], label="d1"), label="fn") + return job + + sync = build() + _run(sync, SyncPipelineOrchestrator()) + got = build() + _run(got, AsyncPipelineOrchestrator()) + assert {"kept", "unit", "triples", "first", "d1"} <= set(batch_nodes) + for label in ("kept", "unit", "triples", "first", "d1"): + assert ( + got.nodes[label] + .as_table(columns=ALL_COLUMNS) + .equals(sync.nodes[label].as_table(columns=ALL_COLUMNS)) + ), label + assert len(list(got.nodes["fn"].iter_data())) == len( + list(sync.nodes["fn"].iter_data()) + ) + + +@function_pod(output_keys="z") +def fails_on_three(d1: int) -> int: + if d1 == 3: + raise ValueError("row 3") + return d1 * 2 + + +def _records(database: InMemoryArrowDatabase) -> int: + return sum( + (database.get_all_records(path) or pa.table({})).num_rows + for path in database.list_table_paths() + ) + + +def test_a_logging_operator_after_a_failing_function_stores_nothing() -> None: + """e7, the function case: under ``fail_fast`` a function node fails on one row and + the LOG operator node after it stores nothing, on main and here. The operator is + not a region node (its input is a function node), so it ends as on main.""" + job = PipelineJob(name="e7", database=InMemoryArrowDatabase()) + with job: + source = DictSource( + [{"k": i, "d1": i} for i in range(6)], + tag_columns=["k"], + tag_only_columns=True, + source_id="six", + ) + computed: Any = fails_on_three.pod(source, label="f") + computed.select_data_columns(["z"], label="sz") + log = InMemoryArrowDatabase() + job.nodes["sz"].attach_databases(pipeline_database=log, cache_mode=CacheMode.LOG) + with pytest.raises(Exception, match="row 3"): + asyncio.run( + job.run_async( + orchestrator=AsyncPipelineOrchestrator(error_policy="fail_fast") + ) + ) + assert _records(log) == 0 + + +class _Recorder(NoOpObserver): + """Records node and row events in the order they happen, from any thread.""" + + def __init__(self) -> None: + self.events: list[tuple[str, str, Any]] = [] + self._lock = threading.Lock() + + def contextualize(self, *identity_path: str) -> _Recorder: + return self + + def _add(self, kind: str, label: str, detail: Any = None) -> None: + with self._lock: + self.events.append((kind, label, detail)) + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + self._add("start", node_label) + + def on_node_end(self, node_label: str, node_hash: str) -> None: + self._add("end", node_label) + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + self._add("data_start", node_label, repr(sorted(tag.as_dict().items()))) + + def on_data_end( + self, + node_label: str, + tag: Any, + input_data: Any, + output_data: Any, + cached: bool, + ) -> None: + self._add("data_end", node_label, repr(sorted(tag.as_dict().items()))) + + +@pytest.mark.parametrize("rows", [5, 300]) +def test_observer_events_keep_mains_invariants(rows: int) -> None: + """e9: a source, two region operators and a function node, async. Each node starts + in topological order, its row events lie between its start and end, an upstream + node ends before its downstream node, and the function node's rows start in the + order they arrive, which is the sync run's order.""" + # A source's node is named by its source's name. + chain = ("numbers", "selected", "filtered", "fn") + + def build() -> PipelineJob: + source = DictSource( + [{"k": i, "d1": i, "d3": f"v{i % 3}"} for i in range(rows)], + tag_columns=["k"], + tag_only_columns=True, + source_id="numbers", + ) + job = PipelineJob(name="observed", database=InMemoryArrowDatabase()) + with job: + selected = source.select_data_columns(["d1", "d3"], label="selected") + kept = selected.filter(d3="v1", label="filtered").select_data_columns( + ["d1"], label="after" + ) + doubled.pod(kept, label="fn") + return job + + sync_events = _Recorder() + _run(build(), SyncPipelineOrchestrator(), observer=sync_events) + recorder = _Recorder() + _run(build(), AsyncPipelineOrchestrator(), observer=recorder) + events = recorder.events + + def index(kind: str, label: str) -> int: + return next( + i for i, (k, name, _) in enumerate(events) if (k, name) == (kind, label) + ) + + labels = {name for _, name, _ in events} + assert set(chain) <= labels + order = (*chain[:3], "after", "fn") + starts = [index("start", label) for label in order] + ends = [index("end", label) for label in order] + # (i) starts in topological order; (iii) an upstream node ends before its + # downstream node. + assert starts == sorted(starts) + assert ends == sorted(ends) + # (ii) every node's row events lie between its start and its end. + for position, (kind, label, _) in enumerate(events): + if kind in ("data_start", "data_end"): + assert index("start", label) < position < index("end", label) + # (iv) the function node's rows start in arrival order, the sync run's order, and + # each ends once, after it started. + row_starts = [d for k, n, d in events if (k, n) == ("data_start", "fn")] + row_ends = [d for k, n, d in events if (k, n) == ("data_end", "fn")] + assert row_starts == [ + d for k, n, d in sync_events.events if (k, n) == ("data_start", "fn") + ] + assert sorted(row_ends) == sorted(row_starts) + for row in row_starts: + assert events.index(("data_start", "fn", row)) < events.index( + ("data_end", "fn", row) + ) + # Each node's own node events are the sync run's. + for label in order: + assert [k for k, n, _ in events if n == label and k in ("start", "end")] == [ + "start", + "end", + ] diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index a2869934b..cfcb43420 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -1589,6 +1589,9 @@ def projected_batch_streams( def pinned_snapshot(self) -> SourceProtocol | None: return None + def snapshot_batch_streams(self) -> Iterator[StreamProtocol] | None: + return None + def to_config( self, db_registry: DatabaseRegistryProtocol | None = None ) -> dict[str, Any]: From d8e9f28ee224bd5b8a77abeddfd45617c0c5701c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 07:54:42 -0800 Subject: [PATCH 02/20] feat(channels): check the token-shape rule on every sent record batch (ITL-1845) An OutputChannel now holds each record batch sent into it to the token-shape rule (ITL-1491), as a stream built from a table is held: after the batch's token types are settled, from the columns' types and the token columns' null counts. Now that channels carry a job's rows in the batch region, a batch that breaks the rule is refused at send, naming the column. Covers part of ITL-1526. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 6 +-- CLAUDE.md | 6 +-- changelog.d/ITL-1845.md | 2 + .../dev/specs/itl-1347-job-table-transport.md | 4 ++ src/orcapod/core/record_batch_channels.py | 10 +++- .../test_record_batch_channels.py | 50 +++++++++++++++++++ 6 files changed, 71 insertions(+), 7 deletions(-) diff --git a/.zed/rules b/.zed/rules index 151d5146c..7b8772231 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1240,9 +1240,9 @@ these preimages anywhere else. The type rule is the pure function `schema_utils.token_layers_fit`; `token_shape_violations` lists the violating columns and `token_shape_error` words the `InputValidationError`, which names the token column, the - data column and both types. Never loosen it. NOT covered: a record batch sent into an - `OutputChannel` (the channels are not wired into nodes; the stream `result()` builds is - checked; the follow-up is ITL-1526), and a `Data` built by hand outside a stream. The null check reads the + data column and both types. Never loosen it. A record batch sent into an + `OutputChannel` is checked by the same rule, per batch, after its token types are settled + (ITL-1845, in part ITL-1526). NOT covered: a `Data` built by hand outside a stream. The null check reads the validity of EVERY list level of a list-typed token column (`schema_utils.null_list_level`: the null count of each level's arrays, no value), and the error says at which level (0 is the token itself). A typed zero-row table and a plain string token are unaffected. No diff --git a/CLAUDE.md b/CLAUDE.md index 62e7dafd3..d91403cd7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1269,9 +1269,9 @@ are defined in one module, `core/row_ids.py`; never build one of these preimages The type rule is the pure function `schema_utils.token_layers_fit`; `token_shape_violations` lists the violating columns and `token_shape_error` words the `InputValidationError`, which names the token column, the - data column and both types. Never loosen it. NOT covered: a record batch sent into an - `OutputChannel` (the channels are not wired into nodes; the stream `result()` builds is - checked; the follow-up is ITL-1526), and a `Data` built by hand outside a stream. The null check reads the + data column and both types. Never loosen it. A record batch sent into an + `OutputChannel` is checked by the same rule, per batch, after its token types are settled + (ITL-1845, in part ITL-1526). NOT covered: a `Data` built by hand outside a stream. The null check reads the validity of EVERY list level of a list-typed token column (`schema_utils.null_list_level`: the null count of each level's arrays, no value), and the error says at which level (0 is the token itself). A typed zero-row table and a plain string token are unaffected. No diff --git a/changelog.d/ITL-1845.md b/changelog.d/ITL-1845.md index d42207a54..da1d67a7c 100644 --- a/changelog.d/ITL-1845.md +++ b/changelog.d/ITL-1845.md @@ -9,3 +9,5 @@ the first rows while the source is being read. Every node shows the same rows, types and hashes as before, and as the sync run. Where an upstream node's end event falls among a downstream node's observer events now moves by a record batch rather than a row. +- An `OutputChannel` checks the source-info token shape rule on every record batch sent + into it. diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 0e1340d90..0fd6cfb17 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1252,6 +1252,10 @@ the corrections are listed below). Scope, as landed: `LOG`, `REPLAY` (the stored table's batches, inputs drained), the zero-row keep, `clear_cache` on failure and `_update_modified_time`; the kept output is `output.result()`. +- **Token shapes per sent batch (ITL-1526, in part).** `OutputChannel` checks the + token-shape rule on every batch sent, after its token types are settled, with the + stream's `token_shape_violations` / `token_shape_error`. A held node's rows on async + stay unchecked (ITL-1534). - **Differences.** e7 (documented, no observable difference), e9 and e10 (awaiting approval). Row order: a region node keeps arrival order, which for one snapshot source is the sync order. diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 9f0629182..d17e9c9bf 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -34,7 +34,7 @@ from orcapod.core.streams.record_batch_input import InputChannel from orcapod.errors import UpstreamFailedError from orcapod.system_constants import constants -from orcapod.utils import arrow_utils +from orcapod.utils import arrow_utils, schema_utils if TYPE_CHECKING: from orcapod.protocols.core_protocols import StreamProtocol @@ -243,6 +243,14 @@ def _check_schema(self, batch: pa.RecordBatch) -> pa.RecordBatch: token_types = settle_token_types( batch, self._token_types, check_empty=self._has_declared_tokens ) + # The token-shape rule (ITL-1491), as a stream built from a table checks it + # (ITL-1526): each batch on its own, the first and an empty one included, after + # the token types are settled, from + # the columns' types and the token columns' null counts; no value is read. + sent = pa.Table.from_batches([batch]) + data_columns = [n for n in self._data_keys if n in sent.column_names] + if found := schema_utils.token_shape_violations(sent, sent, data_columns): + raise schema_utils.token_shape_error(found) self._schema = schema self._token_types = token_types fields = [] diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index f05abad59..fac784487 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -2518,3 +2518,53 @@ async def write() -> None: ) run(write) + + +# --- The token-shape rule on every batch sent (ITL-1845, in part ITL-1526) ----------- + + +@pytest.mark.parametrize( + ("column", "tokens", "kind", "found"), + [ + # One list layer over scalar data. + ("amplitude", ["a::row_0::amplitude"], TOKENS, "_source_amplitude"), + # A null token list over list data. + ("trace", None, TOKENS, "_source_trace"), + ], + ids=["list_over_scalar", "null_list"], +) +def test_a_sent_batch_whose_tokens_break_the_shape_rule_is_refused( + column: str, tokens: list[str] | None, kind: pa.DataType, found: str +) -> None: + """A batch sent into an output channel is held to the token-shape rule, as a + stream built from a table is: the first batch of a stream that declares no token + type, carrying list tokens over a scalar column or a null token list, is refused at + send, naming the column, and a valid batch is still taken after it.""" + from orcapod.errors import InputValidationError + + stream = _UntypedStream._from_derived_table( + source().as_table(columns=ALL), + tag_columns=["subject", "trial"], + data_tags=["trial"], + ) + (batch,) = batches_of(stream) + token_column = f"_source_{column}" + index = batch.schema.get_field_index(token_column) + shaped = pa.RecordBatch.from_arrays( + [ + *batch.columns[:index], + pa.array([tokens] * batch.num_rows, type=kind), + *batch.columns[index + 1 :], + ], + schema=batch.schema.set(index, pa.field(token_column, kind)), + ) + + async def write() -> int: + output = OutputChannel(stream) + with pytest.raises(InputValidationError, match=found): + await output.send(shaped) + await output.send(batch) + await output.close() + return output.result().as_table(columns=ALL).num_rows + + assert run(write) == batch.num_rows From 5b20d3b5be9225bb78b92f5e8981f1662598543d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 08:08:02 -0800 Subject: [PATCH 03/20] docs(hashing): list the batch forms' observer node-hash sites (ITL-1845) Co-Authored-By: Claude Opus 5.5 --- docs/reference/hashing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 686a11742..5fe287326 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -459,7 +459,7 @@ id is a hash (site 8b). | Use | Call sites | |---|---| -| 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` | +| 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/operator_node.py:OperatorJobNode.async_execute_batches`, `core/nodes/source_node.py:SourceNodeBase.execute`, `core/nodes/source_node.py:SourceNodeBase.async_execute`, `core/nodes/source_node.py:SourceNodeBase.async_execute_batches` | | hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` | | in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase._compile_nodes`, `pipeline/base.py:AbstractPipelineBase._compile_nodes..`, `pipeline/base.py:AbstractPipelineBase._validate_invocation`, `pipeline/base.py:AbstractPipelineBase._input_graph_key`, `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 capture keys (ITL-1590) | `pipeline/pod_invocation.py:PodInvocation.capture_keys` | From 1083fae14b67975694aa49295703815391a00295 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 09:59:57 -0800 Subject: [PATCH 04/20] test: compare function nodes order-free; isolate the fork-hook test (ITL-1845) - An async function node yields its rows as their computations end (main's form, outside the batch region), so the region equality test compares function nodes' rows as a multiset. - test_a_forked_child_keeps_no_client_or_rows_of_its_parent assumed no earlier test in the process still held a SpiralDB client; it fails on main too when run after the SpiralDB projection tests. It now starts from registries of its own and restores them. Co-Authored-By: Claude Opus 5.5 --- .../sources/test_spiraldb_lookups.py | 52 +++++++++++++------ .../test_pipeline/test_async_batch_region.py | 7 ++- 2 files changed, 42 insertions(+), 17 deletions(-) diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 31f80cd9e..f155778bd 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -950,21 +950,41 @@ def build() -> None: def test_a_forked_child_keeps_no_client_or_rows_of_its_parent( calls: collections.Counter[str], ) -> None: - """The fork hook itself (``os.register_at_fork``): the child starts empty.""" - source = _source("plain") - assert len(connector_module._clients) == 1 # pyright: ignore[reportPrivateUsage] - assert connector_module._kept_rows # pyright: ignore[reportPrivateUsage] - clients, kept = connector_module._clients, connector_module._kept_rows # pyright: ignore[reportPrivateUsage] - lock = connector_module._registry_lock # pyright: ignore[reportPrivateUsage] + """The fork hook itself (``os.register_at_fork``): the child starts empty. + + The test starts from empty registries of its own, so clients that earlier tests + in the process still hold do not count (the registries are restored after).""" + before = ( + connector_module._clients, # pyright: ignore[reportPrivateUsage] + connector_module._kept_rows, # pyright: ignore[reportPrivateUsage] + connector_module._registry_lock, # pyright: ignore[reportPrivateUsage] + ) + connector_module._forget_in_child() # pyright: ignore[reportPrivateUsage] try: - connector_module._forget_in_child() # pyright: ignore[reportPrivateUsage] - assert len(connector_module._clients) == 0 # pyright: ignore[reportPrivateUsage] - assert connector_module._kept_rows == {} # pyright: ignore[reportPrivateUsage] - calls.clear() - _source("plain") - assert calls["client"] == 1 and calls["read_schemas"] == 1 + source = _source("plain") + assert len(connector_module._clients) == 1 # pyright: ignore[reportPrivateUsage] + assert connector_module._kept_rows # pyright: ignore[reportPrivateUsage] + clients, kept = connector_module._clients, connector_module._kept_rows # pyright: ignore[reportPrivateUsage] + lock = connector_module._registry_lock # pyright: ignore[reportPrivateUsage] + try: + connector_module._forget_in_child() # pyright: ignore[reportPrivateUsage] + assert len(connector_module._clients) == 0 # pyright: ignore[reportPrivateUsage] + assert connector_module._kept_rows == {} # pyright: ignore[reportPrivateUsage] + calls.clear() + _source("plain") + assert calls["client"] == 1 and calls["read_schemas"] == 1 + finally: + connector_module._clients = clients # pyright: ignore[reportPrivateUsage] + connector_module._kept_rows = kept # pyright: ignore[reportPrivateUsage] + connector_module._registry_lock = lock # pyright: ignore[reportPrivateUsage] + assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [ + 0, + 1, + 2, + ] finally: - connector_module._clients = clients # pyright: ignore[reportPrivateUsage] - connector_module._kept_rows = kept # pyright: ignore[reportPrivateUsage] - connector_module._registry_lock = lock # pyright: ignore[reportPrivateUsage] - assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [0, 1, 2] + ( + connector_module._clients, # pyright: ignore[reportPrivateUsage] + connector_module._kept_rows, # pyright: ignore[reportPrivateUsage] + connector_module._registry_lock, # pyright: ignore[reportPrivateUsage] + ) = before diff --git a/tests/test_pipeline/test_async_batch_region.py b/tests/test_pipeline/test_async_batch_region.py index 783d5a193..03341bd62 100644 --- a/tests/test_pipeline/test_async_batch_region.py +++ b/tests/test_pipeline/test_async_batch_region.py @@ -76,7 +76,8 @@ def doubled(d1: int) -> int: ) # Function nodes: a fresh computation names a fresh result, so their source-info -# tokens are compared without values. +# tokens are compared without values, and their rows in no order (main's async +# function node yields rows as their computations end). FUNCTIONS = ("doubled_no_nulls", "doubled_filtered", "doubled_nothing", "doubled_first") @@ -139,6 +140,10 @@ def _shown(job: PipelineJob) -> dict[str, Any]: row_fingerprint(tag, data, source_info=not functional) for tag, data in node.iter_data() ] + if functional: + # A function node is outside the region and keeps main's async form: its + # rows in the order their computations end. + rows.sort() table = node.as_table(columns=ALL_COLUMNS) schema = [ (field.name, str(field.type), field.nullable) From 5a55c903d83c279e9d1e4869f3a1557844439038 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 10:56:58 -0800 Subject: [PATCH 05/20] docs(spec): stage 5a differential result (ITL-1845) Co-Authored-By: Claude Opus 5.5 --- docs/dev/specs/itl-1347-job-table-transport.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 0fd6cfb17..c9d7705da 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1257,7 +1257,16 @@ the corrections are listed below). Scope, as landed: stream's `token_shape_violations` / `token_shape_error`. A held node's rows on async stay unchecked (ITL-1534). - **Differences.** e7 (documented, no observable difference), e9 and e10 (awaiting - approval). Row order: a region node keeps arrival order, which for one snapshot source + approval). +- **Differential (main 2075e85e2 against the branch).** Sync is byte-identical to main + in every fixture (tutorial, spikes, wide), mode and thread count. Async matches main's + async in tutorial and spikes. Async matches the branch's sync except: + - e8 (the side-effect node's `__computed` column); + - in the wide fixture, the stored tables of three function nodes over one function. + They share one result store, so which node computes an input and which reuses it + (`__computed`, `__record_id`) follows the async interleaving. Main's async run + differs from main's sync in the same tables. This is main's behaviour of function + nodes, which stage 5a does not change; their outputs are equal. Row order: a region node keeps arrival order, which for one snapshot source is the sync order. Corrections to this spec found by the survey, which the stage 5 sections above predate: From c664210b163317f4c781ef0f5a0637597ac38326 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 11:31:37 -0800 Subject: [PATCH 06/20] fix(async): region sources keep main's collected output and route (ITL-1845) CodeRabbit on PR #696: - A projected source that sends no row collects the node's own zero-row output, every column of it, as main does (it collected the narrowed description's result). - The whole batches' stream of a narrowed source takes its bindings before the first read, as main collected rows under the bindings the run started with; BatchStreams.read_description captures them. - A bound source whose instance replaces a member of its class stays outside the region, so its replaced async_iter_data is read as on main. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/source_node.py | 17 +++++++-- .../core/operators/static_output_pod.py | 5 ++- src/orcapod/pipeline/async_orchestrator.py | 5 +++ .../test_spiraldb_job_projection.py | 37 +++++++++++++++++++ .../test_pipeline/test_async_batch_region.py | 25 +++++++++++++ 5 files changed, 85 insertions(+), 4 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 126113e50..35dc65d76 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1757,7 +1757,8 @@ async def async_execute_batches( UnboundSourceError: When no concrete data is available. """ from orcapod.core.operators.static_output_pod import ( - stream_from_batches, + BatchStreams, + rows_on_read, whole_on_read, ) from orcapod.core.output_bindings import capture_output_bindings @@ -1789,12 +1790,22 @@ async def async_execute_batches( # The whole read's own stream, its rows read when first read, # as ``execute`` gives it (``whole_on_read``). whole = whole_on_read(self, whole_read(sent), bindings=bindings) + else: + # No row: the node's own zero-row output, every column of it, + # as main collected a node that sent no row. + whole = rows_on_read([], self, bindings=bindings) sent_whole = True if not sent_whole: # The whole batches, kept only when they are not what is sent: a # narrowed description over a whole read (a source that cannot make # the narrowed read), whose output is the whole batches. kept: list[pa.RecordBatch] | None = [] if unread else None + # The whole batches' stream takes the bindings as they are before the + # first read, as main collected a node's rows under the bindings the + # run started with: a rebind during the read makes it stale. + whole_streams = BatchStreams(self) if kept is not None else None + if whole_streams is not None: + whole_streams.read_description() streams = self._snapshot_batch_streams() if streams is not None: _ = await _send_record_batches( @@ -1813,8 +1824,8 @@ async def async_execute_batches( ) for piece in narrowed.to_batches(): await output.send(piece) - if kept is not None: - whole = stream_from_batches(self, kept) + if whole_streams is not None and kept is not None: + whole = whole_streams(kept) if observer is not None: observer.on_node_end(node_label, node_hash) except BaseException as error: diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 4d1e2f0c5..6cebec538 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1292,13 +1292,16 @@ def _description_bindings(self) -> OutputBindings: def read_description( self, declared_tokens: Mapping[str, pa.DataType] | None = None ) -> None: - """Read the description's zero-row table and token types now (reads no row). + """Read the description's zero-row table, token types and output bindings + now (reads no row): the streams made later carry the bindings as they are + now. Args: declared_tokens: The description's token types, when already read (``declared_token_types`` of the same stream). """ _ = self._typed_table() + _ = self._description_bindings() if self._tokens is None: self._tokens = ( declared_token_types(self.stream) diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 966f96b88..91aa8fdbd 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -849,6 +849,11 @@ class (every one is row by row or a barrier), whose one input is a region node if not declared[id(node)]: continue kind = type(source) + # Main's async route reads the instance's ``async_iter_data``: a source + # whose instance replaces one of its class's members stays outside the + # region, which reads it through its class's readers. + if not reads_as_its_class(source, kind): + continue reads_whole = kind.async_iter_data is StreamBase.async_iter_data in_batches = isinstance(source, RootSource) and ( type(source).snapshot_batch_streams diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 8b5f25d1f..80dc2cb30 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -1644,3 +1644,40 @@ def build() -> PipelineJob: assert sorted( repr(_pair(t, d)[0]) for t, d in got.nodes["fn"].iter_data() ) == sorted(repr(_pair(t, d)[0]) for t, d in sync.nodes["fn"].iter_data()) + + +@pytest.mark.parametrize("whole", [False, True]) +def test_a_source_that_sends_no_row_collects_every_column( + project: Any, monkeypatch: pytest.MonkeyPatch, whole: bool +) -> None: + """A source whose read holds no row (a restriction that matches nothing), its + successor reading one column: the async collected output keeps every column of + the node, the unread ones and their source-info columns included, as the sync + route's output does (CodeRabbit on PR #696: the projected read collected the + narrowed columns).""" + + def collected(route: str) -> Any: + with monkeypatch.context() as m: + if whole: + _read_whole(m) + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + source = SpiralDBTableSource( + "p", "wide", tag_only_columns=True, where={"unit": "nobody"} + ) + source.select_data_columns(["x"], label="sx") + node = next(n for n in job.nodes.values() if n.node_type == "source") + dag: OrcaDAG[Any] = OrcaDAG() + dag.add_edge(node, job.nodes["sx"]) + orchestrator = ( + SyncPipelineOrchestrator() + if route == "sync" + else AsyncPipelineOrchestrator() + ) + return orchestrator.run(dag).node_outputs[node] + + got = collected("async").as_table(all_info=True) + expected = collected("sync").as_table(all_info=True) + assert got.num_rows == expected.num_rows == 0 + assert {"y", "blob", "_source_y", "_source_blob"} <= set(got.column_names) + assert got.schema.equals(expected.schema) diff --git a/tests/test_pipeline/test_async_batch_region.py b/tests/test_pipeline/test_async_batch_region.py index 03341bd62..6a2909695 100644 --- a/tests/test_pipeline/test_async_batch_region.py +++ b/tests/test_pipeline/test_async_batch_region.py @@ -503,3 +503,28 @@ def index(kind: str, label: str) -> int: "start", "end", ] + + +def test_a_source_whose_instance_replaces_its_reader_keeps_mains_route( + batch_nodes: list[str], +) -> None: + """A bound source whose instance replaces ``async_iter_data`` stays outside the + region: the async run reads it through the replacement, as main does, and the + operator after it runs on rows (CodeRabbit on PR #696).""" + source = make_source(MAIN) + rows = list(source.iter_data()) + read: list[int] = [] + + async def first_two() -> Any: + read.append(1) + for pair in rows[:2]: + yield pair + + source.async_iter_data = first_two # pyright: ignore[reportAttributeAccessIssue] # an instance-level reader, the case under test + job = PipelineJob(name="replaced", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["d1"], label="selected") + _run(job, AsyncPipelineOrchestrator()) + assert read == [1] + assert "selected" not in batch_nodes + assert len(list(job.nodes["selected"].iter_data())) == 2 From d78a9bbd2dcb9b479fc37696dfd6a84910e77e83 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 12:54:22 -0800 Subject: [PATCH 07/20] fix(async): region outputs end only after their node's work; honour snapshot batches; one collected form (ITL-1845) Independent review of PR #696: - B1: a region output holds its end (OutputChannel hold_end) until its node's kept output, LOG write, modified time and end hook succeeded; a failure there reaches readers as UpstreamFailedError. - B2: a source with its own async_iter_data joins the region only where its snapshot_batch_streams are read as given (reads_snapshot_batches); otherwise it keeps main's row route. - B3: a region node that sent no row is collected as RowsOnRead, as on sync. - S2: a source keeps no whole batches when the run collects no result. - S1/S3: observer rule (v) at record-batch granularity, tested directly; the pinned-main observer test exempts every region node's end; the job matrix covers every exported unary operator; the third-batch failure test asserts the stored rows. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 9 + CLAUDE.md | 9 + changelog.d/ITL-1845.md | 9 +- .../dev/specs/itl-1347-job-table-transport.md | 16 +- src/orcapod/core/nodes/operator_node.py | 16 +- src/orcapod/core/nodes/source_node.py | 43 ++- .../core/operators/static_output_pod.py | 13 +- src/orcapod/core/record_batch_channels.py | 37 +- src/orcapod/pipeline/async_orchestrator.py | 55 ++- .../test_record_batch_channels.py | 46 +++ .../test_spiraldb_job_projection.py | 54 ++- .../test_pipeline/test_async_batch_region.py | 337 +++++++++++++++++- .../test_observer_main_compatibility.py | 29 +- 13 files changed, 616 insertions(+), 57 deletions(-) diff --git a/.zed/rules b/.zed/rules index 7b8772231..40f3944a2 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1630,6 +1630,15 @@ data. The rules: channel and its readers share one BatchStreams (static_output_pod.py): the description is derived once per channel, never per batch; read it when wiring, inside shared_zero_row_memo(). + A source with its own async_iter_data joins only where its batches are read exactly as + snapshot_batch_streams gives them (SourceJobNode.reads_snapshot_batches), otherwise it + stays on main's row route; never read it whole in place of its own reader. Every region + output holds its end (OutputChannel(hold_end=True)) until its node's work after the last + batch (kept output, LOG store, modified time, end hook) returned; the orchestrator then + calls release_end(), so a failure there reaches readers as UpstreamFailedError, never + as a normal end. A region node that sent no row is collected as the sync route collects + it (rows_on_read([], node)). A source keeps the whole batches of a narrowed whole read + only when the run collects results (keep_whole). - A Python declaration with a `float32` or `float16` dict key or set element raises `NarrowFloatKeyError` (ITL-1591, D16, D25 and D41). Narrowing can turn two distinct keys or elements into one stored value and lose an entry. The check in diff --git a/CLAUDE.md b/CLAUDE.md index d91403cd7..3fd49fbaf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1675,6 +1675,15 @@ data. The rules: result; failure selection skips `UpstreamFailedError`. An output channel and its readers share one `BatchStreams` (`static_output_pod.py`): the description is derived once per channel, never per batch; read it when wiring, inside `shared_zero_row_memo()`. + A source with its own `async_iter_data` joins only where its batches are read exactly as + `snapshot_batch_streams` gives them (`SourceJobNode.reads_snapshot_batches`), otherwise it + stays on main's row route; never read it whole in place of its own reader. Every region + output holds its end (`OutputChannel(hold_end=True)`) until its node's work after the last + batch (kept output, `LOG` store, modified time, end hook) returned; the orchestrator then + calls `release_end()`, so a failure there reaches readers as `UpstreamFailedError`, never + as a normal end. A region node that sent no row is collected as the sync route collects + it (`rows_on_read([], node)`). A source keeps the whole batches of a narrowed whole read + only when the run collects results (`keep_whole`). - A Python declaration with a `float32` or `float16` dict key or set element raises `NarrowFloatKeyError` (ITL-1591, D16, D25 and D41). Narrowing can turn two distinct keys or elements into one stored value and lose an entry. The check in diff --git a/changelog.d/ITL-1845.md b/changelog.d/ITL-1845.md index da1d67a7c..48a52aa8d 100644 --- a/changelog.d/ITL-1845.md +++ b/changelog.d/ITL-1845.md @@ -1,3 +1,9 @@ +### Breaking changes and migration + +- A class that implements `SourceProtocol` itself (not a subclass of an Orcapod source) + now needs a `snapshot_batch_streams()` method. Return `None` when the source has no + per-batch scan: an async job then reads it whole, as before. + ### Changed - An async job (`job.run(orchestrator=AsyncPipelineOrchestrator())`, `run_async()`) now @@ -8,6 +14,7 @@ a held node reads them, one record batch at a time, so a function node still starts on the first rows while the source is being read. Every node shows the same rows, types and hashes as before, and as the sync run. Where an upstream node's end event falls among a - downstream node's observer events now moves by a record batch rather than a row. + downstream node's observer events now moves by a record batch rather than a row: a + source that sends one record batch ends before the next node's first row event. - An `OutputChannel` checks the source-info token shape rule on every record batch sent into it. diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index c9d7705da..26b403ae4 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -549,10 +549,10 @@ is unsupported; what the run then does is undefined and is not part of the equal | e2 | An async input row of another data context | The async function node answers it from the cache (the ITL-858 inventory) | A whole-input error before the first batch, as on sync | **ITL-951** (its comment; ITL-858 decision 9). Reproducer: an async function node fed a stream of another data context, with its result stored | approved (developer, 2026-11-22) | | e3 | Function calls and stored rows for duplicate inputs, async; `RunSummary` computed counts | About 3× more calls than sync, and more stored rows (4,188 against 4,060 in ITL-1062's measurement) | Misses are deduplicated by base entry id, so calls, stored rows and counts equal sync | **ITL-1062.** Reproducer: ITL-1062's workshop-shaped pipeline with repeated input data, async | approved (developer, 2026-11-22) | | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | -| e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer's input ends normally; whether a `LOG` operator node after it stores a partial result depends on whether the task group's cancellation reaches it first | Stage 5a (ITL-1845), inside the batch region only: a region node's readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so a region operator never finishes, keeps or stores its output as if its input were complete. **A region `LOG` node stores nothing after an upstream failure, by construction**: it reads the failure from its input channel, raises, and never reaches its store; it no longer depends on cancellation timing. Batches a consumer processed before the failure stay processed, and a function node after the region keeps the results it stored for them, as on `main` (no rollback). At a row boundary the adapter turns the failure into `main`'s normal row-channel close, so nodes outside the region see what they see on `main`. The run raises the producer's own error, as today | **No observable difference found on `main` 2075e85e2**: the stored outcome is unchanged (nothing stored). Reproducers, run on `main` and on the branch: a keyed scan that fails on its third record batch, feeding a `Select` in `LOG` mode (5 runs under each error policy, 10 in all: 0 rows stored every time), and a `fail_fast` function node raising on row 3 of 6 feeding a `Select` in `LOG` mode (5 runs: 0 rows stored). The row documents the internal signal change; both cases are tests that pass on `main` and the branch, with no timing assumption (`test_a_logging_operator_stores_nothing_after_its_source_fails_mid_scan`, `test_a_logging_operator_after_a_failing_function_stores_nothing`) | documented; no approval needed unless the developer asks | +| e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer's input ends normally; whether a `LOG` operator node after it stores a partial result depends on whether the task group's cancellation reaches it first | Stage 5a (ITL-1845), inside the batch region only: a region node's readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so a region operator never finishes, keeps or stores its output as if its input were complete. **A region `LOG` node stores nothing after an upstream failure, by construction**: it reads the failure from its input channel, raises, and never reaches its store; it no longer depends on cancellation timing. That holds also for a failure after the producer's last batch: a region output holds its end from its readers (`OutputChannel(hold_end=True)`) until the producing node's own work after it succeeded (its kept output, `LOG` store, modified time and end hook), and the orchestrator releases it (`release_end`) only when the node returned; a failure there fails the output, so a reader raises `UpstreamFailedError`, never ends normally. Batches still flow while the producer runs. Batches a consumer processed before the failure stay processed, and a function node after the region keeps the results it stored for them, as on `main` (no rollback). At a row boundary the adapter turns the failure into `main`'s normal row-channel close, so nodes outside the region see what they see on `main`. The run raises the producer's own error, as today | **No observable difference found on `main` 2075e85e2**: the stored outcome is unchanged (nothing stored). Reproducers, run on `main` and on the branch: a keyed scan that fails on its third record batch, feeding a `Select` in `LOG` mode (5 runs under each error policy, 10 in all: 0 rows stored every time), and a `fail_fast` function node raising on row 3 of 6 feeding a `Select` in `LOG` mode (5 runs: 0 rows stored). The independent review of PR #696 found a region operator whose `LOG` write or end hook failed after its last batch: `main` stores 0 rows downstream under both policies, the reviewed head stored 5, the fixed branch 0 (`test_a_producer_failing_after_its_last_batch_stores_nothing_downstream`, a failed write and a failing end hook, both policies). The row documents the internal signal change; the cases are tests that pass on `main` and the branch, with no timing assumption (`test_a_logging_operator_stores_nothing_after_its_source_fails_mid_scan`, `test_a_logging_operator_after_a_failing_function_stores_nothing`) | documented; no approval needed unless the developer asks | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | -| e9 | Observer events across nodes, async (batch region) | Upstream end events (`on_node_end` of a source or operator) fall among a downstream node's data events at the granularity of one row: a source ends after about 16 rows have reached the function node, a `Select` after about 135 (in-memory, 200 rows); an off-loop keyed scan interleaves the same way | Each node's own event sequence is `main`'s, and hooks keep `main`'s placement (start at task start, end after the last send and before the output closes), so `main`'s invariants hold: (i) node starts in topological order; (ii) a node's data events lie between its start and end; (iii) an upstream node ends before its downstream node; (iv) a function node's row events in arrival order, in concurrency groups of 16; (v) downstream data events interleave with upstream end events. Only where an upstream end falls among downstream data events moves, in steps of one record batch (an in-memory source sends its table in 65,536-row batches, a keyed scan `batch_rows` rows) | Not a `main` bug: `main`'s interleaving itself depends on buffer sizes and timing, and no rule fixes it. The pinned-`main` observer test (`test_observer_main_compatibility.py`) exempts the end events of region nodes, as it already exempted `SelectDataColumns`' end; the invariants are tested on the branch | awaiting approval | -| e10 | The class of a region node's collected async output (`OrchestratorResult.node_outputs`) | An async node's output is `RowsOnRead` over its collected rows, which compares unequal to the sync route's output stream of the same rows | A region node's output is its output channel's `result()` (for a source with column demand, the whole read, as on sync), the sync route's stream form: the same rows, table, types and hashes, and it now compares equal to the sync output. A projected source's whole read still happens once, when the output is first read | Not a bug on `main`, a form change: the equality between the two routes' outputs followed from their classes, not their rows (`test_outputs_of_two_routes_compare_and_hash_as_main`) | awaiting approval | +| e9 | Observer events across nodes, async (batch region) | Upstream end events (`on_node_end` of a source or operator) fall among a downstream node's data events at the granularity of one row: a source ends after about 16 rows have reached the function node, a `Select` after about 135 (in-memory, 200 rows); an off-loop keyed scan interleaves the same way | Each node's own event sequence is `main`'s, and hooks keep `main`'s placement (start at task start, end after the last send and before the output closes), so `main`'s invariants hold: (i) node starts in topological order; (ii) a node's data events lie between its start and end; (iii) an upstream node ends before its downstream node; (iv) a function node's row events in arrival order, in concurrency groups of 16. (v) holds at record-batch granularity only: downstream data events and upstream end events interleave between record batches, never within one, so a source that sends one record batch (an in-memory source of up to 65,536 rows) and the region operators after it end before the downstream function node's first data event; with several batches (a keyed scan of `batch_rows` rows each, a larger in-memory table) they interleave batch by batch | Not a `main` bug: `main`'s interleaving itself depends on buffer sizes and timing, and no rule fixes it. The pinned-`main` observer test (`test_observer_main_compatibility.py`) exempts the end events of the region nodes by name (the source node and `SelectDataColumns`, `REGION_NODES`), checks their own order, and checks that both were exempted; `test_observer_events_keep_mains_invariants` checks (i) to (iv), each node's own event sequence in order against the sync run's, and (v) at record-batch granularity (300 rows, one batch) | awaiting approval | +| e10 | The class of a region node's collected async output (`OrchestratorResult.node_outputs`) | An async node's output is `RowsOnRead` over its collected rows, which compares unequal to the sync route's output stream of the same rows | A region node that sent rows gives its output channel's `result()` (for a source with column demand, the whole read, as on sync), the sync route's stream form: the same rows, table, types and hashes, and it now compares equal to the sync output, with an equal hash. A region node that sent no row (a filter matching nothing, the nodes after it, every node over a source with no rows) is collected as the sync route collects it, a `RowsOnRead` of no rows, so the two routes give one form, empty or not; a `RowsOnRead` compares by object on both routes (as a function node's output does on `main`), and its stream compares and hashes equal to the sync one. A projected source's whole read still happens once, when the output is first read | Not a bug on `main`, a form change: the equality between the two routes' outputs followed from their classes, not their rows (`test_outputs_of_two_routes_compare_and_hash_as_main`; empty and non-empty: `test_collected_outputs_compare_and_hash_as_the_sync_runs`) | awaiting approval | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its @@ -1224,7 +1224,11 @@ the corrections are listed below). Scope, as landed: `StreamBase` default `async_iter_data`, or answers `snapshot_batch_streams()`, the required `SourceProtocol` member: `RootSource` answers `None`, `SpiralDBTableSource` its per-batch streams, and each wrapper answers for itself) and whose Arrow types are - declared; + declared. A source with its own `async_iter_data` joins only where its batches are + read exactly as `snapshot_batch_streams` gives them + (`SourceJobNode.reads_snapshot_batches`: the table route, no declared form, the + node's data context, a pinned version); otherwise it stays on `main`'s row route, + its own reader, and is never read whole in its place; - a library unary operator job node whose one input is a region node with declared Arrow types (`ROW_BY_ROW` operators per record batch; barriers, `GroupBy`, `PolarsFilter`, `Filter` and `Batch` without a size, by `to_stream()`; `Batch` with a @@ -1234,7 +1238,9 @@ the corrections are listed below). Scope, as landed: row code (joins move in stage 5b). - **Channels.** Each region node writes one `OutputChannel` (`retain` is `materialize_results` for a source node and always true for an operator node, whose - kept output is the result). Every out-edge opens a reader before any task starts. A + kept output is the result). A source node keeps the whole batches of a narrowed whole + read only when the run collects its results (`keep_whole`). Every region output holds + its end until its node's work returned (`hold_end`, `release_end`; e7). Every out-edge opens a reader before any task starts. A region successor reads the `InputChannel`; any other successor gets rows from a boundary adapter (`_rows_from_batches`), which builds each batch's rows as it arrives (D1, early delivery) and turns an `UpstreamFailedError` into `main`'s normal close. diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index a93473acf..33975f352 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -2627,10 +2627,12 @@ async def async_execute_batches( row-by-row operator sends each input batch's result as it arrives, a barrier reads all of its input first (``InputChannel.to_stream``). The kept output is what was sent (``output.result()``, the output retains its batches). A - failure of an input's producer reaches the operator as - ``UpstreamFailedError`` at the failure point, never as a normal end: the - operator then fails, so the node keeps and stores nothing, by construction. A - failure or cancellation fails ``output`` and closes every input. + failure of an input's producer, also one after its last batch (its store, + modified time or end hook), reaches the operator as ``UpstreamFailedError``, + never as a normal end: the producer's output holds its end until its node's + work succeeded (``hold_end``). The operator then fails, so the node keeps and + stores nothing, by construction. A failure or cancellation fails ``output`` + (also once closed, while it holds its end) and closes every input. Args: inputs: The input channels, one per upstream, in the operator's order. @@ -2689,8 +2691,10 @@ async def async_execute_batches( ) operator = cast(StaticOutputOperatorPod, self._operator) # The operator closes its inputs, then the output, once it is done; it - # fails the output if it fails. Nothing awaits between that close and the - # bookkeeping below, so no successor runs before the node ends. + # fails the output if it fails. The output holds its end from its readers + # until the orchestrator releases it after this method returned: a failure + # of the bookkeeping below fails the output, and a reader raises + # ``UpstreamFailedError``, never ends normally (e7). await operator.async_execute_batches(inputs, output) kept = output.result() if kept.as_table(columns=ZERO_ROW_INPUT_COLUMNS).num_rows: diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 35dc65d76..d36f19afc 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1661,6 +1661,17 @@ def _unread_columns(self, read_columns: Collection[str]) -> frozenset[str]: c for c in data_keys if c not in wanted and c not in set(tag_keys) ) + def _reads_its_own_way(self) -> bool: + """Whether this node's bound source reads its rows with its own + ``async_iter_data`` (not the default whole read of ``StreamBase``).""" + from orcapod.core.streams.base import StreamBase + + source = self._bound_stream() + return ( + source is not None + and type(source).async_iter_data is not StreamBase.async_iter_data + ) + def _snapshot_batch_streams(self) -> Iterator[StreamProtocol] | None: """This node's whole rows as per-batch streams of a pinned snapshot, or ``None``: the node is read whole (``open_channel``). @@ -1718,6 +1729,7 @@ async def async_execute_batches( *, observer: ExecutionObserverProtocol | None = None, read_columns: Collection[str] | None = None, + keep_whole: bool = True, ) -> StreamProtocol | None: """Send this node's rows into ``output`` as Arrow record batches, as they are read (ITL-1347, stage 5a). @@ -1746,11 +1758,15 @@ async def async_execute_batches( observer: Optional execution observer. read_columns: The data columns every successor reads (as for ``async_execute``). + keep_whole: Whether to return the node's whole output when the batches + sent are narrowed. Without it (a run that collects no result) the + whole batches of a narrowed whole read are not kept, and nothing is + returned for them. Returns: The node's whole output when the batches sent are a narrowed read's (``whole_on_read``, as ``execute`` gives it, or the whole batches read - as a stream), else + as a stream, kept only with ``keep_whole``), else ``None``: the output channel's result is the node's output. Raises: @@ -1799,7 +1815,9 @@ async def async_execute_batches( # The whole batches, kept only when they are not what is sent: a # narrowed description over a whole read (a source that cannot make # the narrowed read), whose output is the whole batches. - kept: list[pa.RecordBatch] | None = [] if unread else None + kept: list[pa.RecordBatch] | None = ( + [] if unread and keep_whole else None + ) # The whole batches' stream takes the bindings as they are before the # first read, as main collected a node's rows under the bindings the # run started with: a rebind during the read makes it stale. @@ -1807,6 +1825,14 @@ async def async_execute_batches( if whole_streams is not None: whole_streams.read_description() streams = self._snapshot_batch_streams() + if streams is None and self._reads_its_own_way(): + # Admitted for its batches (``reads_snapshot_batches``): a whole + # read would bypass the source's own reader. + raise RuntimeError( + f"The source of {node_label!r} gave no snapshot batches in a " + + "job's async run, and it reads its rows its own way " + + "(async_iter_data): it is not read whole in its place." + ) if streams is not None: _ = await _send_record_batches( streams, @@ -2552,6 +2578,19 @@ def whole() -> ArrowTableStream: return streams, lambda num_rows: WholeRead(whole, None, keys, num_rows) + def reads_snapshot_batches(self) -> bool: + """Whether a job's async batch region can read this node through its bound + source's ``snapshot_batch_streams`` (ITL-1347, stage 5a). + + Exactly where ``_snapshot_batch_streams`` asks the source for its batches: a + projected read could be made of it (``_projection_snapshot``: this class, the + table route, no declared form, the node's data context, a pinned version). A + source that reads its rows its own way (its own ``async_iter_data``) and + cannot be read so stays on main's row route, outside the region: it is never + read whole in place of its own reader. + """ + return self._projection_snapshot() is not None + def _snapshot_batch_streams(self) -> Iterator[StreamProtocol] | None: """The bound source's per-batch snapshot streams (ITL-1347, stage 5a), or ``None``: read whole. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 6cebec538..602be1f8d 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1021,10 +1021,11 @@ async def async_execute_batches( ) -> None: """Run this operator over input channels of Arrow record batches. - The Arrow-record-batch form of ``async_execute`` (ITL-1347, stage 5); the - nodes and the orchestrator still call the row form until they are wired to - this one, which then takes its name. The operator has one body for both - paths, ``static_process``: each input's description is its channel's stream + The Arrow-record-batch form of ``async_execute`` (ITL-1347, stage 5). A job's + async run calls it through ``OperatorJobNode.async_execute_batches`` for the + operator nodes of its batch region (stage 5a, ITL-1845); every other node + still calls the row form. The operator has one body for both paths, + ``static_process``: each input's description is its channel's stream (identity, pipeline hash, data context, keys), as on the sync path. A row-by-row operator (``ROW_BY_ROW``) is applied to each record batch as it @@ -1042,7 +1043,9 @@ async def async_execute_batches( When the operator is done its inputs are closed, then its output (``finish_operator``), so a failing close fails the output. If the operator fails or is cancelled, the output fails instead, so no reader takes it for - complete; every input is closed in either case. + complete; every input is closed in either case. In a job the output holds its + end (``OutputChannel(hold_end=True)``): its readers see the end only once the + node's own work after the close succeeded. Args: inputs: One input channel per input stream, in the operator's order. diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index d17e9c9bf..5eb2d9a9e 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -82,7 +82,7 @@ async def next(self) -> pa.RecordBatch | None: batch = self.queue.popleft() output._notify() # pyright: ignore[reportPrivateUsage] # room for the producer return batch - if output._closed: # pyright: ignore[reportPrivateUsage] + if output._end_published: # pyright: ignore[reportPrivateUsage] return None await output._changed.wait() # pyright: ignore[reportPrivateUsage] return None @@ -124,6 +124,11 @@ class OutputChannel: and ``result`` raises. buffer_size: Without ``retain``, how many record batches each reader queues before ``send`` waits. + hold_end: Hold the end back from the readers after ``close``, until + ``release_end``: the producer's own work after its last batch (a job + node's kept output, store, modified time and end hook) can still fail the + output, so no reader takes it for complete before that work succeeded. + ``result`` is available from ``close`` on. """ def __init__( @@ -132,6 +137,7 @@ def __init__( *, retain: bool = True, buffer_size: int = BATCH_BUFFER_SIZE, + hold_end: bool = False, ) -> None: """Make an output channel for ``stream``'s rows (the arguments: see the class). @@ -151,6 +157,9 @@ def __init__( self._sending = 0 self._send_lock = asyncio.Lock() self._closed = False + # Whether readers see the end: at ``close``, or at ``release_end`` when held. + self._hold_end = hold_end + self._end_published = False self._error: BaseException | None = None self._result: StreamProtocol | None = None # The schema every record batch must have: the description's, or the first @@ -173,6 +182,11 @@ def stream(self) -> StreamProtocol: """The stream whose rows are written here: the description.""" return self._stream + @property + def sent_rows(self) -> bool: + """Whether a record batch with rows was sent.""" + return self._sent > 0 + def _notify(self) -> None: """Wake everything waiting on this channel: readers and a waiting ``send``.""" changed, self._changed = self._changed, asyncio.Event() @@ -356,6 +370,10 @@ async def close(self) -> None: and readers never complete normally with different inputs. The channel fails instead: the waiting send raises ``ChannelClosed``, and every reader's next read raises ``UpstreamFailedError`` whose cause is a ``ChannelClosed``. + + An output that holds its end (``hold_end``) is complete for its producer + (no more sends, ``result`` available); its readers see the end at + ``release_end``. """ if self._closed or self._error is not None: return @@ -366,20 +384,33 @@ async def close(self) -> None: ) else: self._closed = True + self._end_published = not self._hold_end self._notify() + def release_end(self) -> None: + """Let the readers see the end of a closed output that holds it (``hold_end``). + + Does nothing on an output that is not closed, failed, or already shows its + end. + """ + if self._closed and self._error is None and not self._end_published: + self._end_published = True + self._notify() + def fail(self, error: BaseException) -> None: """End the output with the producer's failure or cancellation. Every reader's next read raises ``UpstreamFailedError`` (its cause is ``error``), never a normal end. The failure is seen at once: record batches a reader has not yet read are not delivered first, so no consumer acts on part of - a failed output. Does nothing on a channel already closed or failed. + a failed output. Does nothing on a channel already failed, or closed with its + end shown to the readers; a closed output that holds its end (``hold_end``) + fails. Args: error: The producer's error. """ - if not self._closed and self._error is None: + if not self._end_published and self._error is None: self._error = error self._notify() diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 91aa8fdbd..c11b72c45 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -278,7 +278,11 @@ async def _run_async( else: description = node retain = True - batch_outputs[node] = OutputChannel(description, retain=retain) + # The end is shown to the readers only once the node's own work + # after its last batch succeeded (``_start_region_node``). + batch_outputs[node] = OutputChannel( + description, retain=retain, hold_end=True + ) try: batch_outputs[node].read_description() except Exception: # noqa: BLE001 # read again, and raised, by the node's first send @@ -365,6 +369,7 @@ def collected_output( demand=demands.get(node), whole_outputs=whole_outputs, load_only=load_only, + keep_whole=materialize_results, ) continue writer = node_output_channels[node].writer @@ -472,8 +477,18 @@ def collected_output( # it was computed under are current, as main collected its rows then; # the stream carries those bindings, so using it after a rebind raises # ``StaleOutputError``, as main's collected output does. + # A region node that sent no row is collected as the sync route + # collects it, its rows (none) as a ``RowsOnRead`` (e10), so the two + # routes give one form, empty or not. region_results.update( - (node, output.result()) + ( + node, + output.result() + if output.sent_rows + else rows_on_read( + [], node, bindings=bindings_at_collection[id(node)] + ), + ) for node, output in batch_outputs.items() if id(node) not in whole_outputs ) @@ -859,7 +874,10 @@ class (every one is row by row or a barrier), whose one input is a region node type(source).snapshot_batch_streams is not RootSource.snapshot_batch_streams ) - if reads_whole or in_batches: + # A source with its own reader joins only where its batches are read + # exactly as its ``snapshot_batch_streams`` gives them; otherwise it + # stays on main's row route (its own ``async_iter_data``). + if reads_whole or (in_batches and source_node.reads_snapshot_batches()): region.add(node) elif is_operator_node(node): if not reads_as_its_class(node, OperatorJobNode): @@ -902,9 +920,14 @@ def _start_region_node( demand: frozenset[str] | None, whole_outputs: dict[int, Any], load_only: bool, + keep_whole: bool, ) -> None: """Start a region node's record-batch form (ITL-1347, stage 5a). + The node's output holds its end (``hold_end``): it is released when the node's + work returned, so a reader never ends normally before the producer's own work + after its last batch succeeded. + Args: tg: The run's task group. failed_nodes: The run's record of which node raised each exception. @@ -916,27 +939,37 @@ def _start_region_node( whole_outputs: Where a source node's whole output is recorded when it sent a narrowed read. load_only: Whether the run is load-only. + keep_whole: Whether a source node keeps its whole batches when it sends a + narrowed form of them (only when the run's results are collected). """ if is_source_node(node): source_node = cast("SourceJobNode", node) async def source_work() -> None: whole = await source_node.async_execute_batches( - output, observer=observer, read_columns=demand + output, + observer=observer, + read_columns=demand, + keep_whole=keep_whole, ) if whole is not None: whole_outputs[id(node)] = whole + output.release_end() _start_node(tg, failed_nodes, node, source_work()) else: - _start_node( - tg, - failed_nodes, - node, - node.async_execute_batches( + + async def operator_work() -> None: + # The operator closes the output after its last batch; the node then keeps + # its output, stores it, moves its modified time and calls its end hook. A + # failure there fails the output (the node's handler), so the readers see + # the end only now, when all of it succeeded (e7). + await node.async_execute_batches( inputs, output, observer=observer, load_only=load_only - ), - ) + ) + output.release_end() + + _start_node(tg, failed_nodes, node, operator_work()) async def _rows_from_batches(reader: Any, writer: Any) -> None: diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index fac784487..7ae3ba0c2 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -2568,3 +2568,49 @@ async def write() -> int: return output.result().as_table(columns=ALL).num_rows assert run(write) == batch.num_rows + + +@pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) +@pytest.mark.parametrize("ending", ["released", "failed"]) +def test_an_output_that_holds_its_end_ends_its_readers_only_when_released( + retain: bool, ending: str +) -> None: + """``hold_end``: after ``close`` the readers get every batch but not the end, and + ``result`` is there; ``release_end`` ends them normally, and a ``fail`` before it + reaches them as ``UpstreamFailedError``, never as a normal end (independent review + of PR #696, B1).""" + stream = source(5) + batches = batches_of(stream, rows=2) + + async def read() -> None: + output = OutputChannel(stream, retain=retain, hold_end=True) + readers = [output.open_reader(), output.open_reader()] + for batch in batches: + await output.send(batch) + await output.close() + if retain: + assert output.result().as_table().num_rows == 5 + got: list[list[int]] = [[], []] + + async def drain(position: int) -> None: + async for batch in readers[position]: + got[position].append(batch.num_rows) + + tasks = [asyncio.create_task(drain(i)) for i in (0, 1)] + await asyncio.sleep(0) + await asyncio.sleep(0) + assert got == [[2, 2, 1], [2, 2, 1]] + assert not any(task.done() for task in tasks) + if ending == "released": + output.release_end() + await asyncio.gather(*tasks) + else: + output.fail(RuntimeError("the store refused the write")) + for task in tasks: + with pytest.raises(UpstreamFailedError): + await task + # A failed output has no result. + with pytest.raises(RuntimeError): + _ = output.result() + + run(read) diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 80dc2cb30..cd0bdc7b4 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -24,6 +24,7 @@ from orcapod import PipelineJob, function_pod from orcapod.core.operators.static_output_pod import ( + BatchStreams, _RowsOfStream, # pyright: ignore[reportPrivateUsage] # main's sync output class ) from orcapod.core.streams.arrow_table_stream import pending_whole_read @@ -1500,10 +1501,12 @@ def gated(self: Any) -> Any: monkeypatch.setattr(fake.FakeReader, "read_next_batch", gated) -def _function_job(monkeypatch: pytest.MonkeyPatch) -> PipelineJob: +def _function_job( + monkeypatch: pytest.MonkeyPatch, database: InMemoryArrowDatabase | None = None +) -> PipelineJob: """A source read one row per record batch, a select and ``x_twice``.""" monkeypatch.setattr(fake, "scan_batch_rows", 1) - job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + job = PipelineJob(name="j", database=database or InMemoryArrowDatabase()) with job: selected = SpiralDBTableSource( "p", "wide", tag_only_columns=True, batch_rows=1 @@ -1555,12 +1558,24 @@ def fail_after_two() -> None: raise RuntimeError("the scan failed on its third batch") _gate_scan(monkeypatch, 3, fail_after_two) - job = _function_job(monkeypatch) + database = InMemoryArrowDatabase() + job = _function_job(monkeypatch, database) with pytest.raises(Exception, match="third batch"): asyncio.run( job.run_async(orchestrator=AsyncPipelineOrchestrator(error_policy=policy)) ) assert sorted(X_CALLS) == expected + # The two computed rows are stored, as on main: two results and two pipeline + # records of the function node, nothing else. + stored: dict[str, pa.Table] = {} + for path in database.list_table_paths(): + table = database.get_all_records(path) + assert table is not None + stored[path[-1]] = table + assert sorted(stored) == ["pdb_v2", "rdb_v1"] + results = cast("list[float]", stored["rdb_v1"].column("x2").to_pylist()) + assert sorted(results) == [2 * x for x in expected] + assert stored["pdb_v2"].num_rows == 2 def test_cancelling_a_run_mid_scan_closes_the_scan_on_its_thread( @@ -1681,3 +1696,36 @@ def collected(route: str) -> Any: assert got.num_rows == expected.num_rows == 0 assert {"y", "blob", "_source_y", "_source_blob"} <= set(got.column_names) assert got.schema.equals(expected.schema) + + +@pytest.mark.parametrize("materialize_results", [True, False]) +def test_a_run_that_keeps_no_result_keeps_no_whole_source_batches( + project: Any, monkeypatch: pytest.MonkeyPatch, materialize_results: bool +) -> None: + """A source read whole while its successors read two columns (no projected read), + in a run that collects no result: the source keeps no whole-width record batch + for an output nobody reads; in a run that collects them it keeps them once, its + output (independent review of PR #696, S2).""" + monkeypatch.setattr(fake, "scan_batch_rows", 1) + _read_whole(monkeypatch) + whole: list[int] = [] + original = BatchStreams.__call__ + + def recorded(self: Any, batches: Any, **kwargs: Any) -> Any: + if batches and "blob" in batches[0].schema.names: + whole.append(sum(b.num_rows for b in batches)) + return original(self, batches, **kwargs) + + monkeypatch.setattr(BatchStreams, "__call__", recorded) + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + source = SpiralDBTableSource("p", "wide", tag_only_columns=True, batch_rows=1) + source.select_data_columns(["x"], label="sx") + source.select_data_columns(["y"], label="sy") + job.run( + orchestrator=AsyncPipelineOrchestrator(), + materialize_results=materialize_results, + ) + assert whole == ([6] if materialize_results else []) + assert len(list(job.nodes["sx"].iter_data())) == 6 + assert len(list(job.nodes["sy"].iter_data())) == 6 diff --git a/tests/test_pipeline/test_async_batch_region.py b/tests/test_pipeline/test_async_batch_region.py index 6a2909695..33b11c197 100644 --- a/tests/test_pipeline/test_async_batch_region.py +++ b/tests/test_pipeline/test_async_batch_region.py @@ -14,9 +14,10 @@ import asyncio import threading import warnings -from collections.abc import Iterator +from collections.abc import AsyncIterator, Iterator from typing import Any, Literal +import polars as pl import pyarrow as pa import pytest @@ -24,7 +25,7 @@ from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.sources import ArrowTableSource, DictSource from orcapod.databases import InMemoryArrowDatabase -from orcapod.errors import ProvisionalHashWarning +from orcapod.errors import PolarsFilterWarning, ProvisionalHashWarning from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline.observer import NoOpObserver from orcapod.types import CacheMode @@ -73,6 +74,10 @@ def doubled(d1: int) -> int: "after_filtered", "after_nothing", "after_first", + "tags_selected", + "tags_dropped", + "tags_mapped", + "polars_filtered", ) # Function nodes: a fresh computation names a fresh result, so their source-info @@ -82,8 +87,9 @@ def doubled(d1: int) -> int: def build_job(source: Any, database: Any = None) -> PipelineJob: - """Every library unary operator kind over one source, two of them chained, each - of several feeding a select and a function node.""" + """Every library unary operator kind but ``Pick`` (which needs a dictionary + column: ``test_pick_and_tag_operators_show_the_sync_runs_rows``) over one source, + two of them chained, each of several feeding a select and a function node.""" job = PipelineJob(name="batch_region", database=database or InMemoryArrowDatabase()) with job: source.select_data_columns(["d3", "d1"], label="selected") @@ -100,6 +106,12 @@ def build_job(source: Any, database: Any = None) -> PipelineJob: source.tag_by("d3", "d1", label="tag_by") source.select_columns(["d1", "d3"], label="columns") source.drop_columns(["d2"], label="dropped_columns") + source.select_tag_columns(["t3", "t1"], label="tags_selected") + source.drop_tag_columns(["t2", "t3"], label="tags_dropped") + source.map_tags({"t3": "u3", "t1": "u1"}, label="tags_mapped") + source.polars_filter( + pl.col("d1") > 15, pl.col("d3") != "z", label="polars_filtered" + ) for name, stream in ( ("no_nulls", no_nulls), ("filtered", filtered), @@ -128,6 +140,7 @@ async def recorded(self: Any, *args: Any, **kwargs: Any) -> None: def _run(job: PipelineJob, orchestrator: Any, **kwargs: Any) -> Any: with warnings.catch_warnings(): warnings.simplefilter("ignore", ProvisionalHashWarning) + warnings.simplefilter("ignore", PolarsFilterWarning) return job.run(orchestrator=orchestrator, **kwargs) @@ -162,6 +175,7 @@ def _shown(job: PipelineJob) -> dict[str, Any]: def _build(arrangement: Arrangement) -> PipelineJob: with warnings.catch_warnings(): warnings.simplefilter("ignore", ProvisionalHashWarning) + warnings.simplefilter("ignore", PolarsFilterWarning) return build_job(make_source(MAIN, arrangement)) @@ -180,6 +194,101 @@ def test_every_node_shows_the_sync_runs_rows( assert _shown(async_job) == _shown(sync_job) +# The dictionary encoding Orcapod stores a ``dict[str, int]`` in: ``Pick`` reads a key. +DICT_OF_INT = pa.large_list( + pa.struct( + [ + pa.field("key", pa.large_string(), nullable=False), + pa.field("value", pa.int64()), + ] + ) +) + + +def _plain_tag_source(rows: int, reverse: bool) -> ArrowTableSource: + """Two plain tags and three data columns, one a dictionary, in a declared order + and a table layout that ``reverse`` turns around, in record batches of 3 rows.""" + values: dict[str, list[Any]] = { + "a": [f"u{i % 3}" for i in range(rows)], + "b": list(range(rows)), + "d1": list(range(rows)), + "d2": [float(i) for i in range(rows)], + "struct": [[{"key": "x", "value": i}] for i in range(rows)], + } + types = { + "a": pa.large_string(), + "b": pa.int64(), + "d1": pa.int64(), + "d2": pa.float64(), + "struct": DICT_OF_INT, + } + names = list(reversed(values)) if reverse else list(values) + schema = pa.schema([pa.field(n, types[n], nullable=False) for n in names]) + table = pa.Table.from_pydict({n: values[n] for n in names}, schema=schema) + table = pa.Table.from_batches(table.to_batches(max_chunksize=3), schema=schema) + return ArrowTableSource( + table, + tag_columns=["b", "a"] if reverse else ["a", "b"], + tag_only_columns=True, + source_id="numbers", + ) + + +TAG_REGION = ( + "tag_select", + "tag_drop", + "map_tags", + "map_columns", + "pick", + "polars", +) + + +def _tag_operator_job(rows: int, reverse: bool) -> PipelineJob: + """``Pick``, ``MapColumns``, ``MapTags``, ``SelectTagColumns``, + ``DropTagColumns`` and ``PolarsFilter`` over one source of plain tags, each + several-item argument given in the order ``reverse`` chooses.""" + + def ordered(items: list[Any]) -> list[Any]: + return list(reversed(items)) if reverse else items + + source = _plain_tag_source(rows, reverse) + job = PipelineJob(name="tag_operators", database=InMemoryArrowDatabase()) + with job: + source.select_tag_columns(ordered(["a", "b"]), label="tag_select") + source.drop_tag_columns(ordered(["a", "b"]), label="tag_drop") + source.map_tags(dict(ordered([("a", "a1"), ("b", "b1")])), label="map_tags") + source.map_columns( + dict(ordered([("a", "a1"), ("d1", "one")])), label="map_columns" + ) + source.pick("struct", "x", out="picked", label="pick") + source.polars_filter( + *ordered([pl.col("d1") > 1, pl.col("d2") < 7]), label="polars" + ) + return job + + +@pytest.mark.parametrize("policy", POLICIES) +@pytest.mark.parametrize("rows", [0, 8]) +@pytest.mark.parametrize("reverse", [False, True]) +def test_pick_and_tag_operators_show_the_sync_runs_rows( + reverse: bool, rows: int, policy: Policy, batch_nodes: list[str] +) -> None: + """The unary operators ``build_job`` cannot hold (``Pick`` needs a dictionary, + ``MapColumns`` plain tags), with ``MapTags``, ``SelectTagColumns``, + ``DropTagColumns`` and ``PolarsFilter`` again: in the batch region, in two tag + orders and layouts, with and without rows, they show the sync run's rows.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + warnings.simplefilter("ignore", PolarsFilterWarning) + sync = _tag_operator_job(rows, reverse) + got = _tag_operator_job(rows, reverse) + _run(sync, SyncPipelineOrchestrator(error_policy=policy)) + _run(got, AsyncPipelineOrchestrator(error_policy=policy)) + assert sorted(batch_nodes) == sorted(TAG_REGION) + assert _shown(got) == _shown(sync) + + def _stored(database: InMemoryArrowDatabase) -> list[Any]: """Every stored record, without the columns that hold a time or a random id.""" records: list[Any] = [] @@ -241,6 +350,7 @@ def test_a_load_only_run_shows_the_sync_runs_rows(batch_nodes: list[str]) -> Non def build() -> PipelineJob: with warnings.catch_warnings(): warnings.simplefilter("ignore", ProvisionalHashWarning) + warnings.simplefilter("ignore", PolarsFilterWarning) return build_job(make_source(MAIN), database) _run(build(), SyncPipelineOrchestrator()) @@ -438,10 +548,13 @@ def on_data_end( @pytest.mark.parametrize("rows", [5, 300]) def test_observer_events_keep_mains_invariants(rows: int) -> None: - """e9: a source, two region operators and a function node, async. Each node starts - in topological order, its row events lie between its start and end, an upstream - node ends before its downstream node, and the function node's rows start in the - order they arrive, which is the sync run's order.""" + """e9: a source, three region operators and a function node, async. Each node + starts in topological order, its row events lie between its start and end, an + upstream node ends before its downstream node, the function node's rows start in + the order they arrive (the sync run's order), each node's own event sequence is + the sync run's, and (v) holds at record-batch granularity: the source sends one + record batch, so every upstream node ends before the function node's first row + event.""" # A source's node is named by its source's name. chain = ("numbers", "selected", "filtered", "fn") @@ -497,13 +610,28 @@ def index(kind: str, label: str) -> int: assert events.index(("data_start", "fn", row)) < events.index( ("data_end", "fn", row) ) - # Each node's own node events are the sync run's. - for label in order: - assert [k for k, n, _ in events if n == label and k in ("start", "end")] == [ - "start", - "end", + + # Each node's own events, in the order they happen (not as a set), are the sync + # run's; the function node's row ends follow its computations (checked above). + def sequence(recorded: list[tuple[str, str, Any]], label: str) -> list[Any]: + return [ + (k, d) + for k, n, d in recorded + if n == label and not (label == "fn" and k == "data_end") ] + for label in order: + assert sequence(events, label) == sequence(sync_events.events, label), label + # (v), at record-batch granularity (the approved rule): an upstream node's end + # and a downstream node's row events interleave only between record batches. + # This in-memory source sends its rows in one record batch, so it and the region + # operators after it end before the function node's first row event. + first_row = min( + i for i, (k, n, _) in enumerate(events) if n == "fn" and k == "data_start" + ) + for label in order[:-1]: + assert index("end", label) < first_row, label + def test_a_source_whose_instance_replaces_its_reader_keeps_mains_route( batch_nodes: list[str], @@ -528,3 +656,186 @@ async def first_two() -> Any: assert read == [1] assert "selected" not in batch_nodes assert len(list(job.nodes["selected"].iter_data())) == 2 + + +def _chain() -> PipelineJob: + """A five-row source and two selects, ``up`` then ``down``, both region nodes.""" + job = PipelineJob(name="chain", database=InMemoryArrowDatabase()) + with job: + source = DictSource( + [{"a": "x", "b": i, "d1": i, "d2": 2 * i, "d3": str(i)} for i in range(5)], + tag_columns=["a", "b"], + tag_only_columns=True, + source_id="numbers", + ) + up = source.select_data_columns(["d1", "d2"], label="up") + up.select_data_columns(["d2", "d1"], label="down") + return job + + +class _RefusingDatabase(InMemoryArrowDatabase): + """A store whose every write fails.""" + + def add_records(self, *args: Any, **kwargs: Any) -> Any: + raise RuntimeError("the store refused the write") + + +class _FailingEnd(NoOpObserver): + """An observer whose end hook raises for ``up``.""" + + def contextualize(self, *identity_path: str) -> _FailingEnd: + return self + + def on_node_end(self, node_label: str, node_hash: str) -> None: + if node_label == "up": + raise RuntimeError("the end hook failed") + + +@pytest.mark.parametrize("policy", POLICIES) +@pytest.mark.parametrize("failure", ["store", "end_hook"]) +def test_a_producer_failing_after_its_last_batch_stores_nothing_downstream( + failure: str, policy: Policy, batch_nodes: list[str] +) -> None: + """e7 (independent review of PR #696, B1): the region operator ``up`` sends every + batch, then its LOG write or its end hook fails. Its reader ``down`` (LOG) sees + the failure, never a normal end, and stores nothing; the run raises ``up``'s + error, as on main.""" + job = _chain() + log = InMemoryArrowDatabase() + job.nodes["down"].attach_databases(pipeline_database=log, cache_mode=CacheMode.LOG) + observer = None + if failure == "store": + job.nodes["up"].attach_databases( + pipeline_database=_RefusingDatabase(), cache_mode=CacheMode.LOG + ) + expected = "the store refused the write" + else: + observer = _FailingEnd() + expected = "the end hook failed" + with pytest.raises(Exception, match=expected): + _run(job, AsyncPipelineOrchestrator(error_policy=policy), observer=observer) + assert {"up", "down"} <= set(batch_nodes) + assert _records(log) == 0 + + +def test_a_source_whose_own_reader_has_no_pinned_snapshot_keeps_mains_route( + batch_nodes: list[str], +) -> None: + """A source that reads its rows its own way (``async_iter_data``) and gives + snapshot batches, but keeps no pinned version, is not read through its batches: + it stays on main's row route, outside the region, and its own reader runs (and + raises), as on main; it is never read whole in its place (independent review of + PR #696, B2).""" + calls: list[str] = [] + + class OwnReader(ArrowTableSource): + def snapshot_batch_streams(self) -> Iterator[Any]: + calls.append("snapshot") + yield ArrowTableSource( + self.as_table().slice(0, 1), + tag_columns=["part", "idx"], + tag_only_columns=True, + source_id="snapshot", + ) + raise RuntimeError("the snapshot reader failed") + + async def async_iter_data( # pyright: ignore[reportImplicitOverride] # the reader under test + self, + ) -> AsyncIterator[tuple[Any, Any]]: + calls.append("async") + for stream in self.snapshot_batch_streams(): + for row in stream.iter_data(): + yield row + + schema = pa.schema( + [ + pa.field("part", pa.large_string(), False), + pa.field("idx", pa.int64(), False), + pa.field("x", pa.int64(), False), + pa.field("y", pa.int64(), False), + ] + ) + source = OwnReader( + pa.Table.from_pydict( + {"part": ["a", "b"], "idx": [1, 2], "x": [2, 3], "y": [3, 4]}, + schema=schema, + ), + tag_columns=["part", "idx"], + tag_only_columns=True, + source_id="snapshot", + ) + job = PipelineJob(name="own_reader", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["y", "x"], label="selected") + with pytest.raises(RuntimeError, match="the snapshot reader failed"): + _run(job, AsyncPipelineOrchestrator()) + assert calls == ["async", "snapshot"] + assert "selected" not in batch_nodes + + +class _KeptSync(SyncPipelineOrchestrator): + """The sync orchestrator, keeping its last result.""" + + last: Any = None + + def run(self, *args: Any, **kwargs: Any) -> Any: + self.last = super().run(*args, **kwargs) + return self.last + + +class _KeptAsync(AsyncPipelineOrchestrator): + """The async orchestrator, keeping its last result.""" + + last: Any = None + + def run(self, *args: Any, **kwargs: Any) -> Any: + self.last = super().run(*args, **kwargs) + return self.last + + +@pytest.mark.parametrize("rows", ["some", "none"]) +def test_collected_outputs_compare_and_hash_as_the_sync_runs( + rows: str, batch_nodes: list[str] +) -> None: + """e10 (independent review of PR #696, B3): every node output a run collects has + the sync run's form, empty or not: a region node with rows the same stream, + equal and with an equal hash; one with none (a filter matching no row, the + nodes after it, every node over a source with no rows) the sync run's + ``RowsOnRead``, whose stream is equal and has an equal hash.""" + from orcapod.core.operators.static_output_pod import RowsOnRead + + def build() -> PipelineJob: + source = make_source(MAIN) + if rows == "none": + source = ArrowTableSource( + source.as_table().slice(0, 0), + tag_columns=list(source.keys()[0]), + tag_only_columns=True, + source_id="none", + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ProvisionalHashWarning) + warnings.simplefilter("ignore", PolarsFilterWarning) + return build_job(source) + + sync, run = _KeptSync(), _KeptAsync() + _run(build(), sync) + _run(build(), run) + assert sorted(batch_nodes) == sorted(REGION) + expected = {node.label: s for node, s in sync.last.node_outputs.items()} + got = {node.label: s for node, s in run.last.node_outputs.items()} + assert got.keys() == expected.keys() + empty = {"nothing", "after_nothing"} if rows == "some" else set(REGION) + for label in REGION: + left, right = got[label], expected[label] + assert type(left) is type(right), label + assert isinstance(left, RowsOnRead) == (label in empty), label + if isinstance(left, RowsOnRead): + left, right = left.built(), right.built() + if label == "polars_filtered": + # ``==`` on a ``PolarsFilter`` stream raises on main as here (it compares + # Polars expressions); its identity is compared by its content hash. + assert left.content_hash() == right.content_hash(), label + else: + assert left == right, label + assert hash(left) == hash(right), label diff --git a/tests/test_pipeline/test_observer_main_compatibility.py b/tests/test_pipeline/test_observer_main_compatibility.py index 2c7078eea..99b57f22a 100644 --- a/tests/test_pipeline/test_observer_main_compatibility.py +++ b/tests/test_pipeline/test_observer_main_compatibility.py @@ -403,15 +403,22 @@ def _run_probe(source: Path, path: str) -> dict[str, _RunRecord]: return cast("dict[str, _RunRecord]", json.loads(completed.stdout)) -def _operator_completion(calls: list[list[object]]) -> list[list[object]]: - """Partition out the column selector's async completion after checking its order.""" +# The nodes of this job's async batch region (ITL-1845): the source node, named by +# its source, and the automatic column select, named by its operator. Their end events +# keep their own order, but where they fall among a downstream node's row events +# follows the record batches (the approved rule (v) at record-batch granularity). +REGION_NODES = frozenset({MAIN.source_id, "SelectDataColumns"}) + + +def _region_completion(calls: list[list[object]]) -> list[list[object]]: + """Partition out the region nodes' async end events after checking their order.""" completion: list[list[object]] = [] started: list[list[object]] = [] for call in calls: if len(call) < 4 or call[2] not in ("on_node_start", "on_node_end"): continue payload = call[3] - if not isinstance(payload, list) or payload[0] != "SelectDataColumns": + if not isinstance(payload, list) or payload[0] not in REGION_NODES: continue scope = call[:2] if call[2] == "on_node_start": @@ -514,11 +521,17 @@ def test_run_behavior_matches_reviewed_main(tmp_path: Path, path: str) -> None: _normalize_content_identity(actual["calls"]) _normalize_content_identity(expected["calls"]) if path != "sync": - # The operator forwards rows before it completes. Its end hook can run - # before or after downstream row hooks, even with one input row. - assert _operator_completion(actual["calls"]) == _operator_completion( - expected["calls"] - ), case + # A region node hands its rows on before it completes. Its end hook can + # run before or after downstream row hooks, even with one input row; the + # region nodes' end events, in their own order, are main's. + completion = _region_completion(actual["calls"]) + assert completion == _region_completion(expected["calls"]), case + # Where the observer records node events, both region nodes' end events + # were exempted, by name, not only the operator's. + if scenario in ("continue", "fail_fast", "custom", "composite"): + assert {cast("list[object]", call[3])[0] for call in completion} == set( + REGION_NODES + ), case assert actual == expected, case From 0a41c04119d590dbfc020cd4181875cb6b8ee81c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 12:54:22 -0800 Subject: [PATCH 08/20] test(differential): the wide fixture crosses a source record batch (ITL-1845) Co-Authored-By: Claude Opus 5.5 --- docs/dev/scripts/itl_1347/fixtures.py | 37 ++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/docs/dev/scripts/itl_1347/fixtures.py b/docs/dev/scripts/itl_1347/fixtures.py index c8cc0dc18..ef302449c 100644 --- a/docs/dev/scripts/itl_1347/fixtures.py +++ b/docs/dev/scripts/itl_1347/fixtures.py @@ -12,6 +12,8 @@ unit and counted by a second function pod, with ``Batch``, ``MergeJoin``, ``SemiJoin``, ``PolarsFilter``, ``AddTags``, ``DropNulls``, ``MapData`` and ``Rejoin`` beside it, and a side effect at the end. Every operator of the stage-5 classification appears once. +- ``wide``: stage 5a's batch region (ITL-1845): the spike table twice, more than one + source record batch with the stock dataset, through every kind of unary operator. """ from __future__ import annotations @@ -166,16 +168,37 @@ def report_fn(n_bins: int, ctx: InvocationContext) -> None: return job +# How many times the wide fixture repeats the spike table: the stock dataset has +# about 37,000 spikes, so two copies (about 73,000 rows) are more than one source +# record batch (``SOURCE_BATCH_ROWS``, 65,536 rows). +WIDE_COPIES = 2 + + +def wide_table(data_dir: Path) -> pa.Table: + """The spike table ``WIDE_COPIES`` times, each copy told apart by a ``copy`` tag + (0, 1, ...), copies in order, each in the spike table's order.""" + spikes = spikes_table(data_dir) + copies = [ + spikes.append_column( + pa.field("copy", pa.int64(), nullable=False), + pa.array([copy] * spikes.num_rows, pa.int64()), + ) + for copy in range(WIDE_COPIES) + ] + return pa.concat_tables(copies) + + def build_wide(data_dir: Path, database: Any) -> Any: - """Stage 5a's batch region (ITL-1845): the spike table, above 65,536 rows so an - in-memory source sends several record batches, through every kind of unary - operator, two chained, then a select and a function node on several branches.""" + """Stage 5a's batch region (ITL-1845): the spike table twice (``wide_table``), + above 65,536 rows with the stock dataset so the in-memory source sends several + record batches, through every kind of unary operator, two chained, then a select + and a function node on several branches.""" from orcapod import PipelineJob, function_pod from orcapod.sources import ArrowTableSource spikes = ArrowTableSource( - spikes_table(data_dir), - tag_columns=["subject_id", "session", "probe", "unit", "spike"], + wide_table(data_dir), + tag_columns=["copy", "subject_id", "session", "probe", "unit", "spike"], tag_only_columns=True, source_id="spikes", ) @@ -199,7 +222,9 @@ def time_bin(time_s: float) -> int: label="first_binned", ) spikes.batch(label="all_spikes") - spikes.group_by(["subject_id", "session", "probe", "unit"], label="per_unit") + spikes.group_by( + ["copy", "subject_id", "session", "probe", "unit"], label="per_unit" + ) spikes.map_data({"time_s": "t"}, label="renamed").add_tags( study="itl1347", label="tagged" ).drop_nulls(label="no_nulls") From 701b5c6658117f83ccae5b6a163f6643a2541346 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 12:54:51 -0800 Subject: [PATCH 09/20] test(differential): the wide fixture splits at the source batch size (ITL-1845) Co-Authored-By: Claude Opus 5.5 --- docs/dev/scripts/itl_1347/fixtures.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/dev/scripts/itl_1347/fixtures.py b/docs/dev/scripts/itl_1347/fixtures.py index ef302449c..6b00f98a4 100644 --- a/docs/dev/scripts/itl_1347/fixtures.py +++ b/docs/dev/scripts/itl_1347/fixtures.py @@ -176,7 +176,8 @@ def report_fn(n_bins: int, ctx: InvocationContext) -> None: def wide_table(data_dir: Path) -> pa.Table: """The spike table ``WIDE_COPIES`` times, each copy told apart by a ``copy`` tag - (0, 1, ...), copies in order, each in the spike table's order.""" + (0, 1, ...), copies in order, each in the spike table's order, in one chunk: the + source splits it at its own batch size (65,536 rows), not at the copies.""" spikes = spikes_table(data_dir) copies = [ spikes.append_column( @@ -185,7 +186,7 @@ def wide_table(data_dir: Path) -> pa.Table: ) for copy in range(WIDE_COPIES) ] - return pa.concat_tables(copies) + return pa.concat_tables(copies).combine_chunks() def build_wide(data_dir: Path, database: Any) -> Any: From 4e48084f4d0fff3c80435499c992a2fd894f99b6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 14:40:25 -0800 Subject: [PATCH 10/20] test(async): a source subclass replacing one reader keeps main's route (ITL-1845) Co-Authored-By: Claude Opus 5.5 --- .../test_spiraldb_job_projection.py | 49 ++++++++++++++++++- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index cd0bdc7b4..abfed5a34 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -15,7 +15,7 @@ import dataclasses import datetime import threading -from collections.abc import Callable +from collections.abc import AsyncIterator, Callable, Iterator from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast @@ -27,7 +27,7 @@ BatchStreams, _RowsOfStream, # pyright: ignore[reportPrivateUsage] # main's sync output class ) -from orcapod.core.streams.arrow_table_stream import pending_whole_read +from orcapod.core.streams.arrow_table_stream import ArrowTableStream, pending_whole_read from orcapod.core.sources import spiraldb_table_source as source_module from orcapod.databases import InMemoryArrowDatabase from orcapod.databases import spiraldb_connector as connector_module @@ -1729,3 +1729,48 @@ def recorded(self: Any, batches: Any, **kwargs: Any) -> Any: assert whole == ([6] if materialize_results else []) assert len(list(job.nodes["sx"].iter_data())) == 6 assert len(list(job.nodes["sy"].iter_data())) == 6 + + +@pytest.mark.parametrize("replaced", ["async_iter_data", "snapshot_batch_streams"]) +def test_a_subclass_that_replaces_one_reader_keeps_mains_route( + project: Any, replaced: str +) -> None: + """A keyed source subclass that replaces only its async reader, or only its + snapshot batches, is not read through its batches in an async job: it stays on + main's row route, so its own async reader runs, as on main (CodeRabbit on PR + #696). ``reads_snapshot_batches`` admits only a library source kind's exact + class (``table_is_rows``), so any subclass keeps main's route.""" + calls: list[str] = [] + + class OwnReader(SpiralDBTableSource): + if replaced == "async_iter_data": + + async def async_iter_data( # pyright: ignore[reportImplicitOverride] # the reader under test + self, + ) -> AsyncIterator[tuple[Any, Any]]: + calls.append("async") + for pair in list(self.iter_data())[:2]: + yield pair + + else: + + def snapshot_batch_streams( # pyright: ignore[reportImplicitOverride] # the batches under test + self, + ) -> Iterator[ArrowTableStream]: + calls.append("snapshot") + return super().snapshot_batch_streams() + + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + OwnReader("p", "wide", tag_only_columns=True).select_data_columns( + ["x"], label="sx" + ) + job.run(orchestrator=AsyncPipelineOrchestrator()) + rows = len(list(job.nodes["sx"].iter_data())) + if replaced == "async_iter_data": + assert calls == ["async"] + assert rows == 2 + else: + # Main reads it through the inherited async reader, never its batches. + assert calls == [] + assert rows == 6 From 73e5c689a6416f9a98a5870c39888196ee6f54bc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 15:32:46 -0800 Subject: [PATCH 11/20] docs(spec): stage 5a differential on the fixed head (ITL-1845) Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 28 +++++++++++++------ 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 26b403ae4..c9c263340 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1264,15 +1264,25 @@ the corrections are listed below). Scope, as landed: stay unchecked (ITL-1534). - **Differences.** e7 (documented, no observable difference), e9 and e10 (awaiting approval). -- **Differential (main 2075e85e2 against the branch).** Sync is byte-identical to main - in every fixture (tutorial, spikes, wide), mode and thread count. Async matches main's - async in tutorial and spikes. Async matches the branch's sync except: - - e8 (the side-effect node's `__computed` column); - - in the wide fixture, the stored tables of three function nodes over one function. - They share one result store, so which node computes an input and which reuses it - (`__computed`, `__record_id`) follows the async interleaving. Main's async run - differs from main's sync in the same tables. This is main's behaviour of function - nodes, which stage 5a does not change; their outputs are equal. Row order: a region node keeps arrival order, which for one snapshot source +- **Differential (main 2075e85e2 against the branch, rerun after the independent + review; one Polars thread).** The wide fixture is the spike table twice (`wide_table`): + 73,232 rows with the stock generator, which its in-memory source sends as two record + batches of 65,536 and 7,696 rows on `main` and on the branch. Sync is byte-identical to + main in every fixture (tutorial, spikes, wide) and mode (cold, warm, load-only, held). + Async matches main's async in tutorial and spikes. Async matches the branch's sync + except: + - e8 (the side-effect node's `__computed` column; spikes, cold and held); + - in the wide fixture, the shared result store's Delta version count, the run summary's + computed and reused counts (cold), and the stored tables of three function nodes + over one function. They share one result store, so which node computes an input and + which reuses it (`__computed`) follows the async interleaving: every run computes + 36,029 results in all, and with `__computed` and the calibrated volatile columns + left out the three tables are equal as multisets across main sync, main async, + branch sync and branch async, in every mode. Main's async run differs from main's + sync in exactly these tables, in every mode. This is main's behaviour of function + nodes, which stage 5a does not change; their outputs are equal. The calibration + treats `__record_id` as volatile, so record ids are not compared there. +- **Row order.** A region node keeps arrival order, which for one snapshot source is the sync order. Corrections to this spec found by the survey, which the stage 5 sections above predate: From 72da51d5b3b9706b371d834b550e730b6bbdbbb5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 16:17:21 -0800 Subject: [PATCH 12/20] fix(async): decide a source's route at admission; collect an empty whole-scan source as RowsOnRead; e9 rules (ITL-1845) A source with its own async_iter_data is admitted to the batch region only when its snapshot_batch_streams, asked once before wiring, returns streams, which the node then sends; None keeps it on main's row route. A region node that sent no row is collected as RowsOnRead before the whole-output case. The e9 observer test asserts exactly the approved rules, over one and several record batches. Spec, changelog: e9/e10 approved, PolarsFilter equality (ITL-1877), sync equal under the harness's volatile masks. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 5 +- CLAUDE.md | 5 +- changelog.d/ITL-1845.md | 13 +- .../dev/specs/itl-1347-job-table-transport.md | 29 +-- src/orcapod/core/nodes/source_node.py | 42 +++-- src/orcapod/pipeline/async_orchestrator.py | 66 ++++--- .../test_spiraldb_job_projection.py | 24 ++- .../test_pipeline/test_async_batch_region.py | 175 +++++++++++++----- 8 files changed, 254 insertions(+), 105 deletions(-) diff --git a/.zed/rules b/.zed/rules index 40f3944a2..0109cd6b3 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1631,8 +1631,9 @@ data. The rules: derived once per channel, never per batch; read it when wiring, inside shared_zero_row_memo(). A source with its own async_iter_data joins only where its batches are read exactly as - snapshot_batch_streams gives them (SourceJobNode.reads_snapshot_batches), otherwise it - stays on main's row route; never read it whole in place of its own reader. Every region + snapshot_batch_streams gives them, asked once when the region is decided, before it is + wired (SourceJobNode.region_snapshot_batches; the streams are what it sends); None + keeps it on main's row route, its own reader; never read it whole in place of that reader. Every region output holds its end (OutputChannel(hold_end=True)) until its node's work after the last batch (kept output, LOG store, modified time, end hook) returned; the orchestrator then calls release_end(), so a failure there reaches readers as UpstreamFailedError, never diff --git a/CLAUDE.md b/CLAUDE.md index 3fd49fbaf..e9bf08eef 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1676,8 +1676,9 @@ data. The rules: share one `BatchStreams` (`static_output_pod.py`): the description is derived once per channel, never per batch; read it when wiring, inside `shared_zero_row_memo()`. A source with its own `async_iter_data` joins only where its batches are read exactly as - `snapshot_batch_streams` gives them (`SourceJobNode.reads_snapshot_batches`), otherwise it - stays on main's row route; never read it whole in place of its own reader. Every region + `snapshot_batch_streams` gives them, asked once when the region is decided, before it is + wired (`SourceJobNode.region_snapshot_batches`; the streams are what it sends); `None` + keeps it on main's row route, its own reader; never read it whole in place of that reader. Every region output holds its end (`OutputChannel(hold_end=True)`) until its node's work after the last batch (kept output, `LOG` store, modified time, end hook) returned; the orchestrator then calls `release_end()`, so a failure there reaches readers as `UpstreamFailedError`, never diff --git a/changelog.d/ITL-1845.md b/changelog.d/ITL-1845.md index 48a52aa8d..c49d6cdad 100644 --- a/changelog.d/ITL-1845.md +++ b/changelog.d/ITL-1845.md @@ -2,7 +2,8 @@ - A class that implements `SourceProtocol` itself (not a subclass of an Orcapod source) now needs a `snapshot_batch_streams()` method. Return `None` when the source has no - per-batch scan: an async job then reads it whole, as before. + per-batch snapshot read: an async job then reads the source as before, through its own + `async_iter_data` when it has one (row by row), otherwise whole. ### Changed @@ -13,8 +14,12 @@ `Batch`, `GroupBy`). Rows are built only where a function or side-effect node, a join or a held node reads them, one record batch at a time, so a function node still starts on the first rows while the source is being read. Every node shows the same rows, types and - hashes as before, and as the sync run. Where an upstream node's end event falls among a - downstream node's observer events now moves by a record batch rather than a row: a - source that sends one record batch ends before the next node's first row event. + hashes as before, and as the sync run. Observer events: each node's start still comes + before its own row events and its end after them, ends stay in dependency order, and a + function node's rows start in arrival order. Where an upstream node's end event falls + among a downstream node's row events depends on record batches, backpressure and + scheduling: with an in-memory source, every upstream end can come before the first + downstream row event. A function node's rows complete in an order scheduling decides, + as before. - An `OutputChannel` checks the source-info token shape rule on every record batch sent into it. diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index c9c263340..11924ad32 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -551,8 +551,8 @@ is unsupported; what the run then does is undefined and is not part of the equal | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer's input ends normally; whether a `LOG` operator node after it stores a partial result depends on whether the task group's cancellation reaches it first | Stage 5a (ITL-1845), inside the batch region only: a region node's readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so a region operator never finishes, keeps or stores its output as if its input were complete. **A region `LOG` node stores nothing after an upstream failure, by construction**: it reads the failure from its input channel, raises, and never reaches its store; it no longer depends on cancellation timing. That holds also for a failure after the producer's last batch: a region output holds its end from its readers (`OutputChannel(hold_end=True)`) until the producing node's own work after it succeeded (its kept output, `LOG` store, modified time and end hook), and the orchestrator releases it (`release_end`) only when the node returned; a failure there fails the output, so a reader raises `UpstreamFailedError`, never ends normally. Batches still flow while the producer runs. Batches a consumer processed before the failure stay processed, and a function node after the region keeps the results it stored for them, as on `main` (no rollback). At a row boundary the adapter turns the failure into `main`'s normal row-channel close, so nodes outside the region see what they see on `main`. The run raises the producer's own error, as today | **No observable difference found on `main` 2075e85e2**: the stored outcome is unchanged (nothing stored). Reproducers, run on `main` and on the branch: a keyed scan that fails on its third record batch, feeding a `Select` in `LOG` mode (5 runs under each error policy, 10 in all: 0 rows stored every time), and a `fail_fast` function node raising on row 3 of 6 feeding a `Select` in `LOG` mode (5 runs: 0 rows stored). The independent review of PR #696 found a region operator whose `LOG` write or end hook failed after its last batch: `main` stores 0 rows downstream under both policies, the reviewed head stored 5, the fixed branch 0 (`test_a_producer_failing_after_its_last_batch_stores_nothing_downstream`, a failed write and a failing end hook, both policies). The row documents the internal signal change; the cases are tests that pass on `main` and the branch, with no timing assumption (`test_a_logging_operator_stores_nothing_after_its_source_fails_mid_scan`, `test_a_logging_operator_after_a_failing_function_stores_nothing`) | documented; no approval needed unless the developer asks | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | -| e9 | Observer events across nodes, async (batch region) | Upstream end events (`on_node_end` of a source or operator) fall among a downstream node's data events at the granularity of one row: a source ends after about 16 rows have reached the function node, a `Select` after about 135 (in-memory, 200 rows); an off-loop keyed scan interleaves the same way | Each node's own event sequence is `main`'s, and hooks keep `main`'s placement (start at task start, end after the last send and before the output closes), so `main`'s invariants hold: (i) node starts in topological order; (ii) a node's data events lie between its start and end; (iii) an upstream node ends before its downstream node; (iv) a function node's row events in arrival order, in concurrency groups of 16. (v) holds at record-batch granularity only: downstream data events and upstream end events interleave between record batches, never within one, so a source that sends one record batch (an in-memory source of up to 65,536 rows) and the region operators after it end before the downstream function node's first data event; with several batches (a keyed scan of `batch_rows` rows each, a larger in-memory table) they interleave batch by batch | Not a `main` bug: `main`'s interleaving itself depends on buffer sizes and timing, and no rule fixes it. The pinned-`main` observer test (`test_observer_main_compatibility.py`) exempts the end events of the region nodes by name (the source node and `SelectDataColumns`, `REGION_NODES`), checks their own order, and checks that both were exempted; `test_observer_events_keep_mains_invariants` checks (i) to (iv), each node's own event sequence in order against the sync run's, and (v) at record-batch granularity (300 rows, one batch) | awaiting approval | -| e10 | The class of a region node's collected async output (`OrchestratorResult.node_outputs`) | An async node's output is `RowsOnRead` over its collected rows, which compares unequal to the sync route's output stream of the same rows | A region node that sent rows gives its output channel's `result()` (for a source with column demand, the whole read, as on sync), the sync route's stream form: the same rows, table, types and hashes, and it now compares equal to the sync output, with an equal hash. A region node that sent no row (a filter matching nothing, the nodes after it, every node over a source with no rows) is collected as the sync route collects it, a `RowsOnRead` of no rows, so the two routes give one form, empty or not; a `RowsOnRead` compares by object on both routes (as a function node's output does on `main`), and its stream compares and hashes equal to the sync one. A projected source's whole read still happens once, when the output is first read | Not a bug on `main`, a form change: the equality between the two routes' outputs followed from their classes, not their rows (`test_outputs_of_two_routes_compare_and_hash_as_main`; empty and non-empty: `test_collected_outputs_compare_and_hash_as_the_sync_runs`) | awaiting approval | +| e9 | Observer events across nodes, async (batch region) | Upstream end events (`on_node_end` of a source or operator) fall among a downstream node's data events at the granularity of one row: a source ends after about 16 rows have reached the function node, a `Select` after about 135 (in-memory, 200 rows); an off-loop keyed scan interleaves the same way | What the code does: a region node calls `on_node_start` when its task starts and `on_node_end` after its last send, before its output closes (`main`'s placement). So: each node's start comes before its own data events, and its successful end after its own last send; successful ends stay in dependency order; a function node's row starts keep arrival order. Where an upstream end falls relative to a downstream node's data events depends on record batches, backpressure and scheduling: a record batch is the unit of delivery, so with in-memory sources (one record batch up to 65,536 rows) every upstream end can come before the first downstream data event, and with a scan that sends several batches (a keyed scan waiting on its next read) a downstream function node's row events can come before the source's end, as on `main`. Completion order within a function node (its `on_data_end` events) depends on scheduling, as on `main`. Observed by the delta review of PR #696: in the 73,232-row wide fixture, branch async ends the source and the selector feeding the all-rows function at events 2 and 9, before any of its rows starts, while main async's first source end comes after 73,051 of them; the three function nodes complete their rows in another order, their other events equal | Not a `main` bug: `main`'s interleaving itself depends on buffer sizes and timing, and no rule fixes it. The pinned-`main` observer test (`test_observer_main_compatibility.py`) exempts the end events of the region nodes by name (the source node and `SelectDataColumns`, `REGION_NODES`), checks their own order, and checks that both were exempted; `test_observer_events_keep_mains_invariants` asserts exactly the rules above (each node's start before its own data events and sends, its end after them; ends in dependency order; the function node's row starts in the sync run's order, each row ending once after it started), with one record batch and with several | approved (coordinator, 2026-12-02) | +| e10 | The class of a region node's collected async output (`OrchestratorResult.node_outputs`) | An async node's output is `RowsOnRead` over its collected rows, which compares unequal to the sync route's output stream of the same rows | A region node that sent rows gives its output channel's `result()` (for a source with column demand, the whole read, as on sync), the sync route's stream form: the same rows, table, types and hashes, and it now compares equal to the sync output, with an equal hash, except a `PolarsFilter` node's output, whose direct equality raises on both routes and on `main` (ITL-1877): its streams are compared by content hash. A region node that sent no row (a filter matching nothing, the nodes after it, every node over a source with no rows, also a source that sends a narrowed form of its whole read) is collected as the sync route collects it, a `RowsOnRead` of no rows, so the two routes give one form, empty or not; a `RowsOnRead` compares by object on both routes (as a function node's output does on `main`), and its stream compares and hashes equal to the sync one. A projected source's whole read still happens once, when the output is first read | Not a bug on `main`, a form change: the equality between the two routes' outputs followed from their classes, not their rows (`test_outputs_of_two_routes_compare_and_hash_as_main`; empty and non-empty: `test_collected_outputs_compare_and_hash_as_the_sync_runs`) | approved (coordinator, 2026-12-02) | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` rule (ITL-1355) removes every data-dependent refusal from `Rejoin`: it checks only what its @@ -597,9 +597,10 @@ branch introduces: the branch keeps `main`'s behaviour, and they are documented - **The sync path**, at every stage, by construction and L0–L5. - **Error types and messages**: `Join`'s schema-level checks keep their messages, asserted in L6. -- **Observer events**: the same events, and each node's own events in the same order and - count. Function and side-effect nodes are per row as today; operators and sources call - node hooks only. Where an upstream node's end falls among downstream events moves (e9). +- **Observer events**: the same events, and each node's own events in the same count. + Function and side-effect nodes are per row as today; operators and sources call node + hooks only. Where an upstream node's end falls among downstream events moves, and a + function node's completion order follows scheduling, as on `main` (e9). - **`RunSummary`**: identical on sync; on async it differs only under e3. - **`head()` and the preview**: identical on sync. On async they show arrival order, as on `main`. @@ -1225,10 +1226,12 @@ the corrections are listed below). Scope, as landed: required `SourceProtocol` member: `RootSource` answers `None`, `SpiralDBTableSource` its per-batch streams, and each wrapper answers for itself) and whose Arrow types are declared. A source with its own `async_iter_data` joins only where its batches are - read exactly as `snapshot_batch_streams` gives them - (`SourceJobNode.reads_snapshot_batches`: the table route, no declared form, the - node's data context, a pinned version); otherwise it stays on `main`'s row route, - its own reader, and is never read whole in its place; + read exactly as `snapshot_batch_streams` gives them, asked once when the region is + decided, before the source is wired (`SourceJobNode.region_snapshot_batches`: the + table route, no declared form, the node's data context, a pinned version, and + streams, not `None`, from the method; the streams are what the node sends); + otherwise it stays on `main`'s row route, its own reader, and is never read whole + in its place; - a library unary operator job node whose one input is a region node with declared Arrow types (`ROW_BY_ROW` operators per record batch; barriers, `GroupBy`, `PolarsFilter`, `Filter` and `Batch` without a size, by `to_stream()`; `Batch` with a @@ -1262,13 +1265,13 @@ the corrections are listed below). Scope, as landed: token-shape rule on every batch sent, after its token types are settled, with the stream's `token_shape_violations` / `token_shape_error`. A held node's rows on async stay unchecked (ITL-1534). -- **Differences.** e7 (documented, no observable difference), e9 and e10 (awaiting - approval). +- **Differences.** e7 (documented, no observable difference), e9 and e10 (approved, + coordinator, 2026-12-02). - **Differential (main 2075e85e2 against the branch, rerun after the independent review; one Polars thread).** The wide fixture is the spike table twice (`wide_table`): 73,232 rows with the stock generator, which its in-memory source sends as two record - batches of 65,536 and 7,696 rows on `main` and on the branch. Sync is byte-identical to - main in every fixture (tutorial, spikes, wide) and mode (cold, warm, load-only, held). + batches of 65,536 and 7,696 rows on `main` and on the branch. Sync equals main, under the harness's volatile masks (run-specific columns such as + record ids and timestamps; the stored files are not byte-identical), in every fixture (tutorial, spikes, wide) and mode (cold, warm, load-only, held). Async matches main's async in tutorial and spikes. Async matches the branch's sync except: - e8 (the side-effect node's `__computed` column; spikes, cold and held); diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index d36f19afc..aed829876 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1730,6 +1730,7 @@ async def async_execute_batches( observer: ExecutionObserverProtocol | None = None, read_columns: Collection[str] | None = None, keep_whole: bool = True, + snapshot_streams: Iterator[StreamProtocol] | None = None, ) -> StreamProtocol | None: """Send this node's rows into ``output`` as Arrow record batches, as they are read (ITL-1347, stage 5a). @@ -1762,6 +1763,10 @@ async def async_execute_batches( sent are narrowed. Without it (a run that collects no result) the whole batches of a narrowed whole read are not kept, and nothing is returned for them. + snapshot_streams: The snapshot batch streams the node was admitted to + the region with (``region_snapshot_batches``), sent in place of + asking the source again; closed unread when a projected read is + sent instead. ``None``: asked here. Returns: The node's whole output when the batches sent are a narrowed read's @@ -1824,9 +1829,14 @@ async def async_execute_batches( whole_streams = BatchStreams(self) if kept is not None else None if whole_streams is not None: whole_streams.read_description() - streams = self._snapshot_batch_streams() + streams = ( + snapshot_streams + if snapshot_streams is not None + else self._snapshot_batch_streams() + ) + snapshot_streams = None if streams is None and self._reads_its_own_way(): - # Admitted for its batches (``reads_snapshot_batches``): a whole + # Admitted for its batches (``region_snapshot_batches``): a whole # read would bypass the source's own reader. raise RuntimeError( f"The source of {node_label!r} gave no snapshot batches in a " @@ -1857,6 +1867,12 @@ async def async_execute_batches( except BaseException as error: output.fail(error) raise + finally: + # Streams the node was admitted with and did not send (a projected read + # was sent): an unstarted scan, closed here. + close = getattr(snapshot_streams, "close", None) + if callable(close): + close() await output.close() return whole @@ -2578,18 +2594,20 @@ def whole() -> ArrowTableStream: return streams, lambda num_rows: WholeRead(whole, None, keys, num_rows) - def reads_snapshot_batches(self) -> bool: - """Whether a job's async batch region can read this node through its bound - source's ``snapshot_batch_streams`` (ITL-1347, stage 5a). + def region_snapshot_batches(self) -> Iterator[StreamProtocol] | None: + """The bound source's snapshot batch streams, asked when a job's async run + decides this node's route (ITL-1347, stage 5a), or ``None``. - Exactly where ``_snapshot_batch_streams`` asks the source for its batches: a - projected read could be made of it (``_projection_snapshot``: this class, the - table route, no declared form, the node's data context, a pinned version). A - source that reads its rows its own way (its own ``async_iter_data``) and - cannot be read so stays on main's row route, outside the region: it is never - read whole in place of its own reader. + For a source that reads its rows its own way (its own ``async_iter_data``): + streams admit the node to the batch region, and are what it sends + (``async_execute_batches``' ``snapshot_streams``); ``None`` keeps it on main's + row route, outside the region, so it is never read whole in place of its own + reader. ``None`` both where no projected read could be made of the source + (``_projection_snapshot``: this class, the table route, no declared form, the + node's data context, a pinned version) and where its + ``snapshot_batch_streams`` answers ``None``. """ - return self._projection_snapshot() is not None + return self._snapshot_batch_streams() def _snapshot_batch_streams(self) -> Iterator[StreamProtocol] | None: """The bound source's per-batch snapshot streams (ITL-1347, stage 5a), or diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index c11b72c45..25b59ff85 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -265,7 +265,7 @@ async def _run_async( # (each node derived once, not once per channel and per upstream path); # the memo ends before any task starts. with shared_zero_row_memo(): - region = _batch_region(topo_order, in_edges, held_rows) + region, snapshots = _batch_region(topo_order, in_edges, held_rows) for node in topo_order: if node not in region: continue @@ -340,12 +340,12 @@ async def _run_async( def collected_output( rows: list[tuple[TagProtocol, DataProtocol]], node: StreamProtocol ) -> StreamProtocol: + if node in region_results: + # A region node's output (``region_results``). + return region_results[node] whole = whole_outputs.get(id(node)) if whole is not None: return whole - if node in region_results: - # A region node's output: the record batches it sent. - return region_results[node] return rows_on_read( rows, node, bindings=bindings_at_collection[id(node)] ) @@ -370,6 +370,7 @@ def collected_output( whole_outputs=whole_outputs, load_only=load_only, keep_whole=materialize_results, + snapshot_streams=snapshots.get(id(node)), ) continue writer = node_output_channels[node].writer @@ -479,19 +480,19 @@ def collected_output( # ``StaleOutputError``, as main's collected output does. # A region node that sent no row is collected as the sync route # collects it, its rows (none) as a ``RowsOnRead`` (e10), so the two - # routes give one form, empty or not. - region_results.update( - ( - node, - output.result() - if output.sent_rows - else rows_on_read( + # routes give one form, empty or not: checked first, also for a + # source that sent a narrowed form of its whole read (its whole + # output holds no row either). A source that sent rows of a narrowed + # read is its whole output; any other node the batches it sent. + for node, output in batch_outputs.items(): + if not output.sent_rows: + region_results[node] = rows_on_read( [], node, bindings=bindings_at_collection[id(node)] - ), - ) - for node, output in batch_outputs.items() - if id(node) not in whole_outputs - ) + ) + elif id(node) in whole_outputs: + region_results[node] = whole_outputs[id(node)] + else: + region_results[node] = output.result() return OrchestratorResult( node_outputs=( StreamsOnRead(collectors, collected_output) @@ -814,9 +815,10 @@ def _batch_region( topo_order: list[Any], in_edges: Mapping[Any, list[Any]], held_rows: Mapping[Any, Any] | None, -) -> set[Any]: +) -> tuple[set[Any], dict[int, Any]]: """The nodes of a run whose outputs travel as Arrow record batches (ITL-1347, - stage 5a). + stage 5a), and the snapshot batch streams of the region's sources that read + their rows their own way. The region is decided from the graph and the classes alone, never from rows: @@ -838,8 +840,14 @@ class (every one is row by row or a barrier), whose one input is a region node in_edges: Each node's inputs, in the operator's order. held_rows: The nodes the run holds rather than runs. + A source with its own ``async_iter_data`` is admitted only when its + ``snapshot_batch_streams``, asked here, once, before the source is wired into the + region, returns streams (``SourceJobNode.region_snapshot_batches``); those streams + are the ones the node sends. ``None`` (the protocol's answer for a kind with no + per-batch snapshot read) keeps it on main's row route, its own reader. + Returns: - The region's nodes. + The region's nodes, and the snapshot batch streams asked for, by node id. """ from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode @@ -848,6 +856,7 @@ class (every one is row by row or a barrier), whose one input is a region node unary = _library_unary_operators() region: set[Any] = set() + snapshots: dict[int, Any] = {} # Whether each region node declares its Arrow types, asked once per node. declared: dict[int, bool] = {} for node in topo_order: @@ -874,11 +883,18 @@ class (every one is row by row or a barrier), whose one input is a region node type(source).snapshot_batch_streams is not RootSource.snapshot_batch_streams ) + if reads_whole: + region.add(node) + continue # A source with its own reader joins only where its batches are read - # exactly as its ``snapshot_batch_streams`` gives them; otherwise it - # stays on main's row route (its own ``async_iter_data``). - if reads_whole or (in_batches and source_node.reads_snapshot_batches()): + # exactly as its ``snapshot_batch_streams`` gives them, asked now, before + # it is wired: streams admit it, and are what it sends; ``None`` (no + # per-batch snapshot read) keeps it on main's row route, its own + # ``async_iter_data``. + streams = source_node.region_snapshot_batches() if in_batches else None + if streams is not None: region.add(node) + snapshots[id(node)] = streams elif is_operator_node(node): if not reads_as_its_class(node, OperatorJobNode): continue @@ -892,7 +908,7 @@ class (every one is row by row or a barrier), whose one input is a region node ): region.add(node) declared[id(node)] = operator_node.arrow_types_declared - return region + return region, snapshots def _library_unary_operators() -> frozenset[type]: @@ -921,6 +937,7 @@ def _start_region_node( whole_outputs: dict[int, Any], load_only: bool, keep_whole: bool, + snapshot_streams: Any = None, ) -> None: """Start a region node's record-batch form (ITL-1347, stage 5a). @@ -941,6 +958,8 @@ def _start_region_node( load_only: Whether the run is load-only. keep_whole: Whether a source node keeps its whole batches when it sends a narrowed form of them (only when the run's results are collected). + snapshot_streams: The snapshot batch streams a source node that reads its + rows its own way was admitted with (``_batch_region``), or ``None``. """ if is_source_node(node): source_node = cast("SourceJobNode", node) @@ -951,6 +970,7 @@ async def source_work() -> None: observer=observer, read_columns=demand, keep_whole=keep_whole, + snapshot_streams=snapshot_streams, ) if whole is not None: whole_outputs[id(node)] = whole diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index abfed5a34..5f2fbd8e3 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -25,6 +25,7 @@ from orcapod import PipelineJob, function_pod from orcapod.core.operators.static_output_pod import ( BatchStreams, + RowsOnRead, _RowsOfStream, # pyright: ignore[reportPrivateUsage] # main's sync output class ) from orcapod.core.streams.arrow_table_stream import ArrowTableStream, pending_whole_read @@ -1669,9 +1670,12 @@ def test_a_source_that_sends_no_row_collects_every_column( successor reading one column: the async collected output keeps every column of the node, the unread ones and their source-info columns included, as the sync route's output does (CodeRabbit on PR #696: the projected read collected the - narrowed columns).""" + narrowed columns). Every collected entry, the source's and its successor's, is + of the sync route's class (``RowsOnRead``), also where the source cannot make + the narrowed read and sends a narrowed form of its whole read (delta review of + PR #696, finding 2: that source was collected as its whole batches' stream).""" - def collected(route: str) -> Any: + def collected(route: str) -> tuple[Any, Any]: with monkeypatch.context() as m: if whole: _read_whole(m) @@ -1689,10 +1693,18 @@ def collected(route: str) -> Any: if route == "sync" else AsyncPipelineOrchestrator() ) - return orchestrator.run(dag).node_outputs[node] - - got = collected("async").as_table(all_info=True) - expected = collected("sync").as_table(all_info=True) + outputs = orchestrator.run(dag).node_outputs + return outputs[node], outputs[job.nodes["sx"]] + + got_source, got_selected = collected("async") + expected_source, expected_selected = collected("sync") + assert type(got_source) is type(expected_source) is RowsOnRead + assert type(got_selected) is type(expected_selected) is RowsOnRead + assert got_selected.as_table(all_info=True).equals( + expected_selected.as_table(all_info=True) + ) + got = got_source.as_table(all_info=True) + expected = expected_source.as_table(all_info=True) assert got.num_rows == expected.num_rows == 0 assert {"y", "blob", "_source_y", "_source_blob"} <= set(got.column_names) assert got.schema.equals(expected.schema) diff --git a/tests/test_pipeline/test_async_batch_region.py b/tests/test_pipeline/test_async_batch_region.py index 33b11c197..8bdba2048 100644 --- a/tests/test_pipeline/test_async_batch_region.py +++ b/tests/test_pipeline/test_async_batch_region.py @@ -546,17 +546,27 @@ def on_data_end( self._add("data_end", node_label, repr(sorted(tag.as_dict().items()))) +@pytest.mark.parametrize("batch_rows", [None, 32]) @pytest.mark.parametrize("rows", [5, 300]) -def test_observer_events_keep_mains_invariants(rows: int) -> None: - """e9: a source, three region operators and a function node, async. Each node - starts in topological order, its row events lie between its start and end, an - upstream node ends before its downstream node, the function node's rows start in - the order they arrive (the sync run's order), each node's own event sequence is - the sync run's, and (v) holds at record-batch granularity: the source sends one - record batch, so every upstream node ends before the function node's first row - event.""" +def test_observer_events_keep_mains_invariants( + rows: int, batch_rows: int | None, monkeypatch: pytest.MonkeyPatch +) -> None: + """e9 (approved): a source, three region operators and a function node, async, + the source sending one record batch or several. Exactly the rules e9 states: + each node's start comes before its own data events, and its successful end + after its own last send; successful ends stay in dependency order; the function + node's row starts keep arrival order (the sync run's order). Where an upstream + end falls among downstream data events, and the order in which the function + node's rows complete, depend on record batches, backpressure and scheduling, as + on main, so neither is asserted (delta review of PR #696, finding 3).""" + import orcapod.core.streams.base as stream_base + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.record_batch_channels import OutputChannel + + if batch_rows is not None: + monkeypatch.setattr(stream_base, "SOURCE_BATCH_ROWS", batch_rows) # A source's node is named by its source's name. - chain = ("numbers", "selected", "filtered", "fn") + order = ("numbers", "selected", "filtered", "after", "fn") def build() -> PipelineJob: source = DictSource( @@ -577,6 +587,28 @@ def build() -> PipelineJob: sync_events = _Recorder() _run(build(), SyncPipelineOrchestrator(), observer=sync_events) recorder = _Recorder() + # A region node's sends, recorded beside its hooks: the output channel each + # region node is given, by the node's label. + owners: dict[int, str] = {} + source_batches = SourceJobNode.async_execute_batches + operator_batches = OperatorJobNode.async_execute_batches + send = OutputChannel.send + + async def source_form(self: Any, output: Any, **kwargs: Any) -> Any: + owners[id(output)] = self.label + return await source_batches(self, output, **kwargs) + + async def operator_form(self: Any, inputs: Any, output: Any, **kwargs: Any) -> Any: + owners[id(output)] = self.label + return await operator_batches(self, inputs, output, **kwargs) + + async def recorded_send(self: Any, batch: Any) -> None: + await send(self, batch) + recorder._add("send", owners[id(self)]) # pyright: ignore[reportPrivateUsage] # the recorder of this test + + monkeypatch.setattr(SourceJobNode, "async_execute_batches", source_form) + monkeypatch.setattr(OperatorJobNode, "async_execute_batches", operator_form) + monkeypatch.setattr(OutputChannel, "send", recorded_send) _run(build(), AsyncPipelineOrchestrator(), observer=recorder) events = recorder.events @@ -585,21 +617,27 @@ def index(kind: str, label: str) -> int: i for i, (k, name, _) in enumerate(events) if (k, name) == (kind, label) ) - labels = {name for _, name, _ in events} - assert set(chain) <= labels - order = (*chain[:3], "after", "fn") - starts = [index("start", label) for label in order] + # The four region nodes sent their batches. + assert set(owners.values()) == set(order[:-1]) + assert {n for k, n, _ in events if k == "send"} >= {"numbers", "selected"} + source_sends = sum(1 for k, n, _ in events if (k, n) == ("send", "numbers")) + assert source_sends == (-(-rows // batch_rows) if batch_rows else 1) + # Each node's start comes before its own data events (and sends), and its + # successful end after its own last one. + for label in order: + own = [ + i + for i, (k, n, _) in enumerate(events) + if n == label and k in ("data_start", "data_end", "send") + ] + assert own, label + assert index("start", label) < min(own), label + assert max(own) < index("end", label), label + # Successful ends stay in dependency order. ends = [index("end", label) for label in order] - # (i) starts in topological order; (iii) an upstream node ends before its - # downstream node. - assert starts == sorted(starts) assert ends == sorted(ends) - # (ii) every node's row events lie between its start and its end. - for position, (kind, label, _) in enumerate(events): - if kind in ("data_start", "data_end"): - assert index("start", label) < position < index("end", label) - # (iv) the function node's rows start in arrival order, the sync run's order, and - # each ends once, after it started. + # The function node's row starts keep arrival order, the sync run's; each row + # ends once, after it started, in an order scheduling decides. row_starts = [d for k, n, d in events if (k, n) == ("data_start", "fn")] row_ends = [d for k, n, d in events if (k, n) == ("data_end", "fn")] assert row_starts == [ @@ -611,27 +649,6 @@ def index(kind: str, label: str) -> int: ("data_end", "fn", row) ) - # Each node's own events, in the order they happen (not as a set), are the sync - # run's; the function node's row ends follow its computations (checked above). - def sequence(recorded: list[tuple[str, str, Any]], label: str) -> list[Any]: - return [ - (k, d) - for k, n, d in recorded - if n == label and not (label == "fn" and k == "data_end") - ] - - for label in order: - assert sequence(events, label) == sequence(sync_events.events, label), label - # (v), at record-batch granularity (the approved rule): an upstream node's end - # and a downstream node's row events interleave only between record batches. - # This in-memory source sends its rows in one record batch, so it and the region - # operators after it end before the function node's first row event. - first_row = min( - i for i, (k, n, _) in enumerate(events) if n == "fn" and k == "data_start" - ) - for label in order[:-1]: - assert index("end", label) < first_row, label - def test_a_source_whose_instance_replaces_its_reader_keeps_mains_route( batch_nodes: list[str], @@ -773,6 +790,78 @@ async def async_iter_data( # pyright: ignore[reportImplicitOverride] # the rea assert "selected" not in batch_nodes +@pytest.mark.parametrize("read", [["y", "x"], ["x"]]) +def test_a_pinned_source_without_snapshot_batches_reads_with_its_own_reader( + batch_nodes: list[str], read: list[str] +) -> None: + """A source that keeps a pinned version, reads its rows its own way + (``async_iter_data``) and answers ``None`` from ``snapshot_batch_streams`` (the + protocol's answer for a kind with no per-batch snapshot read) stays on main's + row route: the method is asked once, when the route is decided, and the + source's own reader gives the rows, those of the sync run (delta review of + PR #696, finding 1: the run raised).""" + calls: list[str] = [] + + class NoBatches(ArrowTableSource): + TABLE_IS_ROWS = True + + def pinned_snapshot(self) -> "NoBatches": # pyright: ignore[reportImplicitOverride] # the snapshot under test + return self + + def snapshot_batch_streams(self) -> None: # pyright: ignore[reportImplicitOverride] # the answer under test + calls.append("snapshot") + return None + + async def async_iter_data( # pyright: ignore[reportImplicitOverride] # the reader under test + self, + ) -> AsyncIterator[tuple[Any, Any]]: + calls.append("async") + async for row in super().async_iter_data(): + yield row + + schema = pa.schema( + [ + pa.field("part", pa.large_string(), False), + pa.field("idx", pa.int64(), False), + pa.field("x", pa.int64(), False), + pa.field("y", pa.int64(), False), + ] + ) + table = pa.Table.from_pydict( + { + "part": ["b", "a", "a"], + "idx": [1, 2, 1], + "x": [2, 3, 4], + "y": [3, 4, 5], + }, + schema=schema, + ) + + def build() -> PipelineJob: + job = PipelineJob(name="no_batches", database=InMemoryArrowDatabase()) + with job: + NoBatches( + table, + tag_columns=["part", "idx"], + tag_only_columns=True, + source_id="no_batches", + ).select_data_columns(read, label="selected") + return job + + expected = build() + _run(expected, SyncPipelineOrchestrator()) + calls.clear() + got = build() + _run(got, AsyncPipelineOrchestrator()) + assert calls == ["snapshot", "async"] + assert "selected" not in batch_nodes + assert ( + got.nodes["selected"] + .as_table(all_info=True) + .equals(expected.nodes["selected"].as_table(all_info=True)) + ) + + class _KeptSync(SyncPipelineOrchestrator): """The sync orchestrator, keeping its last result.""" From 92c2b212cc1f8d47c0b367d799b2e5a2df332d06 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 17:19:05 -0800 Subject: [PATCH 13/20] fix(async): close unsent snapshot streams before the end hook; bound region queues by buffer_size (ITL-1845) CodeRabbit on PR #696: a failure to close the snapshot batch streams a source was admitted with now fails its output before on_node_end; a region output's readers queue min(buffer_size, BATCH_BUFFER_SIZE) batches. Tests: the LOG failure targets the data scan only, the gate wait is bounded, function rows compare with their values; docstrings. Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 4 +- src/orcapod/core/nodes/operator_node.py | 3 + src/orcapod/core/nodes/source_node.py | 33 +++++-- src/orcapod/pipeline/async_orchestrator.py | 12 ++- .../test_spiraldb_job_projection.py | 97 +++++++++++++++++-- .../test_pipeline/test_async_batch_region.py | 48 +++++++++ .../test_source_object_registration.py | 2 + 7 files changed, 180 insertions(+), 19 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 11924ad32..33800a93d 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1376,7 +1376,9 @@ Answers to the spec's questions (developer, 2026-11-22, approving the spec as a 6. **Batch and buffer sizes**: - a source sends Arrow record batches of at most 65,536 rows; - an operator sends its result's own record batches; - - an input channel queues 8 batches. + - an input channel queues 8 batches, fewer when the async orchestrator's + `buffer_size` is smaller (`min(buffer_size, BATCH_BUFFER_SIZE)` for a region + output's readers), so lowering it bounds the region's queues too. 7. **Signatures change directly in each stage** on `eywalker/job-speed`, with no thin forms of the old ones. `main` sees one breaking change, at the branch merge. 8. **`node_outputs` holds each node's output stream** (refining decision 1). diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index eaaabcc0e..a1e0c277a 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -2744,6 +2744,9 @@ async def _replay_batches( from orcapod.core.operators.static_output_pod import close_inputs async def read_to_end(channel: RecordBatchInput) -> None: + """Read ``channel`` to its end, discarding its batches; an input's + failure (``UpstreamFailedError``) is raised, which is why the replay + awaits these reads after it has sent every stored batch.""" async for _ in channel: pass diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 4e3655c9c..69b47274c 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1862,17 +1862,24 @@ async def async_execute_batches( await output.send(piece) if whole_streams is not None and kept is not None: whole = whole_streams(kept) + # Streams the node was admitted with and did not send (a projected read + # was sent): an unstarted scan, closed before the end hook, so a failure + # to close fails the output like any other. + unsent, snapshot_streams = snapshot_streams, None + _close_unsent(unsent) if observer is not None: observer.on_node_end(node_label, node_hash) except BaseException as error: + if snapshot_streams is not None: + try: + _close_unsent(snapshot_streams) + except Exception as cleanup: # noqa: BLE001 # the node's own failure is raised + error.add_note( + "Closing the unsent snapshot batch streams also failed: " + + f"{type(cleanup).__name__}: {cleanup}" + ) output.fail(error) raise - finally: - # Streams the node was admitted with and did not send (a projected read - # was sent): an unstarted scan, closed here. - close = getattr(snapshot_streams, "close", None) - if callable(close): - close() await output.close() return whole @@ -3070,6 +3077,14 @@ def _without_columns(table: pa.Table, unread: frozenset[str]) -> pa.Table: return table.drop_columns([c for c in table.column_names if c in dropped]) +def _close_unsent(streams: Iterator[StreamProtocol] | None) -> None: + """Close snapshot batch streams a source node was admitted with and did not + send (a generator: ``close``), if any.""" + close = getattr(streams, "close", None) + if callable(close): + _ = close() + + async def _send_record_batches( streams: Iterator[StreamProtocol], output: RecordBatchOutput, @@ -3100,6 +3115,12 @@ async def _send_record_batches( loop = asyncio.get_running_loop() def next_table() -> pa.Table | None: + """Advance ``streams`` and convert the stream it gives, both on the reader + thread that owns the scan. + + Returns: + The next table to send, or ``None`` only when ``streams`` is exhausted. + """ stream = next(streams, None) return None if stream is None else convert(stream) diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 25b59ff85..1219ace1e 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -215,7 +215,7 @@ async def _run_async( ) -> OrchestratorResult: """Core async logic: wire channels, launch tasks, collect results.""" from orcapod.core.nodes.operator_node import ordered_operator_inputs - from orcapod.core.record_batch_channels import OutputChannel + from orcapod.core.record_batch_channels import BATCH_BUFFER_SIZE, OutputChannel from orcapod.core.streams.base import shared_zero_row_memo from orcapod.core.operators.static_output_pod import ( rows_on_read, @@ -279,9 +279,15 @@ async def _run_async( description = node retain = True # The end is shown to the readers only once the node's own work - # after its last batch succeeded (``_start_region_node``). + # after its last batch succeeded (``_start_region_node``). A + # reader of an output that keeps no batch queues at most + # ``BATCH_BUFFER_SIZE`` batches, fewer when the orchestrator's + # buffer size is smaller, so lowering it bounds the region too. batch_outputs[node] = OutputChannel( - description, retain=retain, hold_end=True + description, + retain=retain, + buffer_size=min(buf, BATCH_BUFFER_SIZE), + hold_end=True, ) try: batch_outputs[node].read_description() diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 5f2fbd8e3..6deae8b83 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -40,6 +40,7 @@ from orcapod.core.streams.base import schema_requires_io, typed_zero_row_table from orcapod.core.streams.view import display_name from orcapod.pipeline.dag import OrcaDAG +from orcapod.pipeline.observer import NoOpObserver from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol from orcapod.sources import SpiralDBTableSource from orcapod.types import CacheMode, ColumnConfig, Condition @@ -1440,11 +1441,16 @@ def test_a_logging_operator_stores_nothing_after_its_source_fails_mid_scan( its input ended normally and the run's cancellation came first.""" if not projected: _read_whole(monkeypatch) + monkeypatch.setattr(fake, "scan_batch_rows", 1) original = fake.FakeReader.read_next_batch + data_batches: list[int] = [] def failing(self: Any) -> Any: - if self._record.batches_read == 2: - raise RuntimeError("the scan failed on its third batch") + """Fail a scan of the table's rows (never a count) on its third batch.""" + if _reads_rows(self._record): + if self._record.batches_read == 2: + raise RuntimeError("the scan failed on its third batch") + data_batches.append(self._record.batches_read) return original(self) monkeypatch.setattr(fake.FakeReader, "read_next_batch", failing) @@ -1459,6 +1465,9 @@ def failing(self: Any) -> Any: asyncio.run( job.run_async(orchestrator=AsyncPipelineOrchestrator(error_policy=policy)) ) + # The data scan delivered two batches before it failed (CodeRabbit on PR #696: + # the failure must not come from the count's reads). + assert data_batches == [0, 1] assert not any( (log.get_all_records(path) or pa.table({})).num_rows for path in log.list_table_paths() @@ -1472,6 +1481,8 @@ def failing(self: Any) -> Any: @function_pod(output_keys="x2") def x_twice(x: float) -> float: + """Twice ``x``; records the call (``X_CALLS``, ``X_CALLED``): a function call + began, not that its result was committed.""" X_CALLS.append(x) X_CALLED.set() return 2 * x @@ -1553,6 +1564,8 @@ def test_a_failing_scan_leaves_the_rows_before_it_computed( ) def fail_after_two() -> None: + """Before the scan reads its third batch, wait until the function node has + been called twice, then fail the scan.""" while len(X_CALLS) < 2: assert X_CALLED.wait(timeout=60) X_CALLED.clear() @@ -1590,6 +1603,8 @@ def test_cancelling_a_run_mid_scan_closes_the_scan_on_its_thread( threads: dict[str, int] = {} def wait_for_release() -> None: + """Record the reading thread, signal that the scan reached the gate + (``reading``) and hold it until the test releases it.""" threads["read"] = threading.get_ident() reading.set() assert release.wait(timeout=60) @@ -1598,6 +1613,8 @@ def wait_for_release() -> None: original_close = fake.FakeReader.close def recorded_close(self: Any) -> None: + """Record the thread that closes a scan of the table's rows, and signal + the close (``closed``).""" if _reads_rows(self._record): threads["close"] = threading.get_ident() closed.set() @@ -1608,10 +1625,19 @@ def recorded_close(self: Any) -> None: async def main() -> set[asyncio.Task[Any]]: run = asyncio.ensure_future(job.run_async()) - while not reading.is_set(): - await asyncio.sleep(0.01) - run.cancel() - release.set() + try: + # The gate or the run's end, whichever comes first, within a deadline. + deadline = asyncio.get_running_loop().time() + 60 + while not reading.is_set(): + if run.done(): + run.result() # raises the run's own error, if any + pytest.fail("the run ended before the scan reached the gate") + if asyncio.get_running_loop().time() > deadline: + pytest.fail("the scan did not reach the gate within 60 s") + await asyncio.sleep(0.01) + run.cancel() + finally: + release.set() with pytest.raises(asyncio.CancelledError): await run return asyncio.all_tasks() - {asyncio.current_task()} @@ -1656,10 +1682,13 @@ def build() -> PipelineJob: .as_table(all_info=True) .equals(sync.nodes[label].as_table(all_info=True)) ), label - # The function node keeps main's async form: rows in completion order. + # The function node keeps main's async form: rows in completion order. Its + # rows are compared as (tags, values) pairs, in no order. assert sorted( - repr(_pair(t, d)[0]) for t, d in got.nodes["fn"].iter_data() - ) == sorted(repr(_pair(t, d)[0]) for t, d in sync.nodes["fn"].iter_data()) + repr((_pair(t, d)[0], d.as_dict())) for t, d in got.nodes["fn"].iter_data() + ) == sorted( + repr((_pair(t, d)[0], d.as_dict())) for t, d in sync.nodes["fn"].iter_data() + ) @pytest.mark.parametrize("whole", [False, True]) @@ -1710,6 +1739,56 @@ def collected(route: str) -> tuple[Any, Any]: assert got.schema.equals(expected.schema) +def test_a_failure_to_close_unsent_snapshot_streams_fails_the_source( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """A source admitted with its snapshot batch streams that sends a projected read + instead closes the unsent streams before its end hook: a failure to close them + fails the source's output like any other failure, so its successor raises and + the source's end is never reported (CodeRabbit on PR #696).""" + + class Unsent: + """Snapshot batch streams that are never read, and fail to close.""" + + def __iter__(self) -> "Unsent": + return self + + def __next__(self) -> Any: + raise AssertionError("the unsent streams were read") + + def close(self) -> None: + raise OSError("closing the unsent scan failed") + + monkeypatch.setattr( + SpiralDBTableSource, "snapshot_batch_streams", lambda self: Unsent() + ) + ends: list[str] = [] + + class Ends(NoOpObserver): + """Records each node's end.""" + + def contextualize(self, *identity_path: str) -> "Ends": + return self + + def on_node_end(self, node_label: str, node_hash: str) -> None: + ends.append(node_label) + + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + SpiralDBTableSource("p", "wide", tag_only_columns=True).select_data_columns( + ["x"], label="sx" + ) + log = InMemoryArrowDatabase() + job.nodes["sx"].attach_databases(pipeline_database=log, cache_mode=CacheMode.LOG) + with pytest.raises(OSError, match="closing the unsent scan failed"): + job.run(orchestrator=AsyncPipelineOrchestrator(), observer=Ends()) + assert ends == [] + assert not any( + (log.get_all_records(path) or pa.table({})).num_rows + for path in log.list_table_paths() + ) + + @pytest.mark.parametrize("materialize_results", [True, False]) def test_a_run_that_keeps_no_result_keeps_no_whole_source_batches( project: Any, monkeypatch: pytest.MonkeyPatch, materialize_results: bool diff --git a/tests/test_pipeline/test_async_batch_region.py b/tests/test_pipeline/test_async_batch_region.py index 8bdba2048..bae2aa870 100644 --- a/tests/test_pipeline/test_async_batch_region.py +++ b/tests/test_pipeline/test_async_batch_region.py @@ -650,6 +650,54 @@ def index(kind: str, label: str) -> int: ) +@pytest.mark.parametrize("buffer_size", [1, 3, 64]) +def test_region_readers_queue_no_more_than_the_orchestrators_buffer_size( + monkeypatch: pytest.MonkeyPatch, buffer_size: int +) -> None: + """A region output's readers queue at most ``BATCH_BUFFER_SIZE`` record batches, + fewer when the orchestrator's buffer size is smaller, and the run shows the sync + run's rows (CodeRabbit on PR #696: a lowered buffer size did not bound the + region's queues).""" + import orcapod.core.streams.base as stream_base + from orcapod.core.record_batch_channels import BATCH_BUFFER_SIZE, OutputChannel + + monkeypatch.setattr(stream_base, "SOURCE_BATCH_ROWS", 2) + sizes: list[int] = [] + original = OutputChannel.__init__ + + def recorded(self: Any, stream: Any, **kwargs: Any) -> None: + sizes.append(kwargs.get("buffer_size", BATCH_BUFFER_SIZE)) + original(self, stream, **kwargs) + + monkeypatch.setattr(OutputChannel, "__init__", recorded) + + def build() -> PipelineJob: + source = DictSource( + [{"k": i, "d1": i, "d3": f"v{i % 3}"} for i in range(12)], + tag_columns=["k"], + tag_only_columns=True, + source_id="numbers", + ) + job = PipelineJob(name="buffered", database=InMemoryArrowDatabase()) + with job: + selected = source.select_data_columns(["d1", "d3"], label="selected") + selected.select_data_columns(["d1"], label="left") + selected.select_data_columns(["d3"], label="right") + return job + + expected = build() + _run(expected, SyncPipelineOrchestrator()) + got = build() + _run(got, AsyncPipelineOrchestrator(buffer_size=buffer_size)) + assert sizes and set(sizes) == {min(buffer_size, BATCH_BUFFER_SIZE)} + for label in ("selected", "left", "right"): + assert ( + got.nodes[label] + .as_table(all_info=True) + .equals(expected.nodes[label].as_table(all_info=True)) + ), label + + def test_a_source_whose_instance_replaces_its_reader_keeps_mains_route( batch_nodes: list[str], ) -> None: diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 619bcb07b..8e113d565 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -1590,6 +1590,8 @@ def pinned_snapshot(self) -> SourceProtocol | None: return None def snapshot_batch_streams(self) -> Iterator[StreamProtocol] | None: + """None: this slot implements the source protocol for the test, with no + per-batch snapshot read.""" return None def to_config( From 99adc19b57e1d51472df981d388154608f7bc033 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 17:49:09 -0800 Subject: [PATCH 14/20] test(compat): compare a shared result store's computed/reused split as a total on async (ITL-1845) The two function nodes of the custom-operator case share one function, so which computes an input and which reuses it follows async scheduling (ITL-1874), on main as here. Async compares each node's rows handled, failed and held, and the run's total computed. Co-Authored-By: Claude Opus 5.5 --- .../test_graph_keys_main_compatibility.py | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/tests/test_pipeline/test_graph_keys_main_compatibility.py b/tests/test_pipeline/test_graph_keys_main_compatibility.py index 56982748f..74e341e99 100644 --- a/tests/test_pipeline/test_graph_keys_main_compatibility.py +++ b/tests/test_pipeline/test_graph_keys_main_compatibility.py @@ -452,7 +452,23 @@ def custom_operator_case(directory: Path, kind: str, mode: str) -> dict[str, Any label: caught(lambda label=label: job.nodes[label].node_hash()) for label in ("ab", "ab_total") } - outcome["summary"] = run(job, mode) + summary = run(job, mode) + if mode == "async": + # The two function nodes share one function, so one result store: which of + # them computes an input and which reuses it follows the async scheduling + # (ITL-1874), on main as here. Each node's rows handled (computed plus + # reused), failed and held, and the run's total computed, do not; the + # split is left out (``None``), the failed and held counts keep their places. + outcome["summary"] = { + label: [None, None, counts[2], counts[3]] + for label, counts in summary.items() + } + outcome["handled"] = { + label: counts[0] + counts[1] for label, counts in summary.items() + } + outcome["computed"] = sum(counts[0] for counts in summary.values()) + else: + outcome["summary"] = summary outcome["rows"] = rows(job) return outcome @@ -938,7 +954,7 @@ def dispatch(args: list[str]) -> Any: raise ValueError(name) -def no_failed_rows(summary: dict[str, list[int]]) -> bool: +def no_failed_rows(summary: dict[str, list[int | None]]) -> bool: """Whether no node of a run summary (``run``'s counts) reports a failed row.""" return all(counts[2] == 0 for counts in summary.values()) From 71131c817517ad95469a5687d58d5494187811e2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 18:21:56 -0800 Subject: [PATCH 15/20] fix(async): admit an own-reader source only when one class defines its reader and its snapshot batches (ITL-1845) CodeRabbit on PR #696: a SpiralDB subclass declaring TABLE_IS_ROWS with its own async_iter_data could be sent the inherited scan. It now keeps main's row route. With column demand, main projects such a subclass past its reader too; that case is pinned to main's behaviour and filed as ITL-1879. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 3 ++- CLAUDE.md | 3 ++- .../dev/specs/itl-1347-job-table-transport.md | 5 +++- src/orcapod/pipeline/async_orchestrator.py | 16 +++++++++++-- .../test_spiraldb_job_projection.py | 24 +++++++++++++++---- 5 files changed, 41 insertions(+), 10 deletions(-) diff --git a/.zed/rules b/.zed/rules index 0109cd6b3..c7ee3c85d 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1632,7 +1632,8 @@ data. The rules: shared_zero_row_memo(). A source with its own async_iter_data joins only where its batches are read exactly as snapshot_batch_streams gives them, asked once when the region is decided, before it is - wired (SourceJobNode.region_snapshot_batches; the streams are what it sends); None + wired (SourceJobNode.region_snapshot_batches; the streams are what it sends), and only + when one class defines both its async_iter_data and its snapshot_batch_streams; None keeps it on main's row route, its own reader; never read it whole in place of that reader. Every region output holds its end (OutputChannel(hold_end=True)) until its node's work after the last batch (kept output, LOG store, modified time, end hook) returned; the orchestrator then diff --git a/CLAUDE.md b/CLAUDE.md index e9bf08eef..dc4a9ddb4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1677,7 +1677,8 @@ data. The rules: channel, never per batch; read it when wiring, inside `shared_zero_row_memo()`. A source with its own `async_iter_data` joins only where its batches are read exactly as `snapshot_batch_streams` gives them, asked once when the region is decided, before it is - wired (`SourceJobNode.region_snapshot_batches`; the streams are what it sends); `None` + wired (`SourceJobNode.region_snapshot_batches`; the streams are what it sends), and only + when one class defines both its `async_iter_data` and its `snapshot_batch_streams`; `None` keeps it on main's row route, its own reader; never read it whole in place of that reader. Every region output holds its end (`OutputChannel(hold_end=True)`) until its node's work after the last batch (kept output, `LOG` store, modified time, end hook) returned; the orchestrator then diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 33800a93d..2db7403dc 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1229,7 +1229,10 @@ the corrections are listed below). Scope, as landed: read exactly as `snapshot_batch_streams` gives them, asked once when the region is decided, before the source is wired (`SourceJobNode.region_snapshot_batches`: the table route, no declared form, the node's data context, a pinned version, and - streams, not `None`, from the method; the streams are what the node sends); + streams, not `None`, from the method; the streams are what the node sends), and + only when one class defines both its `async_iter_data` and its + `snapshot_batch_streams` (a subclass that replaces one and inherits the other + keeps `main`'s route); otherwise it stays on `main`'s row route, its own reader, and is never read whole in its place; - a library unary operator job node whose one input is a region node with declared diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 1219ace1e..db180697c 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -885,9 +885,16 @@ class (every one is row by row or a barrier), whose one input is a region node if not reads_as_its_class(source, kind): continue reads_whole = kind.async_iter_data is StreamBase.async_iter_data - in_batches = isinstance(source, RootSource) and ( - type(source).snapshot_batch_streams + # A source's own reader and its snapshot batches must come from one + # class: a subclass that replaces one of them and inherits the other + # (its reader filtering what the inherited scan sends) stays on main's + # row route. + in_batches = ( + isinstance(source, RootSource) + and type(source).snapshot_batch_streams is not RootSource.snapshot_batch_streams + and _defined_by(kind, "async_iter_data") + is _defined_by(kind, "snapshot_batch_streams") ) if reads_whole: region.add(node) @@ -917,6 +924,11 @@ class (every one is row by row or a barrier), whose one input is a region node return region, snapshots +def _defined_by(kind: type, name: str) -> type | None: + """The class of ``kind``'s method resolution order that defines ``name``.""" + return next((base for base in kind.__mro__ if name in vars(base)), None) + + def _library_unary_operators() -> frozenset[type]: """The library's unary operator classes (exactly these, never a subclass).""" import inspect diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 6deae8b83..5cd79e457 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -1822,18 +1822,26 @@ def recorded(self: Any, batches: Any, **kwargs: Any) -> Any: assert len(list(job.nodes["sy"].iter_data())) == 6 +@pytest.mark.parametrize("read", [["x"], ["x", "y", "blob"]], ids=["one", "all"]) +@pytest.mark.parametrize("declares_rows", [False, True]) @pytest.mark.parametrize("replaced", ["async_iter_data", "snapshot_batch_streams"]) def test_a_subclass_that_replaces_one_reader_keeps_mains_route( - project: Any, replaced: str + project: Any, replaced: str, declares_rows: bool, read: list[str] ) -> None: """A keyed source subclass that replaces only its async reader, or only its snapshot batches, is not read through its batches in an async job: it stays on main's row route, so its own async reader runs, as on main (CodeRabbit on PR - #696). ``reads_snapshot_batches`` admits only a library source kind's exact - class (``table_is_rows``), so any subclass keeps main's route.""" + #696). A subclass is kept off the batch route by ``table_is_rows`` (a library + source kind's exact class), and, when it declares ``TABLE_IS_ROWS`` itself, by + the rule that its async reader and its snapshot batches come from one class + (CodeRabbit on PR #696: such a subclass was sent the inherited scan); read with + one column and with every column.""" calls: list[str] = [] class OwnReader(SpiralDBTableSource): + if declares_rows: + TABLE_IS_ROWS = True + if replaced == "async_iter_data": async def async_iter_data( # pyright: ignore[reportImplicitOverride] # the reader under test @@ -1854,11 +1862,17 @@ def snapshot_batch_streams( # pyright: ignore[reportImplicitOverride] # the ba job = PipelineJob(name="j", database=InMemoryArrowDatabase()) with job: OwnReader("p", "wide", tag_only_columns=True).select_data_columns( - ["x"], label="sx" + read, label="sx" ) job.run(orchestrator=AsyncPipelineOrchestrator()) rows = len(list(job.nodes["sx"].iter_data())) - if replaced == "async_iter_data": + if replaced == "async_iter_data" and declares_rows and read == ["x"]: + # Main's behaviour, kept: with column demand, a subclass that declares + # ``TABLE_IS_ROWS`` is projected past its own reader on main's route too + # (ITL-1798's gate; pre-existing, ITL-1879). + assert calls == [] + assert rows == 6 + elif replaced == "async_iter_data": assert calls == ["async"] assert rows == 2 else: From c10ec1819b3beb59e5d0a69a74594cc7b9bcfa0e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 18:46:54 -0800 Subject: [PATCH 16/20] fix(async): a buffer size below 1 makes the region's reader queues unbounded, as the row channels (ITL-1845) CodeRabbit on PR #696: a nonpositive buffer_size (unbounded asyncio row queues on main) made OutputChannel raise for a graph with region nodes. Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 3 ++- src/orcapod/pipeline/async_orchestrator.py | 22 +++++++++++++++++-- .../test_pipeline/test_async_batch_region.py | 12 +++++++--- 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 2db7403dc..846efb66a 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1381,7 +1381,8 @@ Answers to the spec's questions (developer, 2026-11-22, approving the spec as a - an operator sends its result's own record batches; - an input channel queues 8 batches, fewer when the async orchestrator's `buffer_size` is smaller (`min(buffer_size, BATCH_BUFFER_SIZE)` for a region - output's readers), so lowering it bounds the region's queues too. + output's readers), so lowering it bounds the region's queues too; a `buffer_size` below 1 (unbounded + row channels) makes them unbounded. 7. **Signatures change directly in each stage** on `eywalker/job-speed`, with no thin forms of the old ones. `main` sees one breaking change, at the branch merge. 8. **`node_outputs` holds each node's output stream** (refining decision 1). diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index db180697c..1bee7d729 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -8,6 +8,7 @@ from __future__ import annotations import asyncio +import sys import contextlib import contextvars import logging @@ -282,11 +283,12 @@ async def _run_async( # after its last batch succeeded (``_start_region_node``). A # reader of an output that keeps no batch queues at most # ``BATCH_BUFFER_SIZE`` batches, fewer when the orchestrator's - # buffer size is smaller, so lowering it bounds the region too. + # buffer size is smaller, so lowering it bounds the region too + # (``_region_buffer_size``). batch_outputs[node] = OutputChannel( description, retain=retain, - buffer_size=min(buf, BATCH_BUFFER_SIZE), + buffer_size=_region_buffer_size(buf, BATCH_BUFFER_SIZE), hold_end=True, ) try: @@ -924,6 +926,22 @@ class (every one is row by row or a barrier), whose one input is a region node return region, snapshots +def _region_buffer_size(buffer_size: int, batch_buffer_size: int) -> int: + """How many record batches a region output's reader queues. + + At most ``batch_buffer_size``, fewer when the orchestrator's ``buffer_size`` is + smaller. A ``buffer_size`` below 1 makes the row channels unbounded + (``asyncio.Queue``), so it makes the region's queues unbounded too. + + Args: + buffer_size: The orchestrator's buffer size (rows per row channel). + batch_buffer_size: The record-batch channels' default queue length. + """ + if buffer_size < 1: + return sys.maxsize + return min(buffer_size, batch_buffer_size) + + def _defined_by(kind: type, name: str) -> type | None: """The class of ``kind``'s method resolution order that defines ``name``.""" return next((base for base in kind.__mro__ if name in vars(base)), None) diff --git a/tests/test_pipeline/test_async_batch_region.py b/tests/test_pipeline/test_async_batch_region.py index bae2aa870..4fb27279a 100644 --- a/tests/test_pipeline/test_async_batch_region.py +++ b/tests/test_pipeline/test_async_batch_region.py @@ -650,14 +650,17 @@ def index(kind: str, label: str) -> int: ) -@pytest.mark.parametrize("buffer_size", [1, 3, 64]) +@pytest.mark.parametrize("buffer_size", [-1, 0, 1, 3, 64]) def test_region_readers_queue_no_more_than_the_orchestrators_buffer_size( monkeypatch: pytest.MonkeyPatch, buffer_size: int ) -> None: """A region output's readers queue at most ``BATCH_BUFFER_SIZE`` record batches, fewer when the orchestrator's buffer size is smaller, and the run shows the sync run's rows (CodeRabbit on PR #696: a lowered buffer size did not bound the - region's queues).""" + region's queues). A buffer size below 1, unbounded row channels, makes the + region's queues unbounded too, never an error (CodeRabbit on PR #696).""" + import sys + import orcapod.core.streams.base as stream_base from orcapod.core.record_batch_channels import BATCH_BUFFER_SIZE, OutputChannel @@ -689,7 +692,10 @@ def build() -> PipelineJob: _run(expected, SyncPipelineOrchestrator()) got = build() _run(got, AsyncPipelineOrchestrator(buffer_size=buffer_size)) - assert sizes and set(sizes) == {min(buffer_size, BATCH_BUFFER_SIZE)} + expected_size = ( + min(buffer_size, BATCH_BUFFER_SIZE) if buffer_size >= 1 else sys.maxsize + ) + assert sizes and set(sizes) == {expected_size} for label in ("selected", "left", "right"): assert ( got.nodes[label] From ece7e0c1c0804f1759ecdf2b2e0f3345ca9ee1ce Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 20:30:38 -0800 Subject: [PATCH 17/20] fix(async_orchestrator): leave a source that cannot answer on the row route (ITL-1845) A source node whose snapshot batch streams cannot be asked for while the batch region is decided (a closed source) stays on main's row route, where its own task reads it and raises, instead of stopping the run before any task starts. Adds that regression test and a test pinning the sync types of an empty region result over an all-null source column. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/async_orchestrator.py | 17 ++++++- .../test_spiraldb_job_projection.py | 49 ++++++++++++++++++- .../test_pipeline/test_async_batch_region.py | 39 +++++++++++++++ 3 files changed, 103 insertions(+), 2 deletions(-) diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 1bee7d729..bd0558df8 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -906,7 +906,8 @@ class (every one is row by row or a barrier), whose one input is a region node # it is wired: streams admit it, and are what it sends; ``None`` (no # per-batch snapshot read) keeps it on main's row route, its own # ``async_iter_data``. - streams = source_node.region_snapshot_batches() if in_batches else None + # A source that cannot answer stays there too (``_admitted_snapshot_batches``). + streams = _admitted_snapshot_batches(source_node) if in_batches else None if streams is not None: region.add(node) snapshots[id(node)] = streams @@ -926,6 +927,20 @@ class (every one is row by row or a barrier), whose one input is a region node return region, snapshots +def _admitted_snapshot_batches(source_node: Any) -> Any: + """A source node's snapshot batch streams, asked when the region is decided, or + ``None``: the node stays on main's row route. + + A source that cannot answer (a closed source, a failing pin) is left on main's + row route rather than stopping the run before any task starts: there its own + task reads it and raises, as on main, while the run's other nodes start. + """ + try: + return source_node.region_snapshot_batches() + except Exception: # noqa: BLE001 # in doubt: main's row route, whose read raises it + return None + + def _region_buffer_size(buffer_size: int, batch_buffer_size: int) -> int: """How many record batches a region output's reader queues. diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 5cd79e457..50718122b 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -31,6 +31,7 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream, pending_whole_read from orcapod.core.sources import spiraldb_table_source as source_module from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import SourceCheckFailedWarning from orcapod.databases import spiraldb_connector as connector_module from orcapod.pipeline import ( AsyncPipelineOrchestrator, @@ -42,7 +43,7 @@ from orcapod.pipeline.dag import OrcaDAG from orcapod.pipeline.observer import NoOpObserver from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol -from orcapod.sources import SpiralDBTableSource +from orcapod.sources import DictSource, SpiralDBTableSource from orcapod.types import CacheMode, ColumnConfig, Condition from tests.test_databases import fake_spiral_sdk as fake @@ -1789,6 +1790,52 @@ def on_node_end(self, node_label: str, node_hash: str) -> None: ) +@pytest.mark.parametrize("read", [["x"], ["x", "y", "blob"]], ids=["one", "all"]) +def test_a_closed_source_fails_in_its_own_task_as_on_main( + project: Any, read: list[str] +) -> None: + """A keyed source closed before an async run, beside an independent in-memory + branch: as on main, every node's task starts (the closed source's node, its + successor and the other branch) and the run raises the source's own error from + its node's read, never while the batch region is decided before any task starts + (CodeRabbit on PR #696).""" + starts: list[str] = [] + + class Starts(NoOpObserver): + """Records each node's start.""" + + def contextualize(self, *identity_path: str) -> "Starts": + return self + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + starts.append(node_label) + + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + source.select_data_columns(read, label="sx") + DictSource( + [{"k": 1, "v": 2, "w": 3}, {"k": 2, "v": 4, "w": 5}], + tag_columns=["k"], + tag_only_columns=True, + source_id="other", + ).select_data_columns(["v", "w"], label="other_selected") + source.close() + with ( + pytest.warns(SourceCheckFailedWarning, match="is closed"), + pytest.raises(RuntimeError, match="SpiralDBTableSource is closed"), + ): + job.run(orchestrator=AsyncPipelineOrchestrator(), observer=Starts()) + spiral_node = next( + label + for label, node in job.nodes.items() + if node.node_type == "source" and label != "other" + ) + assert {spiral_node, "sx", "other", "other_selected"} <= set(starts) + + @pytest.mark.parametrize("materialize_results", [True, False]) def test_a_run_that_keeps_no_result_keeps_no_whole_source_batches( project: Any, monkeypatch: pytest.MonkeyPatch, materialize_results: bool diff --git a/tests/test_pipeline/test_async_batch_region.py b/tests/test_pipeline/test_async_batch_region.py index 4fb27279a..27f007088 100644 --- a/tests/test_pipeline/test_async_batch_region.py +++ b/tests/test_pipeline/test_async_batch_region.py @@ -650,6 +650,45 @@ def index(kind: str, label: str) -> int: ) +@pytest.mark.parametrize("operator", ["filter", "drop_nulls"]) +def test_an_empty_region_result_over_an_all_null_column_has_the_sync_types( + operator: str, +) -> None: + """A region operator that drops every row of a source whose data column holds + only nulls: its empty async result has the sync run's columns and types, the + column ``large_string`` as the source declares it, never Arrow ``null``. A + source refuses a column of Arrow type ``null`` at any depth, so no region input + declares one (CodeRabbit on PR #696).""" + + def build() -> PipelineJob: + source = DictSource( + [ + {"k": 1, "n": None, "w": 1, "v": "a"}, + {"k": 2, "n": None, "w": 2, "v": "b"}, + ], + tag_columns=["k", "w"], + tag_only_columns=True, + source_id="all_null", + ) + job = PipelineJob(name="all_null", database=InMemoryArrowDatabase()) + with job: + selected = source.select_data_columns(["n", "v"], label="selected") + if operator == "filter": + selected.filter(v="none", label="emptied") + else: + selected.drop_nulls(["n"], label="emptied") + return job + + expected = build() + _run(expected, SyncPipelineOrchestrator()) + got = build() + _run(got, AsyncPipelineOrchestrator()) + table = got.nodes["emptied"].as_table(all_info=True) + assert table.num_rows == 0 + assert table.schema.field("n").type == pa.large_string() + assert table.schema.equals(expected.nodes["emptied"].as_table(all_info=True).schema) + + @pytest.mark.parametrize("buffer_size", [-1, 0, 1, 3, 64]) def test_region_readers_queue_no_more_than_the_orchestrators_buffer_size( monkeypatch: pytest.MonkeyPatch, buffer_size: int From 708a0533eaa16c2a63abb2af2f1790d0513c87c6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 21:20:30 -0800 Subject: [PATCH 18/20] fix(async_orchestrator): own admitted snapshot streams until the source task begins (ITL-1845) The orchestrator now holds the snapshot batch streams it acquired while deciding the batch region until each source node's task begins and takes its own; streams no task took (a setup failure, a partial admission, a cancellation before a task began) are closed when the run ends. Also words the e9 end-hook placement as before the readers see the end, and says the wide differential fixture uses several unary operators. Co-Authored-By: Claude Opus 5.5 --- docs/dev/scripts/itl_1347/fixtures.py | 8 +- .../dev/specs/itl-1347-job-table-transport.md | 2 +- src/orcapod/pipeline/async_orchestrator.py | 72 ++++++++++++++--- .../test_pipeline/test_async_batch_region.py | 77 +++++++++++++++++++ 4 files changed, 143 insertions(+), 16 deletions(-) diff --git a/docs/dev/scripts/itl_1347/fixtures.py b/docs/dev/scripts/itl_1347/fixtures.py index 6b00f98a4..5c946e19e 100644 --- a/docs/dev/scripts/itl_1347/fixtures.py +++ b/docs/dev/scripts/itl_1347/fixtures.py @@ -13,7 +13,8 @@ ``PolarsFilter``, ``AddTags``, ``DropNulls``, ``MapData`` and ``Rejoin`` beside it, and a side effect at the end. Every operator of the stage-5 classification appears once. - ``wide``: stage 5a's batch region (ITL-1845): the spike table twice, more than one - source record batch with the stock dataset, through every kind of unary operator. + source record batch with the stock dataset, through several unary operators (not + every kind: the public job tests of the batch region cover every unary operator). """ from __future__ import annotations @@ -192,8 +193,9 @@ def wide_table(data_dir: Path) -> pa.Table: def build_wide(data_dir: Path, database: Any) -> Any: """Stage 5a's batch region (ITL-1845): the spike table twice (``wide_table``), above 65,536 rows with the stock dataset so the in-memory source sends several - record batches, through every kind of unary operator, two chained, then a select - and a function node on several branches.""" + record batches, through several unary operators (not every kind; the public job + tests of the batch region cover every one), two chained, then a select and a + function node on several branches.""" from orcapod import PipelineJob, function_pod from orcapod.sources import ArrowTableSource diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 1cd1b2290..81e5e222a 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -551,7 +551,7 @@ is unsupported; what the run then does is undefined and is not part of the equal | e6 | Async values that depend on an earlier validation of the same operator object | `SemiJoin._validated_common_keys` and `Index._element_arrow_type_fallback` hold the last validation's values (ITL-858, section 1.2). One operator object applied to two streams can use the other stream's keys or fallback type | Read from each input's description, with no state | The ITL-858 finding; filed as ITL-1358. Reproducer: one `SemiJoin` instance validated on stream B, then run async over stream A with other keys. To be confirmed in stage 5 | ITL-1358 (filed); fixed with stage 5 once a reproducer confirms it | | e7 | What a consumer does after its producer failed (async, failure path) | The producer closes its output in `finally`, so a consumer's input ends normally; whether a `LOG` operator node after it stores a partial result depends on whether the task group's cancellation reaches it first | Stage 5a (ITL-1845), inside the batch region only: a region node's readers raise `UpstreamFailedError` at the failure point instead of seeing a normal end, so a region operator never finishes, keeps or stores its output as if its input were complete. **A region `LOG` node stores nothing after an upstream failure, by construction**: it reads the failure from its input channel, raises, and never reaches its store; it no longer depends on cancellation timing. That holds also for a failure after the producer's last batch: a region output holds its end from its readers (`OutputChannel(hold_end=True)`) until the producing node's own work after it succeeded (its kept output, `LOG` store, modified time and end hook), and the orchestrator releases it (`release_end`) only when the node returned; a failure there fails the output, so a reader raises `UpstreamFailedError`, never ends normally. Batches still flow while the producer runs. Batches a consumer processed before the failure stay processed, and a function node after the region keeps the results it stored for them, as on `main` (no rollback). At a row boundary the adapter turns the failure into `main`'s normal row-channel close, so nodes outside the region see what they see on `main`. The run raises the producer's own error, as today | **No observable difference found on `main` 2075e85e2**: the stored outcome is unchanged (nothing stored). Reproducers, run on `main` and on the branch: a keyed scan that fails on its third record batch, feeding a `Select` in `LOG` mode (5 runs under each error policy, 10 in all: 0 rows stored every time), and a `fail_fast` function node raising on row 3 of 6 feeding a `Select` in `LOG` mode (5 runs: 0 rows stored). The independent review of PR #696 found a region operator whose `LOG` write or end hook failed after its last batch: `main` stores 0 rows downstream under both policies, the reviewed head stored 5, the fixed branch 0 (`test_a_producer_failing_after_its_last_batch_stores_nothing_downstream`, a failed write and a failing end hook, both policies). The row documents the internal signal change; the cases are tests that pass on `main` and the branch, with no timing assumption (`test_a_logging_operator_stores_nothing_after_its_source_fails_mid_scan`, `test_a_logging_operator_after_a_failing_function_stores_nothing`) | documented; no approval needed unless the developer asks | | e8 | Meta columns of an async side-effect node's rows | An async side-effect node passes on and holds the rows it receives as they are, so a computed row keeps its `__computed` meta column (from the cached function pod), and the node's `as_table(all_info=True)` shows it. On sync, its input is rebuilt from rows (`_rows_to_table` drops meta), so the column is absent | Async drops input meta columns as sync does. With table transport this follows from the transport columns, which hold no meta column | A `main` bug: the async and sync paths give the node different columns. Found by the stage 0 harness on `job-speed` 0e15d0db, which does not change side-effect nodes; the stage 0 differential checks it on pinned `main`. Reproducer: a function node (with a result store) feeding a `tap_pod`, async against sync, comparing the side-effect node's `as_table(all_info=True)` columns | approved (developer, 2026-11-22) | -| e9 | Observer events across nodes, async (batch region) | Upstream end events (`on_node_end` of a source or operator) fall among a downstream node's data events at the granularity of one row: a source ends after about 16 rows have reached the function node, a `Select` after about 135 (in-memory, 200 rows); an off-loop keyed scan interleaves the same way | What the code does: a region node calls `on_node_start` when its task starts and `on_node_end` after its last send, before its output closes (`main`'s placement). So: each node's start comes before its own data events, and its successful end after its own last send; successful ends stay in dependency order; a function node's row starts keep arrival order. Where an upstream end falls relative to a downstream node's data events depends on record batches, backpressure and scheduling: a record batch is the unit of delivery, so with in-memory sources (one record batch up to 65,536 rows) every upstream end can come before the first downstream data event, and with a scan that sends several batches (a keyed scan waiting on its next read) a downstream function node's row events can come before the source's end, as on `main`. Completion order within a function node (its `on_data_end` events) depends on scheduling, as on `main`. Observed by the delta review of PR #696: in the 73,232-row wide fixture, branch async ends the source and the selector feeding the all-rows function at events 2 and 9, before any of its rows starts, while main async's first source end comes after 73,051 of them; the three function nodes complete their rows in another order, their other events equal | Not a `main` bug: `main`'s interleaving itself depends on buffer sizes and timing, and no rule fixes it. The pinned-`main` observer test (`test_observer_main_compatibility.py`) exempts the end events of the region nodes by name (the source node and `SelectDataColumns`, `REGION_NODES`), checks their own order, and checks that both were exempted; `test_observer_events_keep_mains_invariants` asserts exactly the rules above (each node's start before its own data events and sends, its end after them; ends in dependency order; the function node's row starts in the sync run's order, each row ending once after it started), with one record batch and with several | approved (coordinator, 2026-12-02) | +| e9 | Observer events across nodes, async (batch region) | Upstream end events (`on_node_end` of a source or operator) fall among a downstream node's data events at the granularity of one row: a source ends after about 16 rows have reached the function node, a `Select` after about 135 (in-memory, 200 rows); an off-loop keyed scan interleaves the same way | What the code does: a region node calls `on_node_start` when its task starts and `on_node_end` after its last send, before its readers see the end of its output (`main`'s placement: the end hook precedes the end its readers read). A region operator closes its output for writes after its last batch (to assemble the output it keeps), then its node calls the end hook, then the orchestrator releases the held end and the readers see it: observed as close (no end seen yet), hook, release (end seen); a region source calls its end hook before it closes its output. So: each node's start comes before its own data events, and its successful end after its own last send; successful ends stay in dependency order; a function node's row starts keep arrival order. Where an upstream end falls relative to a downstream node's data events depends on record batches, backpressure and scheduling: a record batch is the unit of delivery, so with in-memory sources (one record batch up to 65,536 rows) every upstream end can come before the first downstream data event, and with a scan that sends several batches (a keyed scan waiting on its next read) a downstream function node's row events can come before the source's end, as on `main`. Completion order within a function node (its `on_data_end` events) depends on scheduling, as on `main`. Observed by the delta review of PR #696: in the 73,232-row wide fixture, branch async ends the source and the selector feeding the all-rows function at events 2 and 9, before any of its rows starts, while main async's first source end comes after 73,051 of them; the three function nodes complete their rows in another order, their other events equal | Not a `main` bug: `main`'s interleaving itself depends on buffer sizes and timing, and no rule fixes it. The pinned-`main` observer test (`test_observer_main_compatibility.py`) exempts the end events of the region nodes by name (the source node and `SelectDataColumns`, `REGION_NODES`), checks their own order, and checks that both were exempted; `test_observer_events_keep_mains_invariants` asserts exactly the rules above (each node's start before its own data events and sends, its end after them; ends in dependency order; the function node's row starts in the sync run's order, each row ending once after it started), with one record batch and with several | approved (coordinator, 2026-12-02) | | e10 | The class of a region node's collected async output (`OrchestratorResult.node_outputs`) | An async node's output is `RowsOnRead` over its collected rows, which compares unequal to the sync route's output stream of the same rows | A region node that sent rows gives its output channel's `result()` (for a source with column demand, the whole read, as on sync), the sync route's stream form: the same rows, table, types and hashes, and it now compares equal to the sync output, with an equal hash, except a `PolarsFilter` node's output, whose direct equality raises on both routes and on `main` (ITL-1877): its streams are compared by content hash. A region node that sent no row (a filter matching nothing, the nodes after it, every node over a source with no rows, also a source that sends a narrowed form of its whole read) is collected as the sync route collects it, a `RowsOnRead` of no rows, so the two routes give one form, empty or not; a `RowsOnRead` compares by object on both routes (as a function node's output does on `main`), and its stream compares and hashes equal to the sync one. A projected source's whole read still happens once, when the output is first read | Not a bug on `main`, a form change: the equality between the two routes' outputs followed from their classes, not their rows (`test_outputs_of_two_routes_compare_and_hash_as_main`; empty and non-empty: `test_collected_outputs_compare_and_hash_as_the_sync_runs`) | approved (coordinator, 2026-12-02) | **Resolved: refusals after rows have flowed (was c, question 9).** The developer's `Rejoin` diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index bd0558df8..98b382a66 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -232,6 +232,12 @@ async def _run_async( database_error: OrcapodDatabaseError | TypeIdentityError | None = None # id of each exception a node raised -> that node's label. failed_nodes: dict[int, str] = {} + # The snapshot batch streams the region's sources were admitted with, by node + # id: the orchestrator owns each until its source node's task begins and takes + # it (``_start_region_node``); any still here when the run ends (a setup + # failure, a partial admission, a cancellation before a task started) are + # closed by this method (``_close_owned_snapshots``). + snapshots: dict[int, Any] = {} try: topo_order = list(graph.topological_sort()) buf = self._buffer_size @@ -266,7 +272,7 @@ async def _run_async( # (each node derived once, not once per channel and per upstream path); # the memo ends before any task starts. with shared_zero_row_memo(): - region, snapshots = _batch_region(topo_order, in_edges, held_rows) + region = _batch_region(topo_order, in_edges, held_rows, snapshots) for node in topo_order: if node not in region: continue @@ -378,7 +384,7 @@ def collected_output( whole_outputs=whole_outputs, load_only=load_only, keep_whole=materialize_results, - snapshot_streams=snapshots.get(id(node)), + snapshots=snapshots, ) continue writer = node_output_channels[node].writer @@ -527,9 +533,13 @@ def collected_output( # raises it: a row's error under fail_fast, a side effect's delivery error. raise _single_failure(group, topo_order, failed_nodes) finally: - # A failing on_run_end must not replace a failed database read or write. - with keep_database_error(database_error, "Observer on_run_end"): - effective_observer.on_run_end(run_id) + try: + _close_owned_snapshots(snapshots) + finally: + # A failing on_run_end must not replace a failed database read or + # write. + with keep_database_error(database_error, "Observer on_run_end"): + effective_observer.on_run_end(run_id) async def _source_execution( @@ -823,7 +833,8 @@ def _batch_region( topo_order: list[Any], in_edges: Mapping[Any, list[Any]], held_rows: Mapping[Any, Any] | None, -) -> tuple[set[Any], dict[int, Any]]: + snapshots: dict[int, Any], +) -> set[Any]: """The nodes of a run whose outputs travel as Arrow record batches (ITL-1347, stage 5a), and the snapshot batch streams of the region's sources that read their rows their own way. @@ -847,6 +858,10 @@ class (every one is row by row or a barrier), whose one input is a region node topo_order: The run's nodes, in topological order. in_edges: Each node's inputs, in the operator's order. held_rows: The nodes the run holds rather than runs. + snapshots: Where the snapshot batch streams asked for are put, by node id, + each as soon as it is acquired: the caller owns them from then on, and + closes those no source task took (a later admission or setup step that + raises leaves none open). A source with its own ``async_iter_data`` is admitted only when its ``snapshot_batch_streams``, asked here, once, before the source is wired into the @@ -855,7 +870,7 @@ class (every one is row by row or a barrier), whose one input is a region node per-batch snapshot read) keeps it on main's row route, its own reader. Returns: - The region's nodes, and the snapshot batch streams asked for, by node id. + The region's nodes. """ from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode @@ -864,7 +879,6 @@ class (every one is row by row or a barrier), whose one input is a region node unary = _library_unary_operators() region: set[Any] = set() - snapshots: dict[int, Any] = {} # Whether each region node declares its Arrow types, asked once per node. declared: dict[int, bool] = {} for node in topo_order: @@ -924,7 +938,36 @@ class (every one is row by row or a barrier), whose one input is a region node ): region.add(node) declared[id(node)] = operator_node.arrow_types_declared - return region, snapshots + return region + + +def _close_owned_snapshots(snapshots: dict[int, Any]) -> None: + """Close the snapshot batch streams no source node's task took, emptying + ``snapshots``. + + Every one is closed, also after another's close failed. When the run is raising, + a close failure is noted on that exception; otherwise the first is raised. + """ + failures: list[Exception] = [] + while snapshots: + _, streams = snapshots.popitem() + close = getattr(streams, "close", None) + if not callable(close): + continue + try: + _ = close() + except Exception as failure: # noqa: BLE001 # every stream is closed first + failures.append(failure) + if not failures: + return + raising = sys.exception() + if raising is None: + raise failures[0] + for failure in failures: + raising.add_note( + "Closing snapshot batch streams no source task took also failed: " + + f"{type(failure).__name__}: {failure}" + ) def _admitted_snapshot_batches(source_node: Any) -> Any: @@ -988,7 +1031,7 @@ def _start_region_node( whole_outputs: dict[int, Any], load_only: bool, keep_whole: bool, - snapshot_streams: Any = None, + snapshots: dict[int, Any], ) -> None: """Start a region node's record-batch form (ITL-1347, stage 5a). @@ -1009,13 +1052,18 @@ def _start_region_node( load_only: Whether the run is load-only. keep_whole: Whether a source node keeps its whole batches when it sends a narrowed form of them (only when the run's results are collected). - snapshot_streams: The snapshot batch streams a source node that reads its - rows its own way was admitted with (``_batch_region``), or ``None``. + snapshots: The snapshot batch streams the region's sources were admitted + with, by node id (``_batch_region``), owned by the orchestrator: a source + node's task takes its own when it begins, so streams of a task that + never began stay with the orchestrator, which closes them. """ if is_source_node(node): source_node = cast("SourceJobNode", node) async def source_work() -> None: + # The streams pass to the node here, as its task begins, with no await + # point before ``async_execute_batches`` owns them. + snapshot_streams = snapshots.pop(id(node), None) whole = await source_node.async_execute_batches( output, observer=observer, diff --git a/tests/test_pipeline/test_async_batch_region.py b/tests/test_pipeline/test_async_batch_region.py index 27f007088..e553ac8fc 100644 --- a/tests/test_pipeline/test_async_batch_region.py +++ b/tests/test_pipeline/test_async_batch_region.py @@ -1021,3 +1021,80 @@ def build() -> PipelineJob: else: assert left == right, label assert hash(left) == hash(right), label + + +def test_snapshot_streams_of_sources_whose_tasks_never_began_are_closed() -> None: + """The snapshot batch streams a source was admitted to the region with belong to + the orchestrator until the source node's task begins: when the run's setup fails + after the region was decided (a function node given two inputs), so that no + source task begins, every stream acquired is closed and none is left open + (second delta review of PR #696, finding 1: two acquired, none closed).""" + acquired: list[str] = [] + closed: list[str] = [] + + class Streams: + def __init__(self, source: ArrowTableSource) -> None: + self.source: ArrowTableSource | None = source + acquired.append(source.source_id) + self.name = source.source_id + + def __iter__(self) -> Iterator[ArrowTableSource]: + return self + + def __next__(self) -> ArrowTableSource: + if self.source is None: + raise StopIteration + source, self.source = self.source, None + return source + + def close(self) -> None: + closed.append(self.name) + + class Pinned(ArrowTableSource): + TABLE_IS_ROWS = True + + def pinned_snapshot(self) -> "Pinned": # pyright: ignore[reportImplicitOverride] # the snapshot under test + return self + + def snapshot_batch_streams(self) -> Streams: # pyright: ignore[reportImplicitOverride, reportIncompatibleMethodOverride] # the streams under test + return Streams(self) + + async def async_iter_data( # pyright: ignore[reportImplicitOverride] # the reader under test + self, + ) -> AsyncIterator[tuple[Any, Any]]: + streams = self.snapshot_batch_streams() + try: + for stream in streams: + for row in stream.iter_data(): + yield row + finally: + streams.close() + + @function_pod(output_keys="z") + def increment(x: int) -> int: + return x + 1 + + from orcapod.pipeline.dag import OrcaDAG + + table = pa.Table.from_pydict( + {"k": [0, 1], "x": [1, 2]}, + schema=pa.schema([pa.field(c, pa.int64(), False) for c in ("k", "x")]), + ) + job = PipelineJob(name="setup_failure", database=InMemoryArrowDatabase()) + with job: + left = Pinned(table, tag_columns=["k"], tag_only_columns=True, source_id="left") + right = Pinned( + table, tag_columns=["k"], tag_only_columns=True, source_id="right" + ) + increment.pod(left, label="fn") + right.select_data_columns(["x"], label="right_select") + graph: OrcaDAG[Any] = OrcaDAG() + graph.add_edge(job.nodes["left"], job.nodes["fn"]) + graph.add_edge(job.nodes["right"], job.nodes["fn"]) + with warnings.catch_warnings(): + # The tasks the failed setup created are cancelled before they begin. + warnings.simplefilter("ignore", RuntimeWarning) + with pytest.raises(ValueError, match="expects exactly 1 upstream, got 2"): + asyncio.run(AsyncPipelineOrchestrator().run_async(graph)) + assert len(acquired) == 2 + assert sorted(closed) == sorted(acquired) From 5f0dceeb041bb124c72c7cd93cd7db5c450a5591 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 23:15:39 -0800 Subject: [PATCH 19/20] fix(spiraldb): refuse a pinned snapshot's batches as the source's first scan would (ITL-1845) A keyed SpiralDB source admitted to the async batch region sends the batch streams of a pinned snapshot taken when the region is decided. A refusal its check recorded (or a close) after that and before the node's first scan was not seen by the copy, so the region delivered rows where main's row route raises. The snapshot's batch streams now run the source's own checks before their first scan. Also states the batch region's queue bound in record batches (buffer_size batches of at most the producer's batch size in rows). Co-Authored-By: Claude Opus 5.5 --- .../dev/specs/itl-1347-job-table-transport.md | 10 +++- .../core/sources/spiraldb_table_source.py | 28 +++++++++-- src/orcapod/pipeline/async_orchestrator.py | 6 ++- .../test_spiraldb_job_projection.py | 47 +++++++++++++++++++ 4 files changed, 85 insertions(+), 6 deletions(-) diff --git a/docs/dev/specs/itl-1347-job-table-transport.md b/docs/dev/specs/itl-1347-job-table-transport.md index 81e5e222a..4c513ba59 100644 --- a/docs/dev/specs/itl-1347-job-table-transport.md +++ b/docs/dev/specs/itl-1347-job-table-transport.md @@ -1377,12 +1377,20 @@ Answers to the spec's questions (developer, 2026-11-22, approving the spec as a one column property `arrow_schema()` does not declare, so stored field flags and the operator node's record hashes stay as they are. 6. **Batch and buffer sizes**: - - a source sends Arrow record batches of at most 65,536 rows; + - a source read whole sends Arrow record batches of at most 65,536 rows + (`SOURCE_BATCH_ROWS`); a source that reads in batches (a keyed SpiralDB table) + sends one record batch per batch it reads, of at most its own `batch_rows` rows + (8,192 by default), so the transport sets no row limit of its own; - an operator sends its result's own record batches; - an input channel queues 8 batches, fewer when the async orchestrator's `buffer_size` is smaller (`min(buffer_size, BATCH_BUFFER_SIZE)` for a region output's readers), so lowering it bounds the region's queues too; a `buffer_size` below 1 (unbounded row channels) makes them unbounded. + - The bound is in record batches, not rows or bytes: the record batch is the unit of + delivery. A region reader holds at most `min(buffer_size, 8)` queued batches, each of + at most its producer's batch size in rows (`batch_rows` for a batched source), so + the rows and bytes it holds depend on that batch size and the columns' width. + This holds also in a run that collects no result. 7. **Signatures change directly in each stage** on `eywalker/job-speed`, with no thin forms of the old ones. `main` sees one breaking change, at the branch merge. 8. **`node_outputs` holds each node's output stream** (refining decision 1). diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index f00d6e11e..bced8f4da 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -425,6 +425,10 @@ def __init__( # a schema record that cannot be read): every read refuses with it, before # scanning, until a check accepts the table again. self._refusal: ValueError | InputValidationError | None = None + # The source a pinned snapshot was taken of (``pinned_snapshot``): its + # snapshot batch streams refuse, before their first scan, what a read of + # that source would refuse then. ``None`` for every other source. + self._snapshot_of: SpiralDBTableSource | None = None # The default tags are the primary key, whatever identifies the rows. resolved_tags = ( @@ -673,6 +677,7 @@ def _copy(self) -> "SpiralDBTableSource": duplicate._check_lock = Lock() duplicate._content_hash_cache = {} duplicate._pipeline_hash_cache = {} + duplicate._snapshot_of = None return duplicate def _apply_restriction(self, condition: Condition) -> None: @@ -1201,9 +1206,21 @@ def snapshot_batch_streams(self) -> "Iterator[ArrowTableStream]": at a time, read as they are asked for (ITL-1347, stage 5a). Nothing is read until the first stream is asked for; the caller closes the - generator (on the thread that reads it) when it stops early. + generator (on the thread that reads it) when it stops early. On a pinned + snapshot (``pinned_snapshot``), the first stream asked for first checks the + source it was taken of as that source's own first scan would: a closed source, + or a refusal its latest check recorded, raises before anything is scanned, as + ``async_iter_data`` of that source raises then. """ - return self._batch_streams() + return self._snapshot_streams() + + def _snapshot_streams(self) -> Generator["ArrowTableStream", None, None]: + """``snapshot_batch_streams``' generator: the origin's checks, then the scan.""" + origin = self._snapshot_of + if origin is not None: + # Closed, another process, or a held refusal: raised as its read would. + _ = origin._pinned_table() + yield from self._batch_streams() @override def pinned_snapshot(self) -> "SpiralDBTableSource": @@ -1212,9 +1229,12 @@ def pinned_snapshot(self) -> "SpiralDBTableSource": Every read scans the pinned table handle, an immutable snapshot of one version; a later ``check_for_new_data`` on this source replaces this source's handle and pin, never the copy's. The copy has this source's identity, keys, - restriction and modified time. + restriction and modified time. Its ``snapshot_batch_streams`` refuse, before + their first scan, what a read of this source would refuse then. """ - return self._copy() + snapshot = self._copy() + snapshot._snapshot_of = self + return snapshot @override def projected_table( diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 98b382a66..7aa1a8e1f 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -72,7 +72,11 @@ class AsyncPipelineOrchestrator: signatures. Args: - buffer_size: Channel buffer size. Defaults to 64. + buffer_size: Channel buffer size. Defaults to 64. A row channel queues at + most this many rows. A reader of a batch region output queues at most + ``min(buffer_size, BATCH_BUFFER_SIZE)`` record batches, each of at most + its producer's batch size in rows (a batched source's ``batch_rows``): + a bound in batches, not rows or bytes. Below 1: unbounded. """ def __init__( diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 50718122b..a1738f6a3 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -23,6 +23,7 @@ import pytest from orcapod import PipelineJob, function_pod +from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.operators.static_output_pod import ( BatchStreams, RowsOnRead, @@ -1926,3 +1927,49 @@ def snapshot_batch_streams( # pyright: ignore[reportImplicitOverride] # the ba # Main reads it through the inherited async reader, never its batches. assert calls == [] assert rows == 6 + + +@pytest.mark.parametrize("read", [["x"], ["x", "y", "blob"]], ids=["one", "all"]) +@pytest.mark.parametrize("event", ["refused", "closed"]) +def test_a_source_refused_after_admission_is_refused_at_its_first_scan( + project: Any, monkeypatch: pytest.MonkeyPatch, read: list[str], event: str +) -> None: + """A keyed source admitted to the async batch region whose check records a + refusal (or which is closed) after admission and before its node's task scans: + the first scan raises it, as main's row route does when the source's own reader + first scans, and no row reaches the successor's log (CodeRabbit on PR #696).""" + job = PipelineJob(name="j", database=InMemoryArrowDatabase()) + with job: + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + source.select_data_columns(read, label="sx") + log = InMemoryArrowDatabase() + job.nodes["sx"].attach_databases(pipeline_database=log, cache_mode=CacheMode.LOG) + + def refused(self: Any) -> bool: + raise ValueError("the table is now another table") + + admit = SourceJobNode.region_snapshot_batches + + def admitted_then_changed(self: SourceJobNode) -> Any: + streams = admit(self) + if event == "closed": + source.close() + else: + with monkeypatch.context() as m: + m.setattr(SpiralDBTableSource, "_check_table", refused) + with pytest.raises(ValueError, match="now another table"): + _ = source.check_for_new_data() + return streams + + monkeypatch.setattr(SourceJobNode, "region_snapshot_batches", admitted_then_changed) + expected = ( + (RuntimeError, "SpiralDBTableSource is closed") + if event == "closed" + else (ValueError, "now another table") + ) + with pytest.raises(expected[0], match=expected[1]): + job.run(orchestrator=AsyncPipelineOrchestrator()) + assert not any( + (log.get_all_records(path) or pa.table({})).num_rows + for path in log.list_table_paths() + ) From 57bf204460957ddea92174d4c03c1c7acdb3c83b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 04:56:15 -0800 Subject: [PATCH 20/20] fix(sources): validate projected snapshots before scanning --- .../core/sources/spiraldb_table_source.py | 16 ++++--- .../test_spiraldb_job_projection.py | 44 ++++++++++++++++++- 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index bced8f4da..fd2d2fe96 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1214,13 +1214,15 @@ def snapshot_batch_streams(self) -> "Iterator[ArrowTableStream]": """ return self._snapshot_streams() - def _snapshot_streams(self) -> Generator["ArrowTableStream", None, None]: - """``snapshot_batch_streams``' generator: the origin's checks, then the scan.""" + def _snapshot_streams( + self, *, table_columns: Sequence[str] | None = None + ) -> Generator["ArrowTableStream", None, None]: + """Check the origin before scanning this source's pinned handle in batches.""" origin = self._snapshot_of if origin is not None: # Closed, another process, or a held refusal: raised as its read would. _ = origin._pinned_table() - yield from self._batch_streams() + yield from self._batch_streams(table_columns=table_columns) @override def pinned_snapshot(self) -> "SpiralDBTableSource": @@ -1229,8 +1231,8 @@ def pinned_snapshot(self) -> "SpiralDBTableSource": Every read scans the pinned table handle, an immutable snapshot of one version; a later ``check_for_new_data`` on this source replaces this source's handle and pin, never the copy's. The copy has this source's identity, keys, - restriction and modified time. Its ``snapshot_batch_streams`` refuse, before - their first scan, what a read of this source would refuse then. + restriction and modified time. Its full and projected batch readers refuse, + before their first scan, what a read of this source would refuse then. """ snapshot = self._copy() snapshot._snapshot_of = self @@ -1320,10 +1322,10 @@ def _projected_scan( def _narrowed_streams( self, table_columns: list[str], unread: set[str] ) -> Generator["ArrowTableStream", None, None]: - """``_batch_streams`` over ``table_columns``, each without ``unread``.""" + """Snapshot batches over ``table_columns``, each without ``unread``.""" dropped = unread | {f"{constants.SOURCE_PREFIX}{c}" for c in unread} enriched = {"source": True, "system_tags": True} - for stream in self._batch_streams(table_columns=table_columns): + for stream in self._snapshot_streams(table_columns=table_columns): table = stream.as_table(columns=enriched) yield ArrowTableStream._from_derived_table( table=table.drop_columns( diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index a1738f6a3..c1aed3337 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -1033,13 +1033,14 @@ def answers(*, whole: bool) -> tuple[Any, ...]: assert got[0] == expected[0] # Both routes now collect one stream form (ITL-1347, stage 5a): a sync and an # async output compare equal (main: unequal, ``RowsOnRead`` against a stream). - assert got[0][:3] == (True, True, False) + assert got[0] == (True, True, False, True) # Comparing them compares their identities, which read their rows, as comparing # two sync outputs does on main: each projected output takes its one whole read # then (a whole output holds its rows already). assert got[1] == [_ALL, _ALL] assert expected[1] == [] assert got[2] == expected[2] + assert got[2] == (True, True, True, True, True) def test_a_shallow_copy_shares_the_one_whole_read( @@ -1973,3 +1974,44 @@ def admitted_then_changed(self: SourceJobNode) -> Any: (log.get_all_records(path) or pa.table({})).num_rows for path in log.list_table_paths() ) + + +@pytest.mark.parametrize("event", ["refused", "closed", "advanced"]) +def test_projected_snapshot_checks_origin_before_scanning( + project: Any, monkeypatch: pytest.MonkeyPatch, event: str +) -> None: + """Check the origin at the first scan and keep the snapshot's pinned version.""" + source = SpiralDBTableSource("p", "wide", tag_only_columns=True) + streams = source.pinned_snapshot().projected_batch_streams(["x"]) + assert streams is not None + + if event == "advanced": + _write_newer_version(project) + assert source.check_for_new_data() is True + values = [ + value + for stream in streams + for value in cast("list[float]", stream.as_table()["x"].to_pylist()) + ] + assert sorted(values) == [0.5, 0.5, 1.0, 1.0, 1.5, 1.5] + return + + if event == "closed": + source.close() + expected = (RuntimeError, "SpiralDBTableSource is closed") + else: + + def refused(self: SpiralDBTableSource) -> bool: + raise ValueError("the table is now another table") + + monkeypatch.setattr(SpiralDBTableSource, "_check_table", refused) + expected = (ValueError, "now another table") + with pytest.raises(expected[0], match=expected[1]): + _ = source.check_for_new_data() + + fake.scan_log.clear() + fake.count_log.clear() + with pytest.raises(expected[0], match=expected[1]): + _ = next(streams) + assert not fake.scan_log + assert not fake.count_log